Document image-{next, previous}-file, plus some minor tweak.
[emacs.git] / src / w32fns.c
blob59526936afe0e6306810716a7e682144d83acad8
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2013 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Added by Kevin Gallo */
22 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <math.h>
29 #include <fcntl.h>
30 #include <unistd.h>
32 #include "lisp.h"
33 #include "w32term.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "character.h"
37 #include "buffer.h"
38 #include "intervals.h"
39 #include "dispextern.h"
40 #include "keyboard.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "charset.h"
44 #include "coding.h"
45 #include "ccl.h"
46 #include "fontset.h"
47 #include "systime.h"
48 #include "termhooks.h"
50 #include "w32common.h"
52 #ifdef WINDOWSNT
53 #include "w32heap.h"
54 #include <mbstring.h>
55 #endif /* WINDOWSNT */
57 #if CYGWIN
58 #include "cygw32.h"
59 #else
60 #include "w32.h"
61 #endif
63 #include "bitmaps/gray.xbm"
65 #include <commctrl.h>
66 #include <commdlg.h>
67 #include <shellapi.h>
68 #include <ctype.h>
69 #include <winspool.h>
70 #include <objbase.h>
72 #include <dlgs.h>
73 #include <imm.h>
75 #include "font.h"
76 #include "w32font.h"
78 #ifndef FOF_NO_CONNECTED_ELEMENTS
79 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
80 #endif
82 void syms_of_w32fns (void);
83 void globals_of_w32fns (void);
85 extern void free_frame_menubar (struct frame *);
86 extern int w32_console_toggle_lock_key (int, Lisp_Object);
87 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
88 extern void w32_free_menu_strings (HWND);
89 extern const char *map_w32_filename (const char *, const char **);
90 extern char * w32_strerror (int error_no);
92 /* If non-NULL, a handle to a frame where to display the hourglass cursor. */
93 static HWND hourglass_hwnd = NULL;
95 #ifndef IDC_HAND
96 #define IDC_HAND MAKEINTRESOURCE(32649)
97 #endif
99 Lisp_Object Qsuppress_icon;
100 Lisp_Object Qundefined_color;
101 Lisp_Object Qcancel_timer;
102 Lisp_Object Qfont_param;
103 Lisp_Object Qhyper;
104 Lisp_Object Qsuper;
105 Lisp_Object Qmeta;
106 Lisp_Object Qalt;
107 Lisp_Object Qctrl;
108 Lisp_Object Qcontrol;
109 Lisp_Object Qshift;
110 static Lisp_Object Qgeometry, Qworkarea, Qmm_size, Qframes;
113 /* Prefix for system colors. */
114 #define SYSTEM_COLOR_PREFIX "System"
115 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
117 /* State variables for emulating a three button mouse. */
118 #define LMOUSE 1
119 #define MMOUSE 2
120 #define RMOUSE 4
122 static int button_state = 0;
123 static W32Msg saved_mouse_button_msg;
124 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
125 static W32Msg saved_mouse_move_msg;
126 static unsigned mouse_move_timer = 0;
128 /* Window that is tracking the mouse. */
129 static HWND track_mouse_window;
131 /* Multi-monitor API definitions that are not pulled from the headers
132 since we are compiling for NT 4. */
133 #ifndef MONITOR_DEFAULT_TO_NEAREST
134 #define MONITOR_DEFAULT_TO_NEAREST 2
135 #endif
136 #ifndef MONITORINFOF_PRIMARY
137 #define MONITORINFOF_PRIMARY 1
138 #endif
139 #ifndef SM_XVIRTUALSCREEN
140 #define SM_XVIRTUALSCREEN 76
141 #endif
142 #ifndef SM_YVIRTUALSCREEN
143 #define SM_YVIRTUALSCREEN 77
144 #endif
145 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
146 To avoid a compile error on one or the other, redefine with a new name. */
147 struct MONITOR_INFO
149 DWORD cbSize;
150 RECT rcMonitor;
151 RECT rcWork;
152 DWORD dwFlags;
155 #ifndef CCHDEVICENAME
156 #define CCHDEVICENAME 32
157 #endif
158 struct MONITOR_INFO_EX
160 DWORD cbSize;
161 RECT rcMonitor;
162 RECT rcWork;
163 DWORD dwFlags;
164 char szDevice[CCHDEVICENAME];
167 /* Reportedly, MSVC does not have this in its headers. */
168 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
169 DECLARE_HANDLE(HMONITOR);
170 #endif
172 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
173 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
174 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
175 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
176 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
177 typedef HWND (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
178 typedef HWND (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
179 IN COMPOSITIONFORM *form);
180 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
181 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
182 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
183 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
184 (IN HWND hwnd, IN DWORD dwFlags);
185 typedef BOOL CALLBACK (* MonitorEnum_Proc)
186 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
187 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
188 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
190 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
191 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
192 ImmGetContext_Proc get_ime_context_fn = NULL;
193 ImmReleaseContext_Proc release_ime_context_fn = NULL;
194 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
195 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
196 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
197 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
198 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
200 #ifdef NTGUI_UNICODE
201 #define unicode_append_menu AppendMenuW
202 #else /* !NTGUI_UNICODE */
203 extern AppendMenuW_Proc unicode_append_menu;
204 #endif /* NTGUI_UNICODE */
206 /* Flag to selectively ignore WM_IME_CHAR messages. */
207 static int ignore_ime_char = 0;
209 /* W95 mousewheel handler */
210 unsigned int msh_mousewheel = 0;
212 /* Timers */
213 #define MOUSE_BUTTON_ID 1
214 #define MOUSE_MOVE_ID 2
215 #define MENU_FREE_ID 3
216 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
217 is received. */
218 #define MENU_FREE_DELAY 1000
219 static unsigned menu_free_timer = 0;
221 #ifdef GLYPH_DEBUG
222 static int image_cache_refcount, dpyinfo_refcount;
223 #endif
225 static HWND w32_visible_system_caret_hwnd;
227 static int w32_unicode_gui;
229 /* From w32menu.c */
230 extern HMENU current_popup_menu;
231 static int menubar_in_use = 0;
233 /* From w32uniscribe.c */
234 extern void syms_of_w32uniscribe (void);
235 extern int uniscribe_available;
237 /* Function prototypes for hourglass support. */
238 static void w32_show_hourglass (struct frame *);
239 static void w32_hide_hourglass (void);
241 #ifdef WINDOWSNT
242 /* From w32inevt.c */
243 extern int faked_key;
244 #endif /* WINDOWSNT */
246 /* This gives us the page size and the size of the allocation unit on NT. */
247 SYSTEM_INFO sysinfo_cache;
249 /* This gives us version, build, and platform identification. */
250 OSVERSIONINFO osinfo_cache;
252 DWORD_PTR syspage_mask = 0;
254 /* The major and minor versions of NT. */
255 int w32_major_version;
256 int w32_minor_version;
257 int w32_build_number;
259 /* Distinguish between Windows NT and Windows 95. */
260 int os_subtype;
262 #ifdef HAVE_NTGUI
263 HINSTANCE hinst = NULL;
264 #endif
266 static unsigned int sound_type = 0xFFFFFFFF;
267 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
269 /* Let the user specify a display with a frame.
270 nil stands for the selected frame--or, if that is not a w32 frame,
271 the first display on the list. */
273 struct w32_display_info *
274 check_x_display_info (Lisp_Object frame)
276 if (NILP (frame))
278 struct frame *sf = XFRAME (selected_frame);
280 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
281 return FRAME_DISPLAY_INFO (sf);
282 else
283 return &one_w32_display_info;
285 else if (STRINGP (frame))
286 return x_display_info_for_name (frame);
287 else
289 struct frame *f;
291 CHECK_LIVE_FRAME (frame);
292 f = XFRAME (frame);
293 if (! FRAME_W32_P (f))
294 error ("Non-W32 frame used");
295 return FRAME_DISPLAY_INFO (f);
299 /* Return the Emacs frame-object corresponding to an w32 window.
300 It could be the frame's main window or an icon window. */
302 struct frame *
303 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
305 Lisp_Object tail, frame;
306 struct frame *f;
308 FOR_EACH_FRAME (tail, frame)
310 f = XFRAME (frame);
311 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
312 continue;
314 if (FRAME_W32_WINDOW (f) == wdesc)
315 return f;
317 return 0;
321 static Lisp_Object unwind_create_frame (Lisp_Object);
322 static void unwind_create_tip_frame (Lisp_Object);
323 static void my_create_window (struct frame *);
324 static void my_create_tip_window (struct frame *);
326 /* TODO: Native Input Method support; see x_create_im. */
327 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
328 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
329 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
330 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
331 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
332 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
333 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
334 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
335 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
336 void x_set_menu_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
337 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
338 void x_set_tool_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
343 /* Store the screen positions of frame F into XPTR and YPTR.
344 These are the positions of the containing window manager window,
345 not Emacs's own window. */
347 void
348 x_real_positions (struct frame *f, int *xptr, int *yptr)
350 POINT pt;
351 RECT rect;
353 /* Get the bounds of the WM window. */
354 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
356 pt.x = 0;
357 pt.y = 0;
359 /* Convert (0, 0) in the client area to screen co-ordinates. */
360 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
362 /* Remember x_pixels_diff and y_pixels_diff. */
363 f->x_pixels_diff = pt.x - rect.left;
364 f->y_pixels_diff = pt.y - rect.top;
366 *xptr = rect.left;
367 *yptr = rect.top;
370 /* Returns the window rectangle appropriate for the given fullscreen mode.
371 The normal rect parameter was the window's rectangle prior to entering
372 fullscreen mode. If multiple monitor support is available, the nearest
373 monitor to the window is chosen. */
375 void
376 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
378 struct MONITOR_INFO mi = { sizeof(mi) };
379 if (monitor_from_window_fn && get_monitor_info_fn)
381 HMONITOR monitor =
382 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
383 get_monitor_info_fn (monitor, &mi);
385 else
387 mi.rcMonitor.left = 0;
388 mi.rcMonitor.top = 0;
389 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
390 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
391 mi.rcWork.left = 0;
392 mi.rcWork.top = 0;
393 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
394 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
397 switch (fsmode)
399 case FULLSCREEN_BOTH:
400 rect->left = mi.rcMonitor.left;
401 rect->top = mi.rcMonitor.top;
402 rect->right = mi.rcMonitor.right;
403 rect->bottom = mi.rcMonitor.bottom;
404 break;
405 case FULLSCREEN_MAXIMIZED:
406 rect->left = mi.rcWork.left;
407 rect->top = mi.rcWork.top;
408 rect->right = mi.rcWork.right;
409 rect->bottom = mi.rcWork.bottom;
410 break;
411 case FULLSCREEN_WIDTH:
412 rect->left = mi.rcWork.left;
413 rect->top = normal.top;
414 rect->right = mi.rcWork.right;
415 rect->bottom = normal.bottom;
416 break;
417 case FULLSCREEN_HEIGHT:
418 rect->left = normal.left;
419 rect->top = mi.rcWork.top;
420 rect->right = normal.right;
421 rect->bottom = mi.rcWork.bottom;
422 break;
423 case FULLSCREEN_NONE:
424 default:
425 *rect = normal;
426 break;
432 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
433 Sw32_define_rgb_color, 4, 4, 0,
434 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
435 This adds or updates a named color to `w32-color-map', making it
436 available for use. The original entry's RGB ref is returned, or nil
437 if the entry is new. */)
438 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
440 Lisp_Object rgb;
441 Lisp_Object oldrgb = Qnil;
442 Lisp_Object entry;
444 CHECK_NUMBER (red);
445 CHECK_NUMBER (green);
446 CHECK_NUMBER (blue);
447 CHECK_STRING (name);
449 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
451 block_input ();
453 /* replace existing entry in w32-color-map or add new entry. */
454 entry = Fassoc (name, Vw32_color_map);
455 if (NILP (entry))
457 entry = Fcons (name, rgb);
458 Vw32_color_map = Fcons (entry, Vw32_color_map);
460 else
462 oldrgb = Fcdr (entry);
463 Fsetcdr (entry, rgb);
466 unblock_input ();
468 return (oldrgb);
471 /* The default colors for the w32 color map */
472 typedef struct colormap_t
474 char *name;
475 COLORREF colorref;
476 } colormap_t;
478 colormap_t w32_color_map[] =
480 {"snow" , PALETTERGB (255,250,250)},
481 {"ghost white" , PALETTERGB (248,248,255)},
482 {"GhostWhite" , PALETTERGB (248,248,255)},
483 {"white smoke" , PALETTERGB (245,245,245)},
484 {"WhiteSmoke" , PALETTERGB (245,245,245)},
485 {"gainsboro" , PALETTERGB (220,220,220)},
486 {"floral white" , PALETTERGB (255,250,240)},
487 {"FloralWhite" , PALETTERGB (255,250,240)},
488 {"old lace" , PALETTERGB (253,245,230)},
489 {"OldLace" , PALETTERGB (253,245,230)},
490 {"linen" , PALETTERGB (250,240,230)},
491 {"antique white" , PALETTERGB (250,235,215)},
492 {"AntiqueWhite" , PALETTERGB (250,235,215)},
493 {"papaya whip" , PALETTERGB (255,239,213)},
494 {"PapayaWhip" , PALETTERGB (255,239,213)},
495 {"blanched almond" , PALETTERGB (255,235,205)},
496 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
497 {"bisque" , PALETTERGB (255,228,196)},
498 {"peach puff" , PALETTERGB (255,218,185)},
499 {"PeachPuff" , PALETTERGB (255,218,185)},
500 {"navajo white" , PALETTERGB (255,222,173)},
501 {"NavajoWhite" , PALETTERGB (255,222,173)},
502 {"moccasin" , PALETTERGB (255,228,181)},
503 {"cornsilk" , PALETTERGB (255,248,220)},
504 {"ivory" , PALETTERGB (255,255,240)},
505 {"lemon chiffon" , PALETTERGB (255,250,205)},
506 {"LemonChiffon" , PALETTERGB (255,250,205)},
507 {"seashell" , PALETTERGB (255,245,238)},
508 {"honeydew" , PALETTERGB (240,255,240)},
509 {"mint cream" , PALETTERGB (245,255,250)},
510 {"MintCream" , PALETTERGB (245,255,250)},
511 {"azure" , PALETTERGB (240,255,255)},
512 {"alice blue" , PALETTERGB (240,248,255)},
513 {"AliceBlue" , PALETTERGB (240,248,255)},
514 {"lavender" , PALETTERGB (230,230,250)},
515 {"lavender blush" , PALETTERGB (255,240,245)},
516 {"LavenderBlush" , PALETTERGB (255,240,245)},
517 {"misty rose" , PALETTERGB (255,228,225)},
518 {"MistyRose" , PALETTERGB (255,228,225)},
519 {"white" , PALETTERGB (255,255,255)},
520 {"black" , PALETTERGB ( 0, 0, 0)},
521 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
522 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
523 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
524 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
525 {"dim gray" , PALETTERGB (105,105,105)},
526 {"DimGray" , PALETTERGB (105,105,105)},
527 {"dim grey" , PALETTERGB (105,105,105)},
528 {"DimGrey" , PALETTERGB (105,105,105)},
529 {"slate gray" , PALETTERGB (112,128,144)},
530 {"SlateGray" , PALETTERGB (112,128,144)},
531 {"slate grey" , PALETTERGB (112,128,144)},
532 {"SlateGrey" , PALETTERGB (112,128,144)},
533 {"light slate gray" , PALETTERGB (119,136,153)},
534 {"LightSlateGray" , PALETTERGB (119,136,153)},
535 {"light slate grey" , PALETTERGB (119,136,153)},
536 {"LightSlateGrey" , PALETTERGB (119,136,153)},
537 {"gray" , PALETTERGB (190,190,190)},
538 {"grey" , PALETTERGB (190,190,190)},
539 {"light grey" , PALETTERGB (211,211,211)},
540 {"LightGrey" , PALETTERGB (211,211,211)},
541 {"light gray" , PALETTERGB (211,211,211)},
542 {"LightGray" , PALETTERGB (211,211,211)},
543 {"midnight blue" , PALETTERGB ( 25, 25,112)},
544 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
545 {"navy" , PALETTERGB ( 0, 0,128)},
546 {"navy blue" , PALETTERGB ( 0, 0,128)},
547 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
548 {"cornflower blue" , PALETTERGB (100,149,237)},
549 {"CornflowerBlue" , PALETTERGB (100,149,237)},
550 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
551 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
552 {"slate blue" , PALETTERGB (106, 90,205)},
553 {"SlateBlue" , PALETTERGB (106, 90,205)},
554 {"medium slate blue" , PALETTERGB (123,104,238)},
555 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
556 {"light slate blue" , PALETTERGB (132,112,255)},
557 {"LightSlateBlue" , PALETTERGB (132,112,255)},
558 {"medium blue" , PALETTERGB ( 0, 0,205)},
559 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
560 {"royal blue" , PALETTERGB ( 65,105,225)},
561 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
562 {"blue" , PALETTERGB ( 0, 0,255)},
563 {"dodger blue" , PALETTERGB ( 30,144,255)},
564 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
565 {"deep sky blue" , PALETTERGB ( 0,191,255)},
566 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
567 {"sky blue" , PALETTERGB (135,206,235)},
568 {"SkyBlue" , PALETTERGB (135,206,235)},
569 {"light sky blue" , PALETTERGB (135,206,250)},
570 {"LightSkyBlue" , PALETTERGB (135,206,250)},
571 {"steel blue" , PALETTERGB ( 70,130,180)},
572 {"SteelBlue" , PALETTERGB ( 70,130,180)},
573 {"light steel blue" , PALETTERGB (176,196,222)},
574 {"LightSteelBlue" , PALETTERGB (176,196,222)},
575 {"light blue" , PALETTERGB (173,216,230)},
576 {"LightBlue" , PALETTERGB (173,216,230)},
577 {"powder blue" , PALETTERGB (176,224,230)},
578 {"PowderBlue" , PALETTERGB (176,224,230)},
579 {"pale turquoise" , PALETTERGB (175,238,238)},
580 {"PaleTurquoise" , PALETTERGB (175,238,238)},
581 {"dark turquoise" , PALETTERGB ( 0,206,209)},
582 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
583 {"medium turquoise" , PALETTERGB ( 72,209,204)},
584 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
585 {"turquoise" , PALETTERGB ( 64,224,208)},
586 {"cyan" , PALETTERGB ( 0,255,255)},
587 {"light cyan" , PALETTERGB (224,255,255)},
588 {"LightCyan" , PALETTERGB (224,255,255)},
589 {"cadet blue" , PALETTERGB ( 95,158,160)},
590 {"CadetBlue" , PALETTERGB ( 95,158,160)},
591 {"medium aquamarine" , PALETTERGB (102,205,170)},
592 {"MediumAquamarine" , PALETTERGB (102,205,170)},
593 {"aquamarine" , PALETTERGB (127,255,212)},
594 {"dark green" , PALETTERGB ( 0,100, 0)},
595 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
596 {"dark olive green" , PALETTERGB ( 85,107, 47)},
597 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
598 {"dark sea green" , PALETTERGB (143,188,143)},
599 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
600 {"sea green" , PALETTERGB ( 46,139, 87)},
601 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
602 {"medium sea green" , PALETTERGB ( 60,179,113)},
603 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
604 {"light sea green" , PALETTERGB ( 32,178,170)},
605 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
606 {"pale green" , PALETTERGB (152,251,152)},
607 {"PaleGreen" , PALETTERGB (152,251,152)},
608 {"spring green" , PALETTERGB ( 0,255,127)},
609 {"SpringGreen" , PALETTERGB ( 0,255,127)},
610 {"lawn green" , PALETTERGB (124,252, 0)},
611 {"LawnGreen" , PALETTERGB (124,252, 0)},
612 {"green" , PALETTERGB ( 0,255, 0)},
613 {"chartreuse" , PALETTERGB (127,255, 0)},
614 {"medium spring green" , PALETTERGB ( 0,250,154)},
615 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
616 {"green yellow" , PALETTERGB (173,255, 47)},
617 {"GreenYellow" , PALETTERGB (173,255, 47)},
618 {"lime green" , PALETTERGB ( 50,205, 50)},
619 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
620 {"yellow green" , PALETTERGB (154,205, 50)},
621 {"YellowGreen" , PALETTERGB (154,205, 50)},
622 {"forest green" , PALETTERGB ( 34,139, 34)},
623 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
624 {"olive drab" , PALETTERGB (107,142, 35)},
625 {"OliveDrab" , PALETTERGB (107,142, 35)},
626 {"dark khaki" , PALETTERGB (189,183,107)},
627 {"DarkKhaki" , PALETTERGB (189,183,107)},
628 {"khaki" , PALETTERGB (240,230,140)},
629 {"pale goldenrod" , PALETTERGB (238,232,170)},
630 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
631 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
632 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
633 {"light yellow" , PALETTERGB (255,255,224)},
634 {"LightYellow" , PALETTERGB (255,255,224)},
635 {"yellow" , PALETTERGB (255,255, 0)},
636 {"gold" , PALETTERGB (255,215, 0)},
637 {"light goldenrod" , PALETTERGB (238,221,130)},
638 {"LightGoldenrod" , PALETTERGB (238,221,130)},
639 {"goldenrod" , PALETTERGB (218,165, 32)},
640 {"dark goldenrod" , PALETTERGB (184,134, 11)},
641 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
642 {"rosy brown" , PALETTERGB (188,143,143)},
643 {"RosyBrown" , PALETTERGB (188,143,143)},
644 {"indian red" , PALETTERGB (205, 92, 92)},
645 {"IndianRed" , PALETTERGB (205, 92, 92)},
646 {"saddle brown" , PALETTERGB (139, 69, 19)},
647 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
648 {"sienna" , PALETTERGB (160, 82, 45)},
649 {"peru" , PALETTERGB (205,133, 63)},
650 {"burlywood" , PALETTERGB (222,184,135)},
651 {"beige" , PALETTERGB (245,245,220)},
652 {"wheat" , PALETTERGB (245,222,179)},
653 {"sandy brown" , PALETTERGB (244,164, 96)},
654 {"SandyBrown" , PALETTERGB (244,164, 96)},
655 {"tan" , PALETTERGB (210,180,140)},
656 {"chocolate" , PALETTERGB (210,105, 30)},
657 {"firebrick" , PALETTERGB (178,34, 34)},
658 {"brown" , PALETTERGB (165,42, 42)},
659 {"dark salmon" , PALETTERGB (233,150,122)},
660 {"DarkSalmon" , PALETTERGB (233,150,122)},
661 {"salmon" , PALETTERGB (250,128,114)},
662 {"light salmon" , PALETTERGB (255,160,122)},
663 {"LightSalmon" , PALETTERGB (255,160,122)},
664 {"orange" , PALETTERGB (255,165, 0)},
665 {"dark orange" , PALETTERGB (255,140, 0)},
666 {"DarkOrange" , PALETTERGB (255,140, 0)},
667 {"coral" , PALETTERGB (255,127, 80)},
668 {"light coral" , PALETTERGB (240,128,128)},
669 {"LightCoral" , PALETTERGB (240,128,128)},
670 {"tomato" , PALETTERGB (255, 99, 71)},
671 {"orange red" , PALETTERGB (255, 69, 0)},
672 {"OrangeRed" , PALETTERGB (255, 69, 0)},
673 {"red" , PALETTERGB (255, 0, 0)},
674 {"hot pink" , PALETTERGB (255,105,180)},
675 {"HotPink" , PALETTERGB (255,105,180)},
676 {"deep pink" , PALETTERGB (255, 20,147)},
677 {"DeepPink" , PALETTERGB (255, 20,147)},
678 {"pink" , PALETTERGB (255,192,203)},
679 {"light pink" , PALETTERGB (255,182,193)},
680 {"LightPink" , PALETTERGB (255,182,193)},
681 {"pale violet red" , PALETTERGB (219,112,147)},
682 {"PaleVioletRed" , PALETTERGB (219,112,147)},
683 {"maroon" , PALETTERGB (176, 48, 96)},
684 {"medium violet red" , PALETTERGB (199, 21,133)},
685 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
686 {"violet red" , PALETTERGB (208, 32,144)},
687 {"VioletRed" , PALETTERGB (208, 32,144)},
688 {"magenta" , PALETTERGB (255, 0,255)},
689 {"violet" , PALETTERGB (238,130,238)},
690 {"plum" , PALETTERGB (221,160,221)},
691 {"orchid" , PALETTERGB (218,112,214)},
692 {"medium orchid" , PALETTERGB (186, 85,211)},
693 {"MediumOrchid" , PALETTERGB (186, 85,211)},
694 {"dark orchid" , PALETTERGB (153, 50,204)},
695 {"DarkOrchid" , PALETTERGB (153, 50,204)},
696 {"dark violet" , PALETTERGB (148, 0,211)},
697 {"DarkViolet" , PALETTERGB (148, 0,211)},
698 {"blue violet" , PALETTERGB (138, 43,226)},
699 {"BlueViolet" , PALETTERGB (138, 43,226)},
700 {"purple" , PALETTERGB (160, 32,240)},
701 {"medium purple" , PALETTERGB (147,112,219)},
702 {"MediumPurple" , PALETTERGB (147,112,219)},
703 {"thistle" , PALETTERGB (216,191,216)},
704 {"gray0" , PALETTERGB ( 0, 0, 0)},
705 {"grey0" , PALETTERGB ( 0, 0, 0)},
706 {"dark grey" , PALETTERGB (169,169,169)},
707 {"DarkGrey" , PALETTERGB (169,169,169)},
708 {"dark gray" , PALETTERGB (169,169,169)},
709 {"DarkGray" , PALETTERGB (169,169,169)},
710 {"dark blue" , PALETTERGB ( 0, 0,139)},
711 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
712 {"dark cyan" , PALETTERGB ( 0,139,139)},
713 {"DarkCyan" , PALETTERGB ( 0,139,139)},
714 {"dark magenta" , PALETTERGB (139, 0,139)},
715 {"DarkMagenta" , PALETTERGB (139, 0,139)},
716 {"dark red" , PALETTERGB (139, 0, 0)},
717 {"DarkRed" , PALETTERGB (139, 0, 0)},
718 {"light green" , PALETTERGB (144,238,144)},
719 {"LightGreen" , PALETTERGB (144,238,144)},
722 static Lisp_Object
723 w32_default_color_map (void)
725 int i;
726 colormap_t *pc = w32_color_map;
727 Lisp_Object cmap;
729 block_input ();
731 cmap = Qnil;
733 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
734 pc++, i++)
735 cmap = Fcons (Fcons (build_string (pc->name),
736 make_number (pc->colorref)),
737 cmap);
739 unblock_input ();
741 return (cmap);
744 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
745 0, 0, 0, doc: /* Return the default color map. */)
746 (void)
748 return w32_default_color_map ();
751 static Lisp_Object
752 w32_color_map_lookup (const char *colorname)
754 Lisp_Object tail, ret = Qnil;
756 block_input ();
758 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
760 register Lisp_Object elt, tem;
762 elt = XCAR (tail);
763 if (!CONSP (elt)) continue;
765 tem = XCAR (elt);
767 if (lstrcmpi (SDATA (tem), colorname) == 0)
769 ret = Fcdr (elt);
770 break;
773 QUIT;
776 unblock_input ();
778 return ret;
782 static void
783 add_system_logical_colors_to_map (Lisp_Object *system_colors)
785 HKEY colors_key;
787 /* Other registry operations are done with input blocked. */
788 block_input ();
790 /* Look for "Control Panel/Colors" under User and Machine registry
791 settings. */
792 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
793 KEY_READ, &colors_key) == ERROR_SUCCESS
794 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
795 KEY_READ, &colors_key) == ERROR_SUCCESS)
797 /* List all keys. */
798 char color_buffer[64];
799 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
800 int index = 0;
801 DWORD name_size, color_size;
802 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
804 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
805 color_size = sizeof (color_buffer);
807 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
809 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
810 NULL, NULL, color_buffer, &color_size)
811 == ERROR_SUCCESS)
813 int r, g, b;
814 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
815 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
816 make_number (RGB (r, g, b))),
817 *system_colors);
819 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
820 color_size = sizeof (color_buffer);
821 index++;
823 RegCloseKey (colors_key);
826 unblock_input ();
830 static Lisp_Object
831 x_to_w32_color (const char * colorname)
833 register Lisp_Object ret = Qnil;
835 block_input ();
837 if (colorname[0] == '#')
839 /* Could be an old-style RGB Device specification. */
840 int size = strlen (colorname + 1);
841 char *color = alloca (size + 1);
843 strcpy (color, colorname + 1);
844 if (size == 3 || size == 6 || size == 9 || size == 12)
846 UINT colorval;
847 int i, pos;
848 pos = 0;
849 size /= 3;
850 colorval = 0;
852 for (i = 0; i < 3; i++)
854 char *end;
855 char t;
856 unsigned long value;
858 /* The check for 'x' in the following conditional takes into
859 account the fact that strtol allows a "0x" in front of
860 our numbers, and we don't. */
861 if (!isxdigit (color[0]) || color[1] == 'x')
862 break;
863 t = color[size];
864 color[size] = '\0';
865 value = strtoul (color, &end, 16);
866 color[size] = t;
867 if (errno == ERANGE || end - color != size)
868 break;
869 switch (size)
871 case 1:
872 value = value * 0x10;
873 break;
874 case 2:
875 break;
876 case 3:
877 value /= 0x10;
878 break;
879 case 4:
880 value /= 0x100;
881 break;
883 colorval |= (value << pos);
884 pos += 0x8;
885 if (i == 2)
887 unblock_input ();
888 XSETINT (ret, colorval);
889 return ret;
891 color = end;
895 else if (strnicmp (colorname, "rgb:", 4) == 0)
897 const char *color;
898 UINT colorval;
899 int i, pos;
900 pos = 0;
902 colorval = 0;
903 color = colorname + 4;
904 for (i = 0; i < 3; i++)
906 char *end;
907 unsigned long value;
909 /* The check for 'x' in the following conditional takes into
910 account the fact that strtol allows a "0x" in front of
911 our numbers, and we don't. */
912 if (!isxdigit (color[0]) || color[1] == 'x')
913 break;
914 value = strtoul (color, &end, 16);
915 if (errno == ERANGE)
916 break;
917 switch (end - color)
919 case 1:
920 value = value * 0x10 + value;
921 break;
922 case 2:
923 break;
924 case 3:
925 value /= 0x10;
926 break;
927 case 4:
928 value /= 0x100;
929 break;
930 default:
931 value = ULONG_MAX;
933 if (value == ULONG_MAX)
934 break;
935 colorval |= (value << pos);
936 pos += 0x8;
937 if (i == 2)
939 if (*end != '\0')
940 break;
941 unblock_input ();
942 XSETINT (ret, colorval);
943 return ret;
945 if (*end != '/')
946 break;
947 color = end + 1;
950 else if (strnicmp (colorname, "rgbi:", 5) == 0)
952 /* This is an RGB Intensity specification. */
953 const char *color;
954 UINT colorval;
955 int i, pos;
956 pos = 0;
958 colorval = 0;
959 color = colorname + 5;
960 for (i = 0; i < 3; i++)
962 char *end;
963 double value;
964 UINT val;
966 value = strtod (color, &end);
967 if (errno == ERANGE)
968 break;
969 if (value < 0.0 || value > 1.0)
970 break;
971 val = (UINT)(0x100 * value);
972 /* We used 0x100 instead of 0xFF to give a continuous
973 range between 0.0 and 1.0 inclusive. The next statement
974 fixes the 1.0 case. */
975 if (val == 0x100)
976 val = 0xFF;
977 colorval |= (val << pos);
978 pos += 0x8;
979 if (i == 2)
981 if (*end != '\0')
982 break;
983 unblock_input ();
984 XSETINT (ret, colorval);
985 return ret;
987 if (*end != '/')
988 break;
989 color = end + 1;
992 /* I am not going to attempt to handle any of the CIE color schemes
993 or TekHVC, since I don't know the algorithms for conversion to
994 RGB. */
996 /* If we fail to lookup the color name in w32_color_map, then check the
997 colorname to see if it can be crudely approximated: If the X color
998 ends in a number (e.g., "darkseagreen2"), strip the number and
999 return the result of looking up the base color name. */
1000 ret = w32_color_map_lookup (colorname);
1001 if (NILP (ret))
1003 int len = strlen (colorname);
1005 if (isdigit (colorname[len - 1]))
1007 char *ptr, *approx = alloca (len + 1);
1009 strcpy (approx, colorname);
1010 ptr = &approx[len - 1];
1011 while (ptr > approx && isdigit (*ptr))
1012 *ptr-- = '\0';
1014 ret = w32_color_map_lookup (approx);
1018 unblock_input ();
1019 return ret;
1022 void
1023 w32_regenerate_palette (struct frame *f)
1025 struct w32_palette_entry * list;
1026 LOGPALETTE * log_palette;
1027 HPALETTE new_palette;
1028 int i;
1030 /* don't bother trying to create palette if not supported */
1031 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1032 return;
1034 log_palette = (LOGPALETTE *)
1035 alloca (sizeof (LOGPALETTE) +
1036 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1037 log_palette->palVersion = 0x300;
1038 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1040 list = FRAME_DISPLAY_INFO (f)->color_list;
1041 for (i = 0;
1042 i < FRAME_DISPLAY_INFO (f)->num_colors;
1043 i++, list = list->next)
1044 log_palette->palPalEntry[i] = list->entry;
1046 new_palette = CreatePalette (log_palette);
1048 enter_crit ();
1050 if (FRAME_DISPLAY_INFO (f)->palette)
1051 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1052 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1054 /* Realize display palette and garbage all frames. */
1055 release_frame_dc (f, get_frame_dc (f));
1057 leave_crit ();
1060 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1061 #define SET_W32_COLOR(pe, color) \
1062 do \
1064 pe.peRed = GetRValue (color); \
1065 pe.peGreen = GetGValue (color); \
1066 pe.peBlue = GetBValue (color); \
1067 pe.peFlags = 0; \
1068 } while (0)
1070 #if 0
1071 /* Keep these around in case we ever want to track color usage. */
1072 void
1073 w32_map_color (struct frame *f, COLORREF color)
1075 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1077 if (NILP (Vw32_enable_palette))
1078 return;
1080 /* check if color is already mapped */
1081 while (list)
1083 if (W32_COLOR (list->entry) == color)
1085 ++list->refcount;
1086 return;
1088 list = list->next;
1091 /* not already mapped, so add to list and recreate Windows palette */
1092 list = xmalloc (sizeof (struct w32_palette_entry));
1093 SET_W32_COLOR (list->entry, color);
1094 list->refcount = 1;
1095 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1096 FRAME_DISPLAY_INFO (f)->color_list = list;
1097 FRAME_DISPLAY_INFO (f)->num_colors++;
1099 /* set flag that palette must be regenerated */
1100 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1103 void
1104 w32_unmap_color (struct frame *f, COLORREF color)
1106 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1107 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1109 if (NILP (Vw32_enable_palette))
1110 return;
1112 /* check if color is already mapped */
1113 while (list)
1115 if (W32_COLOR (list->entry) == color)
1117 if (--list->refcount == 0)
1119 *prev = list->next;
1120 xfree (list);
1121 FRAME_DISPLAY_INFO (f)->num_colors--;
1122 break;
1124 else
1125 return;
1127 prev = &list->next;
1128 list = list->next;
1131 /* set flag that palette must be regenerated */
1132 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1134 #endif
1137 /* Gamma-correct COLOR on frame F. */
1139 void
1140 gamma_correct (struct frame *f, COLORREF *color)
1142 if (f->gamma)
1144 *color = PALETTERGB (
1145 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1146 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1147 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1152 /* Decide if color named COLOR is valid for the display associated with
1153 the selected frame; if so, return the rgb values in COLOR_DEF.
1154 If ALLOC is nonzero, allocate a new colormap cell. */
1157 w32_defined_color (struct frame *f, const char *color, XColor *color_def, int alloc)
1159 register Lisp_Object tem;
1160 COLORREF w32_color_ref;
1162 tem = x_to_w32_color (color);
1164 if (!NILP (tem))
1166 if (f)
1168 /* Apply gamma correction. */
1169 w32_color_ref = XUINT (tem);
1170 gamma_correct (f, &w32_color_ref);
1171 XSETINT (tem, w32_color_ref);
1174 /* Map this color to the palette if it is enabled. */
1175 if (!NILP (Vw32_enable_palette))
1177 struct w32_palette_entry * entry =
1178 one_w32_display_info.color_list;
1179 struct w32_palette_entry ** prev =
1180 &one_w32_display_info.color_list;
1182 /* check if color is already mapped */
1183 while (entry)
1185 if (W32_COLOR (entry->entry) == XUINT (tem))
1186 break;
1187 prev = &entry->next;
1188 entry = entry->next;
1191 if (entry == NULL && alloc)
1193 /* not already mapped, so add to list */
1194 entry = xmalloc (sizeof (struct w32_palette_entry));
1195 SET_W32_COLOR (entry->entry, XUINT (tem));
1196 entry->next = NULL;
1197 *prev = entry;
1198 one_w32_display_info.num_colors++;
1200 /* set flag that palette must be regenerated */
1201 one_w32_display_info.regen_palette = TRUE;
1204 /* Ensure COLORREF value is snapped to nearest color in (default)
1205 palette by simulating the PALETTERGB macro. This works whether
1206 or not the display device has a palette. */
1207 w32_color_ref = XUINT (tem) | 0x2000000;
1209 color_def->pixel = w32_color_ref;
1210 color_def->red = GetRValue (w32_color_ref) * 256;
1211 color_def->green = GetGValue (w32_color_ref) * 256;
1212 color_def->blue = GetBValue (w32_color_ref) * 256;
1214 return 1;
1216 else
1218 return 0;
1222 /* Given a string ARG naming a color, compute a pixel value from it
1223 suitable for screen F.
1224 If F is not a color screen, return DEF (default) regardless of what
1225 ARG says. */
1228 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1230 XColor cdef;
1232 CHECK_STRING (arg);
1234 if (strcmp (SDATA (arg), "black") == 0)
1235 return BLACK_PIX_DEFAULT (f);
1236 else if (strcmp (SDATA (arg), "white") == 0)
1237 return WHITE_PIX_DEFAULT (f);
1239 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1240 return def;
1242 /* w32_defined_color is responsible for coping with failures
1243 by looking for a near-miss. */
1244 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1245 return cdef.pixel;
1247 /* defined_color failed; return an ultimate default. */
1248 return def;
1253 /* Functions called only from `x_set_frame_param'
1254 to set individual parameters.
1256 If FRAME_W32_WINDOW (f) is 0,
1257 the frame is being created and its window does not exist yet.
1258 In that case, just record the parameter's new value
1259 in the standard place; do not attempt to change the window. */
1261 void
1262 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1264 struct w32_output *x = f->output_data.w32;
1265 PIX_TYPE fg, old_fg;
1267 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1268 old_fg = FRAME_FOREGROUND_PIXEL (f);
1269 FRAME_FOREGROUND_PIXEL (f) = fg;
1271 if (FRAME_W32_WINDOW (f) != 0)
1273 if (x->cursor_pixel == old_fg)
1275 x->cursor_pixel = fg;
1276 x->cursor_gc->background = fg;
1279 update_face_from_frame_parameter (f, Qforeground_color, arg);
1280 if (FRAME_VISIBLE_P (f))
1281 redraw_frame (f);
1285 void
1286 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1288 FRAME_BACKGROUND_PIXEL (f)
1289 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1291 if (FRAME_W32_WINDOW (f) != 0)
1293 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1294 FRAME_BACKGROUND_PIXEL (f));
1296 update_face_from_frame_parameter (f, Qbackground_color, arg);
1298 if (FRAME_VISIBLE_P (f))
1299 redraw_frame (f);
1303 void
1304 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1306 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1307 int count;
1308 int mask_color;
1310 if (!EQ (Qnil, arg))
1311 f->output_data.w32->mouse_pixel
1312 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1313 mask_color = FRAME_BACKGROUND_PIXEL (f);
1315 /* Don't let pointers be invisible. */
1316 if (mask_color == f->output_data.w32->mouse_pixel
1317 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1318 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1320 #if 0 /* TODO : Mouse cursor customization. */
1321 block_input ();
1323 /* It's not okay to crash if the user selects a screwy cursor. */
1324 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1326 if (!EQ (Qnil, Vx_pointer_shape))
1328 CHECK_NUMBER (Vx_pointer_shape);
1329 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1331 else
1332 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1333 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1335 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1337 CHECK_NUMBER (Vx_nontext_pointer_shape);
1338 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1339 XINT (Vx_nontext_pointer_shape));
1341 else
1342 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1343 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1345 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1347 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1348 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1349 XINT (Vx_hourglass_pointer_shape));
1351 else
1352 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1353 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1355 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1356 if (!EQ (Qnil, Vx_mode_pointer_shape))
1358 CHECK_NUMBER (Vx_mode_pointer_shape);
1359 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1360 XINT (Vx_mode_pointer_shape));
1362 else
1363 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1364 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1366 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1368 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1369 hand_cursor
1370 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1371 XINT (Vx_sensitive_text_pointer_shape));
1373 else
1374 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1376 if (!NILP (Vx_window_horizontal_drag_shape))
1378 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1379 horizontal_drag_cursor
1380 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1381 XINT (Vx_window_horizontal_drag_shape));
1383 else
1384 horizontal_drag_cursor
1385 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1387 if (!NILP (Vx_window_vertical_drag_shape))
1389 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1390 vertical_drag_cursor
1391 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1392 XINT (Vx_window_vertical_drag_shape));
1394 else
1395 vertical_drag_cursor
1396 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_v_double_arrow);
1398 /* Check and report errors with the above calls. */
1399 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1400 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1403 XColor fore_color, back_color;
1405 fore_color.pixel = f->output_data.w32->mouse_pixel;
1406 back_color.pixel = mask_color;
1407 XQueryColor (FRAME_W32_DISPLAY (f),
1408 DefaultColormap (FRAME_W32_DISPLAY (f),
1409 DefaultScreen (FRAME_W32_DISPLAY (f))),
1410 &fore_color);
1411 XQueryColor (FRAME_W32_DISPLAY (f),
1412 DefaultColormap (FRAME_W32_DISPLAY (f),
1413 DefaultScreen (FRAME_W32_DISPLAY (f))),
1414 &back_color);
1415 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1416 &fore_color, &back_color);
1417 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1418 &fore_color, &back_color);
1419 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1420 &fore_color, &back_color);
1421 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1422 &fore_color, &back_color);
1423 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1424 &fore_color, &back_color);
1427 if (FRAME_W32_WINDOW (f) != 0)
1428 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1430 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1431 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1432 f->output_data.w32->text_cursor = cursor;
1434 if (nontext_cursor != f->output_data.w32->nontext_cursor
1435 && f->output_data.w32->nontext_cursor != 0)
1436 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1437 f->output_data.w32->nontext_cursor = nontext_cursor;
1439 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1440 && f->output_data.w32->hourglass_cursor != 0)
1441 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1442 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1444 if (mode_cursor != f->output_data.w32->modeline_cursor
1445 && f->output_data.w32->modeline_cursor != 0)
1446 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1447 f->output_data.w32->modeline_cursor = mode_cursor;
1449 if (hand_cursor != f->output_data.w32->hand_cursor
1450 && f->output_data.w32->hand_cursor != 0)
1451 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1452 f->output_data.w32->hand_cursor = hand_cursor;
1454 XFlush (FRAME_W32_DISPLAY (f));
1455 unblock_input ();
1457 update_face_from_frame_parameter (f, Qmouse_color, arg);
1458 #endif /* TODO */
1461 void
1462 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1464 unsigned long fore_pixel, pixel;
1466 if (!NILP (Vx_cursor_fore_pixel))
1467 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1468 WHITE_PIX_DEFAULT (f));
1469 else
1470 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1472 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1474 /* Make sure that the cursor color differs from the background color. */
1475 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1477 pixel = f->output_data.w32->mouse_pixel;
1478 if (pixel == fore_pixel)
1479 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1482 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1483 f->output_data.w32->cursor_pixel = pixel;
1485 if (FRAME_W32_WINDOW (f) != 0)
1487 block_input ();
1488 /* Update frame's cursor_gc. */
1489 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1490 f->output_data.w32->cursor_gc->background = pixel;
1492 unblock_input ();
1494 if (FRAME_VISIBLE_P (f))
1496 x_update_cursor (f, 0);
1497 x_update_cursor (f, 1);
1501 update_face_from_frame_parameter (f, Qcursor_color, arg);
1504 /* Set the border-color of frame F to pixel value PIX.
1505 Note that this does not fully take effect if done before
1506 F has a window. */
1508 void
1509 x_set_border_pixel (struct frame *f, int pix)
1512 f->output_data.w32->border_pixel = pix;
1514 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1516 if (FRAME_VISIBLE_P (f))
1517 redraw_frame (f);
1521 /* Set the border-color of frame F to value described by ARG.
1522 ARG can be a string naming a color.
1523 The border-color is used for the border that is drawn by the server.
1524 Note that this does not fully take effect if done before
1525 F has a window; it must be redone when the window is created. */
1527 void
1528 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1530 int pix;
1532 CHECK_STRING (arg);
1533 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1534 x_set_border_pixel (f, pix);
1535 update_face_from_frame_parameter (f, Qborder_color, arg);
1539 void
1540 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1542 set_frame_cursor_types (f, arg);
1545 void
1546 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1548 int result;
1550 if (NILP (arg) && NILP (oldval))
1551 return;
1553 if (STRINGP (arg) && STRINGP (oldval)
1554 && EQ (Fstring_equal (oldval, arg), Qt))
1555 return;
1557 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1558 return;
1560 block_input ();
1562 result = x_bitmap_icon (f, arg);
1563 if (result)
1565 unblock_input ();
1566 error ("No icon window available");
1569 unblock_input ();
1572 void
1573 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1575 if (STRINGP (arg))
1577 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1578 return;
1580 else if (!NILP (arg) || NILP (oldval))
1581 return;
1583 fset_icon_name (f, arg);
1585 #if 0
1586 if (f->output_data.w32->icon_bitmap != 0)
1587 return;
1589 block_input ();
1591 result = x_text_icon (f,
1592 SSDATA ((!NILP (f->icon_name)
1593 ? f->icon_name
1594 : !NILP (f->title)
1595 ? f->title
1596 : f->name)));
1598 if (result)
1600 unblock_input ();
1601 error ("No icon window available");
1604 /* If the window was unmapped (and its icon was mapped),
1605 the new icon is not mapped, so map the window in its stead. */
1606 if (FRAME_VISIBLE_P (f))
1608 #ifdef USE_X_TOOLKIT
1609 XtPopup (f->output_data.w32->widget, XtGrabNone);
1610 #endif
1611 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1614 XFlush (FRAME_W32_DISPLAY (f));
1615 unblock_input ();
1616 #endif
1620 void
1621 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1623 int nlines;
1625 /* Right now, menu bars don't work properly in minibuf-only frames;
1626 most of the commands try to apply themselves to the minibuffer
1627 frame itself, and get an error because you can't switch buffers
1628 in or split the minibuffer window. */
1629 if (FRAME_MINIBUF_ONLY_P (f))
1630 return;
1632 if (INTEGERP (value))
1633 nlines = XINT (value);
1634 else
1635 nlines = 0;
1637 FRAME_MENU_BAR_LINES (f) = 0;
1638 FRAME_MENU_BAR_HEIGHT (f) = 0;
1639 if (nlines)
1640 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1641 else
1643 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1644 free_frame_menubar (f);
1645 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1647 /* Adjust the frame size so that the client (text) dimensions
1648 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1649 set correctly. */
1650 x_set_window_size (f, 0, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 1);
1651 do_pending_window_change (0);
1653 adjust_frame_glyphs (f);
1657 /* Set the number of lines used for the tool bar of frame F to VALUE.
1658 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1659 the old number of tool bar lines (and is unused). This function may
1660 change the height of all windows on frame F to match the new tool bar
1661 height. By design, the frame's height doesn't change (but maybe it
1662 should if we don't get enough space otherwise). */
1664 void
1665 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1667 int delta, nlines, root_height;
1668 int unit = FRAME_LINE_HEIGHT (f);
1670 /* Treat tool bars like menu bars. */
1671 if (FRAME_MINIBUF_ONLY_P (f))
1672 return;
1674 /* Use VALUE only if an integer >= 0. */
1675 if (INTEGERP (value) && XINT (value) >= 0)
1676 nlines = XFASTINT (value);
1677 else
1678 nlines = 0;
1680 /* Make sure we redisplay all windows in this frame. */
1681 windows_or_buffers_changed = 23;
1683 /* DELTA is in pixels now. */
1684 delta = (nlines - FRAME_TOOL_BAR_LINES (f)) * unit;
1686 /* Don't resize the tool-bar to more than we have room for. FIXME:
1687 This must use window_sizable eventually !!!!!!!!!!!! */
1688 if (delta > 0)
1690 root_height = WINDOW_PIXEL_HEIGHT (XWINDOW (FRAME_ROOT_WINDOW (f)));
1691 if (root_height - delta < unit)
1693 delta = root_height - unit;
1694 nlines = (root_height / unit) + min (1, (root_height % unit));
1698 FRAME_TOOL_BAR_LINES (f) = nlines;
1699 FRAME_TOOL_BAR_HEIGHT (f) = nlines * FRAME_LINE_HEIGHT (f);
1700 ++windows_or_buffers_changed;
1701 resize_frame_windows (f, FRAME_TEXT_HEIGHT (f), 0, 1);
1702 adjust_frame_glyphs (f);
1704 /* We also have to make sure that the internal border at the top of
1705 the frame, below the menu bar or tool bar, is redrawn when the
1706 tool bar disappears. This is so because the internal border is
1707 below the tool bar if one is displayed, but is below the menu bar
1708 if there isn't a tool bar. The tool bar draws into the area
1709 below the menu bar. */
1710 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1712 clear_frame (f);
1713 clear_current_matrices (f);
1716 /* If the tool bar gets smaller, the internal border below it
1717 has to be cleared. It was formerly part of the display
1718 of the larger tool bar, and updating windows won't clear it. */
1719 if (delta < 0)
1721 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1722 int width = FRAME_PIXEL_WIDTH (f);
1723 int y = nlines * unit;
1725 block_input ();
1727 HDC hdc = get_frame_dc (f);
1728 w32_clear_area (f, hdc, 0, y, width, height);
1729 release_frame_dc (f, hdc);
1731 unblock_input ();
1733 if (WINDOWP (f->tool_bar_window))
1734 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1737 run_window_configuration_change_hook (f);
1742 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1743 w32_id_name.
1745 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1746 name; if NAME is a string, set F's name to NAME and set
1747 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1749 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1750 suggesting a new name, which lisp code should override; if
1751 F->explicit_name is set, ignore the new name; otherwise, set it. */
1753 void
1754 x_set_name (struct frame *f, Lisp_Object name, int explicit)
1756 /* Make sure that requests from lisp code override requests from
1757 Emacs redisplay code. */
1758 if (explicit)
1760 /* If we're switching from explicit to implicit, we had better
1761 update the mode lines and thereby update the title. */
1762 if (f->explicit_name && NILP (name))
1763 update_mode_lines = 25;
1765 f->explicit_name = ! NILP (name);
1767 else if (f->explicit_name)
1768 return;
1770 /* If NAME is nil, set the name to the w32_id_name. */
1771 if (NILP (name))
1773 /* Check for no change needed in this very common case
1774 before we do any consing. */
1775 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1776 SDATA (f->name)))
1777 return;
1778 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1780 else
1781 CHECK_STRING (name);
1783 /* Don't change the name if it's already NAME. */
1784 if (! NILP (Fstring_equal (name, f->name)))
1785 return;
1787 fset_name (f, name);
1789 /* For setting the frame title, the title parameter should override
1790 the name parameter. */
1791 if (! NILP (f->title))
1792 name = f->title;
1794 if (FRAME_W32_WINDOW (f))
1796 block_input ();
1797 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1798 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1799 unblock_input ();
1803 /* This function should be called when the user's lisp code has
1804 specified a name for the frame; the name will override any set by the
1805 redisplay code. */
1806 void
1807 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1809 x_set_name (f, arg, 1);
1812 /* This function should be called by Emacs redisplay code to set the
1813 name; names set this way will never override names set by the user's
1814 lisp code. */
1815 void
1816 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1818 x_set_name (f, arg, 0);
1821 /* Change the title of frame F to NAME.
1822 If NAME is nil, use the frame name as the title. */
1824 void
1825 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1827 /* Don't change the title if it's already NAME. */
1828 if (EQ (name, f->title))
1829 return;
1831 update_mode_lines = 26;
1833 fset_title (f, name);
1835 if (NILP (name))
1836 name = f->name;
1838 if (FRAME_W32_WINDOW (f))
1840 block_input ();
1841 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1842 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1843 unblock_input ();
1847 void
1848 x_set_scroll_bar_default_width (struct frame *f)
1850 int wid = FRAME_COLUMN_WIDTH (f);
1852 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1853 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
1854 wid - 1) / wid;
1858 /* Subroutines for creating a frame. */
1860 Cursor
1861 w32_load_cursor (LPCTSTR name)
1863 /* Try first to load cursor from application resource. */
1864 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1865 name, IMAGE_CURSOR, 0, 0,
1866 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1867 if (!cursor)
1869 /* Then try to load a shared predefined cursor. */
1870 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1871 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1873 return cursor;
1876 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1878 #define INIT_WINDOW_CLASS(WC) \
1879 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1880 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1881 (WC).cbClsExtra = 0; \
1882 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1883 (WC).hInstance = hinst; \
1884 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1885 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1886 (WC).hbrBackground = NULL; \
1887 (WC).lpszMenuName = NULL; \
1889 static BOOL
1890 w32_init_class (HINSTANCE hinst)
1892 if (w32_unicode_gui)
1894 WNDCLASSW uwc;
1895 INIT_WINDOW_CLASS(uwc);
1896 uwc.lpszClassName = L"Emacs";
1898 return RegisterClassW (&uwc);
1900 else
1902 WNDCLASS wc;
1903 INIT_WINDOW_CLASS(wc);
1904 wc.lpszClassName = EMACS_CLASS;
1906 return RegisterClassA (&wc);
1910 static HWND
1911 w32_createscrollbar (struct frame *f, struct scroll_bar * bar)
1913 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1914 /* Position and size of scroll bar. */
1915 bar->left, bar->top, bar->width, bar->height,
1916 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1919 static void
1920 w32_createwindow (struct frame *f)
1922 HWND hwnd;
1923 RECT rect;
1924 Lisp_Object top = Qunbound;
1925 Lisp_Object left = Qunbound;
1926 struct w32_display_info *dpyinfo = &one_w32_display_info;
1928 rect.left = rect.top = 0;
1929 rect.right = FRAME_PIXEL_WIDTH (f);
1930 rect.bottom = FRAME_PIXEL_HEIGHT (f);
1932 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
1933 FRAME_EXTERNAL_MENU_BAR (f));
1935 /* Do first time app init */
1937 w32_init_class (hinst);
1939 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
1941 XSETINT (left, f->left_pos);
1942 XSETINT (top, f->top_pos);
1944 else if (EQ (left, Qunbound) && EQ (top, Qunbound))
1946 /* When called with RES_TYPE_NUMBER, w32_get_arg will return zero
1947 for anything that is not a number and is not Qunbound. */
1948 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
1949 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
1952 FRAME_W32_WINDOW (f) = hwnd
1953 = CreateWindow (EMACS_CLASS,
1954 f->namebuf,
1955 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
1956 EQ (left, Qunbound) ? CW_USEDEFAULT : XINT (left),
1957 EQ (top, Qunbound) ? CW_USEDEFAULT : XINT (top),
1958 rect.right - rect.left,
1959 rect.bottom - rect.top,
1960 NULL,
1961 NULL,
1962 hinst,
1963 NULL);
1965 if (hwnd)
1967 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
1968 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
1969 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
1970 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
1971 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
1973 /* Enable drag-n-drop. */
1974 DragAcceptFiles (hwnd, TRUE);
1976 /* Do this to discard the default setting specified by our parent. */
1977 ShowWindow (hwnd, SW_HIDE);
1979 /* Update frame positions. */
1980 GetWindowRect (hwnd, &rect);
1981 f->left_pos = rect.left;
1982 f->top_pos = rect.top;
1986 static void
1987 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1989 wmsg->msg.hwnd = hwnd;
1990 wmsg->msg.message = msg;
1991 wmsg->msg.wParam = wParam;
1992 wmsg->msg.lParam = lParam;
1993 wmsg->msg.time = GetMessageTime ();
1995 post_msg (wmsg);
1998 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
1999 between left and right keys as advertised. We test for this
2000 support dynamically, and set a flag when the support is absent. If
2001 absent, we keep track of the left and right control and alt keys
2002 ourselves. This is particularly necessary on keyboards that rely
2003 upon the AltGr key, which is represented as having the left control
2004 and right alt keys pressed. For these keyboards, we need to know
2005 when the left alt key has been pressed in addition to the AltGr key
2006 so that we can properly support M-AltGr-key sequences (such as M-@
2007 on Swedish keyboards). */
2009 #define EMACS_LCONTROL 0
2010 #define EMACS_RCONTROL 1
2011 #define EMACS_LMENU 2
2012 #define EMACS_RMENU 3
2014 static int modifiers[4];
2015 static int modifiers_recorded;
2016 static int modifier_key_support_tested;
2018 static void
2019 test_modifier_support (unsigned int wparam)
2021 unsigned int l, r;
2023 if (wparam != VK_CONTROL && wparam != VK_MENU)
2024 return;
2025 if (wparam == VK_CONTROL)
2027 l = VK_LCONTROL;
2028 r = VK_RCONTROL;
2030 else
2032 l = VK_LMENU;
2033 r = VK_RMENU;
2035 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2036 modifiers_recorded = 1;
2037 else
2038 modifiers_recorded = 0;
2039 modifier_key_support_tested = 1;
2042 static void
2043 record_keydown (unsigned int wparam, unsigned int lparam)
2045 int i;
2047 if (!modifier_key_support_tested)
2048 test_modifier_support (wparam);
2050 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2051 return;
2053 if (wparam == VK_CONTROL)
2054 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2055 else
2056 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2058 modifiers[i] = 1;
2061 static void
2062 record_keyup (unsigned int wparam, unsigned int lparam)
2064 int i;
2066 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2067 return;
2069 if (wparam == VK_CONTROL)
2070 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2071 else
2072 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2074 modifiers[i] = 0;
2077 /* Emacs can lose focus while a modifier key has been pressed. When
2078 it regains focus, be conservative and clear all modifiers since
2079 we cannot reconstruct the left and right modifier state. */
2080 static void
2081 reset_modifiers (void)
2083 SHORT ctrl, alt;
2085 if (GetFocus () == NULL)
2086 /* Emacs doesn't have keyboard focus. Do nothing. */
2087 return;
2089 ctrl = GetAsyncKeyState (VK_CONTROL);
2090 alt = GetAsyncKeyState (VK_MENU);
2092 if (!(ctrl & 0x08000))
2093 /* Clear any recorded control modifier state. */
2094 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2096 if (!(alt & 0x08000))
2097 /* Clear any recorded alt modifier state. */
2098 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2100 /* Update the state of all modifier keys, because modifiers used in
2101 hot-key combinations can get stuck on if Emacs loses focus as a
2102 result of a hot-key being pressed. */
2104 BYTE keystate[256];
2106 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2108 GetKeyboardState (keystate);
2109 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2110 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2111 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2112 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2113 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2114 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2115 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2116 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2117 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2118 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2119 SetKeyboardState (keystate);
2123 /* Synchronize modifier state with what is reported with the current
2124 keystroke. Even if we cannot distinguish between left and right
2125 modifier keys, we know that, if no modifiers are set, then neither
2126 the left or right modifier should be set. */
2127 static void
2128 sync_modifiers (void)
2130 if (!modifiers_recorded)
2131 return;
2133 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2134 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2136 if (!(GetKeyState (VK_MENU) & 0x8000))
2137 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2140 static int
2141 modifier_set (int vkey)
2143 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2144 toggle keys is not an omission! If you want to add it, you will
2145 have to make changes in the default sub-case of the WM_KEYDOWN
2146 switch, because if the NUMLOCK modifier is set, the code there
2147 will directly convert any key that looks like an ASCII letter,
2148 and also downcase those that look like upper-case ASCII. */
2149 if (vkey == VK_CAPITAL)
2151 if (NILP (Vw32_enable_caps_lock))
2152 return 0;
2153 else
2154 return (GetKeyState (vkey) & 0x1);
2156 if (vkey == VK_SCROLL)
2158 if (NILP (Vw32_scroll_lock_modifier)
2159 /* w32-scroll-lock-modifier can be any non-nil value that is
2160 not one of the modifiers, in which case it shall be ignored. */
2161 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2162 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2163 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2164 || EQ (Vw32_scroll_lock_modifier, Qalt)
2165 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2166 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2167 return 0;
2168 else
2169 return (GetKeyState (vkey) & 0x1);
2172 if (!modifiers_recorded)
2173 return (GetKeyState (vkey) & 0x8000);
2175 switch (vkey)
2177 case VK_LCONTROL:
2178 return modifiers[EMACS_LCONTROL];
2179 case VK_RCONTROL:
2180 return modifiers[EMACS_RCONTROL];
2181 case VK_LMENU:
2182 return modifiers[EMACS_LMENU];
2183 case VK_RMENU:
2184 return modifiers[EMACS_RMENU];
2186 return (GetKeyState (vkey) & 0x8000);
2189 /* Convert between the modifier bits W32 uses and the modifier bits
2190 Emacs uses. */
2192 unsigned int
2193 w32_key_to_modifier (int key)
2195 Lisp_Object key_mapping;
2197 switch (key)
2199 case VK_LWIN:
2200 key_mapping = Vw32_lwindow_modifier;
2201 break;
2202 case VK_RWIN:
2203 key_mapping = Vw32_rwindow_modifier;
2204 break;
2205 case VK_APPS:
2206 key_mapping = Vw32_apps_modifier;
2207 break;
2208 case VK_SCROLL:
2209 key_mapping = Vw32_scroll_lock_modifier;
2210 break;
2211 default:
2212 key_mapping = Qnil;
2215 /* NB. This code runs in the input thread, asynchronously to the lisp
2216 thread, so we must be careful to ensure access to lisp data is
2217 thread-safe. The following code is safe because the modifier
2218 variable values are updated atomically from lisp and symbols are
2219 not relocated by GC. Also, we don't have to worry about seeing GC
2220 markbits here. */
2221 if (EQ (key_mapping, Qhyper))
2222 return hyper_modifier;
2223 if (EQ (key_mapping, Qsuper))
2224 return super_modifier;
2225 if (EQ (key_mapping, Qmeta))
2226 return meta_modifier;
2227 if (EQ (key_mapping, Qalt))
2228 return alt_modifier;
2229 if (EQ (key_mapping, Qctrl))
2230 return ctrl_modifier;
2231 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2232 return ctrl_modifier;
2233 if (EQ (key_mapping, Qshift))
2234 return shift_modifier;
2236 /* Don't generate any modifier if not explicitly requested. */
2237 return 0;
2240 static unsigned int
2241 w32_get_modifiers (void)
2243 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2244 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2245 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2246 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2247 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2248 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2249 (modifier_set (VK_MENU) ?
2250 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2253 /* We map the VK_* modifiers into console modifier constants
2254 so that we can use the same routines to handle both console
2255 and window input. */
2257 static int
2258 construct_console_modifiers (void)
2260 int mods;
2262 mods = 0;
2263 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2264 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2265 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2266 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2267 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2268 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2269 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2270 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2271 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2272 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2273 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2275 return mods;
2278 static int
2279 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2281 int mods;
2283 /* Convert to emacs modifiers. */
2284 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2286 return mods;
2289 unsigned int
2290 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2292 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2293 return virt_key;
2295 if (virt_key == VK_RETURN)
2296 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2298 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2299 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2301 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2302 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2304 if (virt_key == VK_CLEAR)
2305 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2307 return virt_key;
2310 /* List of special key combinations which w32 would normally capture,
2311 but Emacs should grab instead. Not directly visible to lisp, to
2312 simplify synchronization. Each item is an integer encoding a virtual
2313 key code and modifier combination to capture. */
2314 static Lisp_Object w32_grabbed_keys;
2316 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2317 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2318 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2319 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2321 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2322 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2323 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2325 /* Register hot-keys for reserved key combinations when Emacs has
2326 keyboard focus, since this is the only way Emacs can receive key
2327 combinations like Alt-Tab which are used by the system. */
2329 static void
2330 register_hot_keys (HWND hwnd)
2332 Lisp_Object keylist;
2334 /* Use CONSP, since we are called asynchronously. */
2335 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2337 Lisp_Object key = XCAR (keylist);
2339 /* Deleted entries get set to nil. */
2340 if (!INTEGERP (key))
2341 continue;
2343 RegisterHotKey (hwnd, HOTKEY_ID (key),
2344 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2348 static void
2349 unregister_hot_keys (HWND hwnd)
2351 Lisp_Object keylist;
2353 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2355 Lisp_Object key = XCAR (keylist);
2357 if (!INTEGERP (key))
2358 continue;
2360 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2364 #if EMACSDEBUG
2365 const char*
2366 w32_name_of_message (UINT msg)
2368 unsigned i;
2369 static char buf[64];
2370 static const struct {
2371 UINT msg;
2372 const char* name;
2373 } msgnames[] = {
2374 #define M(msg) { msg, # msg }
2375 M (WM_PAINT),
2376 M (WM_TIMER),
2377 M (WM_USER),
2378 M (WM_MOUSEMOVE),
2379 M (WM_LBUTTONUP),
2380 M (WM_KEYDOWN),
2381 M (WM_EMACS_KILL),
2382 M (WM_EMACS_CREATEWINDOW),
2383 M (WM_EMACS_DONE),
2384 M (WM_EMACS_CREATESCROLLBAR),
2385 M (WM_EMACS_SHOWWINDOW),
2386 M (WM_EMACS_SETWINDOWPOS),
2387 M (WM_EMACS_DESTROYWINDOW),
2388 M (WM_EMACS_TRACKPOPUPMENU),
2389 M (WM_EMACS_SETFOCUS),
2390 M (WM_EMACS_SETFOREGROUND),
2391 M (WM_EMACS_SETLOCALE),
2392 M (WM_EMACS_SETKEYBOARDLAYOUT),
2393 M (WM_EMACS_REGISTER_HOT_KEY),
2394 M (WM_EMACS_UNREGISTER_HOT_KEY),
2395 M (WM_EMACS_TOGGLE_LOCK_KEY),
2396 M (WM_EMACS_TRACK_CARET),
2397 M (WM_EMACS_DESTROY_CARET),
2398 M (WM_EMACS_SHOW_CARET),
2399 M (WM_EMACS_HIDE_CARET),
2400 M (WM_EMACS_SETCURSOR),
2401 M (WM_EMACS_PAINT),
2402 M (WM_CHAR),
2403 #undef M
2404 { 0, 0 }
2407 for (i = 0; msgnames[i].name; ++i)
2408 if (msgnames[i].msg == msg)
2409 return msgnames[i].name;
2411 sprintf (buf, "message 0x%04x", (unsigned)msg);
2412 return buf;
2414 #endif /* EMACSDEBUG */
2416 /* Here's an overview of how Emacs input works in GUI sessions on
2417 MS-Windows. (For description of non-GUI input, see the commentary
2418 before w32_console_read_socket in w32inevt.c.)
2420 System messages are read and processed by w32_msg_pump below. This
2421 function runs in a separate thread. It handles a small number of
2422 custom WM_EMACS_* messages (posted by the main thread, look for
2423 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2424 is the main window procedure for the entire Emacs application.
2426 w32_wnd_proc also runs in the same separate input thread. It
2427 handles some messages, mostly those that need GDI calls, by itself.
2428 For the others, it calls my_post_msg, which inserts the messages
2429 into the input queue serviced by w32_read_socket.
2431 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2432 called synchronously from keyboard.c when it is known or suspected
2433 that some input is available. w32_read_socket either handles
2434 messages immediately, or converts them into Emacs input events and
2435 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2436 them and process them when read_char and its callers require
2437 input.
2439 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2440 select(2) takes the place of w32_read_socket.
2444 /* Main message dispatch loop. */
2446 static void
2447 w32_msg_pump (deferred_msg * msg_buf)
2449 MSG msg;
2450 WPARAM result;
2451 HWND focus_window;
2453 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2455 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2458 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2459 /* w32_name_of_message (msg.message), msg.time)); */
2461 if (msg.hwnd == NULL)
2463 switch (msg.message)
2465 case WM_NULL:
2466 /* Produced by complete_deferred_msg; just ignore. */
2467 break;
2468 case WM_EMACS_CREATEWINDOW:
2469 /* Initialize COM for this window. Even though we don't use it,
2470 some third party shell extensions can cause it to be used in
2471 system dialogs, which causes a crash if it is not initialized.
2472 This is a known bug in Windows, which was fixed long ago, but
2473 the patch for XP is not publicly available until XP SP3,
2474 and older versions will never be patched. */
2475 CoInitialize (NULL);
2476 w32_createwindow ((struct frame *) msg.wParam);
2477 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2478 emacs_abort ();
2479 break;
2480 case WM_EMACS_SETLOCALE:
2481 SetThreadLocale (msg.wParam);
2482 /* Reply is not expected. */
2483 break;
2484 case WM_EMACS_SETKEYBOARDLAYOUT:
2485 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2486 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2487 result, 0))
2488 emacs_abort ();
2489 break;
2490 case WM_EMACS_REGISTER_HOT_KEY:
2491 focus_window = GetFocus ();
2492 if (focus_window != NULL)
2493 RegisterHotKey (focus_window,
2494 RAW_HOTKEY_ID (msg.wParam),
2495 RAW_HOTKEY_MODIFIERS (msg.wParam),
2496 RAW_HOTKEY_VK_CODE (msg.wParam));
2497 /* Reply is not expected. */
2498 break;
2499 case WM_EMACS_UNREGISTER_HOT_KEY:
2500 focus_window = GetFocus ();
2501 if (focus_window != NULL)
2502 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2503 /* Mark item as erased. NB: this code must be
2504 thread-safe. The next line is okay because the cons
2505 cell is never made into garbage and is not relocated by
2506 GC. */
2507 XSETCAR (XIL ((EMACS_INT) msg.lParam), Qnil);
2508 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2509 emacs_abort ();
2510 break;
2511 case WM_EMACS_TOGGLE_LOCK_KEY:
2513 int vk_code = (int) msg.wParam;
2514 int cur_state = (GetKeyState (vk_code) & 1);
2515 Lisp_Object new_state = XIL ((EMACS_INT) msg.lParam);
2517 /* NB: This code must be thread-safe. It is safe to
2518 call NILP because symbols are not relocated by GC,
2519 and pointer here is not touched by GC (so the markbit
2520 can't be set). Numbers are safe because they are
2521 immediate values. */
2522 if (NILP (new_state)
2523 || (NUMBERP (new_state)
2524 && ((XUINT (new_state)) & 1) != cur_state))
2526 one_w32_display_info.faked_key = vk_code;
2528 keybd_event ((BYTE) vk_code,
2529 (BYTE) MapVirtualKey (vk_code, 0),
2530 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2531 keybd_event ((BYTE) vk_code,
2532 (BYTE) MapVirtualKey (vk_code, 0),
2533 KEYEVENTF_EXTENDEDKEY | 0, 0);
2534 keybd_event ((BYTE) vk_code,
2535 (BYTE) MapVirtualKey (vk_code, 0),
2536 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2537 cur_state = !cur_state;
2539 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2540 cur_state, 0))
2541 emacs_abort ();
2543 break;
2544 #ifdef MSG_DEBUG
2545 /* Broadcast messages make it here, so you need to be looking
2546 for something in particular for this to be useful. */
2547 default:
2548 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2549 #endif
2552 else
2554 if (w32_unicode_gui)
2555 DispatchMessageW (&msg);
2556 else
2557 DispatchMessageA (&msg);
2560 /* Exit nested loop when our deferred message has completed. */
2561 if (msg_buf->completed)
2562 break;
2566 deferred_msg * deferred_msg_head;
2568 static deferred_msg *
2569 find_deferred_msg (HWND hwnd, UINT msg)
2571 deferred_msg * item;
2573 /* Don't actually need synchronization for read access, since
2574 modification of single pointer is always atomic. */
2575 /* enter_crit (); */
2577 for (item = deferred_msg_head; item != NULL; item = item->next)
2578 if (item->w32msg.msg.hwnd == hwnd
2579 && item->w32msg.msg.message == msg)
2580 break;
2582 /* leave_crit (); */
2584 return item;
2587 static LRESULT
2588 send_deferred_msg (deferred_msg * msg_buf,
2589 HWND hwnd,
2590 UINT msg,
2591 WPARAM wParam,
2592 LPARAM lParam)
2594 /* Only input thread can send deferred messages. */
2595 if (GetCurrentThreadId () != dwWindowsThreadId)
2596 emacs_abort ();
2598 /* It is an error to send a message that is already deferred. */
2599 if (find_deferred_msg (hwnd, msg) != NULL)
2600 emacs_abort ();
2602 /* Enforced synchronization is not needed because this is the only
2603 function that alters deferred_msg_head, and the following critical
2604 section is guaranteed to only be serially reentered (since only the
2605 input thread can call us). */
2607 /* enter_crit (); */
2609 msg_buf->completed = 0;
2610 msg_buf->next = deferred_msg_head;
2611 deferred_msg_head = msg_buf;
2612 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2614 /* leave_crit (); */
2616 /* Start a new nested message loop to process other messages until
2617 this one is completed. */
2618 w32_msg_pump (msg_buf);
2620 deferred_msg_head = msg_buf->next;
2622 return msg_buf->result;
2625 void
2626 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2628 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2630 if (msg_buf == NULL)
2631 /* Message may have been canceled, so don't abort. */
2632 return;
2634 msg_buf->result = result;
2635 msg_buf->completed = 1;
2637 /* Ensure input thread is woken so it notices the completion. */
2638 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2641 static void
2642 cancel_all_deferred_msgs (void)
2644 deferred_msg * item;
2646 /* Don't actually need synchronization for read access, since
2647 modification of single pointer is always atomic. */
2648 /* enter_crit (); */
2650 for (item = deferred_msg_head; item != NULL; item = item->next)
2652 item->result = 0;
2653 item->completed = 1;
2656 /* leave_crit (); */
2658 /* Ensure input thread is woken so it notices the completion. */
2659 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2662 DWORD WINAPI
2663 w32_msg_worker (void *arg)
2665 MSG msg;
2666 deferred_msg dummy_buf;
2668 /* Ensure our message queue is created */
2670 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2672 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2673 emacs_abort ();
2675 memset (&dummy_buf, 0, sizeof (dummy_buf));
2676 dummy_buf.w32msg.msg.hwnd = NULL;
2677 dummy_buf.w32msg.msg.message = WM_NULL;
2679 /* This is the initial message loop which should only exit when the
2680 application quits. */
2681 w32_msg_pump (&dummy_buf);
2683 return 0;
2686 static void
2687 signal_user_input (void)
2689 /* Interrupt any lisp that wants to be interrupted by input. */
2690 if (!NILP (Vthrow_on_input))
2692 Vquit_flag = Vthrow_on_input;
2693 /* Doing a QUIT from this thread is a bad idea, since this
2694 unwinds the stack of the Lisp thread, and the Windows runtime
2695 rightfully barfs. Disabled. */
2696 #if 0
2697 /* If we're inside a function that wants immediate quits,
2698 do it now. */
2699 if (immediate_quit && NILP (Vinhibit_quit))
2701 immediate_quit = 0;
2702 QUIT;
2704 #endif
2709 static void
2710 post_character_message (HWND hwnd, UINT msg,
2711 WPARAM wParam, LPARAM lParam,
2712 DWORD modifiers)
2714 W32Msg wmsg;
2716 wmsg.dwModifiers = modifiers;
2718 /* Detect quit_char and set quit-flag directly. Note that we
2719 still need to post a message to ensure the main thread will be
2720 woken up if blocked in sys_select, but we do NOT want to post
2721 the quit_char message itself (because it will usually be as if
2722 the user had typed quit_char twice). Instead, we post a dummy
2723 message that has no particular effect. */
2725 int c = wParam;
2726 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2727 c = make_ctrl_char (c) & 0377;
2728 if (c == quit_char
2729 || (wmsg.dwModifiers == 0
2730 && w32_quit_key && wParam == w32_quit_key))
2732 Vquit_flag = Qt;
2734 /* The choice of message is somewhat arbitrary, as long as
2735 the main thread handler just ignores it. */
2736 msg = WM_NULL;
2738 /* Interrupt any blocking system calls. */
2739 signal_quit ();
2741 /* As a safety precaution, forcibly complete any deferred
2742 messages. This is a kludge, but I don't see any particularly
2743 clean way to handle the situation where a deferred message is
2744 "dropped" in the lisp thread, and will thus never be
2745 completed, eg. by the user trying to activate the menubar
2746 when the lisp thread is busy, and then typing C-g when the
2747 menubar doesn't open promptly (with the result that the
2748 menubar never responds at all because the deferred
2749 WM_INITMENU message is never completed). Another problem
2750 situation is when the lisp thread calls SendMessage (to send
2751 a window manager command) when a message has been deferred;
2752 the lisp thread gets blocked indefinitely waiting for the
2753 deferred message to be completed, which itself is waiting for
2754 the lisp thread to respond.
2756 Note that we don't want to block the input thread waiting for
2757 a response from the lisp thread (although that would at least
2758 solve the deadlock problem above), because we want to be able
2759 to receive C-g to interrupt the lisp thread. */
2760 cancel_all_deferred_msgs ();
2762 else
2763 signal_user_input ();
2766 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2769 /* Main window procedure */
2771 static LRESULT CALLBACK
2772 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2774 struct frame *f;
2775 struct w32_display_info *dpyinfo = &one_w32_display_info;
2776 W32Msg wmsg;
2777 int windows_translate;
2778 int key;
2780 /* Note that it is okay to call x_window_to_frame, even though we are
2781 not running in the main lisp thread, because frame deletion
2782 requires the lisp thread to synchronize with this thread. Thus, if
2783 a frame struct is returned, it can be used without concern that the
2784 lisp thread might make it disappear while we are using it.
2786 NB. Walking the frame list in this thread is safe (as long as
2787 writes of Lisp_Object slots are atomic, which they are on Windows).
2788 Although delete-frame can destructively modify the frame list while
2789 we are walking it, a garbage collection cannot occur until after
2790 delete-frame has synchronized with this thread.
2792 It is also safe to use functions that make GDI calls, such as
2793 w32_clear_rect, because these functions must obtain a DC handle
2794 from the frame struct using get_frame_dc which is thread-aware. */
2796 switch (msg)
2798 case WM_ERASEBKGND:
2799 f = x_window_to_frame (dpyinfo, hwnd);
2800 if (f)
2802 HDC hdc = get_frame_dc (f);
2803 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2804 w32_clear_rect (f, hdc, &wmsg.rect);
2805 release_frame_dc (f, hdc);
2807 #if defined (W32_DEBUG_DISPLAY)
2808 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2810 wmsg.rect.left, wmsg.rect.top,
2811 wmsg.rect.right, wmsg.rect.bottom));
2812 #endif /* W32_DEBUG_DISPLAY */
2814 return 1;
2815 case WM_PALETTECHANGED:
2816 /* ignore our own changes */
2817 if ((HWND)wParam != hwnd)
2819 f = x_window_to_frame (dpyinfo, hwnd);
2820 if (f)
2821 /* get_frame_dc will realize our palette and force all
2822 frames to be redrawn if needed. */
2823 release_frame_dc (f, get_frame_dc (f));
2825 return 0;
2826 case WM_PAINT:
2828 PAINTSTRUCT paintStruct;
2829 RECT update_rect;
2830 memset (&update_rect, 0, sizeof (update_rect));
2832 f = x_window_to_frame (dpyinfo, hwnd);
2833 if (f == 0)
2835 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2836 return 0;
2839 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2840 fails. Apparently this can happen under some
2841 circumstances. */
2842 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2844 enter_crit ();
2845 BeginPaint (hwnd, &paintStruct);
2847 /* The rectangles returned by GetUpdateRect and BeginPaint
2848 do not always match. Play it safe by assuming both areas
2849 are invalid. */
2850 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2852 #if defined (W32_DEBUG_DISPLAY)
2853 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2855 wmsg.rect.left, wmsg.rect.top,
2856 wmsg.rect.right, wmsg.rect.bottom));
2857 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2858 update_rect.left, update_rect.top,
2859 update_rect.right, update_rect.bottom));
2860 #endif
2861 EndPaint (hwnd, &paintStruct);
2862 leave_crit ();
2864 /* Change the message type to prevent Windows from
2865 combining WM_PAINT messages in the Lisp thread's queue,
2866 since Windows assumes that each message queue is
2867 dedicated to one frame and does not bother checking
2868 that hwnd matches before combining them. */
2869 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
2871 return 0;
2874 /* If GetUpdateRect returns 0 (meaning there is no update
2875 region), assume the whole window needs to be repainted. */
2876 GetClientRect (hwnd, &wmsg.rect);
2877 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2878 return 0;
2881 case WM_INPUTLANGCHANGE:
2882 /* Inform lisp thread of keyboard layout changes. */
2883 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2885 /* Clear dead keys in the keyboard state; for simplicity only
2886 preserve modifier key states. */
2888 int i;
2889 BYTE keystate[256];
2891 GetKeyboardState (keystate);
2892 for (i = 0; i < 256; i++)
2893 if (1
2894 && i != VK_SHIFT
2895 && i != VK_LSHIFT
2896 && i != VK_RSHIFT
2897 && i != VK_CAPITAL
2898 && i != VK_NUMLOCK
2899 && i != VK_SCROLL
2900 && i != VK_CONTROL
2901 && i != VK_LCONTROL
2902 && i != VK_RCONTROL
2903 && i != VK_MENU
2904 && i != VK_LMENU
2905 && i != VK_RMENU
2906 && i != VK_LWIN
2907 && i != VK_RWIN)
2908 keystate[i] = 0;
2909 SetKeyboardState (keystate);
2911 goto dflt;
2913 case WM_HOTKEY:
2914 /* Synchronize hot keys with normal input. */
2915 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2916 return (0);
2918 case WM_KEYUP:
2919 case WM_SYSKEYUP:
2920 record_keyup (wParam, lParam);
2921 goto dflt;
2923 case WM_KEYDOWN:
2924 case WM_SYSKEYDOWN:
2925 /* Ignore keystrokes we fake ourself; see below. */
2926 if (dpyinfo->faked_key == wParam)
2928 dpyinfo->faked_key = 0;
2929 /* Make sure TranslateMessage sees them though (as long as
2930 they don't produce WM_CHAR messages). This ensures that
2931 indicator lights are toggled promptly on Windows 9x, for
2932 example. */
2933 if (wParam < 256 && lispy_function_keys[wParam])
2935 windows_translate = 1;
2936 goto translate;
2938 return 0;
2941 /* Synchronize modifiers with current keystroke. */
2942 sync_modifiers ();
2943 record_keydown (wParam, lParam);
2944 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2946 windows_translate = 0;
2948 switch (wParam)
2950 case VK_LWIN:
2951 if (NILP (Vw32_pass_lwindow_to_system))
2953 /* Prevent system from acting on keyup (which opens the
2954 Start menu if no other key was pressed) by simulating a
2955 press of Space which we will ignore. */
2956 if (GetAsyncKeyState (wParam) & 1)
2958 if (NUMBERP (Vw32_phantom_key_code))
2959 key = XUINT (Vw32_phantom_key_code) & 255;
2960 else
2961 key = VK_SPACE;
2962 dpyinfo->faked_key = key;
2963 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2966 if (!NILP (Vw32_lwindow_modifier))
2967 return 0;
2968 break;
2969 case VK_RWIN:
2970 if (NILP (Vw32_pass_rwindow_to_system))
2972 if (GetAsyncKeyState (wParam) & 1)
2974 if (NUMBERP (Vw32_phantom_key_code))
2975 key = XUINT (Vw32_phantom_key_code) & 255;
2976 else
2977 key = VK_SPACE;
2978 dpyinfo->faked_key = key;
2979 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2982 if (!NILP (Vw32_rwindow_modifier))
2983 return 0;
2984 break;
2985 case VK_APPS:
2986 if (!NILP (Vw32_apps_modifier))
2987 return 0;
2988 break;
2989 case VK_MENU:
2990 if (NILP (Vw32_pass_alt_to_system))
2991 /* Prevent DefWindowProc from activating the menu bar if an
2992 Alt key is pressed and released by itself. */
2993 return 0;
2994 windows_translate = 1;
2995 break;
2996 case VK_CAPITAL:
2997 /* Decide whether to treat as modifier or function key. */
2998 if (NILP (Vw32_enable_caps_lock))
2999 goto disable_lock_key;
3000 windows_translate = 1;
3001 break;
3002 case VK_NUMLOCK:
3003 /* Decide whether to treat as modifier or function key. */
3004 if (NILP (Vw32_enable_num_lock))
3005 goto disable_lock_key;
3006 windows_translate = 1;
3007 break;
3008 case VK_SCROLL:
3009 /* Decide whether to treat as modifier or function key. */
3010 if (NILP (Vw32_scroll_lock_modifier))
3011 goto disable_lock_key;
3012 windows_translate = 1;
3013 break;
3014 disable_lock_key:
3015 /* Ensure the appropriate lock key state (and indicator light)
3016 remains in the same state. We do this by faking another
3017 press of the relevant key. Apparently, this really is the
3018 only way to toggle the state of the indicator lights. */
3019 dpyinfo->faked_key = wParam;
3020 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3021 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3022 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3023 KEYEVENTF_EXTENDEDKEY | 0, 0);
3024 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3025 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3026 /* Ensure indicator lights are updated promptly on Windows 9x
3027 (TranslateMessage apparently does this), after forwarding
3028 input event. */
3029 post_character_message (hwnd, msg, wParam, lParam,
3030 w32_get_key_modifiers (wParam, lParam));
3031 windows_translate = 1;
3032 break;
3033 case VK_CONTROL:
3034 case VK_SHIFT:
3035 case VK_PROCESSKEY: /* Generated by IME. */
3036 windows_translate = 1;
3037 break;
3038 case VK_CANCEL:
3039 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3040 which is confusing for purposes of key binding; convert
3041 VK_CANCEL events into VK_PAUSE events. */
3042 wParam = VK_PAUSE;
3043 break;
3044 case VK_PAUSE:
3045 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3046 for purposes of key binding; convert these back into
3047 VK_NUMLOCK events, at least when we want to see NumLock key
3048 presses. (Note that there is never any possibility that
3049 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3050 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3051 wParam = VK_NUMLOCK;
3052 break;
3053 default:
3054 /* If not defined as a function key, change it to a WM_CHAR message. */
3055 if (wParam > 255 || !lispy_function_keys[wParam])
3057 DWORD modifiers = construct_console_modifiers ();
3059 if (!NILP (Vw32_recognize_altgr)
3060 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3062 /* Always let TranslateMessage handle AltGr key chords;
3063 for some reason, ToAscii doesn't always process AltGr
3064 chords correctly. */
3065 windows_translate = 1;
3067 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3069 /* Handle key chords including any modifiers other
3070 than shift directly, in order to preserve as much
3071 modifier information as possible. */
3072 if ('A' <= wParam && wParam <= 'Z')
3074 /* Don't translate modified alphabetic keystrokes,
3075 so the user doesn't need to constantly switch
3076 layout to type control or meta keystrokes when
3077 the normal layout translates alphabetic
3078 characters to non-ascii characters. */
3079 if (!modifier_set (VK_SHIFT))
3080 wParam += ('a' - 'A');
3081 msg = WM_CHAR;
3083 else
3085 /* Try to handle other keystrokes by determining the
3086 base character (ie. translating the base key plus
3087 shift modifier). */
3088 int add;
3089 KEY_EVENT_RECORD key;
3091 key.bKeyDown = TRUE;
3092 key.wRepeatCount = 1;
3093 key.wVirtualKeyCode = wParam;
3094 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3095 key.uChar.AsciiChar = 0;
3096 key.dwControlKeyState = modifiers;
3098 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3099 /* 0 means an unrecognized keycode, negative means
3100 dead key. Ignore both. */
3101 while (--add >= 0)
3103 /* Forward asciified character sequence. */
3104 post_character_message
3105 (hwnd, WM_CHAR,
3106 (unsigned char) key.uChar.AsciiChar, lParam,
3107 w32_get_key_modifiers (wParam, lParam));
3108 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3110 return 0;
3113 else
3115 /* Let TranslateMessage handle everything else. */
3116 windows_translate = 1;
3121 translate:
3122 if (windows_translate)
3124 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3125 windows_msg.time = GetMessageTime ();
3126 TranslateMessage (&windows_msg);
3127 goto dflt;
3130 /* Fall through */
3132 case WM_SYSCHAR:
3133 case WM_CHAR:
3134 if (wParam > 255 )
3136 W32Msg wmsg;
3138 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3139 signal_user_input ();
3140 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3143 else
3144 post_character_message (hwnd, msg, wParam, lParam,
3145 w32_get_key_modifiers (wParam, lParam));
3146 break;
3148 case WM_UNICHAR:
3149 /* WM_UNICHAR looks promising from the docs, but the exact
3150 circumstances in which TranslateMessage sends it is one of those
3151 Microsoft secret API things that EU and US courts are supposed
3152 to have put a stop to already. Spy++ shows it being sent to Notepad
3153 and other MS apps, but never to Emacs.
3155 Some third party IMEs send it in accordance with the official
3156 documentation though, so handle it here.
3158 UNICODE_NOCHAR is used to test for support for this message.
3159 TRUE indicates that the message is supported. */
3160 if (wParam == UNICODE_NOCHAR)
3161 return TRUE;
3164 W32Msg wmsg;
3165 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3166 signal_user_input ();
3167 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3169 break;
3171 case WM_IME_CHAR:
3172 /* If we can't get the IME result as Unicode, use default processing,
3173 which will at least allow characters decodable in the system locale
3174 get through. */
3175 if (!get_composition_string_fn)
3176 goto dflt;
3178 else if (!ignore_ime_char)
3180 wchar_t * buffer;
3181 int size, i;
3182 W32Msg wmsg;
3183 HIMC context = get_ime_context_fn (hwnd);
3184 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3185 /* Get buffer size. */
3186 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3187 buffer = alloca (size);
3188 size = get_composition_string_fn (context, GCS_RESULTSTR,
3189 buffer, size);
3190 release_ime_context_fn (hwnd, context);
3192 signal_user_input ();
3193 for (i = 0; i < size / sizeof (wchar_t); i++)
3195 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3196 lParam);
3198 /* Ignore the messages for the rest of the
3199 characters in the string that was output above. */
3200 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3202 else
3203 ignore_ime_char--;
3205 break;
3207 case WM_IME_STARTCOMPOSITION:
3208 if (!set_ime_composition_window_fn)
3209 goto dflt;
3210 else
3212 COMPOSITIONFORM form;
3213 HIMC context;
3214 struct window *w;
3216 /* Implementation note: The code below does something that
3217 one shouldn't do: it accesses the window object from a
3218 separate thread, while the main (a.k.a. "Lisp") thread
3219 runs and can legitimately delete and even GC it. That is
3220 why we are extra careful not to futz with a window that
3221 is different from the one recorded when the system caret
3222 coordinates were last modified. That is also why we are
3223 careful not to move the IME window if the window
3224 described by W was deleted, as indicated by its buffer
3225 field being reset to nil. */
3226 f = x_window_to_frame (dpyinfo, hwnd);
3227 if (!(f && FRAME_LIVE_P (f)))
3228 break;
3229 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3230 /* Punt if someone changed the frame's selected window
3231 behind our back. */
3232 if (w != w32_system_caret_window)
3233 break;
3235 form.dwStyle = CFS_RECT;
3236 form.ptCurrentPos.x = w32_system_caret_x;
3237 form.ptCurrentPos.y = w32_system_caret_y;
3239 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3240 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3241 + w32_system_caret_hdr_height);
3242 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3243 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3244 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3245 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3246 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3247 - w32_system_caret_mode_height);
3249 /* Punt if the window was deleted behind our back. */
3250 if (!BUFFERP (w->contents))
3251 break;
3253 context = get_ime_context_fn (hwnd);
3255 if (!context)
3256 break;
3258 set_ime_composition_window_fn (context, &form);
3259 release_ime_context_fn (hwnd, context);
3261 break;
3263 case WM_IME_ENDCOMPOSITION:
3264 ignore_ime_char = 0;
3265 goto dflt;
3267 /* Simulate middle mouse button events when left and right buttons
3268 are used together, but only if user has two button mouse. */
3269 case WM_LBUTTONDOWN:
3270 case WM_RBUTTONDOWN:
3271 if (w32_num_mouse_buttons > 2)
3272 goto handle_plain_button;
3275 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3276 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3278 if (button_state & this)
3279 return 0;
3281 if (button_state == 0)
3282 SetCapture (hwnd);
3284 button_state |= this;
3286 if (button_state & other)
3288 if (mouse_button_timer)
3290 KillTimer (hwnd, mouse_button_timer);
3291 mouse_button_timer = 0;
3293 /* Generate middle mouse event instead. */
3294 msg = WM_MBUTTONDOWN;
3295 button_state |= MMOUSE;
3297 else if (button_state & MMOUSE)
3299 /* Ignore button event if we've already generated a
3300 middle mouse down event. This happens if the
3301 user releases and press one of the two buttons
3302 after we've faked a middle mouse event. */
3303 return 0;
3305 else
3307 /* Flush out saved message. */
3308 post_msg (&saved_mouse_button_msg);
3310 wmsg.dwModifiers = w32_get_modifiers ();
3311 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3312 signal_user_input ();
3314 /* Clear message buffer. */
3315 saved_mouse_button_msg.msg.hwnd = 0;
3317 else
3319 /* Hold onto message for now. */
3320 mouse_button_timer =
3321 SetTimer (hwnd, MOUSE_BUTTON_ID,
3322 w32_mouse_button_tolerance, NULL);
3323 saved_mouse_button_msg.msg.hwnd = hwnd;
3324 saved_mouse_button_msg.msg.message = msg;
3325 saved_mouse_button_msg.msg.wParam = wParam;
3326 saved_mouse_button_msg.msg.lParam = lParam;
3327 saved_mouse_button_msg.msg.time = GetMessageTime ();
3328 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3331 return 0;
3333 case WM_LBUTTONUP:
3334 case WM_RBUTTONUP:
3335 if (w32_num_mouse_buttons > 2)
3336 goto handle_plain_button;
3339 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3340 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3342 if ((button_state & this) == 0)
3343 return 0;
3345 button_state &= ~this;
3347 if (button_state & MMOUSE)
3349 /* Only generate event when second button is released. */
3350 if ((button_state & other) == 0)
3352 msg = WM_MBUTTONUP;
3353 button_state &= ~MMOUSE;
3355 if (button_state) emacs_abort ();
3357 else
3358 return 0;
3360 else
3362 /* Flush out saved message if necessary. */
3363 if (saved_mouse_button_msg.msg.hwnd)
3365 post_msg (&saved_mouse_button_msg);
3368 wmsg.dwModifiers = w32_get_modifiers ();
3369 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3370 signal_user_input ();
3372 /* Always clear message buffer and cancel timer. */
3373 saved_mouse_button_msg.msg.hwnd = 0;
3374 KillTimer (hwnd, mouse_button_timer);
3375 mouse_button_timer = 0;
3377 if (button_state == 0)
3378 ReleaseCapture ();
3380 return 0;
3382 case WM_XBUTTONDOWN:
3383 case WM_XBUTTONUP:
3384 if (w32_pass_extra_mouse_buttons_to_system)
3385 goto dflt;
3386 /* else fall through and process them. */
3387 case WM_MBUTTONDOWN:
3388 case WM_MBUTTONUP:
3389 handle_plain_button:
3391 BOOL up;
3392 int button;
3394 /* Ignore middle and extra buttons as long as the menu is active. */
3395 f = x_window_to_frame (dpyinfo, hwnd);
3396 if (f && f->output_data.w32->menubar_active)
3397 return 0;
3399 if (parse_button (msg, HIWORD (wParam), &button, &up))
3401 if (up) ReleaseCapture ();
3402 else SetCapture (hwnd);
3403 button = (button == 0) ? LMOUSE :
3404 ((button == 1) ? MMOUSE : RMOUSE);
3405 if (up)
3406 button_state &= ~button;
3407 else
3408 button_state |= button;
3412 wmsg.dwModifiers = w32_get_modifiers ();
3413 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3414 signal_user_input ();
3416 /* Need to return true for XBUTTON messages, false for others,
3417 to indicate that we processed the message. */
3418 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3420 case WM_MOUSEMOVE:
3421 /* Ignore mouse movements as long as the menu is active. These
3422 movements are processed by the window manager anyway, and
3423 it's wrong to handle them as if they happened on the
3424 underlying frame. */
3425 f = x_window_to_frame (dpyinfo, hwnd);
3426 if (f && f->output_data.w32->menubar_active)
3427 return 0;
3429 /* If the mouse has just moved into the frame, start tracking
3430 it, so we will be notified when it leaves the frame. Mouse
3431 tracking only works under W98 and NT4 and later. On earlier
3432 versions, there is no way of telling when the mouse leaves the
3433 frame, so we just have to put up with help-echo and mouse
3434 highlighting remaining while the frame is not active. */
3435 if (track_mouse_event_fn && !track_mouse_window
3436 /* If the menu bar is active, turning on tracking of mouse
3437 movement events might send these events to the tooltip
3438 frame, if the user happens to move the mouse pointer over
3439 the tooltip. But since we don't process events for
3440 tooltip frames, this causes Windows to present a
3441 hourglass cursor, which is ugly and unexpected. So don't
3442 enable tracking mouse events in this case; they will be
3443 restarted when the menu pops down. (Confusingly, the
3444 menubar_active member of f->output_data.w32, tested
3445 above, is only set when a menu was popped up _not_ from
3446 the frame's menu bar, but via x-popup-menu.) */
3447 && !menubar_in_use)
3449 TRACKMOUSEEVENT tme;
3450 tme.cbSize = sizeof (tme);
3451 tme.dwFlags = TME_LEAVE;
3452 tme.hwndTrack = hwnd;
3454 track_mouse_event_fn (&tme);
3455 track_mouse_window = hwnd;
3457 case WM_VSCROLL:
3458 if (w32_mouse_move_interval <= 0
3459 || (msg == WM_MOUSEMOVE && button_state == 0))
3461 wmsg.dwModifiers = w32_get_modifiers ();
3462 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3463 return 0;
3466 /* Hang onto mouse move and scroll messages for a bit, to avoid
3467 sending such events to Emacs faster than it can process them.
3468 If we get more events before the timer from the first message
3469 expires, we just replace the first message. */
3471 if (saved_mouse_move_msg.msg.hwnd == 0)
3472 mouse_move_timer =
3473 SetTimer (hwnd, MOUSE_MOVE_ID,
3474 w32_mouse_move_interval, NULL);
3476 /* Hold onto message for now. */
3477 saved_mouse_move_msg.msg.hwnd = hwnd;
3478 saved_mouse_move_msg.msg.message = msg;
3479 saved_mouse_move_msg.msg.wParam = wParam;
3480 saved_mouse_move_msg.msg.lParam = lParam;
3481 saved_mouse_move_msg.msg.time = GetMessageTime ();
3482 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3484 return 0;
3486 case WM_MOUSEWHEEL:
3487 case WM_DROPFILES:
3488 wmsg.dwModifiers = w32_get_modifiers ();
3489 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3490 signal_user_input ();
3491 return 0;
3493 case WM_APPCOMMAND:
3494 if (w32_pass_multimedia_buttons_to_system)
3495 goto dflt;
3496 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3497 case WM_MOUSEHWHEEL:
3498 wmsg.dwModifiers = w32_get_modifiers ();
3499 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3500 signal_user_input ();
3501 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3502 handled, to prevent the system trying to handle it by faking
3503 scroll bar events. */
3504 return 1;
3506 case WM_TIMER:
3507 /* Flush out saved messages if necessary. */
3508 if (wParam == mouse_button_timer)
3510 if (saved_mouse_button_msg.msg.hwnd)
3512 post_msg (&saved_mouse_button_msg);
3513 signal_user_input ();
3514 saved_mouse_button_msg.msg.hwnd = 0;
3516 KillTimer (hwnd, mouse_button_timer);
3517 mouse_button_timer = 0;
3519 else if (wParam == mouse_move_timer)
3521 if (saved_mouse_move_msg.msg.hwnd)
3523 post_msg (&saved_mouse_move_msg);
3524 saved_mouse_move_msg.msg.hwnd = 0;
3526 KillTimer (hwnd, mouse_move_timer);
3527 mouse_move_timer = 0;
3529 else if (wParam == menu_free_timer)
3531 KillTimer (hwnd, menu_free_timer);
3532 menu_free_timer = 0;
3533 f = x_window_to_frame (dpyinfo, hwnd);
3534 /* If a popup menu is active, don't wipe its strings. */
3535 if (menubar_in_use
3536 && current_popup_menu == NULL)
3538 /* Free memory used by owner-drawn and help-echo strings. */
3539 w32_free_menu_strings (hwnd);
3540 if (f)
3541 f->output_data.w32->menubar_active = 0;
3542 menubar_in_use = 0;
3545 return 0;
3547 case WM_NCACTIVATE:
3548 /* Windows doesn't send us focus messages when putting up and
3549 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3550 The only indication we get that something happened is receiving
3551 this message afterwards. So this is a good time to reset our
3552 keyboard modifiers' state. */
3553 reset_modifiers ();
3554 goto dflt;
3556 case WM_INITMENU:
3557 button_state = 0;
3558 ReleaseCapture ();
3559 /* We must ensure menu bar is fully constructed and up to date
3560 before allowing user interaction with it. To achieve this
3561 we send this message to the lisp thread and wait for a
3562 reply (whose value is not actually needed) to indicate that
3563 the menu bar is now ready for use, so we can now return.
3565 To remain responsive in the meantime, we enter a nested message
3566 loop that can process all other messages.
3568 However, we skip all this if the message results from calling
3569 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3570 thread a message because it is blocked on us at this point. We
3571 set menubar_active before calling TrackPopupMenu to indicate
3572 this (there is no possibility of confusion with real menubar
3573 being active). */
3575 f = x_window_to_frame (dpyinfo, hwnd);
3576 if (f
3577 && (f->output_data.w32->menubar_active
3578 /* We can receive this message even in the absence of a
3579 menubar (ie. when the system menu is activated) - in this
3580 case we do NOT want to forward the message, otherwise it
3581 will cause the menubar to suddenly appear when the user
3582 had requested it to be turned off! */
3583 || f->output_data.w32->menubar_widget == NULL))
3584 return 0;
3587 deferred_msg msg_buf;
3589 /* Detect if message has already been deferred; in this case
3590 we cannot return any sensible value to ignore this. */
3591 if (find_deferred_msg (hwnd, msg) != NULL)
3592 emacs_abort ();
3594 menubar_in_use = 1;
3596 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3599 case WM_EXITMENULOOP:
3600 f = x_window_to_frame (dpyinfo, hwnd);
3602 /* If a menu is still active, check again after a short delay,
3603 since Windows often (always?) sends the WM_EXITMENULOOP
3604 before the corresponding WM_COMMAND message.
3605 Don't do this if a popup menu is active, since it is only
3606 menubar menus that require cleaning up in this way.
3608 if (f && menubar_in_use && current_popup_menu == NULL)
3609 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3611 /* If hourglass cursor should be displayed, display it now. */
3612 if (f && f->output_data.w32->hourglass_p)
3613 SetCursor (f->output_data.w32->hourglass_cursor);
3615 goto dflt;
3617 case WM_MENUSELECT:
3618 /* Direct handling of help_echo in menus. Should be safe now
3619 that we generate the help_echo by placing a help event in the
3620 keyboard buffer. */
3622 HMENU menu = (HMENU) lParam;
3623 UINT menu_item = (UINT) LOWORD (wParam);
3624 UINT flags = (UINT) HIWORD (wParam);
3626 w32_menu_display_help (hwnd, menu, menu_item, flags);
3628 return 0;
3630 case WM_MEASUREITEM:
3631 f = x_window_to_frame (dpyinfo, hwnd);
3632 if (f)
3634 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3636 if (pMis->CtlType == ODT_MENU)
3638 /* Work out dimensions for popup menu titles. */
3639 char * title = (char *) pMis->itemData;
3640 HDC hdc = GetDC (hwnd);
3641 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3642 LOGFONT menu_logfont;
3643 HFONT old_font;
3644 SIZE size;
3646 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3647 menu_logfont.lfWeight = FW_BOLD;
3648 menu_font = CreateFontIndirect (&menu_logfont);
3649 old_font = SelectObject (hdc, menu_font);
3651 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3652 if (title)
3654 if (unicode_append_menu)
3655 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3656 wcslen ((WCHAR *) title),
3657 &size);
3658 else
3659 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3661 pMis->itemWidth = size.cx;
3662 if (pMis->itemHeight < size.cy)
3663 pMis->itemHeight = size.cy;
3665 else
3666 pMis->itemWidth = 0;
3668 SelectObject (hdc, old_font);
3669 DeleteObject (menu_font);
3670 ReleaseDC (hwnd, hdc);
3671 return TRUE;
3674 return 0;
3676 case WM_DRAWITEM:
3677 f = x_window_to_frame (dpyinfo, hwnd);
3678 if (f)
3680 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3682 if (pDis->CtlType == ODT_MENU)
3684 /* Draw popup menu title. */
3685 char * title = (char *) pDis->itemData;
3686 if (title)
3688 HDC hdc = pDis->hDC;
3689 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3690 LOGFONT menu_logfont;
3691 HFONT old_font;
3693 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3694 menu_logfont.lfWeight = FW_BOLD;
3695 menu_font = CreateFontIndirect (&menu_logfont);
3696 old_font = SelectObject (hdc, menu_font);
3698 /* Always draw title as if not selected. */
3699 if (unicode_append_menu)
3700 ExtTextOutW (hdc,
3701 pDis->rcItem.left
3702 + GetSystemMetrics (SM_CXMENUCHECK),
3703 pDis->rcItem.top,
3704 ETO_OPAQUE, &pDis->rcItem,
3705 (WCHAR *) title,
3706 wcslen ((WCHAR *) title), NULL);
3707 else
3708 ExtTextOut (hdc,
3709 pDis->rcItem.left
3710 + GetSystemMetrics (SM_CXMENUCHECK),
3711 pDis->rcItem.top,
3712 ETO_OPAQUE, &pDis->rcItem,
3713 title, strlen (title), NULL);
3715 SelectObject (hdc, old_font);
3716 DeleteObject (menu_font);
3718 return TRUE;
3721 return 0;
3723 #if 0
3724 /* Still not right - can't distinguish between clicks in the
3725 client area of the frame from clicks forwarded from the scroll
3726 bars - may have to hook WM_NCHITTEST to remember the mouse
3727 position and then check if it is in the client area ourselves. */
3728 case WM_MOUSEACTIVATE:
3729 /* Discard the mouse click that activates a frame, allowing the
3730 user to click anywhere without changing point (or worse!).
3731 Don't eat mouse clicks on scrollbars though!! */
3732 if (LOWORD (lParam) == HTCLIENT )
3733 return MA_ACTIVATEANDEAT;
3734 goto dflt;
3735 #endif
3737 case WM_MOUSELEAVE:
3738 /* No longer tracking mouse. */
3739 track_mouse_window = NULL;
3741 case WM_ACTIVATEAPP:
3742 case WM_ACTIVATE:
3743 case WM_WINDOWPOSCHANGED:
3744 case WM_SHOWWINDOW:
3745 /* Inform lisp thread that a frame might have just been obscured
3746 or exposed, so should recheck visibility of all frames. */
3747 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3748 goto dflt;
3750 case WM_SETFOCUS:
3751 dpyinfo->faked_key = 0;
3752 reset_modifiers ();
3753 register_hot_keys (hwnd);
3754 goto command;
3755 case WM_KILLFOCUS:
3756 unregister_hot_keys (hwnd);
3757 button_state = 0;
3758 ReleaseCapture ();
3759 /* Relinquish the system caret. */
3760 if (w32_system_caret_hwnd)
3762 w32_visible_system_caret_hwnd = NULL;
3763 w32_system_caret_hwnd = NULL;
3764 DestroyCaret ();
3766 goto command;
3767 case WM_COMMAND:
3768 menubar_in_use = 0;
3769 f = x_window_to_frame (dpyinfo, hwnd);
3770 if (f && HIWORD (wParam) == 0)
3772 if (menu_free_timer)
3774 KillTimer (hwnd, menu_free_timer);
3775 menu_free_timer = 0;
3778 case WM_MOVE:
3779 case WM_SIZE:
3780 command:
3781 wmsg.dwModifiers = w32_get_modifiers ();
3782 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3783 goto dflt;
3785 case WM_DESTROY:
3786 CoUninitialize ();
3787 return 0;
3789 case WM_CLOSE:
3790 wmsg.dwModifiers = w32_get_modifiers ();
3791 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3792 return 0;
3794 case WM_WINDOWPOSCHANGING:
3795 /* Don't restrict the sizing of tip frames. */
3796 if (frame_resize_pixelwise || hwnd == tip_window)
3797 return 0;
3799 /* Don't restrict the sizing of fullscreened frames, allowing them to be
3800 flush with the sides of the screen. */
3801 f = x_window_to_frame (dpyinfo, hwnd);
3802 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
3803 return 0;
3806 WINDOWPLACEMENT wp;
3807 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3809 wp.length = sizeof (WINDOWPLACEMENT);
3810 GetWindowPlacement (hwnd, &wp);
3812 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
3814 RECT rect;
3815 int wdiff;
3816 int hdiff;
3817 DWORD font_width;
3818 DWORD line_height;
3819 DWORD internal_border;
3820 DWORD scrollbar_extra;
3821 RECT wr;
3823 wp.length = sizeof (wp);
3824 GetWindowRect (hwnd, &wr);
3826 enter_crit ();
3828 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3829 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3830 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3831 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3833 leave_crit ();
3835 memset (&rect, 0, sizeof (rect));
3836 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3837 GetMenu (hwnd) != NULL);
3839 /* Force width and height of client area to be exact
3840 multiples of the character cell dimensions. */
3841 wdiff = (lppos->cx - (rect.right - rect.left)
3842 - 2 * internal_border - scrollbar_extra)
3843 % font_width;
3844 hdiff = (lppos->cy - (rect.bottom - rect.top)
3845 - 2 * internal_border)
3846 % line_height;
3848 if (wdiff || hdiff)
3850 /* For right/bottom sizing we can just fix the sizes.
3851 However for top/left sizing we will need to fix the X
3852 and Y positions as well. */
3854 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3855 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3857 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3858 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3860 if (wp.showCmd != SW_SHOWMAXIMIZED
3861 && (lppos->flags & SWP_NOMOVE) == 0)
3863 if (lppos->x != wr.left || lppos->y != wr.top)
3865 lppos->x += wdiff;
3866 lppos->y += hdiff;
3868 else
3870 lppos->flags |= SWP_NOMOVE;
3874 return 0;
3879 goto dflt;
3881 case WM_GETMINMAXINFO:
3882 /* Hack to allow resizing the Emacs frame above the screen size.
3883 Note that Windows 9x limits coordinates to 16-bits. */
3884 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3885 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3886 return 0;
3888 case WM_SETCURSOR:
3889 if (LOWORD (lParam) == HTCLIENT)
3891 f = x_window_to_frame (dpyinfo, hwnd);
3892 if (f && f->output_data.w32->hourglass_p
3893 && !menubar_in_use && !current_popup_menu)
3894 SetCursor (f->output_data.w32->hourglass_cursor);
3895 else if (f)
3896 SetCursor (f->output_data.w32->current_cursor);
3897 return 0;
3899 goto dflt;
3901 case WM_EMACS_SETCURSOR:
3903 Cursor cursor = (Cursor) wParam;
3904 f = x_window_to_frame (dpyinfo, hwnd);
3905 if (f && cursor)
3907 f->output_data.w32->current_cursor = cursor;
3908 if (!f->output_data.w32->hourglass_p)
3909 SetCursor (cursor);
3911 return 0;
3914 case WM_EMACS_CREATESCROLLBAR:
3915 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3916 (struct scroll_bar *) lParam);
3918 case WM_EMACS_SHOWWINDOW:
3919 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3921 case WM_EMACS_BRINGTOTOP:
3922 case WM_EMACS_SETFOREGROUND:
3924 HWND foreground_window;
3925 DWORD foreground_thread, retval;
3927 /* On NT 5.0, and apparently Windows 98, it is necessary to
3928 attach to the thread that currently has focus in order to
3929 pull the focus away from it. */
3930 foreground_window = GetForegroundWindow ();
3931 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3932 if (!foreground_window
3933 || foreground_thread == GetCurrentThreadId ()
3934 || !AttachThreadInput (GetCurrentThreadId (),
3935 foreground_thread, TRUE))
3936 foreground_thread = 0;
3938 retval = SetForegroundWindow ((HWND) wParam);
3939 if (msg == WM_EMACS_BRINGTOTOP)
3940 retval = BringWindowToTop ((HWND) wParam);
3942 /* Detach from the previous foreground thread. */
3943 if (foreground_thread)
3944 AttachThreadInput (GetCurrentThreadId (),
3945 foreground_thread, FALSE);
3947 return retval;
3950 case WM_EMACS_SETWINDOWPOS:
3952 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3953 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3954 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3957 case WM_EMACS_DESTROYWINDOW:
3958 DragAcceptFiles ((HWND) wParam, FALSE);
3959 return DestroyWindow ((HWND) wParam);
3961 case WM_EMACS_HIDE_CARET:
3962 return HideCaret (hwnd);
3964 case WM_EMACS_SHOW_CARET:
3965 return ShowCaret (hwnd);
3967 case WM_EMACS_DESTROY_CARET:
3968 w32_system_caret_hwnd = NULL;
3969 w32_visible_system_caret_hwnd = NULL;
3970 return DestroyCaret ();
3972 case WM_EMACS_TRACK_CARET:
3973 /* If there is currently no system caret, create one. */
3974 if (w32_system_caret_hwnd == NULL)
3976 /* Use the default caret width, and avoid changing it
3977 unnecessarily, as it confuses screen reader software. */
3978 w32_system_caret_hwnd = hwnd;
3979 CreateCaret (hwnd, NULL, 0,
3980 w32_system_caret_height);
3983 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3984 return 0;
3985 /* Ensure visible caret gets turned on when requested. */
3986 else if (w32_use_visible_system_caret
3987 && w32_visible_system_caret_hwnd != hwnd)
3989 w32_visible_system_caret_hwnd = hwnd;
3990 return ShowCaret (hwnd);
3992 /* Ensure visible caret gets turned off when requested. */
3993 else if (!w32_use_visible_system_caret
3994 && w32_visible_system_caret_hwnd)
3996 w32_visible_system_caret_hwnd = NULL;
3997 return HideCaret (hwnd);
3999 else
4000 return 1;
4002 case WM_EMACS_TRACKPOPUPMENU:
4004 UINT flags;
4005 POINT *pos;
4006 int retval;
4007 pos = (POINT *)lParam;
4008 flags = TPM_CENTERALIGN;
4009 if (button_state & LMOUSE)
4010 flags |= TPM_LEFTBUTTON;
4011 else if (button_state & RMOUSE)
4012 flags |= TPM_RIGHTBUTTON;
4014 /* Remember we did a SetCapture on the initial mouse down event,
4015 so for safety, we make sure the capture is canceled now. */
4016 ReleaseCapture ();
4017 button_state = 0;
4019 /* Use menubar_active to indicate that WM_INITMENU is from
4020 TrackPopupMenu below, and should be ignored. */
4021 f = x_window_to_frame (dpyinfo, hwnd);
4022 if (f)
4023 f->output_data.w32->menubar_active = 1;
4025 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4026 0, hwnd, NULL))
4028 MSG amsg;
4029 /* Eat any mouse messages during popupmenu */
4030 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4031 PM_REMOVE));
4032 /* Get the menu selection, if any */
4033 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4035 retval = LOWORD (amsg.wParam);
4037 else
4039 retval = 0;
4042 else
4044 retval = -1;
4047 return retval;
4049 case WM_EMACS_FILENOTIFY:
4050 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4051 return 1;
4053 default:
4054 /* Check for messages registered at runtime. */
4055 if (msg == msh_mousewheel)
4057 wmsg.dwModifiers = w32_get_modifiers ();
4058 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4059 signal_user_input ();
4060 return 0;
4063 dflt:
4064 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4067 /* The most common default return code for handled messages is 0. */
4068 return 0;
4071 static void
4072 my_create_window (struct frame * f)
4074 MSG msg;
4076 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4077 emacs_abort ();
4078 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4082 /* Create a tooltip window. Unlike my_create_window, we do not do this
4083 indirectly via the Window thread, as we do not need to process Window
4084 messages for the tooltip. Creating tooltips indirectly also creates
4085 deadlocks when tooltips are created for menu items. */
4086 static void
4087 my_create_tip_window (struct frame *f)
4089 RECT rect;
4091 rect.left = rect.top = 0;
4092 rect.right = FRAME_PIXEL_WIDTH (f);
4093 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4095 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4096 FRAME_EXTERNAL_MENU_BAR (f));
4098 tip_window = FRAME_W32_WINDOW (f)
4099 = CreateWindow (EMACS_CLASS,
4100 f->namebuf,
4101 f->output_data.w32->dwStyle,
4102 f->left_pos,
4103 f->top_pos,
4104 rect.right - rect.left,
4105 rect.bottom - rect.top,
4106 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4107 NULL,
4108 hinst,
4109 NULL);
4111 if (tip_window)
4113 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4114 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4115 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4116 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4118 /* Tip frames have no scrollbars. */
4119 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
4121 /* Do this to discard the default setting specified by our parent. */
4122 ShowWindow (tip_window, SW_HIDE);
4127 /* Create and set up the w32 window for frame F. */
4129 static void
4130 w32_window (struct frame *f, long window_prompting, int minibuffer_only)
4132 block_input ();
4134 /* Use the resource name as the top-level window name
4135 for looking up resources. Make a non-Lisp copy
4136 for the window manager, so GC relocation won't bother it.
4138 Elsewhere we specify the window name for the window manager. */
4139 f->namebuf = xstrdup (SSDATA (Vx_resource_name));
4141 my_create_window (f);
4143 validate_x_resource_name ();
4145 /* x_set_name normally ignores requests to set the name if the
4146 requested name is the same as the current name. This is the one
4147 place where that assumption isn't correct; f->name is set, but
4148 the server hasn't been told. */
4150 Lisp_Object name;
4151 int explicit = f->explicit_name;
4153 f->explicit_name = 0;
4154 name = f->name;
4155 fset_name (f, Qnil);
4156 x_set_name (f, name, explicit);
4159 unblock_input ();
4161 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4162 initialize_frame_menubar (f);
4164 if (FRAME_W32_WINDOW (f) == 0)
4165 error ("Unable to create window");
4168 /* Handle the icon stuff for this window. Perhaps later we might
4169 want an x_set_icon_position which can be called interactively as
4170 well. */
4172 static void
4173 x_icon (struct frame *f, Lisp_Object parms)
4175 Lisp_Object icon_x, icon_y;
4176 struct w32_display_info *dpyinfo = &one_w32_display_info;
4178 /* Set the position of the icon. Note that Windows 95 groups all
4179 icons in the tray. */
4180 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4181 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4182 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4184 CHECK_NUMBER (icon_x);
4185 CHECK_NUMBER (icon_y);
4187 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4188 error ("Both left and top icon corners of icon must be specified");
4190 block_input ();
4192 #if 0 /* TODO */
4193 /* Start up iconic or window? */
4194 x_wm_set_window_state
4195 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4196 ? IconicState
4197 : NormalState));
4199 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4200 ? f->icon_name
4201 : f->name)));
4202 #endif
4204 unblock_input ();
4208 static void
4209 x_make_gc (struct frame *f)
4211 XGCValues gc_values;
4213 block_input ();
4215 /* Create the GC's of this frame.
4216 Note that many default values are used. */
4218 /* Normal video */
4219 gc_values.font = FRAME_FONT (f);
4221 /* Cursor has cursor-color background, background-color foreground. */
4222 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4223 gc_values.background = f->output_data.w32->cursor_pixel;
4224 f->output_data.w32->cursor_gc
4225 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4226 (GCFont | GCForeground | GCBackground),
4227 &gc_values);
4229 /* Reliefs. */
4230 f->output_data.w32->white_relief.gc = 0;
4231 f->output_data.w32->black_relief.gc = 0;
4233 unblock_input ();
4237 /* Handler for signals raised during x_create_frame and
4238 x_create_tip_frame. FRAME is the frame which is partially
4239 constructed. */
4241 static Lisp_Object
4242 unwind_create_frame (Lisp_Object frame)
4244 struct frame *f = XFRAME (frame);
4246 /* If frame is ``official'', nothing to do. */
4247 if (NILP (Fmemq (frame, Vframe_list)))
4249 #ifdef GLYPH_DEBUG
4250 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4251 #endif
4253 x_free_frame_resources (f);
4254 free_glyphs (f);
4256 #ifdef GLYPH_DEBUG
4257 /* Check that reference counts are indeed correct. */
4258 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4259 eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
4260 #endif
4261 return Qt;
4264 return Qnil;
4267 static void
4268 do_unwind_create_frame (Lisp_Object frame)
4270 unwind_create_frame (frame);
4273 static void
4274 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4276 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4277 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4278 RES_TYPE_STRING);
4279 Lisp_Object font;
4280 if (EQ (font_param, Qunbound))
4281 font_param = Qnil;
4282 font = !NILP (font_param) ? font_param
4283 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4285 if (!STRINGP (font))
4287 int i;
4288 static char *names[]
4289 = { "Courier New-10",
4290 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4291 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4292 "Fixedsys",
4293 NULL };
4295 for (i = 0; names[i]; i++)
4297 font = font_open_by_name (f, build_unibyte_string (names[i]));
4298 if (! NILP (font))
4299 break;
4301 if (NILP (font))
4302 error ("No suitable font was found");
4304 else if (!NILP (font_param))
4306 /* Remember the explicit font parameter, so we can re-apply it after
4307 we've applied the `default' face settings. */
4308 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4310 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4313 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4314 1, 1, 0,
4315 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4316 Return an Emacs frame object.
4317 PARAMETERS is an alist of frame parameters.
4318 If the parameters specify that the frame should not have a minibuffer,
4319 and do not specify a specific minibuffer window to use,
4320 then `default-minibuffer-frame' must be a frame whose minibuffer can
4321 be shared by the new frame.
4323 This function is an internal primitive--use `make-frame' instead. */)
4324 (Lisp_Object parameters)
4326 struct frame *f;
4327 Lisp_Object frame, tem;
4328 Lisp_Object name;
4329 int minibuffer_only = 0;
4330 long window_prompting = 0;
4331 int width, height;
4332 ptrdiff_t count = SPECPDL_INDEX ();
4333 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4334 Lisp_Object display;
4335 struct w32_display_info *dpyinfo = NULL;
4336 Lisp_Object parent;
4337 struct kboard *kb;
4339 /* Make copy of frame parameters because the original is in pure
4340 storage now. */
4341 parameters = Fcopy_alist (parameters);
4343 /* Use this general default value to start with
4344 until we know if this frame has a specified name. */
4345 Vx_resource_name = Vinvocation_name;
4347 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4348 if (EQ (display, Qunbound))
4349 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4350 if (EQ (display, Qunbound))
4351 display = Qnil;
4352 dpyinfo = check_x_display_info (display);
4353 kb = dpyinfo->terminal->kboard;
4355 if (!dpyinfo->terminal->name)
4356 error ("Terminal is not live, can't create new frames on it");
4358 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4359 if (!STRINGP (name)
4360 && ! EQ (name, Qunbound)
4361 && ! NILP (name))
4362 error ("Invalid frame name--not a string or nil");
4364 if (STRINGP (name))
4365 Vx_resource_name = name;
4367 /* See if parent window is specified. */
4368 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4369 if (EQ (parent, Qunbound))
4370 parent = Qnil;
4371 if (! NILP (parent))
4372 CHECK_NUMBER (parent);
4374 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4375 /* No need to protect DISPLAY because that's not used after passing
4376 it to make_frame_without_minibuffer. */
4377 frame = Qnil;
4378 GCPRO4 (parameters, parent, name, frame);
4379 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
4380 RES_TYPE_SYMBOL);
4381 if (EQ (tem, Qnone) || NILP (tem))
4382 f = make_frame_without_minibuffer (Qnil, kb, display);
4383 else if (EQ (tem, Qonly))
4385 f = make_minibuffer_frame ();
4386 minibuffer_only = 1;
4388 else if (WINDOWP (tem))
4389 f = make_frame_without_minibuffer (tem, kb, display);
4390 else
4391 f = make_frame (1);
4393 XSETFRAME (frame, f);
4395 /* By default, make scrollbars the system standard width. */
4396 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4398 f->terminal = dpyinfo->terminal;
4400 f->output_method = output_w32;
4401 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
4402 FRAME_FONTSET (f) = -1;
4404 fset_icon_name
4405 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
4406 RES_TYPE_STRING));
4407 if (! STRINGP (f->icon_name))
4408 fset_icon_name (f, Qnil);
4410 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
4412 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
4413 record_unwind_protect (do_unwind_create_frame, frame);
4414 #ifdef GLYPH_DEBUG
4415 image_cache_refcount =
4416 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
4417 dpyinfo_refcount = dpyinfo->reference_count;
4418 #endif /* GLYPH_DEBUG */
4420 /* Specify the parent under which to make this window. */
4422 if (!NILP (parent))
4424 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4425 f->output_data.w32->explicit_parent = 1;
4427 else
4429 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4430 f->output_data.w32->explicit_parent = 0;
4433 /* Set the name; the functions to which we pass f expect the name to
4434 be set. */
4435 if (EQ (name, Qunbound) || NILP (name))
4437 fset_name (f, build_string (dpyinfo->w32_id_name));
4438 f->explicit_name = 0;
4440 else
4442 fset_name (f, name);
4443 f->explicit_name = 1;
4444 /* use the frame's title when getting resources for this frame. */
4445 specbind (Qx_resource_name, name);
4448 if (uniscribe_available)
4449 register_font_driver (&uniscribe_font_driver, f);
4450 register_font_driver (&w32font_driver, f);
4452 x_default_parameter (f, parameters, Qfont_backend, Qnil,
4453 "fontBackend", "FontBackend", RES_TYPE_STRING);
4454 /* Extract the window parameters from the supplied values
4455 that are needed to determine window geometry. */
4456 x_default_font_parameter (f, parameters);
4457 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4458 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4460 /* We recognize either internalBorderWidth or internalBorder
4461 (which is what xterm calls it). */
4462 if (NILP (Fassq (Qinternal_border_width, parameters)))
4464 Lisp_Object value;
4466 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
4467 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4468 if (! EQ (value, Qunbound))
4469 parameters = Fcons (Fcons (Qinternal_border_width, value),
4470 parameters);
4472 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4473 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4474 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4475 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
4476 NULL, NULL, RES_TYPE_NUMBER);
4477 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
4478 NULL, NULL, RES_TYPE_NUMBER);
4479 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4480 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4482 /* Also do the stuff which must be set before the window exists. */
4483 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4484 "foreground", "Foreground", RES_TYPE_STRING);
4485 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4486 "background", "Background", RES_TYPE_STRING);
4487 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4488 "pointerColor", "Foreground", RES_TYPE_STRING);
4489 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4490 "borderColor", "BorderColor", RES_TYPE_STRING);
4491 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4492 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4493 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4494 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4495 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4496 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4497 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4498 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4500 /* Init faces before x_default_parameter is called for scroll-bar
4501 parameters because that function calls x_set_scroll_bar_width,
4502 which calls change_frame_size, which calls Fset_window_buffer,
4503 which runs hooks, which call Fvertical_motion. At the end, we
4504 end up in init_iterator with a null face cache, which should not
4505 happen. */
4506 init_frame_faces (f);
4508 /* PXW: This is a duplicate from below. We have to do it here since
4509 otherwise x_set_tool_bar_lines will work with the character sizes
4510 installed by init_frame_faces while the frame's pixel size is still
4511 calculated from a character size of 1 and we subsequently hit the
4512 eassert (height >= 0) assertion in window_box_height. The
4513 non-pixelwise code apparently worked around this because it had one
4514 frame line vs one toolbar line which left us with a zero root
4515 window height which was obviously wrong as well ... */
4516 width = FRAME_TEXT_WIDTH (f);
4517 height = FRAME_TEXT_HEIGHT (f);
4518 FRAME_TEXT_HEIGHT (f) = 0;
4519 SET_FRAME_WIDTH (f, 0);
4520 change_frame_size (f, width, height, 1, 0, 0, 1);
4522 /* The X resources controlling the menu-bar and tool-bar are
4523 processed specially at startup, and reflected in the mode
4524 variables; ignore them here. */
4525 x_default_parameter (f, parameters, Qmenu_bar_lines,
4526 NILP (Vmenu_bar_mode)
4527 ? make_number (0) : make_number (1),
4528 NULL, NULL, RES_TYPE_NUMBER);
4529 x_default_parameter (f, parameters, Qtool_bar_lines,
4530 NILP (Vtool_bar_mode)
4531 ? make_number (0) : make_number (1),
4532 NULL, NULL, RES_TYPE_NUMBER);
4534 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4535 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4536 x_default_parameter (f, parameters, Qtitle, Qnil,
4537 "title", "Title", RES_TYPE_STRING);
4538 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4539 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4541 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4542 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4544 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4545 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4546 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4547 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4548 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4549 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4550 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
4552 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
4554 window_prompting = x_figure_window_size (f, parameters, 1);
4556 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4557 f->no_split = minibuffer_only || EQ (tem, Qt);
4559 w32_window (f, window_prompting, minibuffer_only);
4560 x_icon (f, parameters);
4562 x_make_gc (f);
4564 /* Now consider the frame official. */
4565 f->terminal->reference_count++;
4566 FRAME_DISPLAY_INFO (f)->reference_count++;
4567 Vframe_list = Fcons (frame, Vframe_list);
4569 /* We need to do this after creating the window, so that the
4570 icon-creation functions can say whose icon they're describing. */
4571 x_default_parameter (f, parameters, Qicon_type, Qnil,
4572 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4574 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4575 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4576 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4577 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4578 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4579 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4580 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4581 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4582 x_default_parameter (f, parameters, Qalpha, Qnil,
4583 "alpha", "Alpha", RES_TYPE_NUMBER);
4585 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4586 Change will not be effected unless different from the current
4587 FRAME_LINES (f). */
4588 width = FRAME_TEXT_WIDTH (f);
4589 height = FRAME_TEXT_HEIGHT (f);
4590 FRAME_TEXT_HEIGHT (f) = 0;
4591 SET_FRAME_WIDTH (f, 0);
4592 change_frame_size (f, width, height, 1, 0, 0, 1);
4594 /* Tell the server what size and position, etc, we want, and how
4595 badly we want them. This should be done after we have the menu
4596 bar so that its size can be taken into account. */
4597 block_input ();
4598 x_wm_set_size_hint (f, window_prompting, 0);
4599 unblock_input ();
4601 /* Make the window appear on the frame and enable display, unless
4602 the caller says not to. However, with explicit parent, Emacs
4603 cannot control visibility, so don't try. */
4604 if (! f->output_data.w32->explicit_parent)
4606 Lisp_Object visibility;
4608 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4609 if (EQ (visibility, Qunbound))
4610 visibility = Qt;
4612 if (EQ (visibility, Qicon))
4613 x_iconify_frame (f);
4614 else if (! NILP (visibility))
4615 x_make_frame_visible (f);
4616 else
4617 /* Must have been Qnil. */
4621 /* Initialize `default-minibuffer-frame' in case this is the first
4622 frame on this terminal. */
4623 if (FRAME_HAS_MINIBUF_P (f)
4624 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
4625 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
4626 kset_default_minibuffer_frame (kb, frame);
4628 /* All remaining specified parameters, which have not been "used"
4629 by x_get_arg and friends, now go in the misc. alist of the frame. */
4630 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4631 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4632 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
4634 UNGCPRO;
4636 /* Make sure windows on this frame appear in calls to next-window
4637 and similar functions. */
4638 Vwindow_list = Qnil;
4640 return unbind_to (count, frame);
4643 /* FRAME is used only to get a handle on the X display. We don't pass the
4644 display info directly because we're called from frame.c, which doesn't
4645 know about that structure. */
4646 Lisp_Object
4647 x_get_focus_frame (struct frame *frame)
4649 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
4650 Lisp_Object xfocus;
4651 if (! dpyinfo->w32_focus_frame)
4652 return Qnil;
4654 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4655 return xfocus;
4658 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4659 doc: /* Internal function called by `color-defined-p', which see.
4660 \(Note that the Nextstep version of this function ignores FRAME.) */)
4661 (Lisp_Object color, Lisp_Object frame)
4663 XColor foo;
4664 struct frame *f = decode_window_system_frame (frame);
4666 CHECK_STRING (color);
4668 if (w32_defined_color (f, SDATA (color), &foo, 0))
4669 return Qt;
4670 else
4671 return Qnil;
4674 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
4675 doc: /* Internal function called by `color-values', which see. */)
4676 (Lisp_Object color, Lisp_Object frame)
4678 XColor foo;
4679 struct frame *f = decode_window_system_frame (frame);
4681 CHECK_STRING (color);
4683 if (w32_defined_color (f, SDATA (color), &foo, 0))
4684 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4685 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4686 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
4687 else
4688 return Qnil;
4691 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
4692 doc: /* Internal function called by `display-color-p', which see. */)
4693 (Lisp_Object display)
4695 struct w32_display_info *dpyinfo = check_x_display_info (display);
4697 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4698 return Qnil;
4700 return Qt;
4703 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4704 Sx_display_grayscale_p, 0, 1, 0,
4705 doc: /* Return t if DISPLAY supports shades of gray.
4706 Note that color displays do support shades of gray.
4707 The optional argument DISPLAY specifies which display to ask about.
4708 DISPLAY should be either a frame or a display name (a string).
4709 If omitted or nil, that stands for the selected frame's display. */)
4710 (Lisp_Object display)
4712 struct w32_display_info *dpyinfo = check_x_display_info (display);
4714 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4715 return Qnil;
4717 return Qt;
4720 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4721 Sx_display_pixel_width, 0, 1, 0,
4722 doc: /* Return the width in pixels of DISPLAY.
4723 The optional argument DISPLAY specifies which display to ask about.
4724 DISPLAY should be either a frame or a display name (a string).
4725 If omitted or nil, that stands for the selected frame's display.
4727 On \"multi-monitor\" setups this refers to the pixel width for all
4728 physical monitors associated with DISPLAY. To get information for
4729 each physical monitor, use `display-monitor-attributes-list'. */)
4730 (Lisp_Object display)
4732 struct w32_display_info *dpyinfo = check_x_display_info (display);
4734 return make_number (x_display_pixel_width (dpyinfo));
4737 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
4738 Sx_display_pixel_height, 0, 1, 0,
4739 doc: /* Return the height in pixels of DISPLAY.
4740 The optional argument DISPLAY specifies which display to ask about.
4741 DISPLAY should be either a frame or a display name (a string).
4742 If omitted or nil, that stands for the selected frame's display.
4744 On \"multi-monitor\" setups this refers to the pixel height for all
4745 physical monitors associated with DISPLAY. To get information for
4746 each physical monitor, use `display-monitor-attributes-list'. */)
4747 (Lisp_Object display)
4749 struct w32_display_info *dpyinfo = check_x_display_info (display);
4751 return make_number (x_display_pixel_height (dpyinfo));
4754 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
4755 0, 1, 0,
4756 doc: /* Return the number of bitplanes of DISPLAY.
4757 The optional argument DISPLAY specifies which display to ask about.
4758 DISPLAY should be either a frame or a display name (a string).
4759 If omitted or nil, that stands for the selected frame's display. */)
4760 (Lisp_Object display)
4762 struct w32_display_info *dpyinfo = check_x_display_info (display);
4764 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4767 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
4768 0, 1, 0,
4769 doc: /* Return the number of color cells of DISPLAY.
4770 The optional argument DISPLAY specifies which display to ask about.
4771 DISPLAY should be either a frame or a display name (a string).
4772 If omitted or nil, that stands for the selected frame's display. */)
4773 (Lisp_Object display)
4775 struct w32_display_info *dpyinfo = check_x_display_info (display);
4776 int cap;
4778 /* Don't use NCOLORS: it returns incorrect results under remote
4779 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4780 * overflow and because probably is more meaningful on Windows
4781 * anyway. */
4783 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
4784 return make_number (cap);
4787 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4788 Sx_server_max_request_size,
4789 0, 1, 0,
4790 doc: /* Return the maximum request size of the server of DISPLAY.
4791 The optional argument DISPLAY specifies which display to ask about.
4792 DISPLAY should be either a frame or a display name (a string).
4793 If omitted or nil, that stands for the selected frame's display. */)
4794 (Lisp_Object display)
4796 return make_number (1);
4799 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
4800 doc: /* Return the "vendor ID" string of the W32 system (Microsoft).
4801 The optional argument DISPLAY specifies which display to ask about.
4802 DISPLAY should be either a frame or a display name (a string).
4803 If omitted or nil, that stands for the selected frame's display. */)
4804 (Lisp_Object display)
4806 return build_string ("Microsoft Corp.");
4809 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
4810 doc: /* Return the version numbers of the server of DISPLAY.
4811 The value is a list of three integers: the major and minor
4812 version numbers of the X Protocol in use, and the distributor-specific
4813 release number. See also the function `x-server-vendor'.
4815 The optional argument DISPLAY specifies which display to ask about.
4816 DISPLAY should be either a frame or a display name (a string).
4817 If omitted or nil, that stands for the selected frame's display. */)
4818 (Lisp_Object display)
4820 return list3i (w32_major_version, w32_minor_version, w32_build_number);
4823 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
4824 doc: /* Return the number of screens on the server of DISPLAY.
4825 The optional argument DISPLAY specifies which display to ask about.
4826 DISPLAY should be either a frame or a display name (a string).
4827 If omitted or nil, that stands for the selected frame's display. */)
4828 (Lisp_Object display)
4830 return make_number (1);
4833 DEFUN ("x-display-mm-height", Fx_display_mm_height,
4834 Sx_display_mm_height, 0, 1, 0,
4835 doc: /* Return the height in millimeters of DISPLAY.
4836 The optional argument DISPLAY specifies which display to ask about.
4837 DISPLAY should be either a frame or a display name (a string).
4838 If omitted or nil, that stands for the selected frame's display.
4840 On \"multi-monitor\" setups this refers to the height in millimeters for
4841 all physical monitors associated with DISPLAY. To get information
4842 for each physical monitor, use `display-monitor-attributes-list'. */)
4843 (Lisp_Object display)
4845 struct w32_display_info *dpyinfo = check_x_display_info (display);
4846 HDC hdc;
4847 double mm_per_pixel;
4849 hdc = GetDC (NULL);
4850 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
4851 / GetDeviceCaps (hdc, VERTRES));
4852 ReleaseDC (NULL, hdc);
4854 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
4857 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
4858 doc: /* Return the width 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 width in millimeters for
4864 all physical monitors associated with TERMINAL. 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, HORZSIZE)
4874 / GetDeviceCaps (hdc, HORZRES));
4875 ReleaseDC (NULL, hdc);
4877 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
4880 DEFUN ("x-display-backing-store", Fx_display_backing_store,
4881 Sx_display_backing_store, 0, 1, 0,
4882 doc: /* Return an indication of whether DISPLAY does backing store.
4883 The value may be `always', `when-mapped', or `not-useful'.
4884 The optional argument DISPLAY specifies which display to ask about.
4885 DISPLAY should be either a frame or a display name (a string).
4886 If omitted or nil, that stands for the selected frame's display. */)
4887 (Lisp_Object display)
4889 return intern ("not-useful");
4892 DEFUN ("x-display-visual-class", Fx_display_visual_class,
4893 Sx_display_visual_class, 0, 1, 0,
4894 doc: /* Return the visual class of DISPLAY.
4895 The value is one of the symbols `static-gray', `gray-scale',
4896 `static-color', `pseudo-color', `true-color', or `direct-color'.
4898 The optional argument DISPLAY specifies which display to ask about.
4899 DISPLAY should be either a frame or a display name (a string).
4900 If omitted or nil, that stands for the selected frame's display. */)
4901 (Lisp_Object display)
4903 struct w32_display_info *dpyinfo = check_x_display_info (display);
4904 Lisp_Object result = Qnil;
4906 if (dpyinfo->has_palette)
4907 result = intern ("pseudo-color");
4908 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
4909 result = intern ("static-grey");
4910 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
4911 result = intern ("static-color");
4912 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
4913 result = intern ("true-color");
4915 return result;
4918 DEFUN ("x-display-save-under", Fx_display_save_under,
4919 Sx_display_save_under, 0, 1, 0,
4920 doc: /* Return t if DISPLAY supports the save-under feature.
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 return Qnil;
4929 static BOOL CALLBACK
4930 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
4932 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
4934 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
4936 return TRUE;
4939 static Lisp_Object
4940 w32_display_monitor_attributes_list (void)
4942 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
4943 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
4944 int i, n_monitors;
4945 HMONITOR *monitors;
4946 struct gcpro gcpro1, gcpro2, gcpro3;
4948 if (!(enum_display_monitors_fn && get_monitor_info_fn
4949 && monitor_from_window_fn))
4950 return Qnil;
4952 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
4953 (LPARAM) &monitor_list)
4954 || NILP (monitor_list))
4955 return Qnil;
4957 n_monitors = 0;
4958 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
4959 n_monitors++;
4961 monitors = xmalloc (n_monitors * sizeof (*monitors));
4962 for (i = 0; i < n_monitors; i++)
4964 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
4965 monitor_list = XCDR (monitor_list);
4968 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
4969 FOR_EACH_FRAME (rest, frame)
4971 struct frame *f = XFRAME (frame);
4973 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
4975 HMONITOR monitor =
4976 monitor_from_window_fn (FRAME_W32_WINDOW (f),
4977 MONITOR_DEFAULT_TO_NEAREST);
4979 for (i = 0; i < n_monitors; i++)
4980 if (monitors[i] == monitor)
4981 break;
4983 if (i < n_monitors)
4984 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
4988 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
4990 for (i = 0; i < n_monitors; i++)
4992 Lisp_Object geometry, workarea, name, attributes = Qnil;
4993 HDC hdc;
4994 int width_mm, height_mm;
4995 struct MONITOR_INFO_EX mi;
4997 mi.cbSize = sizeof (mi);
4998 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
4999 continue;
5001 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5002 if (hdc == NULL)
5003 continue;
5004 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5005 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5006 DeleteDC (hdc);
5008 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5009 attributes);
5011 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5013 attributes = Fcons (Fcons (Qname, name), attributes);
5015 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5016 attributes);
5018 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5019 mi.rcWork.right - mi.rcWork.left,
5020 mi.rcWork.bottom - mi.rcWork.top);
5021 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5023 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5024 mi.rcMonitor.right - mi.rcMonitor.left,
5025 mi.rcMonitor.bottom - mi.rcMonitor.top);
5026 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5028 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5029 primary_monitor_attributes = attributes;
5030 else
5031 attributes_list = Fcons (attributes, attributes_list);
5034 if (!NILP (primary_monitor_attributes))
5035 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5037 UNGCPRO;
5039 xfree (monitors);
5041 return attributes_list;
5044 static Lisp_Object
5045 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5047 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5048 HDC hdc;
5049 double mm_per_pixel;
5050 int pixel_width, pixel_height, width_mm, height_mm;
5051 RECT workarea_rect;
5053 /* Fallback: treat (possibly) multiple physical monitors as if they
5054 formed a single monitor as a whole. This should provide a
5055 consistent result at least on single monitor environments. */
5056 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5057 attributes);
5059 frames = Qnil;
5060 FOR_EACH_FRAME (rest, frame)
5062 struct frame *f = XFRAME (frame);
5064 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5065 frames = Fcons (frame, frames);
5067 attributes = Fcons (Fcons (Qframes, frames), attributes);
5069 pixel_width = x_display_pixel_width (dpyinfo);
5070 pixel_height = x_display_pixel_height (dpyinfo);
5072 hdc = GetDC (NULL);
5073 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5074 / GetDeviceCaps (hdc, HORZRES));
5075 width_mm = pixel_width * mm_per_pixel + 0.5;
5076 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5077 / GetDeviceCaps (hdc, VERTRES));
5078 height_mm = pixel_height * mm_per_pixel + 0.5;
5079 ReleaseDC (NULL, hdc);
5080 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5081 attributes);
5083 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5084 we don't care. */
5085 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5086 GetSystemMetrics (SM_YVIRTUALSCREEN),
5087 pixel_width, pixel_height);
5088 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5089 workarea = list4i (workarea_rect.left, workarea_rect.top,
5090 workarea_rect.right - workarea_rect.left,
5091 workarea_rect.bottom - workarea_rect.top);
5092 else
5093 workarea = geometry;
5094 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5096 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5098 return list1 (attributes);
5101 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5102 Sw32_display_monitor_attributes_list,
5103 0, 1, 0,
5104 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5106 The optional argument DISPLAY specifies which display to ask about.
5107 DISPLAY should be either a frame or a display name (a string).
5108 If omitted or nil, that stands for the selected frame's display.
5110 Internal use only, use `display-monitor-attributes-list' instead. */)
5111 (Lisp_Object display)
5113 struct w32_display_info *dpyinfo = check_x_display_info (display);
5114 Lisp_Object attributes_list;
5116 block_input ();
5117 attributes_list = w32_display_monitor_attributes_list ();
5118 if (NILP (attributes_list))
5119 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5120 unblock_input ();
5122 return attributes_list;
5125 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5126 doc: /* Set the sound generated when the bell is rung.
5127 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5128 to use the corresponding system sound for the bell. The 'silent sound
5129 prevents Emacs from making any sound at all.
5130 SOUND is nil to use the normal beep. */)
5131 (Lisp_Object sound)
5133 CHECK_SYMBOL (sound);
5135 if (NILP (sound))
5136 sound_type = 0xFFFFFFFF;
5137 else if (EQ (sound, intern ("asterisk")))
5138 sound_type = MB_ICONASTERISK;
5139 else if (EQ (sound, intern ("exclamation")))
5140 sound_type = MB_ICONEXCLAMATION;
5141 else if (EQ (sound, intern ("hand")))
5142 sound_type = MB_ICONHAND;
5143 else if (EQ (sound, intern ("question")))
5144 sound_type = MB_ICONQUESTION;
5145 else if (EQ (sound, intern ("ok")))
5146 sound_type = MB_OK;
5147 else if (EQ (sound, intern ("silent")))
5148 sound_type = MB_EMACS_SILENT;
5149 else
5150 sound_type = 0xFFFFFFFF;
5152 return sound;
5156 x_screen_planes (register struct frame *f)
5158 return FRAME_DISPLAY_INFO (f)->n_planes;
5161 /* Return the display structure for the display named NAME.
5162 Open a new connection if necessary. */
5164 struct w32_display_info *
5165 x_display_info_for_name (Lisp_Object name)
5167 struct w32_display_info *dpyinfo;
5169 CHECK_STRING (name);
5171 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5172 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5173 return dpyinfo;
5175 /* Use this general default value to start with. */
5176 Vx_resource_name = Vinvocation_name;
5178 validate_x_resource_name ();
5180 dpyinfo = w32_term_init (name, (unsigned char *)0,
5181 SSDATA (Vx_resource_name));
5183 if (dpyinfo == 0)
5184 error ("Cannot connect to server %s", SDATA (name));
5186 XSETFASTINT (Vwindow_system_version, w32_major_version);
5188 return dpyinfo;
5191 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5192 1, 3, 0, doc: /* Open a connection to a display server.
5193 DISPLAY is the name of the display to connect to.
5194 Optional second arg XRM-STRING is a string of resources in xrdb format.
5195 If the optional third arg MUST-SUCCEED is non-nil,
5196 terminate Emacs if we can't open the connection.
5197 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5198 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5200 unsigned char *xrm_option;
5201 struct w32_display_info *dpyinfo;
5203 CHECK_STRING (display);
5205 /* Signal an error in order to encourage correct use from callers.
5206 * If we ever support multiple window systems in the same Emacs,
5207 * we'll need callers to be precise about what window system they
5208 * want. */
5210 if (strcmp (SSDATA (display), "w32") != 0)
5211 error ("The name of the display in this Emacs must be \"w32\"");
5213 /* If initialization has already been done, return now to avoid
5214 overwriting critical parts of one_w32_display_info. */
5215 if (window_system_available (NULL))
5216 return Qnil;
5218 if (! NILP (xrm_string))
5219 CHECK_STRING (xrm_string);
5221 /* Allow color mapping to be defined externally; first look in user's
5222 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5224 Lisp_Object color_file;
5225 struct gcpro gcpro1;
5227 color_file = build_string ("~/rgb.txt");
5229 GCPRO1 (color_file);
5231 if (NILP (Ffile_readable_p (color_file)))
5232 color_file =
5233 Fexpand_file_name (build_string ("rgb.txt"),
5234 Fsymbol_value (intern ("data-directory")));
5236 Vw32_color_map = Fx_load_color_file (color_file);
5238 UNGCPRO;
5240 if (NILP (Vw32_color_map))
5241 Vw32_color_map = w32_default_color_map ();
5243 /* Merge in system logical colors. */
5244 add_system_logical_colors_to_map (&Vw32_color_map);
5246 if (! NILP (xrm_string))
5247 xrm_option = SDATA (xrm_string);
5248 else
5249 xrm_option = (unsigned char *) 0;
5251 /* Use this general default value to start with. */
5252 /* First remove .exe suffix from invocation-name - it looks ugly. */
5254 char basename[ MAX_PATH ], *str;
5256 strcpy (basename, SDATA (Vinvocation_name));
5257 str = strrchr (basename, '.');
5258 if (str) *str = 0;
5259 Vinvocation_name = build_string (basename);
5261 Vx_resource_name = Vinvocation_name;
5263 validate_x_resource_name ();
5265 /* This is what opens the connection and sets x_current_display.
5266 This also initializes many symbols, such as those used for input. */
5267 dpyinfo = w32_term_init (display, xrm_option,
5268 SSDATA (Vx_resource_name));
5270 if (dpyinfo == 0)
5272 if (!NILP (must_succeed))
5273 fatal ("Cannot connect to server %s.\n",
5274 SDATA (display));
5275 else
5276 error ("Cannot connect to server %s", SDATA (display));
5279 XSETFASTINT (Vwindow_system_version, w32_major_version);
5280 return Qnil;
5283 DEFUN ("x-close-connection", Fx_close_connection,
5284 Sx_close_connection, 1, 1, 0,
5285 doc: /* Close the connection to DISPLAY's server.
5286 For DISPLAY, specify either a frame or a display name (a string).
5287 If DISPLAY is nil, that stands for the selected frame's display. */)
5288 (Lisp_Object display)
5290 struct w32_display_info *dpyinfo = check_x_display_info (display);
5292 if (dpyinfo->reference_count > 0)
5293 error ("Display still has frames on it");
5295 block_input ();
5296 x_destroy_all_bitmaps (dpyinfo);
5298 x_delete_display (dpyinfo);
5299 unblock_input ();
5301 return Qnil;
5304 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5305 doc: /* Return the list of display names that Emacs has connections to. */)
5306 (void)
5308 Lisp_Object result = Qnil;
5309 struct w32_display_info *wdi;
5311 for (wdi = x_display_list; wdi; wdi = wdi->next)
5312 result = Fcons (XCAR (wdi->name_list_element), result);
5314 return result;
5317 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5318 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5319 This function only has an effect on X Windows. With MS Windows, it is
5320 defined but does nothing.
5322 If ON is nil, allow buffering of requests.
5323 Turning on synchronization prohibits the Xlib routines from buffering
5324 requests and seriously degrades performance, but makes debugging much
5325 easier.
5326 The optional second argument TERMINAL specifies which display to act on.
5327 TERMINAL should be a terminal object, a frame or a display name (a string).
5328 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5329 (Lisp_Object on, Lisp_Object display)
5331 return Qnil;
5336 /***********************************************************************
5337 Window properties
5338 ***********************************************************************/
5340 #if 0 /* TODO : port window properties to W32 */
5342 DEFUN ("x-change-window-property", Fx_change_window_property,
5343 Sx_change_window_property, 2, 6, 0,
5344 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5345 PROP must be a string. VALUE may be a string or a list of conses,
5346 numbers and/or strings. If an element in the list is a string, it is
5347 converted to an atom and the value of the Atom is used. If an element
5348 is a cons, it is converted to a 32 bit number where the car is the 16
5349 top bits and the cdr is the lower 16 bits.
5351 FRAME nil or omitted means use the selected frame.
5352 If TYPE is given and non-nil, it is the name of the type of VALUE.
5353 If TYPE is not given or nil, the type is STRING.
5354 FORMAT gives the size in bits of each element if VALUE is a list.
5355 It must be one of 8, 16 or 32.
5356 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
5357 If OUTER-P is non-nil, the property is changed for the outer X window of
5358 FRAME. Default is to change on the edit X window. */)
5359 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5360 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
5362 struct frame *f = decode_window_system_frame (frame);
5363 Atom prop_atom;
5365 CHECK_STRING (prop);
5366 CHECK_STRING (value);
5368 block_input ();
5369 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5370 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5371 prop_atom, XA_STRING, 8, PropModeReplace,
5372 SDATA (value), SCHARS (value));
5374 /* Make sure the property is set when we return. */
5375 XFlush (FRAME_W32_DISPLAY (f));
5376 unblock_input ();
5378 return value;
5382 DEFUN ("x-delete-window-property", Fx_delete_window_property,
5383 Sx_delete_window_property, 1, 2, 0,
5384 doc: /* Remove window property PROP from X window of FRAME.
5385 FRAME nil or omitted means use the selected frame. Value is PROP. */)
5386 (Lisp_Object prop, Lisp_Object frame)
5388 struct frame *f = decode_window_system_frame (frame);
5389 Atom prop_atom;
5391 CHECK_STRING (prop);
5392 block_input ();
5393 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5394 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
5396 /* Make sure the property is removed when we return. */
5397 XFlush (FRAME_W32_DISPLAY (f));
5398 unblock_input ();
5400 return prop;
5404 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
5405 1, 6, 0,
5406 doc: /* Value is the value of window property PROP on FRAME.
5407 If FRAME is nil or omitted, use the selected frame.
5409 On X Windows, the following optional arguments are also accepted:
5410 If TYPE is nil or omitted, get the property as a string.
5411 Otherwise TYPE is the name of the atom that denotes the type expected.
5412 If SOURCE is non-nil, get the property on that window instead of from
5413 FRAME. The number 0 denotes the root window.
5414 If DELETE-P is non-nil, delete the property after retrieving it.
5415 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5417 On MS Windows, this function accepts but ignores those optional arguments.
5419 Value is nil if FRAME hasn't a property with name PROP or if PROP has
5420 no value of TYPE (always string in the MS Windows case). */)
5421 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5422 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
5424 struct frame *f = decode_window_system_frame (frame);
5425 Atom prop_atom;
5426 int rc;
5427 Lisp_Object prop_value = Qnil;
5428 char *tmp_data = NULL;
5429 Atom actual_type;
5430 int actual_format;
5431 unsigned long actual_size, bytes_remaining;
5433 CHECK_STRING (prop);
5434 block_input ();
5435 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5436 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5437 prop_atom, 0, 0, False, XA_STRING,
5438 &actual_type, &actual_format, &actual_size,
5439 &bytes_remaining, (unsigned char **) &tmp_data);
5440 if (rc == Success)
5442 int size = bytes_remaining;
5444 XFree (tmp_data);
5445 tmp_data = NULL;
5447 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5448 prop_atom, 0, bytes_remaining,
5449 False, XA_STRING,
5450 &actual_type, &actual_format,
5451 &actual_size, &bytes_remaining,
5452 (unsigned char **) &tmp_data);
5453 if (rc == Success)
5454 prop_value = make_string (tmp_data, size);
5456 XFree (tmp_data);
5459 unblock_input ();
5461 return prop_value;
5463 return Qnil;
5466 #endif /* TODO */
5469 /***********************************************************************
5470 Busy cursor
5471 ***********************************************************************/
5473 void
5474 w32_note_current_window (void)
5476 struct frame * f = SELECTED_FRAME ();
5478 if (!FRAME_W32_P (f))
5479 return;
5481 hourglass_hwnd = FRAME_W32_WINDOW (f);
5484 void
5485 show_hourglass (struct atimer *timer)
5487 struct frame *f;
5489 hourglass_atimer = NULL;
5491 block_input ();
5492 f = x_window_to_frame (&one_w32_display_info,
5493 hourglass_hwnd);
5495 if (f)
5496 f->output_data.w32->hourglass_p = 0;
5497 else
5498 f = SELECTED_FRAME ();
5500 if (!FRAME_W32_P (f))
5502 unblock_input ();
5503 return;
5506 w32_show_hourglass (f);
5507 unblock_input ();
5510 void
5511 hide_hourglass (void)
5513 block_input ();
5514 w32_hide_hourglass ();
5515 unblock_input ();
5519 /* Display an hourglass cursor. Set the hourglass_p flag in display info
5520 to indicate that an hourglass cursor is shown. */
5522 static void
5523 w32_show_hourglass (struct frame *f)
5525 if (!hourglass_shown_p)
5527 f->output_data.w32->hourglass_p = 1;
5528 if (!menubar_in_use && !current_popup_menu)
5529 SetCursor (f->output_data.w32->hourglass_cursor);
5530 hourglass_shown_p = 1;
5535 /* Hide the hourglass cursor on all frames, if it is currently shown. */
5537 static void
5538 w32_hide_hourglass (void)
5540 if (hourglass_shown_p)
5542 struct frame *f = x_window_to_frame (&one_w32_display_info,
5543 hourglass_hwnd);
5544 if (f)
5545 f->output_data.w32->hourglass_p = 0;
5546 else
5547 /* If frame was deleted, restore to selected frame's cursor. */
5548 f = SELECTED_FRAME ();
5550 if (FRAME_W32_P (f))
5551 SetCursor (f->output_data.w32->current_cursor);
5552 else
5553 /* No cursors on non GUI frames - restore to stock arrow cursor. */
5554 SetCursor (w32_load_cursor (IDC_ARROW));
5556 hourglass_shown_p = 0;
5562 /***********************************************************************
5563 Tool tips
5564 ***********************************************************************/
5566 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5567 Lisp_Object, Lisp_Object);
5568 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5569 Lisp_Object, int, int, int *, int *);
5571 /* The frame of a currently visible tooltip. */
5573 Lisp_Object tip_frame;
5575 /* If non-nil, a timer started that hides the last tooltip when it
5576 fires. */
5578 Lisp_Object tip_timer;
5579 Window tip_window;
5581 /* If non-nil, a vector of 3 elements containing the last args
5582 with which x-show-tip was called. See there. */
5584 Lisp_Object last_show_tip_args;
5587 static void
5588 unwind_create_tip_frame (Lisp_Object frame)
5590 Lisp_Object deleted;
5592 deleted = unwind_create_frame (frame);
5593 if (EQ (deleted, Qt))
5595 tip_window = NULL;
5596 tip_frame = Qnil;
5601 /* Create a frame for a tooltip on the display described by DPYINFO.
5602 PARMS is a list of frame parameters. TEXT is the string to
5603 display in the tip frame. Value is the frame.
5605 Note that functions called here, esp. x_default_parameter can
5606 signal errors, for instance when a specified color name is
5607 undefined. We have to make sure that we're in a consistent state
5608 when this happens. */
5610 static Lisp_Object
5611 x_create_tip_frame (struct w32_display_info *dpyinfo,
5612 Lisp_Object parms, Lisp_Object text)
5614 struct frame *f;
5615 Lisp_Object frame;
5616 Lisp_Object name;
5617 long window_prompting = 0;
5618 int width, height;
5619 ptrdiff_t count = SPECPDL_INDEX ();
5620 struct gcpro gcpro1, gcpro2, gcpro3;
5621 struct kboard *kb;
5622 int face_change_count_before = face_change_count;
5623 Lisp_Object buffer;
5624 struct buffer *old_buffer;
5626 /* Use this general default value to start with until we know if
5627 this frame has a specified name. */
5628 Vx_resource_name = Vinvocation_name;
5630 kb = dpyinfo->terminal->kboard;
5632 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5633 avoid destructive changes behind our caller's back. */
5634 parms = Fcopy_alist (parms);
5636 /* Get the name of the frame to use for resource lookup. */
5637 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
5638 if (!STRINGP (name)
5639 && !EQ (name, Qunbound)
5640 && !NILP (name))
5641 error ("Invalid frame name--not a string or nil");
5642 Vx_resource_name = name;
5644 frame = Qnil;
5645 GCPRO3 (parms, name, frame);
5646 /* Make a frame without minibuffer nor mode-line. */
5647 f = make_frame (0);
5648 f->wants_modeline = 0;
5649 XSETFRAME (frame, f);
5651 buffer = Fget_buffer_create (build_string (" *tip*"));
5652 /* Use set_window_buffer instead of Fset_window_buffer (see
5653 discussion of bug#11984, bug#12025, bug#12026). */
5654 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, 0, 0);
5655 old_buffer = current_buffer;
5656 set_buffer_internal_1 (XBUFFER (buffer));
5657 bset_truncate_lines (current_buffer, Qnil);
5658 specbind (Qinhibit_read_only, Qt);
5659 specbind (Qinhibit_modification_hooks, Qt);
5660 Ferase_buffer ();
5661 Finsert (1, &text);
5662 set_buffer_internal_1 (old_buffer);
5664 record_unwind_protect (unwind_create_tip_frame, frame);
5666 /* By setting the output method, we're essentially saying that
5667 the frame is live, as per FRAME_LIVE_P. If we get a signal
5668 from this point on, x_destroy_window might screw up reference
5669 counts etc. */
5670 f->terminal = dpyinfo->terminal;
5671 f->output_method = output_w32;
5672 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5674 FRAME_FONTSET (f) = -1;
5675 fset_icon_name (f, Qnil);
5677 #ifdef GLYPH_DEBUG
5678 image_cache_refcount =
5679 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5680 dpyinfo_refcount = dpyinfo->reference_count;
5681 #endif /* GLYPH_DEBUG */
5682 FRAME_KBOARD (f) = kb;
5683 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5684 f->output_data.w32->explicit_parent = 0;
5686 /* Set the name; the functions to which we pass f expect the name to
5687 be set. */
5688 if (EQ (name, Qunbound) || NILP (name))
5690 fset_name (f, build_string (dpyinfo->w32_id_name));
5691 f->explicit_name = 0;
5693 else
5695 fset_name (f, name);
5696 f->explicit_name = 1;
5697 /* use the frame's title when getting resources for this frame. */
5698 specbind (Qx_resource_name, name);
5701 if (uniscribe_available)
5702 register_font_driver (&uniscribe_font_driver, f);
5703 register_font_driver (&w32font_driver, f);
5705 x_default_parameter (f, parms, Qfont_backend, Qnil,
5706 "fontBackend", "FontBackend", RES_TYPE_STRING);
5708 /* Extract the window parameters from the supplied values
5709 that are needed to determine window geometry. */
5710 x_default_font_parameter (f, parms);
5712 x_default_parameter (f, parms, Qborder_width, make_number (2),
5713 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5714 /* This defaults to 2 in order to match xterm. We recognize either
5715 internalBorderWidth or internalBorder (which is what xterm calls
5716 it). */
5717 if (NILP (Fassq (Qinternal_border_width, parms)))
5719 Lisp_Object value;
5721 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
5722 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5723 if (! EQ (value, Qunbound))
5724 parms = Fcons (Fcons (Qinternal_border_width, value),
5725 parms);
5727 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
5728 "internalBorderWidth", "internalBorderWidth",
5729 RES_TYPE_NUMBER);
5730 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5731 NULL, NULL, RES_TYPE_NUMBER);
5732 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5733 NULL, NULL, RES_TYPE_NUMBER);
5735 /* Also do the stuff which must be set before the window exists. */
5736 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5737 "foreground", "Foreground", RES_TYPE_STRING);
5738 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5739 "background", "Background", RES_TYPE_STRING);
5740 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5741 "pointerColor", "Foreground", RES_TYPE_STRING);
5742 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5743 "cursorColor", "Foreground", RES_TYPE_STRING);
5744 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5745 "borderColor", "BorderColor", RES_TYPE_STRING);
5747 /* Init faces before x_default_parameter is called for scroll-bar
5748 parameters because that function calls x_set_scroll_bar_width,
5749 which calls change_frame_size, which calls Fset_window_buffer,
5750 which runs hooks, which call Fvertical_motion. At the end, we
5751 end up in init_iterator with a null face cache, which should not
5752 happen. */
5753 init_frame_faces (f);
5755 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
5756 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5758 window_prompting = x_figure_window_size (f, parms, 0);
5760 /* No fringes on tip frame. */
5761 f->fringe_cols = 0;
5762 f->left_fringe_width = 0;
5763 f->right_fringe_width = 0;
5765 block_input ();
5766 my_create_tip_window (f);
5767 unblock_input ();
5769 x_make_gc (f);
5771 x_default_parameter (f, parms, Qauto_raise, Qnil,
5772 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5773 x_default_parameter (f, parms, Qauto_lower, Qnil,
5774 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5775 x_default_parameter (f, parms, Qcursor_type, Qbox,
5776 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5778 /* Dimensions, especially FRAME_LINES (f), must be done via
5779 change_frame_size. Change will not be effected unless different
5780 from the current FRAME_LINES (f). */
5781 width = FRAME_COLS (f);
5782 height = FRAME_LINES (f);
5783 FRAME_LINES (f) = 0;
5784 SET_FRAME_COLS (f, 0);
5785 change_frame_size (f, width, height, 1, 0, 0, 0);
5787 /* Add `tooltip' frame parameter's default value. */
5788 if (NILP (Fframe_parameter (frame, Qtooltip)))
5789 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
5791 /* Set up faces after all frame parameters are known. This call
5792 also merges in face attributes specified for new frames.
5794 Frame parameters may be changed if .Xdefaults contains
5795 specifications for the default font. For example, if there is an
5796 `Emacs.default.attributeBackground: pink', the `background-color'
5797 attribute of the frame get's set, which let's the internal border
5798 of the tooltip frame appear in pink. Prevent this. */
5800 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
5801 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5802 Lisp_Object colors = Qnil;
5804 /* Set tip_frame here, so that */
5805 tip_frame = frame;
5806 call2 (Qface_set_after_frame_default, frame, Qnil);
5808 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
5809 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5810 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5811 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5813 if (!NILP (colors))
5814 Fmodify_frame_parameters (frame, colors);
5817 f->no_split = 1;
5819 UNGCPRO;
5821 /* Now that the frame is official, it counts as a reference to
5822 its display. */
5823 FRAME_DISPLAY_INFO (f)->reference_count++;
5824 f->terminal->reference_count++;
5826 /* It is now ok to make the frame official even if we get an error
5827 below. And the frame needs to be on Vframe_list or making it
5828 visible won't work. */
5829 Vframe_list = Fcons (frame, Vframe_list);
5831 /* Setting attributes of faces of the tooltip frame from resources
5832 and similar will increment face_change_count, which leads to the
5833 clearing of all current matrices. Since this isn't necessary
5834 here, avoid it by resetting face_change_count to the value it
5835 had before we created the tip frame. */
5836 face_change_count = face_change_count_before;
5838 /* Discard the unwind_protect. */
5839 return unbind_to (count, frame);
5843 /* Compute where to display tip frame F. PARMS is the list of frame
5844 parameters for F. DX and DY are specified offsets from the current
5845 location of the mouse. WIDTH and HEIGHT are the width and height
5846 of the tooltip. Return coordinates relative to the root window of
5847 the display in *ROOT_X, and *ROOT_Y. */
5849 static void
5850 compute_tip_xy (struct frame *f,
5851 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5852 int width, int height, int *root_x, int *root_y)
5854 Lisp_Object left, top;
5855 int min_x, min_y, max_x, max_y;
5857 /* User-specified position? */
5858 left = Fcdr (Fassq (Qleft, parms));
5859 top = Fcdr (Fassq (Qtop, parms));
5861 /* Move the tooltip window where the mouse pointer is. Resize and
5862 show it. */
5863 if (!INTEGERP (left) || !INTEGERP (top))
5865 POINT pt;
5867 /* Default min and max values. */
5868 min_x = 0;
5869 min_y = 0;
5870 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5871 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
5873 block_input ();
5874 GetCursorPos (&pt);
5875 *root_x = pt.x;
5876 *root_y = pt.y;
5877 unblock_input ();
5879 /* If multiple monitor support is available, constrain the tip onto
5880 the current monitor. This improves the above by allowing negative
5881 co-ordinates if monitor positions are such that they are valid, and
5882 snaps a tooltip onto a single monitor if we are close to the edge
5883 where it would otherwise flow onto the other monitor (or into
5884 nothingness if there is a gap in the overlap). */
5885 if (monitor_from_point_fn && get_monitor_info_fn)
5887 struct MONITOR_INFO info;
5888 HMONITOR monitor
5889 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5890 info.cbSize = sizeof (info);
5892 if (get_monitor_info_fn (monitor, &info))
5894 min_x = info.rcWork.left;
5895 min_y = info.rcWork.top;
5896 max_x = info.rcWork.right;
5897 max_y = info.rcWork.bottom;
5902 if (INTEGERP (top))
5903 *root_y = XINT (top);
5904 else if (*root_y + XINT (dy) <= min_y)
5905 *root_y = min_y; /* Can happen for negative dy */
5906 else if (*root_y + XINT (dy) + height <= max_y)
5907 /* It fits below the pointer */
5908 *root_y += XINT (dy);
5909 else if (height + XINT (dy) + min_y <= *root_y)
5910 /* It fits above the pointer. */
5911 *root_y -= height + XINT (dy);
5912 else
5913 /* Put it on the top. */
5914 *root_y = min_y;
5916 if (INTEGERP (left))
5917 *root_x = XINT (left);
5918 else if (*root_x + XINT (dx) <= min_x)
5919 *root_x = 0; /* Can happen for negative dx */
5920 else if (*root_x + XINT (dx) + width <= max_x)
5921 /* It fits to the right of the pointer. */
5922 *root_x += XINT (dx);
5923 else if (width + XINT (dx) + min_x <= *root_x)
5924 /* It fits to the left of the pointer. */
5925 *root_x -= width + XINT (dx);
5926 else
5927 /* Put it left justified on the screen -- it ought to fit that way. */
5928 *root_x = min_x;
5932 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
5933 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
5934 A tooltip window is a small window displaying a string.
5936 This is an internal function; Lisp code should call `tooltip-show'.
5938 FRAME nil or omitted means use the selected frame.
5940 PARMS is an optional list of frame parameters which can be
5941 used to change the tooltip's appearance.
5943 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
5944 means use the default timeout of 5 seconds.
5946 If the list of frame parameters PARMS contains a `left' parameter,
5947 the tooltip is displayed at that x-position. Otherwise it is
5948 displayed at the mouse position, with offset DX added (default is 5 if
5949 DX isn't specified). Likewise for the y-position; if a `top' frame
5950 parameter is specified, it determines the y-position of the tooltip
5951 window, otherwise it is displayed at the mouse position, with offset
5952 DY added (default is -10).
5954 A tooltip's maximum size is specified by `x-max-tooltip-size'.
5955 Text larger than the specified size is clipped. */)
5956 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
5958 struct frame *f;
5959 struct window *w;
5960 int root_x, root_y;
5961 struct buffer *old_buffer;
5962 struct text_pos pos;
5963 int i, width, height, seen_reversed_p;
5964 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5965 int old_windows_or_buffers_changed = windows_or_buffers_changed;
5966 ptrdiff_t count = SPECPDL_INDEX ();
5968 specbind (Qinhibit_redisplay, Qt);
5970 GCPRO4 (string, parms, frame, timeout);
5972 CHECK_STRING (string);
5973 f = decode_window_system_frame (frame);
5974 if (NILP (timeout))
5975 timeout = make_number (5);
5976 else
5977 CHECK_NATNUM (timeout);
5979 if (NILP (dx))
5980 dx = make_number (5);
5981 else
5982 CHECK_NUMBER (dx);
5984 if (NILP (dy))
5985 dy = make_number (-10);
5986 else
5987 CHECK_NUMBER (dy);
5989 if (NILP (last_show_tip_args))
5990 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
5992 if (!NILP (tip_frame))
5994 Lisp_Object last_string = AREF (last_show_tip_args, 0);
5995 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
5996 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
5998 if (EQ (frame, last_frame)
5999 && !NILP (Fequal (last_string, string))
6000 && !NILP (Fequal (last_parms, parms)))
6002 struct frame *f = XFRAME (tip_frame);
6004 /* Only DX and DY have changed. */
6005 if (!NILP (tip_timer))
6007 Lisp_Object timer = tip_timer;
6008 tip_timer = Qnil;
6009 call1 (Qcancel_timer, timer);
6012 block_input ();
6013 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6014 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6016 /* Put tooltip in topmost group and in position. */
6017 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6018 root_x, root_y, 0, 0,
6019 SWP_NOSIZE | SWP_NOACTIVATE);
6021 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6022 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6023 0, 0, 0, 0,
6024 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
6026 unblock_input ();
6027 goto start_timer;
6031 /* Hide a previous tip, if any. */
6032 Fx_hide_tip ();
6034 ASET (last_show_tip_args, 0, string);
6035 ASET (last_show_tip_args, 1, frame);
6036 ASET (last_show_tip_args, 2, parms);
6038 /* Add default values to frame parameters. */
6039 if (NILP (Fassq (Qname, parms)))
6040 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6041 if (NILP (Fassq (Qinternal_border_width, parms)))
6042 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6043 if (NILP (Fassq (Qright_divider_width, parms)))
6044 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6045 if (NILP (Fassq (Qbottom_divider_width, parms)))
6046 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6047 if (NILP (Fassq (Qborder_width, parms)))
6048 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6049 if (NILP (Fassq (Qborder_color, parms)))
6050 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6051 if (NILP (Fassq (Qbackground_color, parms)))
6052 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6053 parms);
6055 /* Block input until the tip has been fully drawn, to avoid crashes
6056 when drawing tips in menus. */
6057 block_input ();
6059 /* Create a frame for the tooltip, and record it in the global
6060 variable tip_frame. */
6061 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6062 f = XFRAME (frame);
6064 /* Set up the frame's root window. */
6065 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6066 w->left_col = 0;
6067 w->top_line = 0;
6068 w->pixel_left = 0;
6069 w->pixel_top = 0;
6071 if (CONSP (Vx_max_tooltip_size)
6072 && INTEGERP (XCAR (Vx_max_tooltip_size))
6073 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6074 && INTEGERP (XCDR (Vx_max_tooltip_size))
6075 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6077 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6078 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6080 else
6082 w->total_cols = 80;
6083 w->total_lines = 40;
6086 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6087 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6089 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6090 adjust_frame_glyphs (f);
6091 w->pseudo_window_p = 1;
6093 /* Display the tooltip text in a temporary buffer. */
6094 old_buffer = current_buffer;
6095 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6096 bset_truncate_lines (current_buffer, Qnil);
6097 clear_glyph_matrix (w->desired_matrix);
6098 clear_glyph_matrix (w->current_matrix);
6099 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6100 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6102 /* Compute width and height of the tooltip. */
6103 width = height = seen_reversed_p = 0;
6104 for (i = 0; i < w->desired_matrix->nrows; ++i)
6106 struct glyph_row *row = &w->desired_matrix->rows[i];
6107 struct glyph *last;
6108 int row_width;
6110 /* Stop at the first empty row at the end. */
6111 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6112 break;
6114 /* Let the row go over the full width of the frame. */
6115 row->full_width_p = 1;
6117 row_width = row->pixel_width;
6118 if (row->used[TEXT_AREA])
6120 if (!row->reversed_p)
6122 /* There's a glyph at the end of rows that is used to
6123 place the cursor there. Don't include the width of
6124 this glyph. */
6125 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6126 if (INTEGERP (last->object))
6127 row_width -= last->pixel_width;
6129 else
6131 /* There could be a stretch glyph at the beginning of R2L
6132 rows that is produced by extend_face_to_end_of_line.
6133 Don't count that glyph. */
6134 struct glyph *g = row->glyphs[TEXT_AREA];
6136 if (g->type == STRETCH_GLYPH && INTEGERP (g->object))
6138 row_width -= g->pixel_width;
6139 seen_reversed_p = 1;
6144 height += row->height;
6145 width = max (width, row_width);
6148 /* If we've seen partial-length R2L rows, we need to re-adjust the
6149 tool-tip frame width and redisplay it again, to avoid over-wide
6150 tips due to the stretch glyph that extends R2L lines to full
6151 width of the frame. */
6152 if (seen_reversed_p)
6154 /* PXW: Why do we do the pixel-to-cols conversion only if
6155 seen_reversed_p holds? Don't we have to set other fields of
6156 the window/frame structure?
6158 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6159 not in pixels. */
6160 w->pixel_width = width;
6161 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6162 w->total_cols = width;
6163 FRAME_TOTAL_COLS (f) = width;
6164 SET_FRAME_WIDTH (f, width);
6165 adjust_frame_glyphs (f);
6166 w->pseudo_window_p = 1;
6167 clear_glyph_matrix (w->desired_matrix);
6168 clear_glyph_matrix (w->current_matrix);
6169 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6170 width = height = 0;
6171 /* Recompute width and height of the tooltip. */
6172 for (i = 0; i < w->desired_matrix->nrows; ++i)
6174 struct glyph_row *row = &w->desired_matrix->rows[i];
6175 struct glyph *last;
6176 int row_width;
6178 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6179 break;
6180 row->full_width_p = 1;
6181 row_width = row->pixel_width;
6182 if (row->used[TEXT_AREA] && !row->reversed_p)
6184 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6185 if (INTEGERP (last->object))
6186 row_width -= last->pixel_width;
6189 height += row->height;
6190 width = max (width, row_width);
6194 /* Add the frame's internal border to the width and height the w32
6195 window should have. */
6196 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6197 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6199 /* Move the tooltip window where the mouse pointer is. Resize and
6200 show it.
6202 PXW: This should use the frame's pixel coordinates. */
6203 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6206 /* Adjust Window size to take border into account. */
6207 RECT rect;
6208 rect.left = rect.top = 0;
6209 rect.right = width;
6210 rect.bottom = height;
6211 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6212 FRAME_EXTERNAL_MENU_BAR (f));
6214 /* Position and size tooltip, and put it in the topmost group.
6215 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6216 peculiarity of w32 display: without it, some fonts cause the
6217 last character of the tip to be truncated or wrapped around to
6218 the next line. */
6219 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6220 root_x, root_y,
6221 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6222 rect.bottom - rect.top, SWP_NOACTIVATE);
6224 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6225 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6226 0, 0, 0, 0,
6227 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
6229 /* Let redisplay know that we have made the frame visible already. */
6230 SET_FRAME_VISIBLE (f, 1);
6232 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6235 /* Draw into the window. */
6236 w->must_be_updated_p = 1;
6237 update_single_window (w, 1);
6239 unblock_input ();
6241 /* Restore original current buffer. */
6242 set_buffer_internal_1 (old_buffer);
6243 windows_or_buffers_changed = old_windows_or_buffers_changed;
6245 start_timer:
6246 /* Let the tip disappear after timeout seconds. */
6247 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6248 intern ("x-hide-tip"));
6250 UNGCPRO;
6251 return unbind_to (count, Qnil);
6255 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6256 doc: /* Hide the current tooltip window, if there is any.
6257 Value is t if tooltip was open, nil otherwise. */)
6258 (void)
6260 ptrdiff_t count;
6261 Lisp_Object deleted, frame, timer;
6262 struct gcpro gcpro1, gcpro2;
6264 /* Return quickly if nothing to do. */
6265 if (NILP (tip_timer) && NILP (tip_frame))
6266 return Qnil;
6268 frame = tip_frame;
6269 timer = tip_timer;
6270 GCPRO2 (frame, timer);
6271 tip_frame = tip_timer = deleted = Qnil;
6273 count = SPECPDL_INDEX ();
6274 specbind (Qinhibit_redisplay, Qt);
6275 specbind (Qinhibit_quit, Qt);
6277 if (!NILP (timer))
6278 call1 (Qcancel_timer, timer);
6280 if (FRAMEP (frame))
6282 delete_frame (frame, Qnil);
6283 deleted = Qt;
6286 UNGCPRO;
6287 return unbind_to (count, deleted);
6290 /***********************************************************************
6291 File selection dialog
6292 ***********************************************************************/
6294 #define FILE_NAME_TEXT_FIELD edt1
6295 #define FILE_NAME_COMBO_BOX cmb13
6296 #define FILE_NAME_LIST lst1
6298 /* Callback for altering the behavior of the Open File dialog.
6299 Makes the Filename text field contain "Current Directory" and be
6300 read-only when "Directories" is selected in the filter. This
6301 allows us to work around the fact that the standard Open File
6302 dialog does not support directories. */
6303 static UINT_PTR CALLBACK
6304 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6306 if (msg == WM_NOTIFY)
6308 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6309 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6310 int dropdown_changed;
6311 int dir_index;
6312 #ifdef NTGUI_UNICODE
6313 const int use_unicode = 1;
6314 #else /* !NTGUI_UNICODE */
6315 int use_unicode = w32_unicode_filenames;
6316 #endif /* NTGUI_UNICODE */
6318 /* Detect when the Filter dropdown is changed. */
6319 if (use_unicode)
6320 dropdown_changed =
6321 notify_w->hdr.code == CDN_TYPECHANGE
6322 || notify_w->hdr.code == CDN_INITDONE;
6323 else
6324 dropdown_changed =
6325 notify_a->hdr.code == CDN_TYPECHANGE
6326 || notify_a->hdr.code == CDN_INITDONE;
6327 if (dropdown_changed)
6329 HWND dialog = GetParent (hwnd);
6330 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6331 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6332 int hdr_code;
6334 /* At least on Windows 7, the above attempt to get the window handle
6335 to the File Name Text Field fails. The following code does the
6336 job though. Note that this code is based on my examination of the
6337 window hierarchy using Microsoft Spy++. bk */
6338 if (edit_control == NULL)
6340 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6341 if (tmp)
6343 tmp = GetWindow (tmp, GW_CHILD);
6344 if (tmp)
6345 edit_control = GetWindow (tmp, GW_CHILD);
6349 /* Directories is in index 2. */
6350 if (use_unicode)
6352 dir_index = notify_w->lpOFN->nFilterIndex;
6353 hdr_code = notify_w->hdr.code;
6355 else
6357 dir_index = notify_a->lpOFN->nFilterIndex;
6358 hdr_code = notify_a->hdr.code;
6360 if (dir_index == 2)
6362 if (use_unicode)
6363 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6364 (LPARAM)L"Current Directory");
6365 else
6366 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6367 (LPARAM)"Current Directory");
6368 EnableWindow (edit_control, FALSE);
6369 /* Note that at least on Windows 7, the above call to EnableWindow
6370 disables the window that would ordinarily have focus. If we
6371 do not set focus to some other window here, focus will land in
6372 no man's land and the user will be unable to tab through the
6373 dialog box (pressing tab will only result in a beep).
6374 Avoid that problem by setting focus to the list here. */
6375 if (hdr_code == CDN_INITDONE)
6376 SetFocus (list);
6378 else
6380 /* Don't override default filename on init done. */
6381 if (hdr_code == CDN_TYPECHANGE)
6383 if (use_unicode)
6384 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6385 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6386 else
6387 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6388 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6390 EnableWindow (edit_control, TRUE);
6394 return 0;
6397 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6398 doc: /* Read file name, prompting with PROMPT in directory DIR.
6399 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6400 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6401 or directory must exist.
6403 This function is only defined on NS, MS Windows, and X Windows with the
6404 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6405 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories. */)
6406 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6408 /* Filter index: 1: All Files, 2: Directories only */
6409 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6410 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6412 Lisp_Object filename = default_filename;
6413 struct frame *f = SELECTED_FRAME ();
6414 BOOL file_opened = FALSE;
6415 Lisp_Object orig_dir = dir;
6416 Lisp_Object orig_prompt = prompt;
6418 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6419 compatibility) we end up with the old file dialogs. Define a big
6420 enough struct for the new dialog to trick GetOpenFileName into
6421 giving us the new dialogs on newer versions of Windows. */
6422 struct {
6423 OPENFILENAMEW details;
6424 #if _WIN32_WINNT < 0x500 /* < win2k */
6425 PVOID pvReserved;
6426 DWORD dwReserved;
6427 DWORD FlagsEx;
6428 #endif /* < win2k */
6429 } new_file_details_w;
6431 #ifdef NTGUI_UNICODE
6432 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6433 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6434 const int use_unicode = 1;
6435 #else /* not NTGUI_UNICODE */
6436 struct {
6437 OPENFILENAMEA details;
6438 #if _WIN32_WINNT < 0x500 /* < win2k */
6439 PVOID pvReserved;
6440 DWORD dwReserved;
6441 DWORD FlagsEx;
6442 #endif /* < win2k */
6443 } new_file_details_a;
6444 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6445 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6446 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6447 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6448 int use_unicode = w32_unicode_filenames;
6449 wchar_t *prompt_w;
6450 char *prompt_a;
6451 int len;
6452 char fname_ret[MAX_UTF8_PATH];
6453 #endif /* NTGUI_UNICODE */
6455 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
6456 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
6459 struct gcpro gcpro1, gcpro2;
6460 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
6462 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6463 system file encoding expected by the platform APIs (e.g. Cygwin's
6464 POSIX implementation) may not be the same as the encoding expected
6465 by the Windows "ANSI" APIs! */
6467 CHECK_STRING (prompt);
6468 CHECK_STRING (dir);
6470 dir = Fexpand_file_name (dir, Qnil);
6472 if (STRINGP (filename))
6473 filename = Ffile_name_nondirectory (filename);
6474 else
6475 filename = empty_unibyte_string;
6477 #ifdef CYGWIN
6478 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
6479 if (SCHARS (filename) > 0)
6480 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
6481 #endif
6483 CHECK_STRING (dir);
6484 CHECK_STRING (filename);
6486 /* The code in file_dialog_callback that attempts to set the text
6487 of the file name edit window when handling the CDN_INITDONE
6488 WM_NOTIFY message does not work. Setting filename to "Current
6489 Directory" in the only_dir_p case here does work however. */
6490 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6491 filename = build_string ("Current Directory");
6493 /* Convert the values we've computed so far to system form. */
6494 #ifdef NTGUI_UNICODE
6495 to_unicode (prompt, &prompt);
6496 to_unicode (dir, &dir);
6497 to_unicode (filename, &filename);
6498 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6499 report_file_error ("filename too long", default_filename);
6501 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
6502 #else /* !NTGUI_UNICODE */
6503 prompt = ENCODE_FILE (prompt);
6504 dir = ENCODE_FILE (dir);
6505 filename = ENCODE_FILE (filename);
6507 /* We modify these in-place, so make copies for safety. */
6508 dir = Fcopy_sequence (dir);
6509 unixtodos_filename (SDATA (dir));
6510 filename = Fcopy_sequence (filename);
6511 unixtodos_filename (SDATA (filename));
6512 if (SBYTES (filename) >= MAX_UTF8_PATH)
6513 report_file_error ("filename too long", default_filename);
6514 if (w32_unicode_filenames)
6516 filename_to_utf16 (SSDATA (dir), dir_w);
6517 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6519 /* filename_to_utf16 sets errno to ENOENT when the file
6520 name is too long or cannot be converted to UTF-16. */
6521 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6522 report_file_error ("filename too long", default_filename);
6524 len = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6525 SSDATA (prompt), -1, NULL, 0);
6526 if (len > 32768)
6527 len = 32768;
6528 prompt_w = alloca (len * sizeof (wchar_t));
6529 MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6530 SSDATA (prompt), -1, prompt_w, len);
6532 else
6534 filename_to_ansi (SSDATA (dir), dir_a);
6535 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6537 /* filename_to_ansi sets errno to ENOENT when the file
6538 name is too long or cannot be converted to UTF-16. */
6539 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6540 report_file_error ("filename too long", default_filename);
6542 len = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6543 SSDATA (prompt), -1, NULL, 0);
6544 if (len > 32768)
6545 len = 32768;
6546 prompt_w = alloca (len * sizeof (wchar_t));
6547 MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6548 SSDATA (prompt), -1, prompt_w, len);
6549 len = WideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
6550 if (len > 32768)
6551 len = 32768;
6552 prompt_a = alloca (len);
6553 WideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
6555 #endif /* NTGUI_UNICODE */
6557 /* Fill in the structure for the call to GetOpenFileName below.
6558 For NTGUI_UNICODE builds (which run only on NT), we just use
6559 the actual size of the structure. For non-NTGUI_UNICODE
6560 builds, we tell the OS we're using an old version of the
6561 structure if the OS isn't new enough to support the newer
6562 version. */
6563 if (use_unicode)
6565 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6566 if (w32_major_version > 4 && w32_major_version < 95)
6567 file_details_w->lStructSize = sizeof (new_file_details_w);
6568 else
6569 file_details_w->lStructSize = sizeof (*file_details_w);
6570 /* Set up the inout parameter for the selected file name. */
6571 file_details_w->lpstrFile = filename_buf_w;
6572 file_details_w->nMaxFile =
6573 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6574 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6575 /* Undocumented Bug in Common File Dialog:
6576 If a filter is not specified, shell links are not resolved. */
6577 file_details_w->lpstrFilter = filter_w;
6578 #ifdef NTGUI_UNICODE
6579 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
6580 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
6581 #else
6582 file_details_w->lpstrInitialDir = dir_w;
6583 file_details_w->lpstrTitle = prompt_w;
6584 #endif
6585 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6586 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6587 | OFN_EXPLORER | OFN_ENABLEHOOK);
6588 if (!NILP (mustmatch))
6590 /* Require that the path to the parent directory exists. */
6591 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6592 /* If we are looking for a file, require that it exists. */
6593 if (NILP (only_dir_p))
6594 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6597 #ifndef NTGUI_UNICODE
6598 else
6600 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6601 if (w32_major_version > 4 && w32_major_version < 95)
6602 file_details_a->lStructSize = sizeof (new_file_details_a);
6603 else
6604 file_details_a->lStructSize = sizeof (*file_details_a);
6605 file_details_a->lpstrFile = filename_buf_a;
6606 file_details_a->nMaxFile =
6607 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6608 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6609 file_details_a->lpstrFilter = filter_a;
6610 file_details_a->lpstrInitialDir = dir_a;
6611 file_details_a->lpstrTitle = prompt_a;
6612 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6613 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6614 | OFN_EXPLORER | OFN_ENABLEHOOK);
6615 if (!NILP (mustmatch))
6617 /* Require that the path to the parent directory exists. */
6618 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6619 /* If we are looking for a file, require that it exists. */
6620 if (NILP (only_dir_p))
6621 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6624 #endif /* !NTGUI_UNICODE */
6627 int count = SPECPDL_INDEX ();
6628 /* Prevent redisplay. */
6629 specbind (Qinhibit_redisplay, Qt);
6630 block_input ();
6631 if (use_unicode)
6633 file_details_w->lpfnHook = file_dialog_callback;
6635 file_opened = GetOpenFileNameW (file_details_w);
6637 #ifndef NTGUI_UNICODE
6638 else
6640 file_details_a->lpfnHook = file_dialog_callback;
6642 file_opened = GetOpenFileNameA (file_details_a);
6644 #endif /* !NTGUI_UNICODE */
6645 unblock_input ();
6646 unbind_to (count, Qnil);
6649 if (file_opened)
6651 /* Get an Emacs string from the value Windows gave us. */
6652 #ifdef NTGUI_UNICODE
6653 filename = from_unicode_buffer (filename_buf_w);
6654 #else /* !NTGUI_UNICODE */
6655 if (use_unicode)
6656 filename_from_utf16 (filename_buf_w, fname_ret);
6657 else
6658 filename_from_ansi (filename_buf_a, fname_ret);
6659 dostounix_filename (fname_ret);
6660 filename = DECODE_FILE (build_unibyte_string (fname_ret));
6661 #endif /* NTGUI_UNICODE */
6663 #ifdef CYGWIN
6664 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
6665 #endif /* CYGWIN */
6667 /* Strip the dummy filename off the end of the string if we
6668 added it to select a directory. */
6669 if ((use_unicode && file_details_w->nFilterIndex == 2)
6670 #ifndef NTGUI_UNICODE
6671 || (!use_unicode && file_details_a->nFilterIndex == 2)
6672 #endif
6674 filename = Ffile_name_directory (filename);
6676 /* User canceled the dialog without making a selection. */
6677 else if (!CommDlgExtendedError ())
6678 filename = Qnil;
6679 /* An error occurred, fallback on reading from the mini-buffer. */
6680 else
6681 filename = Fcompleting_read (
6682 orig_prompt,
6683 intern ("read-file-name-internal"),
6684 orig_dir,
6685 mustmatch,
6686 orig_dir,
6687 Qfile_name_history,
6688 default_filename,
6689 Qnil);
6691 UNGCPRO;
6694 /* Make "Cancel" equivalent to C-g. */
6695 if (NILP (filename))
6696 Fsignal (Qquit, Qnil);
6698 RETURN_UNGCPRO (filename);
6702 #ifdef WINDOWSNT
6703 /* Moving files to the system recycle bin.
6704 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6705 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6706 Ssystem_move_file_to_trash, 1, 1, 0,
6707 doc: /* Move file or directory named FILENAME to the recycle bin. */)
6708 (Lisp_Object filename)
6710 Lisp_Object handler;
6711 Lisp_Object encoded_file;
6712 Lisp_Object operation;
6714 operation = Qdelete_file;
6715 if (!NILP (Ffile_directory_p (filename))
6716 && NILP (Ffile_symlink_p (filename)))
6718 operation = intern ("delete-directory");
6719 filename = Fdirectory_file_name (filename);
6722 /* Must have fully qualified file names for moving files to Recycle
6723 Bin. */
6724 filename = Fexpand_file_name (filename, Qnil);
6726 handler = Ffind_file_name_handler (filename, operation);
6727 if (!NILP (handler))
6728 return call2 (handler, operation, filename);
6729 else
6731 const char * path;
6732 int result;
6734 encoded_file = ENCODE_FILE (filename);
6736 path = map_w32_filename (SDATA (encoded_file), NULL);
6738 /* The Unicode version of SHFileOperation is not supported on
6739 Windows 9X. */
6740 if (w32_unicode_filenames && os_subtype != OS_9X)
6742 SHFILEOPSTRUCTW file_op_w;
6743 /* We need one more element beyond MAX_PATH because this is
6744 a list of file names, with the last element double-null
6745 terminated. */
6746 wchar_t tmp_path_w[MAX_PATH + 1];
6748 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6749 filename_to_utf16 (path, tmp_path_w);
6751 /* On Windows, write permission is required to delete/move files. */
6752 _wchmod (tmp_path_w, 0666);
6754 memset (&file_op_w, 0, sizeof (file_op_w));
6755 file_op_w.hwnd = HWND_DESKTOP;
6756 file_op_w.wFunc = FO_DELETE;
6757 file_op_w.pFrom = tmp_path_w;
6758 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6759 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6760 file_op_w.fAnyOperationsAborted = FALSE;
6762 result = SHFileOperationW (&file_op_w);
6764 else
6766 SHFILEOPSTRUCTA file_op_a;
6767 char tmp_path_a[MAX_PATH + 1];
6769 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6770 filename_to_ansi (path, tmp_path_a);
6772 /* If a file cannot be represented in ANSI codepage, don't
6773 let them inadvertently delete other files because some
6774 characters are interpreted as a wildcards. */
6775 if (_mbspbrk (tmp_path_a, "?*"))
6776 result = ERROR_FILE_NOT_FOUND;
6777 else
6779 _chmod (tmp_path_a, 0666);
6781 memset (&file_op_a, 0, sizeof (file_op_a));
6782 file_op_a.hwnd = HWND_DESKTOP;
6783 file_op_a.wFunc = FO_DELETE;
6784 file_op_a.pFrom = tmp_path_a;
6785 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6786 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6787 file_op_a.fAnyOperationsAborted = FALSE;
6789 result = SHFileOperationA (&file_op_a);
6792 if (result != 0)
6793 report_file_error ("Removing old name", list1 (filename));
6795 return Qnil;
6798 #endif /* WINDOWSNT */
6801 /***********************************************************************
6802 w32 specialized functions
6803 ***********************************************************************/
6805 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6806 Sw32_send_sys_command, 1, 2, 0,
6807 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
6808 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
6809 to minimize), #xf120 to restore frame to original size, and #xf100
6810 to activate the menubar for keyboard access. #xf140 activates the
6811 screen saver if defined.
6813 If optional parameter FRAME is not specified, use selected frame. */)
6814 (Lisp_Object command, Lisp_Object frame)
6816 struct frame *f = decode_window_system_frame (frame);
6818 CHECK_NUMBER (command);
6820 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
6822 return Qnil;
6825 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
6826 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6827 This is a wrapper around the ShellExecute system function, which
6828 invokes the application registered to handle OPERATION for DOCUMENT.
6830 OPERATION is either nil or a string that names a supported operation.
6831 What operations can be used depends on the particular DOCUMENT and its
6832 handler application, but typically it is one of the following common
6833 operations:
6835 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6836 executable program. If it is an application, that
6837 application is launched in the current buffer's default
6838 directory. Otherwise, the application associated with
6839 DOCUMENT is launched in the buffer's default directory.
6840 \"print\" - print DOCUMENT, which must be a file
6841 \"explore\" - start the Windows Explorer on DOCUMENT
6842 \"edit\" - launch an editor and open DOCUMENT for editing; which
6843 editor is launched depends on the association for the
6844 specified DOCUMENT
6845 \"find\" - initiate search starting from DOCUMENT which must specify
6846 a directory
6847 nil - invoke the default OPERATION, or \"open\" if default is
6848 not defined or unavailable
6850 DOCUMENT is typically the name of a document file or a URL, but can
6851 also be a program executable to run, or a directory to open in the
6852 Windows Explorer.
6854 If DOCUMENT is a program executable, the optional third arg PARAMETERS
6855 can be a string containing command line parameters that will be passed
6856 to the program; otherwise, PARAMETERS should be nil or unspecified.
6858 Optional fourth argument SHOW-FLAG can be used to control how the
6859 application will be displayed when it is invoked. If SHOW-FLAG is nil
6860 or unspecified, the application is displayed normally, otherwise it is
6861 an integer representing a ShowWindow flag:
6863 0 - start hidden
6864 1 - start normally
6865 3 - start maximized
6866 6 - start minimized */)
6867 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
6869 char *errstr;
6870 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6871 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
6872 intptr_t result;
6873 #ifndef CYGWIN
6874 int use_unicode = w32_unicode_filenames;
6875 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
6876 #endif
6878 CHECK_STRING (document);
6880 #ifdef CYGWIN
6881 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
6882 if (STRINGP (document))
6883 document = Fcygwin_convert_file_name_to_windows (document, Qt);
6885 /* Encode filename, current directory and parameters. */
6886 current_dir = GUI_ENCODE_FILE (current_dir);
6887 if (STRINGP (document))
6889 document = GUI_ENCODE_FILE (document);
6890 doc_w = GUI_SDATA (document);
6892 if (STRINGP (parameters))
6894 parameters = GUI_ENCODE_SYSTEM (parameters);
6895 params_w = GUI_SDATA (parameters);
6897 if (STRINGP (operation))
6899 operation = GUI_ENCODE_SYSTEM (operation);
6900 ops_w = GUI_SDATA (operation);
6902 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6903 GUI_SDATA (current_dir),
6904 (INTEGERP (show_flag)
6905 ? XINT (show_flag) : SW_SHOWDEFAULT));
6906 #else /* !CYGWIN */
6907 if (use_unicode)
6909 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
6911 /* Encode filename, current directory and parameters, and
6912 convert operation to UTF-16. */
6913 current_dir = ENCODE_FILE (current_dir);
6914 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
6915 if (STRINGP (document))
6917 document = ENCODE_FILE (document);
6918 filename_to_utf16 (SSDATA (document), document_w);
6919 doc_w = document_w;
6921 if (STRINGP (parameters))
6923 int len;
6925 parameters = ENCODE_SYSTEM (parameters);
6926 len = MultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
6927 SSDATA (parameters), -1, NULL, 0);
6928 if (len > 32768)
6929 len = 32768;
6930 params_w = alloca (len * sizeof (wchar_t));
6931 MultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
6932 SSDATA (parameters), -1, params_w, len);
6934 if (STRINGP (operation))
6936 /* Assume OPERATION is pure ASCII. */
6937 const char *s = SSDATA (operation);
6938 wchar_t *d;
6939 int len = SBYTES (operation) + 1;
6941 if (len > 32768)
6942 len = 32768;
6943 d = ops_w = alloca (len * sizeof (wchar_t));
6944 while (d < ops_w + len - 1)
6945 *d++ = *s++;
6946 *d = 0;
6948 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6949 current_dir_w,
6950 (INTEGERP (show_flag)
6951 ? XINT (show_flag) : SW_SHOWDEFAULT));
6953 else
6955 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
6957 current_dir = ENCODE_FILE (current_dir);
6958 filename_to_ansi (SSDATA (current_dir), current_dir_a);
6959 if (STRINGP (document))
6961 ENCODE_FILE (document);
6962 filename_to_ansi (SSDATA (document), document_a);
6963 doc_a = document_a;
6965 if (STRINGP (parameters))
6967 parameters = ENCODE_SYSTEM (parameters);
6968 params_a = SSDATA (parameters);
6970 if (STRINGP (operation))
6972 /* Assume OPERATION is pure ASCII. */
6973 ops_a = SSDATA (operation);
6975 result = (intptr_t) ShellExecuteA (NULL, ops_a, doc_a, params_a,
6976 current_dir_a,
6977 (INTEGERP (show_flag)
6978 ? XINT (show_flag) : SW_SHOWDEFAULT));
6980 #endif /* !CYGWIN */
6982 if (result > 32)
6983 return Qt;
6985 switch (result)
6987 case SE_ERR_ACCESSDENIED:
6988 errstr = w32_strerror (ERROR_ACCESS_DENIED);
6989 break;
6990 case SE_ERR_ASSOCINCOMPLETE:
6991 case SE_ERR_NOASSOC:
6992 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
6993 break;
6994 case SE_ERR_DDEBUSY:
6995 case SE_ERR_DDEFAIL:
6996 errstr = w32_strerror (ERROR_DDE_FAIL);
6997 break;
6998 case SE_ERR_DDETIMEOUT:
6999 errstr = w32_strerror (ERROR_TIMEOUT);
7000 break;
7001 case SE_ERR_DLLNOTFOUND:
7002 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7003 break;
7004 case SE_ERR_FNF:
7005 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7006 break;
7007 case SE_ERR_OOM:
7008 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7009 break;
7010 case SE_ERR_PNF:
7011 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7012 break;
7013 case SE_ERR_SHARE:
7014 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7015 break;
7016 default:
7017 errstr = w32_strerror (0);
7018 break;
7020 /* The error string might be encoded in the locale's encoding. */
7021 if (!NILP (Vlocale_coding_system))
7023 Lisp_Object decoded =
7024 code_convert_string_norecord (build_unibyte_string (errstr),
7025 Vlocale_coding_system, 0);
7026 errstr = SSDATA (decoded);
7028 error ("ShellExecute failed: %s", errstr);
7031 /* Lookup virtual keycode from string representing the name of a
7032 non-ascii keystroke into the corresponding virtual key, using
7033 lispy_function_keys. */
7034 static int
7035 lookup_vk_code (char *key)
7037 int i;
7039 for (i = 0; i < 256; i++)
7040 if (lispy_function_keys[i]
7041 && strcmp (lispy_function_keys[i], key) == 0)
7042 return i;
7044 return -1;
7047 /* Convert a one-element vector style key sequence to a hot key
7048 definition. */
7049 static Lisp_Object
7050 w32_parse_hot_key (Lisp_Object key)
7052 /* Copied from Fdefine_key and store_in_keymap. */
7053 register Lisp_Object c;
7054 int vk_code;
7055 int lisp_modifiers;
7056 int w32_modifiers;
7057 struct gcpro gcpro1;
7059 CHECK_VECTOR (key);
7061 if (ASIZE (key) != 1)
7062 return Qnil;
7064 GCPRO1 (key);
7066 c = AREF (key, 0);
7068 if (CONSP (c) && lucid_event_type_list_p (c))
7069 c = Fevent_convert_list (c);
7071 UNGCPRO;
7073 if (! INTEGERP (c) && ! SYMBOLP (c))
7074 error ("Key definition is invalid");
7076 /* Work out the base key and the modifiers. */
7077 if (SYMBOLP (c))
7079 c = parse_modifiers (c);
7080 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7081 c = Fcar (c);
7082 if (!SYMBOLP (c))
7083 emacs_abort ();
7084 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7086 else if (INTEGERP (c))
7088 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7089 /* Many ascii characters are their own virtual key code. */
7090 vk_code = XINT (c) & CHARACTERBITS;
7093 if (vk_code < 0 || vk_code > 255)
7094 return Qnil;
7096 if ((lisp_modifiers & meta_modifier) != 0
7097 && !NILP (Vw32_alt_is_meta))
7098 lisp_modifiers |= alt_modifier;
7100 /* Supply defs missing from mingw32. */
7101 #ifndef MOD_ALT
7102 #define MOD_ALT 0x0001
7103 #define MOD_CONTROL 0x0002
7104 #define MOD_SHIFT 0x0004
7105 #define MOD_WIN 0x0008
7106 #endif
7108 /* Convert lisp modifiers to Windows hot-key form. */
7109 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7110 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7111 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7112 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7114 return HOTKEY (vk_code, w32_modifiers);
7117 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7118 Sw32_register_hot_key, 1, 1, 0,
7119 doc: /* Register KEY as a hot-key combination.
7120 Certain key combinations like Alt-Tab are reserved for system use on
7121 Windows, and therefore are normally intercepted by the system. However,
7122 most of these key combinations can be received by registering them as
7123 hot-keys, overriding their special meaning.
7125 KEY must be a one element key definition in vector form that would be
7126 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7127 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7128 is always interpreted as the Windows modifier keys.
7130 The return value is the hotkey-id if registered, otherwise nil. */)
7131 (Lisp_Object key)
7133 key = w32_parse_hot_key (key);
7135 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7137 /* Reuse an empty slot if possible. */
7138 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7140 /* Safe to add new key to list, even if we have focus. */
7141 if (NILP (item))
7142 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7143 else
7144 XSETCAR (item, key);
7146 /* Notify input thread about new hot-key definition, so that it
7147 takes effect without needing to switch focus. */
7148 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7149 (WPARAM) XLI (key), 0);
7152 return key;
7155 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7156 Sw32_unregister_hot_key, 1, 1, 0,
7157 doc: /* Unregister KEY as a hot-key combination. */)
7158 (Lisp_Object key)
7160 Lisp_Object item;
7162 if (!INTEGERP (key))
7163 key = w32_parse_hot_key (key);
7165 item = Fmemq (key, w32_grabbed_keys);
7167 if (!NILP (item))
7169 /* Notify input thread about hot-key definition being removed, so
7170 that it takes effect without needing focus switch. */
7171 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7172 (WPARAM) XINT (XCAR (item)), (LPARAM) XLI (item)))
7174 MSG msg;
7175 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7177 return Qt;
7179 return Qnil;
7182 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7183 Sw32_registered_hot_keys, 0, 0, 0,
7184 doc: /* Return list of registered hot-key IDs. */)
7185 (void)
7187 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7190 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7191 Sw32_reconstruct_hot_key, 1, 1, 0,
7192 doc: /* Convert hot-key ID to a lisp key combination.
7193 usage: (w32-reconstruct-hot-key ID) */)
7194 (Lisp_Object hotkeyid)
7196 int vk_code, w32_modifiers;
7197 Lisp_Object key;
7199 CHECK_NUMBER (hotkeyid);
7201 vk_code = HOTKEY_VK_CODE (hotkeyid);
7202 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7204 if (vk_code < 256 && lispy_function_keys[vk_code])
7205 key = intern (lispy_function_keys[vk_code]);
7206 else
7207 key = make_number (vk_code);
7209 key = Fcons (key, Qnil);
7210 if (w32_modifiers & MOD_SHIFT)
7211 key = Fcons (Qshift, key);
7212 if (w32_modifiers & MOD_CONTROL)
7213 key = Fcons (Qctrl, key);
7214 if (w32_modifiers & MOD_ALT)
7215 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7216 if (w32_modifiers & MOD_WIN)
7217 key = Fcons (Qhyper, key);
7219 return key;
7222 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7223 Sw32_toggle_lock_key, 1, 2, 0,
7224 doc: /* Toggle the state of the lock key KEY.
7225 KEY can be `capslock', `kp-numlock', or `scroll'.
7226 If the optional parameter NEW-STATE is a number, then the state of KEY
7227 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
7228 (Lisp_Object key, Lisp_Object new_state)
7230 int vk_code;
7232 if (EQ (key, intern ("capslock")))
7233 vk_code = VK_CAPITAL;
7234 else if (EQ (key, intern ("kp-numlock")))
7235 vk_code = VK_NUMLOCK;
7236 else if (EQ (key, intern ("scroll")))
7237 vk_code = VK_SCROLL;
7238 else
7239 return Qnil;
7241 if (!dwWindowsThreadId)
7242 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7244 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7245 (WPARAM) vk_code, (LPARAM) XLI (new_state)))
7247 MSG msg;
7248 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7249 return make_number (msg.wParam);
7251 return Qnil;
7254 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7255 2, 2, 0,
7256 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7258 This is a direct interface to the Windows API FindWindow function. */)
7259 (Lisp_Object class, Lisp_Object name)
7261 HWND hnd;
7263 if (!NILP (class))
7264 CHECK_STRING (class);
7265 if (!NILP (name))
7266 CHECK_STRING (name);
7268 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7269 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7270 if (!hnd)
7271 return Qnil;
7272 return Qt;
7275 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7276 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7277 FRAME must be a live frame and defaults to the selected one.
7279 The boundary rectangle is a list of four elements, specifying the left,
7280 top, right and bottom screen coordinates of FRAME including menu and
7281 title bar and decorations. Optional argument CLIENT non-nil means to
7282 return the boundaries of the client rectangle which excludes menu and
7283 title bar and decorations. */)
7284 (Lisp_Object frame, Lisp_Object client)
7286 struct frame *f = decode_live_frame (frame);
7287 RECT rect;
7289 if (!NILP (client))
7290 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7291 else
7292 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7294 return list4 (make_number (rect.left), make_number (rect.top),
7295 make_number (rect.right), make_number (rect.bottom));
7298 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7299 doc: /* Get power status information from Windows system.
7301 The following %-sequences are provided:
7302 %L AC line status (verbose)
7303 %B Battery status (verbose)
7304 %b Battery status, empty means high, `-' means low,
7305 `!' means critical, and `+' means charging
7306 %p Battery load percentage
7307 %s Remaining time (to charge or discharge) in seconds
7308 %m Remaining time (to charge or discharge) in minutes
7309 %h Remaining time (to charge or discharge) in hours
7310 %t Remaining time (to charge or discharge) in the form `h:min' */)
7311 (void)
7313 Lisp_Object status = Qnil;
7315 SYSTEM_POWER_STATUS system_status;
7316 if (GetSystemPowerStatus (&system_status))
7318 Lisp_Object line_status, battery_status, battery_status_symbol;
7319 Lisp_Object load_percentage, seconds, minutes, hours, remain;
7321 long seconds_left = (long) system_status.BatteryLifeTime;
7323 if (system_status.ACLineStatus == 0)
7324 line_status = build_string ("off-line");
7325 else if (system_status.ACLineStatus == 1)
7326 line_status = build_string ("on-line");
7327 else
7328 line_status = build_string ("N/A");
7330 if (system_status.BatteryFlag & 128)
7332 battery_status = build_string ("N/A");
7333 battery_status_symbol = empty_unibyte_string;
7335 else if (system_status.BatteryFlag & 8)
7337 battery_status = build_string ("charging");
7338 battery_status_symbol = build_string ("+");
7339 if (system_status.BatteryFullLifeTime != -1L)
7340 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7342 else if (system_status.BatteryFlag & 4)
7344 battery_status = build_string ("critical");
7345 battery_status_symbol = build_string ("!");
7347 else if (system_status.BatteryFlag & 2)
7349 battery_status = build_string ("low");
7350 battery_status_symbol = build_string ("-");
7352 else if (system_status.BatteryFlag & 1)
7354 battery_status = build_string ("high");
7355 battery_status_symbol = empty_unibyte_string;
7357 else
7359 battery_status = build_string ("medium");
7360 battery_status_symbol = empty_unibyte_string;
7363 if (system_status.BatteryLifePercent > 100)
7364 load_percentage = build_string ("N/A");
7365 else
7367 char buffer[16];
7368 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
7369 load_percentage = build_string (buffer);
7372 if (seconds_left < 0)
7373 seconds = minutes = hours = remain = build_string ("N/A");
7374 else
7376 long m;
7377 float h;
7378 char buffer[16];
7379 snprintf (buffer, 16, "%ld", seconds_left);
7380 seconds = build_string (buffer);
7382 m = seconds_left / 60;
7383 snprintf (buffer, 16, "%ld", m);
7384 minutes = build_string (buffer);
7386 h = seconds_left / 3600.0;
7387 snprintf (buffer, 16, "%3.1f", h);
7388 hours = build_string (buffer);
7390 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
7391 remain = build_string (buffer);
7394 status = listn (CONSTYPE_HEAP, 8,
7395 Fcons (make_number ('L'), line_status),
7396 Fcons (make_number ('B'), battery_status),
7397 Fcons (make_number ('b'), battery_status_symbol),
7398 Fcons (make_number ('p'), load_percentage),
7399 Fcons (make_number ('s'), seconds),
7400 Fcons (make_number ('m'), minutes),
7401 Fcons (make_number ('h'), hours),
7402 Fcons (make_number ('t'), remain));
7404 return status;
7408 #ifdef WINDOWSNT
7409 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
7410 doc: /* Return storage information about the file system FILENAME is on.
7411 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7412 storage of the file system, FREE is the free storage, and AVAIL is the
7413 storage available to a non-superuser. All 3 numbers are in bytes.
7414 If the underlying system call fails, value is nil. */)
7415 (Lisp_Object filename)
7417 Lisp_Object encoded, value;
7419 CHECK_STRING (filename);
7420 filename = Fexpand_file_name (filename, Qnil);
7421 encoded = ENCODE_FILE (filename);
7423 value = Qnil;
7425 /* Determining the required information on Windows turns out, sadly,
7426 to be more involved than one would hope. The original Windows API
7427 call for this will return bogus information on some systems, but we
7428 must dynamically probe for the replacement api, since that was
7429 added rather late on. */
7431 HMODULE hKernel = GetModuleHandle ("kernel32");
7432 BOOL (*pfn_GetDiskFreeSpaceExW)
7433 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7434 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7435 BOOL (*pfn_GetDiskFreeSpaceExA)
7436 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7437 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
7438 bool have_pfn_GetDiskFreeSpaceEx =
7439 (w32_unicode_filenames && pfn_GetDiskFreeSpaceExW
7440 || !w32_unicode_filenames && pfn_GetDiskFreeSpaceExA);
7442 /* On Windows, we may need to specify the root directory of the
7443 volume holding FILENAME. */
7444 char rootname[MAX_UTF8_PATH];
7445 wchar_t rootname_w[MAX_PATH];
7446 char rootname_a[MAX_PATH];
7447 char *name = SDATA (encoded);
7448 BOOL result;
7450 /* find the root name of the volume if given */
7451 if (isalpha (name[0]) && name[1] == ':')
7453 rootname[0] = name[0];
7454 rootname[1] = name[1];
7455 rootname[2] = '\\';
7456 rootname[3] = 0;
7458 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7460 char *str = rootname;
7461 int slashes = 4;
7464 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7465 break;
7466 *str++ = *name++;
7468 while ( *name );
7470 *str++ = '\\';
7471 *str = 0;
7474 if (w32_unicode_filenames)
7475 filename_to_utf16 (rootname, rootname_w);
7476 else
7477 filename_to_ansi (rootname, rootname_a);
7479 if (have_pfn_GetDiskFreeSpaceEx)
7481 /* Unsigned large integers cannot be cast to double, so
7482 use signed ones instead. */
7483 LARGE_INTEGER availbytes;
7484 LARGE_INTEGER freebytes;
7485 LARGE_INTEGER totalbytes;
7487 if (w32_unicode_filenames)
7488 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7489 (ULARGE_INTEGER *)&availbytes,
7490 (ULARGE_INTEGER *)&totalbytes,
7491 (ULARGE_INTEGER *)&freebytes);
7492 else
7493 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7494 (ULARGE_INTEGER *)&availbytes,
7495 (ULARGE_INTEGER *)&totalbytes,
7496 (ULARGE_INTEGER *)&freebytes);
7497 if (result)
7498 value = list3 (make_float ((double) totalbytes.QuadPart),
7499 make_float ((double) freebytes.QuadPart),
7500 make_float ((double) availbytes.QuadPart));
7502 else
7504 DWORD sectors_per_cluster;
7505 DWORD bytes_per_sector;
7506 DWORD free_clusters;
7507 DWORD total_clusters;
7509 if (w32_unicode_filenames)
7510 result = GetDiskFreeSpaceW (rootname_w,
7511 &sectors_per_cluster,
7512 &bytes_per_sector,
7513 &free_clusters,
7514 &total_clusters);
7515 else
7516 result = GetDiskFreeSpaceA (rootname_a,
7517 &sectors_per_cluster,
7518 &bytes_per_sector,
7519 &free_clusters,
7520 &total_clusters);
7521 if (result)
7522 value = list3 (make_float ((double) total_clusters
7523 * sectors_per_cluster * bytes_per_sector),
7524 make_float ((double) free_clusters
7525 * sectors_per_cluster * bytes_per_sector),
7526 make_float ((double) free_clusters
7527 * sectors_per_cluster * bytes_per_sector));
7531 return value;
7533 #endif /* WINDOWSNT */
7536 #ifdef WINDOWSNT
7537 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7538 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
7539 (void)
7541 static char pname_buf[256];
7542 int err;
7543 HANDLE hPrn;
7544 PRINTER_INFO_2W *ppi2w = NULL;
7545 PRINTER_INFO_2A *ppi2a = NULL;
7546 DWORD dwNeeded = 0, dwReturned = 0;
7547 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7548 char port_name[MAX_UTF8_PATH];
7550 /* Retrieve the default string from Win.ini (the registry).
7551 * String will be in form "printername,drivername,portname".
7552 * This is the most portable way to get the default printer. */
7553 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7554 return Qnil;
7555 /* printername precedes first "," character */
7556 strtok (pname_buf, ",");
7557 /* We want to know more than the printer name */
7558 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7559 return Qnil;
7560 /* GetPrinterW is not supported by unicows.dll. */
7561 if (w32_unicode_filenames && os_subtype != OS_9X)
7562 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7563 else
7564 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
7565 if (dwNeeded == 0)
7567 ClosePrinter (hPrn);
7568 return Qnil;
7570 /* Call GetPrinter again with big enough memory block. */
7571 if (w32_unicode_filenames && os_subtype != OS_9X)
7573 /* Allocate memory for the PRINTER_INFO_2 struct. */
7574 ppi2w = xmalloc (dwNeeded);
7575 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
7576 ClosePrinter (hPrn);
7577 if (!err)
7579 xfree (ppi2w);
7580 return Qnil;
7583 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7584 && ppi2w->pServerName)
7586 filename_from_utf16 (ppi2w->pServerName, server_name);
7587 filename_from_utf16 (ppi2w->pShareName, share_name);
7589 else
7591 server_name[0] = '\0';
7592 filename_from_utf16 (ppi2w->pPortName, port_name);
7595 else
7597 ppi2a = xmalloc (dwNeeded);
7598 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7599 ClosePrinter (hPrn);
7600 if (!err)
7602 xfree (ppi2a);
7603 return Qnil;
7606 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7607 && ppi2a->pServerName)
7609 filename_from_ansi (ppi2a->pServerName, server_name);
7610 filename_from_ansi (ppi2a->pShareName, share_name);
7612 else
7614 server_name[0] = '\0';
7615 filename_from_ansi (ppi2a->pPortName, port_name);
7619 if (server_name[0])
7621 /* a remote printer */
7622 if (server_name[0] == '\\')
7623 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7624 share_name);
7625 else
7626 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7627 share_name);
7628 pname_buf[sizeof (pname_buf) - 1] = '\0';
7630 else
7632 /* a local printer */
7633 strncpy (pname_buf, port_name, sizeof (pname_buf));
7634 pname_buf[sizeof (pname_buf) - 1] = '\0';
7635 /* `pPortName' can include several ports, delimited by ','.
7636 * we only use the first one. */
7637 strtok (pname_buf, ",");
7640 return DECODE_FILE (build_unibyte_string (pname_buf));
7642 #endif /* WINDOWSNT */
7645 /* Equivalent of strerror for W32 error codes. */
7646 char *
7647 w32_strerror (int error_no)
7649 static char buf[500];
7650 DWORD ret;
7652 if (error_no == 0)
7653 error_no = GetLastError ();
7655 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7656 FORMAT_MESSAGE_IGNORE_INSERTS,
7657 NULL,
7658 error_no,
7659 0, /* choose most suitable language */
7660 buf, sizeof (buf), NULL);
7662 while (ret > 0 && (buf[ret - 1] == '\n' ||
7663 buf[ret - 1] == '\r' ))
7664 --ret;
7665 buf[ret] = '\0';
7666 if (!ret)
7667 sprintf (buf, "w32 error %u", error_no);
7669 return buf;
7672 /* For convenience when debugging. (You cannot call GetLastError
7673 directly from GDB: it will crash, because it uses the __stdcall
7674 calling convention, not the _cdecl convention assumed by GDB.) */
7675 DWORD
7676 w32_last_error (void)
7678 return GetLastError ();
7681 /* Cache information describing the NT system for later use. */
7682 void
7683 cache_system_info (void)
7685 union
7687 struct info
7689 char major;
7690 char minor;
7691 short platform;
7692 } info;
7693 DWORD data;
7694 } version;
7696 /* Cache the module handle of Emacs itself. */
7697 hinst = GetModuleHandle (NULL);
7699 /* Cache the version of the operating system. */
7700 version.data = GetVersion ();
7701 w32_major_version = version.info.major;
7702 w32_minor_version = version.info.minor;
7704 if (version.info.platform & 0x8000)
7705 os_subtype = OS_9X;
7706 else
7707 os_subtype = OS_NT;
7709 /* Cache page size, allocation unit, processor type, etc. */
7710 GetSystemInfo (&sysinfo_cache);
7711 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
7713 /* Cache os info. */
7714 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7715 GetVersionEx (&osinfo_cache);
7717 w32_build_number = osinfo_cache.dwBuildNumber;
7718 if (os_subtype == OS_9X)
7719 w32_build_number &= 0xffff;
7721 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
7724 #ifdef EMACSDEBUG
7725 void
7726 _DebPrint (const char *fmt, ...)
7728 char buf[1024];
7729 va_list args;
7731 va_start (args, fmt);
7732 vsprintf (buf, fmt, args);
7733 va_end (args);
7734 #if CYGWIN
7735 fprintf (stderr, "%s", buf);
7736 #endif
7737 OutputDebugString (buf);
7739 #endif
7742 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
7744 int cur_state = (GetKeyState (vk_code) & 1);
7746 if (NILP (new_state)
7747 || (NUMBERP (new_state)
7748 && ((XUINT (new_state)) & 1) != cur_state))
7750 #ifdef WINDOWSNT
7751 faked_key = vk_code;
7752 #endif /* WINDOWSNT */
7754 keybd_event ((BYTE) vk_code,
7755 (BYTE) MapVirtualKey (vk_code, 0),
7756 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7757 keybd_event ((BYTE) vk_code,
7758 (BYTE) MapVirtualKey (vk_code, 0),
7759 KEYEVENTF_EXTENDEDKEY | 0, 0);
7760 keybd_event ((BYTE) vk_code,
7761 (BYTE) MapVirtualKey (vk_code, 0),
7762 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7763 cur_state = !cur_state;
7766 return cur_state;
7769 /* Translate console modifiers to emacs modifiers.
7770 German keyboard support (Kai Morgan Zeise 2/18/95). */
7772 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
7774 int retval = 0;
7776 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
7777 pressed, first remove those modifiers. */
7778 if (!NILP (Vw32_recognize_altgr)
7779 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7780 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7781 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
7783 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
7784 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
7786 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7788 retval |= ctrl_modifier;
7789 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7790 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7791 retval |= meta_modifier;
7794 if (mods & LEFT_WIN_PRESSED)
7795 retval |= w32_key_to_modifier (VK_LWIN);
7796 if (mods & RIGHT_WIN_PRESSED)
7797 retval |= w32_key_to_modifier (VK_RWIN);
7798 if (mods & APPS_PRESSED)
7799 retval |= w32_key_to_modifier (VK_APPS);
7800 if (mods & SCROLLLOCK_ON)
7801 retval |= w32_key_to_modifier (VK_SCROLL);
7803 /* Just in case someone wanted the original behavior, make it
7804 optional by setting w32-capslock-is-shiftlock to t. */
7805 if (NILP (Vw32_capslock_is_shiftlock)
7806 /* Keys that should _not_ be affected by CapsLock. */
7807 && ( (key == VK_BACK)
7808 || (key == VK_TAB)
7809 || (key == VK_CLEAR)
7810 || (key == VK_RETURN)
7811 || (key == VK_ESCAPE)
7812 || ((key >= VK_SPACE) && (key <= VK_HELP))
7813 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
7814 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
7817 /* Only consider shift state. */
7818 if ((mods & SHIFT_PRESSED) != 0)
7819 retval |= shift_modifier;
7821 else
7823 /* Ignore CapsLock state if not enabled. */
7824 if (NILP (Vw32_enable_caps_lock))
7825 mods &= ~CAPSLOCK_ON;
7826 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
7827 retval |= shift_modifier;
7830 return retval;
7833 /* The return code indicates key code size. cpID is the codepage to
7834 use for translation to Unicode; -1 means use the current console
7835 input codepage. */
7837 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
7839 unsigned int key_code = event->wVirtualKeyCode;
7840 unsigned int mods = event->dwControlKeyState;
7841 BYTE keystate[256];
7842 static BYTE ansi_code[4];
7843 static int isdead = 0;
7845 if (isdead == 2)
7847 event->uChar.AsciiChar = ansi_code[2];
7848 isdead = 0;
7849 return 1;
7851 if (event->uChar.AsciiChar != 0)
7852 return 1;
7854 memset (keystate, 0, sizeof (keystate));
7855 keystate[key_code] = 0x80;
7856 if (mods & SHIFT_PRESSED)
7857 keystate[VK_SHIFT] = 0x80;
7858 if (mods & CAPSLOCK_ON)
7859 keystate[VK_CAPITAL] = 1;
7860 /* If we recognize right-alt and left-ctrl as AltGr, set the key
7861 states accordingly before invoking ToAscii. */
7862 if (!NILP (Vw32_recognize_altgr)
7863 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
7865 keystate[VK_CONTROL] = 0x80;
7866 keystate[VK_LCONTROL] = 0x80;
7867 keystate[VK_MENU] = 0x80;
7868 keystate[VK_RMENU] = 0x80;
7871 #if 0
7872 /* Because of an OS bug, ToAscii corrupts the stack when called to
7873 convert a dead key in console mode on NT4. Unfortunately, trying
7874 to check for dead keys using MapVirtualKey doesn't work either -
7875 these functions apparently use internal information about keyboard
7876 layout which doesn't get properly updated in console programs when
7877 changing layout (though apparently it gets partly updated,
7878 otherwise ToAscii wouldn't crash). */
7879 if (is_dead_key (event->wVirtualKeyCode))
7880 return 0;
7881 #endif
7883 /* On NT, call ToUnicode instead and then convert to the current
7884 console input codepage. */
7885 if (os_subtype == OS_NT)
7887 WCHAR buf[128];
7889 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
7890 keystate, buf, 128, 0);
7891 if (isdead > 0)
7893 /* When we are called from the GUI message processing code,
7894 we are passed the current keyboard codepage, a positive
7895 number, to use below. */
7896 if (cpId == -1)
7897 cpId = GetConsoleCP ();
7899 event->uChar.UnicodeChar = buf[isdead - 1];
7900 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
7901 ansi_code, 4, NULL, NULL);
7903 else
7904 isdead = 0;
7906 else
7908 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
7909 keystate, (LPWORD) ansi_code, 0);
7912 if (isdead == 0)
7913 return 0;
7914 event->uChar.AsciiChar = ansi_code[0];
7915 return isdead;
7919 void
7920 w32_sys_ring_bell (struct frame *f)
7922 if (sound_type == 0xFFFFFFFF)
7924 Beep (666, 100);
7926 else if (sound_type == MB_EMACS_SILENT)
7928 /* Do nothing. */
7930 else
7931 MessageBeep (sound_type);
7935 /***********************************************************************
7936 Initialization
7937 ***********************************************************************/
7939 /* Keep this list in the same order as frame_parms in frame.c.
7940 Use 0 for unsupported frame parameters. */
7942 frame_parm_handler w32_frame_parm_handlers[] =
7944 x_set_autoraise,
7945 x_set_autolower,
7946 x_set_background_color,
7947 x_set_border_color,
7948 x_set_border_width,
7949 x_set_cursor_color,
7950 x_set_cursor_type,
7951 x_set_font,
7952 x_set_foreground_color,
7953 x_set_icon_name,
7954 x_set_icon_type,
7955 x_set_internal_border_width,
7956 x_set_right_divider_width,
7957 x_set_bottom_divider_width,
7958 x_set_menu_bar_lines,
7959 x_set_mouse_color,
7960 x_explicitly_set_name,
7961 x_set_scroll_bar_width,
7962 x_set_title,
7963 x_set_unsplittable,
7964 x_set_vertical_scroll_bars,
7965 x_set_visibility,
7966 x_set_tool_bar_lines,
7967 0, /* x_set_scroll_bar_foreground, */
7968 0, /* x_set_scroll_bar_background, */
7969 x_set_screen_gamma,
7970 x_set_line_spacing,
7971 x_set_fringe_width,
7972 x_set_fringe_width,
7973 0, /* x_set_wait_for_wm, */
7974 x_set_fullscreen,
7975 x_set_font_backend,
7976 x_set_alpha,
7977 0, /* x_set_sticky */
7978 0, /* x_set_tool_bar_position */
7981 void
7982 syms_of_w32fns (void)
7984 globals_of_w32fns ();
7985 track_mouse_window = NULL;
7987 w32_visible_system_caret_hwnd = NULL;
7989 DEFSYM (Qsuppress_icon, "suppress-icon");
7990 DEFSYM (Qundefined_color, "undefined-color");
7991 DEFSYM (Qcancel_timer, "cancel-timer");
7992 DEFSYM (Qhyper, "hyper");
7993 DEFSYM (Qsuper, "super");
7994 DEFSYM (Qmeta, "meta");
7995 DEFSYM (Qalt, "alt");
7996 DEFSYM (Qctrl, "ctrl");
7997 DEFSYM (Qcontrol, "control");
7998 DEFSYM (Qshift, "shift");
7999 DEFSYM (Qfont_param, "font-parameter");
8000 DEFSYM (Qgeometry, "geometry");
8001 DEFSYM (Qworkarea, "workarea");
8002 DEFSYM (Qmm_size, "mm-size");
8003 DEFSYM (Qframes, "frames");
8004 /* This is the end of symbol initialization. */
8007 Fput (Qundefined_color, Qerror_conditions,
8008 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8009 Fput (Qundefined_color, Qerror_message,
8010 build_pure_c_string ("Undefined color"));
8012 staticpro (&w32_grabbed_keys);
8013 w32_grabbed_keys = Qnil;
8015 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8016 doc: /* An array of color name mappings for Windows. */);
8017 Vw32_color_map = Qnil;
8019 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8020 doc: /* Non-nil if Alt key presses are passed on to Windows.
8021 When non-nil, for example, Alt pressed and released and then space will
8022 open the System menu. When nil, Emacs processes the Alt key events, and
8023 then silently swallows them. */);
8024 Vw32_pass_alt_to_system = Qnil;
8026 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8027 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8028 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8029 Vw32_alt_is_meta = Qt;
8031 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8032 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8033 w32_quit_key = 0;
8035 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8036 Vw32_pass_lwindow_to_system,
8037 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8039 When non-nil, the Start menu is opened by tapping the key.
8040 If you set this to nil, the left \"Windows\" key is processed by Emacs
8041 according to the value of `w32-lwindow-modifier', which see.
8043 Note that some combinations of the left \"Windows\" key with other keys are
8044 caught by Windows at low level, and so binding them in Emacs will have no
8045 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8046 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8047 the doc string of `w32-phantom-key-code'. */);
8048 Vw32_pass_lwindow_to_system = Qt;
8050 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8051 Vw32_pass_rwindow_to_system,
8052 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8054 When non-nil, the Start menu is opened by tapping the key.
8055 If you set this to nil, the right \"Windows\" key is processed by Emacs
8056 according to the value of `w32-rwindow-modifier', which see.
8058 Note that some combinations of the right \"Windows\" key with other keys are
8059 caught by Windows at low level, and so binding them in Emacs will have no
8060 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8061 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8062 the doc string of `w32-phantom-key-code'. */);
8063 Vw32_pass_rwindow_to_system = Qt;
8065 DEFVAR_LISP ("w32-phantom-key-code",
8066 Vw32_phantom_key_code,
8067 doc: /* Virtual key code used to generate \"phantom\" key presses.
8068 Value is a number between 0 and 255.
8070 Phantom key presses are generated in order to stop the system from
8071 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8072 `w32-pass-rwindow-to-system' is nil. */);
8073 /* Although 255 is technically not a valid key code, it works and
8074 means that this hack won't interfere with any real key code. */
8075 XSETINT (Vw32_phantom_key_code, 255);
8077 DEFVAR_LISP ("w32-enable-num-lock",
8078 Vw32_enable_num_lock,
8079 doc: /* If non-nil, the Num Lock key acts normally.
8080 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8081 Vw32_enable_num_lock = Qt;
8083 DEFVAR_LISP ("w32-enable-caps-lock",
8084 Vw32_enable_caps_lock,
8085 doc: /* If non-nil, the Caps Lock key acts normally.
8086 Set to nil to handle Caps Lock as the `capslock' key. */);
8087 Vw32_enable_caps_lock = Qt;
8089 DEFVAR_LISP ("w32-scroll-lock-modifier",
8090 Vw32_scroll_lock_modifier,
8091 doc: /* Modifier to use for the Scroll Lock ON state.
8092 The value can be hyper, super, meta, alt, control or shift for the
8093 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8094 Any other value will cause the Scroll Lock key to be ignored. */);
8095 Vw32_scroll_lock_modifier = Qnil;
8097 DEFVAR_LISP ("w32-lwindow-modifier",
8098 Vw32_lwindow_modifier,
8099 doc: /* Modifier to use for the left \"Windows\" key.
8100 The value can be hyper, super, meta, alt, control or shift for the
8101 respective modifier, or nil to appear as the `lwindow' key.
8102 Any other value will cause the key to be ignored. */);
8103 Vw32_lwindow_modifier = Qnil;
8105 DEFVAR_LISP ("w32-rwindow-modifier",
8106 Vw32_rwindow_modifier,
8107 doc: /* Modifier to use for the right \"Windows\" key.
8108 The value can be hyper, super, meta, alt, control or shift for the
8109 respective modifier, or nil to appear as the `rwindow' key.
8110 Any other value will cause the key to be ignored. */);
8111 Vw32_rwindow_modifier = Qnil;
8113 DEFVAR_LISP ("w32-apps-modifier",
8114 Vw32_apps_modifier,
8115 doc: /* Modifier to use for the \"Apps\" key.
8116 The value can be hyper, super, meta, alt, control or shift for the
8117 respective modifier, or nil to appear as the `apps' key.
8118 Any other value will cause the key to be ignored. */);
8119 Vw32_apps_modifier = Qnil;
8121 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
8122 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8123 w32_enable_synthesized_fonts = 0;
8125 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
8126 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8127 Vw32_enable_palette = Qt;
8129 DEFVAR_INT ("w32-mouse-button-tolerance",
8130 w32_mouse_button_tolerance,
8131 doc: /* Analogue of double click interval for faking middle mouse events.
8132 The value is the minimum time in milliseconds that must elapse between
8133 left and right button down events before they are considered distinct events.
8134 If both mouse buttons are depressed within this interval, a middle mouse
8135 button down event is generated instead. */);
8136 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8138 DEFVAR_INT ("w32-mouse-move-interval",
8139 w32_mouse_move_interval,
8140 doc: /* Minimum interval between mouse move events.
8141 The value is the minimum time in milliseconds that must elapse between
8142 successive mouse move (or scroll bar drag) events before they are
8143 reported as lisp events. */);
8144 w32_mouse_move_interval = 0;
8146 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8147 w32_pass_extra_mouse_buttons_to_system,
8148 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8149 Recent versions of Windows support mice with up to five buttons.
8150 Since most applications don't support these extra buttons, most mouse
8151 drivers will allow you to map them to functions at the system level.
8152 If this variable is non-nil, Emacs will pass them on, allowing the
8153 system to handle them. */);
8154 w32_pass_extra_mouse_buttons_to_system = 0;
8156 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8157 w32_pass_multimedia_buttons_to_system,
8158 doc: /* If non-nil, media buttons are passed to Windows.
8159 Some modern keyboards contain buttons for controlling media players, web
8160 browsers and other applications. Generally these buttons are handled on a
8161 system wide basis, but by setting this to nil they are made available
8162 to Emacs for binding. Depending on your keyboard, additional keys that
8163 may be available are:
8165 browser-back, browser-forward, browser-refresh, browser-stop,
8166 browser-search, browser-favorites, browser-home,
8167 mail, mail-reply, mail-forward, mail-send,
8168 app-1, app-2,
8169 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8170 spell-check, correction-list, toggle-dictate-command,
8171 media-next, media-previous, media-stop, media-play-pause, media-select,
8172 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8173 media-channel-up, media-channel-down,
8174 volume-mute, volume-up, volume-down,
8175 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8176 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8177 w32_pass_multimedia_buttons_to_system = 1;
8179 #if 0 /* TODO: Mouse cursor customization. */
8180 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
8181 doc: /* The shape of the pointer when over text.
8182 Changing the value does not affect existing frames
8183 unless you set the mouse color. */);
8184 Vx_pointer_shape = Qnil;
8186 Vx_nontext_pointer_shape = Qnil;
8188 Vx_mode_pointer_shape = Qnil;
8190 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
8191 doc: /* The shape of the pointer when Emacs is busy.
8192 This variable takes effect when you create a new frame
8193 or when you set the mouse color. */);
8194 Vx_hourglass_pointer_shape = Qnil;
8196 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8197 Vx_sensitive_text_pointer_shape,
8198 doc: /* The shape of the pointer when over mouse-sensitive text.
8199 This variable takes effect when you create a new frame
8200 or when you set the mouse color. */);
8201 Vx_sensitive_text_pointer_shape = Qnil;
8203 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8204 Vx_window_horizontal_drag_shape,
8205 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8206 This variable takes effect when you create a new frame
8207 or when you set the mouse color. */);
8208 Vx_window_horizontal_drag_shape = Qnil;
8210 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8211 Vx_window_vertical_drag_shape,
8212 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8213 This variable takes effect when you create a new frame
8214 or when you set the mouse color. */);
8215 Vx_window_vertical_drag_shape = Qnil;
8216 #endif
8218 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
8219 doc: /* A string indicating the foreground color of the cursor box. */);
8220 Vx_cursor_fore_pixel = Qnil;
8222 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
8223 doc: /* Maximum size for tooltips.
8224 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8225 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8227 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
8228 doc: /* Non-nil if no window manager is in use.
8229 Emacs doesn't try to figure this out; this is always nil
8230 unless you set it to something else. */);
8231 /* We don't have any way to find this out, so set it to nil
8232 and maybe the user would like to set it to t. */
8233 Vx_no_window_manager = Qnil;
8235 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8236 Vx_pixel_size_width_font_regexp,
8237 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8239 Since Emacs gets width of a font matching with this regexp from
8240 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8241 such a font. This is especially effective for such large fonts as
8242 Chinese, Japanese, and Korean. */);
8243 Vx_pixel_size_width_font_regexp = Qnil;
8245 DEFVAR_LISP ("w32-bdf-filename-alist",
8246 Vw32_bdf_filename_alist,
8247 doc: /* List of bdf fonts and their corresponding filenames. */);
8248 Vw32_bdf_filename_alist = Qnil;
8250 DEFVAR_BOOL ("w32-strict-fontnames",
8251 w32_strict_fontnames,
8252 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8253 Default is nil, which allows old fontnames that are not XLFD compliant,
8254 and allows third-party CJK display to work by specifying false charset
8255 fields to trick Emacs into translating to Big5, SJIS etc.
8256 Setting this to t will prevent wrong fonts being selected when
8257 fontsets are automatically created. */);
8258 w32_strict_fontnames = 0;
8260 DEFVAR_BOOL ("w32-strict-painting",
8261 w32_strict_painting,
8262 doc: /* Non-nil means use strict rules for repainting frames.
8263 Set this to nil to get the old behavior for repainting; this should
8264 only be necessary if the default setting causes problems. */);
8265 w32_strict_painting = 1;
8267 #if 0 /* TODO: Port to W32 */
8268 defsubr (&Sx_change_window_property);
8269 defsubr (&Sx_delete_window_property);
8270 defsubr (&Sx_window_property);
8271 #endif
8272 defsubr (&Sxw_display_color_p);
8273 defsubr (&Sx_display_grayscale_p);
8274 defsubr (&Sxw_color_defined_p);
8275 defsubr (&Sxw_color_values);
8276 defsubr (&Sx_server_max_request_size);
8277 defsubr (&Sx_server_vendor);
8278 defsubr (&Sx_server_version);
8279 defsubr (&Sx_display_pixel_width);
8280 defsubr (&Sx_display_pixel_height);
8281 defsubr (&Sx_display_mm_width);
8282 defsubr (&Sx_display_mm_height);
8283 defsubr (&Sx_display_screens);
8284 defsubr (&Sx_display_planes);
8285 defsubr (&Sx_display_color_cells);
8286 defsubr (&Sx_display_visual_class);
8287 defsubr (&Sx_display_backing_store);
8288 defsubr (&Sx_display_save_under);
8289 defsubr (&Sx_create_frame);
8290 defsubr (&Sx_open_connection);
8291 defsubr (&Sx_close_connection);
8292 defsubr (&Sx_display_list);
8293 defsubr (&Sx_synchronize);
8295 /* W32 specific functions */
8297 defsubr (&Sw32_define_rgb_color);
8298 defsubr (&Sw32_default_color_map);
8299 defsubr (&Sw32_display_monitor_attributes_list);
8300 defsubr (&Sw32_send_sys_command);
8301 defsubr (&Sw32_shell_execute);
8302 defsubr (&Sw32_register_hot_key);
8303 defsubr (&Sw32_unregister_hot_key);
8304 defsubr (&Sw32_registered_hot_keys);
8305 defsubr (&Sw32_reconstruct_hot_key);
8306 defsubr (&Sw32_toggle_lock_key);
8307 defsubr (&Sw32_window_exists_p);
8308 defsubr (&Sw32_frame_rect);
8309 defsubr (&Sw32_battery_status);
8311 #ifdef WINDOWSNT
8312 defsubr (&Sfile_system_info);
8313 defsubr (&Sdefault_printer_name);
8314 #endif
8316 defsubr (&Sset_message_beep);
8318 hourglass_hwnd = NULL;
8320 defsubr (&Sx_show_tip);
8321 defsubr (&Sx_hide_tip);
8322 tip_timer = Qnil;
8323 staticpro (&tip_timer);
8324 tip_frame = Qnil;
8325 staticpro (&tip_frame);
8327 last_show_tip_args = Qnil;
8328 staticpro (&last_show_tip_args);
8330 defsubr (&Sx_file_dialog);
8331 #ifdef WINDOWSNT
8332 defsubr (&Ssystem_move_file_to_trash);
8333 #endif
8338 /* Crashing and reporting backtrace. */
8340 #ifndef CYGWIN
8341 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8342 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8343 #endif
8344 static DWORD except_code;
8345 static PVOID except_addr;
8347 #ifndef CYGWIN
8348 /* This handler records the exception code and the address where it
8349 was triggered so that this info could be included in the backtrace.
8350 Without that, the backtrace in some cases has no information
8351 whatsoever about the offending code, and looks as if the top-level
8352 exception handler in the MinGW startup code di the one that
8353 crashed. */
8354 static LONG CALLBACK
8355 my_exception_handler (EXCEPTION_POINTERS * exception_data)
8357 except_code = exception_data->ExceptionRecord->ExceptionCode;
8358 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8360 if (prev_exception_handler)
8361 return prev_exception_handler (exception_data);
8362 return EXCEPTION_EXECUTE_HANDLER;
8364 #endif
8366 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8367 PULONG);
8369 #define BACKTRACE_LIMIT_MAX 62
8372 w32_backtrace (void **buffer, int limit)
8374 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8375 HMODULE hm_kernel32 = NULL;
8377 if (!s_pfn_CaptureStackBackTrace)
8379 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8380 s_pfn_CaptureStackBackTrace =
8381 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8382 "RtlCaptureStackBackTrace");
8384 if (s_pfn_CaptureStackBackTrace)
8385 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8386 buffer, NULL);
8387 return 0;
8390 void
8391 emacs_abort (void)
8393 int button;
8394 button = MessageBox (NULL,
8395 "A fatal error has occurred!\n\n"
8396 "Would you like to attach a debugger?\n\n"
8397 "Select:\n"
8398 "YES -- to debug Emacs, or\n"
8399 "NO -- to abort Emacs and produce a backtrace\n"
8400 " (emacs_backtrace.txt in current directory)."
8401 #if __GNUC__
8402 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8403 "\"continue\" inside GDB before clicking YES.)"
8404 #endif
8405 , "Emacs Abort Dialog",
8406 MB_ICONEXCLAMATION | MB_TASKMODAL
8407 | MB_SETFOREGROUND | MB_YESNO);
8408 switch (button)
8410 case IDYES:
8411 DebugBreak ();
8412 exit (2); /* tell the compiler we will never return */
8413 case IDNO:
8414 default:
8416 void *stack[BACKTRACE_LIMIT_MAX + 1];
8417 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8419 if (i)
8421 int errfile_fd = -1;
8422 int j;
8423 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
8424 /* The type below should really be 'void *', but
8425 INT_BUFSIZE_BOUND cannot handle that without
8426 triggering compiler warnings (under certain
8427 pedantic warning switches), it wants an
8428 integer type. */
8429 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
8430 #ifdef CYGWIN
8431 int stderr_fd = 2;
8432 #else
8433 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
8434 int stderr_fd = -1;
8436 if (errout && errout != INVALID_HANDLE_VALUE)
8437 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
8438 #endif
8440 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8441 but not on Windows 7. addr2line doesn't mind a missing
8442 "0x", but will be confused by an extra one. */
8443 if (except_addr)
8444 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8445 except_code, except_addr);
8446 if (stderr_fd >= 0)
8448 if (except_addr)
8449 write (stderr_fd, buf, strlen (buf));
8450 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8452 #ifdef CYGWIN
8453 #define _open open
8454 #endif
8455 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8456 if (errfile_fd >= 0)
8458 lseek (errfile_fd, 0L, SEEK_END);
8459 if (except_addr)
8460 write (errfile_fd, buf, strlen (buf));
8461 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8464 for (j = 0; j < i; j++)
8466 /* stack[] gives the return addresses, whereas we want
8467 the address of the call, so decrease each address
8468 by approximate size of 1 CALL instruction. */
8469 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
8470 if (stderr_fd >= 0)
8471 write (stderr_fd, buf, strlen (buf));
8472 if (errfile_fd >= 0)
8473 write (errfile_fd, buf, strlen (buf));
8475 if (i == BACKTRACE_LIMIT_MAX)
8477 if (stderr_fd >= 0)
8478 write (stderr_fd, "...\r\n", 5);
8479 if (errfile_fd >= 0)
8480 write (errfile_fd, "...\r\n", 5);
8482 if (errfile_fd >= 0)
8483 close (errfile_fd);
8485 abort ();
8486 break;
8493 /* Initialization. */
8496 globals_of_w32fns is used to initialize those global variables that
8497 must always be initialized on startup even when the global variable
8498 initialized is non zero (see the function main in emacs.c).
8499 globals_of_w32fns is called from syms_of_w32fns when the global
8500 variable initialized is 0 and directly from main when initialized
8501 is non zero.
8503 void
8504 globals_of_w32fns (void)
8506 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8508 TrackMouseEvent not available in all versions of Windows, so must load
8509 it dynamically. Do it once, here, instead of every time it is used.
8511 track_mouse_event_fn = (TrackMouseEvent_Proc)
8512 GetProcAddress (user32_lib, "TrackMouseEvent");
8514 monitor_from_point_fn = (MonitorFromPoint_Proc)
8515 GetProcAddress (user32_lib, "MonitorFromPoint");
8516 get_monitor_info_fn = (GetMonitorInfo_Proc)
8517 GetProcAddress (user32_lib, "GetMonitorInfoA");
8518 monitor_from_window_fn = (MonitorFromWindow_Proc)
8519 GetProcAddress (user32_lib, "MonitorFromWindow");
8520 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8521 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8524 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8525 get_composition_string_fn = (ImmGetCompositionString_Proc)
8526 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8527 get_ime_context_fn = (ImmGetContext_Proc)
8528 GetProcAddress (imm32_lib, "ImmGetContext");
8529 release_ime_context_fn = (ImmReleaseContext_Proc)
8530 GetProcAddress (imm32_lib, "ImmReleaseContext");
8531 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8532 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8535 except_code = 0;
8536 except_addr = 0;
8537 #ifndef CYGWIN
8538 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8539 #endif
8541 DEFVAR_INT ("w32-ansi-code-page",
8542 w32_ansi_code_page,
8543 doc: /* The ANSI code page used by the system. */);
8544 w32_ansi_code_page = GetACP ();
8546 if (os_subtype == OS_NT)
8547 w32_unicode_gui = 1;
8548 else
8549 w32_unicode_gui = 0;
8551 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8552 InitCommonControls ();
8554 syms_of_w32uniscribe ();
8557 #ifdef NTGUI_UNICODE
8559 Lisp_Object
8560 ntgui_encode_system (Lisp_Object str)
8562 Lisp_Object encoded;
8563 to_unicode (str, &encoded);
8564 return encoded;
8567 #endif /* NTGUI_UNICODE */