Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / src / w32fns.c
blob3d300d7e5df61df4564cbbd1a91d4330af0b36f4
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2014 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Added by Kevin Gallo */
22 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <math.h>
29 #include <fcntl.h>
30 #include <unistd.h>
32 #include "lisp.h"
33 #include "w32term.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "character.h"
37 #include "buffer.h"
38 #include "intervals.h"
39 #include "dispextern.h"
40 #include "keyboard.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "charset.h"
44 #include "coding.h"
45 #include "ccl.h"
46 #include "fontset.h"
47 #include "systime.h"
48 #include "termhooks.h"
50 #include "w32common.h"
52 #ifdef WINDOWSNT
53 #include "w32heap.h"
54 #include <mbstring.h>
55 #endif /* WINDOWSNT */
57 #if CYGWIN
58 #include "cygw32.h"
59 #else
60 #include "w32.h"
61 #endif
63 #include "bitmaps/gray.xbm"
65 #include <commctrl.h>
66 #include <commdlg.h>
67 #include <shellapi.h>
68 #include <ctype.h>
69 #include <winspool.h>
70 #include <objbase.h>
72 #include <dlgs.h>
73 #include <imm.h>
75 #include "font.h"
76 #include "w32font.h"
78 #ifndef FOF_NO_CONNECTED_ELEMENTS
79 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
80 #endif
82 void syms_of_w32fns (void);
83 void globals_of_w32fns (void);
85 extern void free_frame_menubar (struct frame *);
86 extern int w32_console_toggle_lock_key (int, Lisp_Object);
87 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
88 extern void w32_free_menu_strings (HWND);
89 extern const char *map_w32_filename (const char *, const char **);
90 extern char * w32_strerror (int error_no);
92 /* 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. Note: The
1687 calculations below and the subsequent call to resize_frame_windows
1688 are inherently flawed because they can make the toolbar higher than
1689 the containing frame. */
1690 if (delta > 0)
1692 root_height = WINDOW_PIXEL_HEIGHT (XWINDOW (FRAME_ROOT_WINDOW (f)));
1693 if (root_height - delta < unit)
1695 delta = root_height - unit;
1696 /* When creating a new frame and toolbar mode is enabled, we
1697 need at least one toolbar line. */
1698 nlines = max (FRAME_TOOL_BAR_LINES (f) + delta / unit, 1);
1702 FRAME_TOOL_BAR_LINES (f) = nlines;
1703 FRAME_TOOL_BAR_HEIGHT (f) = nlines * FRAME_LINE_HEIGHT (f);
1704 ++windows_or_buffers_changed;
1705 resize_frame_windows (f, FRAME_TEXT_HEIGHT (f), 0, 1);
1706 adjust_frame_glyphs (f);
1708 /* We also have to make sure that the internal border at the top of
1709 the frame, below the menu bar or tool bar, is redrawn when the
1710 tool bar disappears. This is so because the internal border is
1711 below the tool bar if one is displayed, but is below the menu bar
1712 if there isn't a tool bar. The tool bar draws into the area
1713 below the menu bar. */
1714 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1716 clear_frame (f);
1717 clear_current_matrices (f);
1720 /* If the tool bar gets smaller, the internal border below it
1721 has to be cleared. It was formerly part of the display
1722 of the larger tool bar, and updating windows won't clear it. */
1723 if (delta < 0)
1725 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1726 int width = FRAME_PIXEL_WIDTH (f);
1727 int y = nlines * unit;
1729 block_input ();
1731 HDC hdc = get_frame_dc (f);
1732 w32_clear_area (f, hdc, 0, y, width, height);
1733 release_frame_dc (f, hdc);
1735 unblock_input ();
1737 if (WINDOWP (f->tool_bar_window))
1738 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1741 run_window_configuration_change_hook (f);
1746 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1747 w32_id_name.
1749 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1750 name; if NAME is a string, set F's name to NAME and set
1751 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1753 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1754 suggesting a new name, which lisp code should override; if
1755 F->explicit_name is set, ignore the new name; otherwise, set it. */
1757 void
1758 x_set_name (struct frame *f, Lisp_Object name, int explicit)
1760 /* Make sure that requests from lisp code override requests from
1761 Emacs redisplay code. */
1762 if (explicit)
1764 /* If we're switching from explicit to implicit, we had better
1765 update the mode lines and thereby update the title. */
1766 if (f->explicit_name && NILP (name))
1767 update_mode_lines = 25;
1769 f->explicit_name = ! NILP (name);
1771 else if (f->explicit_name)
1772 return;
1774 /* If NAME is nil, set the name to the w32_id_name. */
1775 if (NILP (name))
1777 /* Check for no change needed in this very common case
1778 before we do any consing. */
1779 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1780 SDATA (f->name)))
1781 return;
1782 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1784 else
1785 CHECK_STRING (name);
1787 /* Don't change the name if it's already NAME. */
1788 if (! NILP (Fstring_equal (name, f->name)))
1789 return;
1791 fset_name (f, name);
1793 /* For setting the frame title, the title parameter should override
1794 the name parameter. */
1795 if (! NILP (f->title))
1796 name = f->title;
1798 if (FRAME_W32_WINDOW (f))
1800 block_input ();
1801 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1802 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1803 unblock_input ();
1807 /* This function should be called when the user's lisp code has
1808 specified a name for the frame; the name will override any set by the
1809 redisplay code. */
1810 void
1811 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1813 x_set_name (f, arg, 1);
1816 /* This function should be called by Emacs redisplay code to set the
1817 name; names set this way will never override names set by the user's
1818 lisp code. */
1819 void
1820 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1822 x_set_name (f, arg, 0);
1825 /* Change the title of frame F to NAME.
1826 If NAME is nil, use the frame name as the title. */
1828 void
1829 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1831 /* Don't change the title if it's already NAME. */
1832 if (EQ (name, f->title))
1833 return;
1835 update_mode_lines = 26;
1837 fset_title (f, name);
1839 if (NILP (name))
1840 name = f->name;
1842 if (FRAME_W32_WINDOW (f))
1844 block_input ();
1845 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1846 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1847 unblock_input ();
1851 void
1852 x_set_scroll_bar_default_width (struct frame *f)
1854 int wid = FRAME_COLUMN_WIDTH (f);
1856 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1857 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
1858 wid - 1) / wid;
1862 /* Subroutines for creating a frame. */
1864 Cursor
1865 w32_load_cursor (LPCTSTR name)
1867 /* Try first to load cursor from application resource. */
1868 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1869 name, IMAGE_CURSOR, 0, 0,
1870 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1871 if (!cursor)
1873 /* Then try to load a shared predefined cursor. */
1874 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1875 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1877 return cursor;
1880 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1882 #define INIT_WINDOW_CLASS(WC) \
1883 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1884 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1885 (WC).cbClsExtra = 0; \
1886 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1887 (WC).hInstance = hinst; \
1888 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1889 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1890 (WC).hbrBackground = NULL; \
1891 (WC).lpszMenuName = NULL; \
1893 static BOOL
1894 w32_init_class (HINSTANCE hinst)
1896 if (w32_unicode_gui)
1898 WNDCLASSW uwc;
1899 INIT_WINDOW_CLASS(uwc);
1900 uwc.lpszClassName = L"Emacs";
1902 return RegisterClassW (&uwc);
1904 else
1906 WNDCLASS wc;
1907 INIT_WINDOW_CLASS(wc);
1908 wc.lpszClassName = EMACS_CLASS;
1910 return RegisterClassA (&wc);
1914 static HWND
1915 w32_createscrollbar (struct frame *f, struct scroll_bar * bar)
1917 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1918 /* Position and size of scroll bar. */
1919 bar->left, bar->top, bar->width, bar->height,
1920 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1923 static void
1924 w32_createwindow (struct frame *f)
1926 HWND hwnd;
1927 RECT rect;
1928 Lisp_Object top = Qunbound;
1929 Lisp_Object left = Qunbound;
1930 struct w32_display_info *dpyinfo = &one_w32_display_info;
1932 rect.left = rect.top = 0;
1933 rect.right = FRAME_PIXEL_WIDTH (f);
1934 rect.bottom = FRAME_PIXEL_HEIGHT (f);
1936 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
1937 FRAME_EXTERNAL_MENU_BAR (f));
1939 /* Do first time app init */
1941 w32_init_class (hinst);
1943 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
1945 XSETINT (left, f->left_pos);
1946 XSETINT (top, f->top_pos);
1948 else if (EQ (left, Qunbound) && EQ (top, Qunbound))
1950 /* When called with RES_TYPE_NUMBER, w32_get_arg will return zero
1951 for anything that is not a number and is not Qunbound. */
1952 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
1953 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
1956 FRAME_W32_WINDOW (f) = hwnd
1957 = CreateWindow (EMACS_CLASS,
1958 f->namebuf,
1959 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
1960 EQ (left, Qunbound) ? CW_USEDEFAULT : XINT (left),
1961 EQ (top, Qunbound) ? CW_USEDEFAULT : XINT (top),
1962 rect.right - rect.left,
1963 rect.bottom - rect.top,
1964 NULL,
1965 NULL,
1966 hinst,
1967 NULL);
1969 if (hwnd)
1971 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
1972 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
1973 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
1974 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
1975 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
1977 /* Enable drag-n-drop. */
1978 DragAcceptFiles (hwnd, TRUE);
1980 /* Do this to discard the default setting specified by our parent. */
1981 ShowWindow (hwnd, SW_HIDE);
1983 /* Update frame positions. */
1984 GetWindowRect (hwnd, &rect);
1985 f->left_pos = rect.left;
1986 f->top_pos = rect.top;
1990 static void
1991 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1993 wmsg->msg.hwnd = hwnd;
1994 wmsg->msg.message = msg;
1995 wmsg->msg.wParam = wParam;
1996 wmsg->msg.lParam = lParam;
1997 wmsg->msg.time = GetMessageTime ();
1999 post_msg (wmsg);
2002 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2003 between left and right keys as advertised. We test for this
2004 support dynamically, and set a flag when the support is absent. If
2005 absent, we keep track of the left and right control and alt keys
2006 ourselves. This is particularly necessary on keyboards that rely
2007 upon the AltGr key, which is represented as having the left control
2008 and right alt keys pressed. For these keyboards, we need to know
2009 when the left alt key has been pressed in addition to the AltGr key
2010 so that we can properly support M-AltGr-key sequences (such as M-@
2011 on Swedish keyboards). */
2013 #define EMACS_LCONTROL 0
2014 #define EMACS_RCONTROL 1
2015 #define EMACS_LMENU 2
2016 #define EMACS_RMENU 3
2018 static int modifiers[4];
2019 static int modifiers_recorded;
2020 static int modifier_key_support_tested;
2022 static void
2023 test_modifier_support (unsigned int wparam)
2025 unsigned int l, r;
2027 if (wparam != VK_CONTROL && wparam != VK_MENU)
2028 return;
2029 if (wparam == VK_CONTROL)
2031 l = VK_LCONTROL;
2032 r = VK_RCONTROL;
2034 else
2036 l = VK_LMENU;
2037 r = VK_RMENU;
2039 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2040 modifiers_recorded = 1;
2041 else
2042 modifiers_recorded = 0;
2043 modifier_key_support_tested = 1;
2046 static void
2047 record_keydown (unsigned int wparam, unsigned int lparam)
2049 int i;
2051 if (!modifier_key_support_tested)
2052 test_modifier_support (wparam);
2054 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2055 return;
2057 if (wparam == VK_CONTROL)
2058 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2059 else
2060 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2062 modifiers[i] = 1;
2065 static void
2066 record_keyup (unsigned int wparam, unsigned int lparam)
2068 int i;
2070 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2071 return;
2073 if (wparam == VK_CONTROL)
2074 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2075 else
2076 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2078 modifiers[i] = 0;
2081 /* Emacs can lose focus while a modifier key has been pressed. When
2082 it regains focus, be conservative and clear all modifiers since
2083 we cannot reconstruct the left and right modifier state. */
2084 static void
2085 reset_modifiers (void)
2087 SHORT ctrl, alt;
2089 if (GetFocus () == NULL)
2090 /* Emacs doesn't have keyboard focus. Do nothing. */
2091 return;
2093 ctrl = GetAsyncKeyState (VK_CONTROL);
2094 alt = GetAsyncKeyState (VK_MENU);
2096 if (!(ctrl & 0x08000))
2097 /* Clear any recorded control modifier state. */
2098 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2100 if (!(alt & 0x08000))
2101 /* Clear any recorded alt modifier state. */
2102 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2104 /* Update the state of all modifier keys, because modifiers used in
2105 hot-key combinations can get stuck on if Emacs loses focus as a
2106 result of a hot-key being pressed. */
2108 BYTE keystate[256];
2110 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2112 GetKeyboardState (keystate);
2113 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2114 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2115 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2116 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2117 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2118 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2119 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2120 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2121 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2122 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2123 SetKeyboardState (keystate);
2127 /* Synchronize modifier state with what is reported with the current
2128 keystroke. Even if we cannot distinguish between left and right
2129 modifier keys, we know that, if no modifiers are set, then neither
2130 the left or right modifier should be set. */
2131 static void
2132 sync_modifiers (void)
2134 if (!modifiers_recorded)
2135 return;
2137 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2138 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2140 if (!(GetKeyState (VK_MENU) & 0x8000))
2141 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2144 static int
2145 modifier_set (int vkey)
2147 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2148 toggle keys is not an omission! If you want to add it, you will
2149 have to make changes in the default sub-case of the WM_KEYDOWN
2150 switch, because if the NUMLOCK modifier is set, the code there
2151 will directly convert any key that looks like an ASCII letter,
2152 and also downcase those that look like upper-case ASCII. */
2153 if (vkey == VK_CAPITAL)
2155 if (NILP (Vw32_enable_caps_lock))
2156 return 0;
2157 else
2158 return (GetKeyState (vkey) & 0x1);
2160 if (vkey == VK_SCROLL)
2162 if (NILP (Vw32_scroll_lock_modifier)
2163 /* w32-scroll-lock-modifier can be any non-nil value that is
2164 not one of the modifiers, in which case it shall be ignored. */
2165 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2166 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2167 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2168 || EQ (Vw32_scroll_lock_modifier, Qalt)
2169 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2170 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2171 return 0;
2172 else
2173 return (GetKeyState (vkey) & 0x1);
2176 if (!modifiers_recorded)
2177 return (GetKeyState (vkey) & 0x8000);
2179 switch (vkey)
2181 case VK_LCONTROL:
2182 return modifiers[EMACS_LCONTROL];
2183 case VK_RCONTROL:
2184 return modifiers[EMACS_RCONTROL];
2185 case VK_LMENU:
2186 return modifiers[EMACS_LMENU];
2187 case VK_RMENU:
2188 return modifiers[EMACS_RMENU];
2190 return (GetKeyState (vkey) & 0x8000);
2193 /* Convert between the modifier bits W32 uses and the modifier bits
2194 Emacs uses. */
2196 unsigned int
2197 w32_key_to_modifier (int key)
2199 Lisp_Object key_mapping;
2201 switch (key)
2203 case VK_LWIN:
2204 key_mapping = Vw32_lwindow_modifier;
2205 break;
2206 case VK_RWIN:
2207 key_mapping = Vw32_rwindow_modifier;
2208 break;
2209 case VK_APPS:
2210 key_mapping = Vw32_apps_modifier;
2211 break;
2212 case VK_SCROLL:
2213 key_mapping = Vw32_scroll_lock_modifier;
2214 break;
2215 default:
2216 key_mapping = Qnil;
2219 /* NB. This code runs in the input thread, asynchronously to the lisp
2220 thread, so we must be careful to ensure access to lisp data is
2221 thread-safe. The following code is safe because the modifier
2222 variable values are updated atomically from lisp and symbols are
2223 not relocated by GC. Also, we don't have to worry about seeing GC
2224 markbits here. */
2225 if (EQ (key_mapping, Qhyper))
2226 return hyper_modifier;
2227 if (EQ (key_mapping, Qsuper))
2228 return super_modifier;
2229 if (EQ (key_mapping, Qmeta))
2230 return meta_modifier;
2231 if (EQ (key_mapping, Qalt))
2232 return alt_modifier;
2233 if (EQ (key_mapping, Qctrl))
2234 return ctrl_modifier;
2235 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2236 return ctrl_modifier;
2237 if (EQ (key_mapping, Qshift))
2238 return shift_modifier;
2240 /* Don't generate any modifier if not explicitly requested. */
2241 return 0;
2244 static unsigned int
2245 w32_get_modifiers (void)
2247 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2248 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2249 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2250 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2251 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2252 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2253 (modifier_set (VK_MENU) ?
2254 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2257 /* We map the VK_* modifiers into console modifier constants
2258 so that we can use the same routines to handle both console
2259 and window input. */
2261 static int
2262 construct_console_modifiers (void)
2264 int mods;
2266 mods = 0;
2267 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2268 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2269 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2270 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2271 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2272 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2273 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2274 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2275 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2276 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2277 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2279 return mods;
2282 static int
2283 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2285 int mods;
2287 /* Convert to emacs modifiers. */
2288 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2290 return mods;
2293 unsigned int
2294 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2296 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2297 return virt_key;
2299 if (virt_key == VK_RETURN)
2300 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2302 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2303 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2305 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2306 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2308 if (virt_key == VK_CLEAR)
2309 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2311 return virt_key;
2314 /* List of special key combinations which w32 would normally capture,
2315 but Emacs should grab instead. Not directly visible to lisp, to
2316 simplify synchronization. Each item is an integer encoding a virtual
2317 key code and modifier combination to capture. */
2318 static Lisp_Object w32_grabbed_keys;
2320 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2321 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2322 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2323 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2325 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2326 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2327 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2329 /* Register hot-keys for reserved key combinations when Emacs has
2330 keyboard focus, since this is the only way Emacs can receive key
2331 combinations like Alt-Tab which are used by the system. */
2333 static void
2334 register_hot_keys (HWND hwnd)
2336 Lisp_Object keylist;
2338 /* Use CONSP, since we are called asynchronously. */
2339 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2341 Lisp_Object key = XCAR (keylist);
2343 /* Deleted entries get set to nil. */
2344 if (!INTEGERP (key))
2345 continue;
2347 RegisterHotKey (hwnd, HOTKEY_ID (key),
2348 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2352 static void
2353 unregister_hot_keys (HWND hwnd)
2355 Lisp_Object keylist;
2357 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2359 Lisp_Object key = XCAR (keylist);
2361 if (!INTEGERP (key))
2362 continue;
2364 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2368 #if EMACSDEBUG
2369 const char*
2370 w32_name_of_message (UINT msg)
2372 unsigned i;
2373 static char buf[64];
2374 static const struct {
2375 UINT msg;
2376 const char* name;
2377 } msgnames[] = {
2378 #define M(msg) { msg, # msg }
2379 M (WM_PAINT),
2380 M (WM_TIMER),
2381 M (WM_USER),
2382 M (WM_MOUSEMOVE),
2383 M (WM_LBUTTONUP),
2384 M (WM_KEYDOWN),
2385 M (WM_EMACS_KILL),
2386 M (WM_EMACS_CREATEWINDOW),
2387 M (WM_EMACS_DONE),
2388 M (WM_EMACS_CREATESCROLLBAR),
2389 M (WM_EMACS_SHOWWINDOW),
2390 M (WM_EMACS_SETWINDOWPOS),
2391 M (WM_EMACS_DESTROYWINDOW),
2392 M (WM_EMACS_TRACKPOPUPMENU),
2393 M (WM_EMACS_SETFOCUS),
2394 M (WM_EMACS_SETFOREGROUND),
2395 M (WM_EMACS_SETLOCALE),
2396 M (WM_EMACS_SETKEYBOARDLAYOUT),
2397 M (WM_EMACS_REGISTER_HOT_KEY),
2398 M (WM_EMACS_UNREGISTER_HOT_KEY),
2399 M (WM_EMACS_TOGGLE_LOCK_KEY),
2400 M (WM_EMACS_TRACK_CARET),
2401 M (WM_EMACS_DESTROY_CARET),
2402 M (WM_EMACS_SHOW_CARET),
2403 M (WM_EMACS_HIDE_CARET),
2404 M (WM_EMACS_SETCURSOR),
2405 M (WM_EMACS_PAINT),
2406 M (WM_CHAR),
2407 #undef M
2408 { 0, 0 }
2411 for (i = 0; msgnames[i].name; ++i)
2412 if (msgnames[i].msg == msg)
2413 return msgnames[i].name;
2415 sprintf (buf, "message 0x%04x", (unsigned)msg);
2416 return buf;
2418 #endif /* EMACSDEBUG */
2420 /* Here's an overview of how Emacs input works in GUI sessions on
2421 MS-Windows. (For description of non-GUI input, see the commentary
2422 before w32_console_read_socket in w32inevt.c.)
2424 System messages are read and processed by w32_msg_pump below. This
2425 function runs in a separate thread. It handles a small number of
2426 custom WM_EMACS_* messages (posted by the main thread, look for
2427 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2428 is the main window procedure for the entire Emacs application.
2430 w32_wnd_proc also runs in the same separate input thread. It
2431 handles some messages, mostly those that need GDI calls, by itself.
2432 For the others, it calls my_post_msg, which inserts the messages
2433 into the input queue serviced by w32_read_socket.
2435 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2436 called synchronously from keyboard.c when it is known or suspected
2437 that some input is available. w32_read_socket either handles
2438 messages immediately, or converts them into Emacs input events and
2439 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2440 them and process them when read_char and its callers require
2441 input.
2443 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2444 select(2) takes the place of w32_read_socket.
2448 /* Main message dispatch loop. */
2450 static void
2451 w32_msg_pump (deferred_msg * msg_buf)
2453 MSG msg;
2454 WPARAM result;
2455 HWND focus_window;
2457 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2459 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2462 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2463 /* w32_name_of_message (msg.message), msg.time)); */
2465 if (msg.hwnd == NULL)
2467 switch (msg.message)
2469 case WM_NULL:
2470 /* Produced by complete_deferred_msg; just ignore. */
2471 break;
2472 case WM_EMACS_CREATEWINDOW:
2473 /* Initialize COM for this window. Even though we don't use it,
2474 some third party shell extensions can cause it to be used in
2475 system dialogs, which causes a crash if it is not initialized.
2476 This is a known bug in Windows, which was fixed long ago, but
2477 the patch for XP is not publicly available until XP SP3,
2478 and older versions will never be patched. */
2479 CoInitialize (NULL);
2480 w32_createwindow ((struct frame *) msg.wParam);
2481 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2482 emacs_abort ();
2483 break;
2484 case WM_EMACS_SETLOCALE:
2485 SetThreadLocale (msg.wParam);
2486 /* Reply is not expected. */
2487 break;
2488 case WM_EMACS_SETKEYBOARDLAYOUT:
2489 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2490 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2491 result, 0))
2492 emacs_abort ();
2493 break;
2494 case WM_EMACS_REGISTER_HOT_KEY:
2495 focus_window = GetFocus ();
2496 if (focus_window != NULL)
2497 RegisterHotKey (focus_window,
2498 RAW_HOTKEY_ID (msg.wParam),
2499 RAW_HOTKEY_MODIFIERS (msg.wParam),
2500 RAW_HOTKEY_VK_CODE (msg.wParam));
2501 /* Reply is not expected. */
2502 break;
2503 case WM_EMACS_UNREGISTER_HOT_KEY:
2504 focus_window = GetFocus ();
2505 if (focus_window != NULL)
2506 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2507 /* Mark item as erased. NB: this code must be
2508 thread-safe. The next line is okay because the cons
2509 cell is never made into garbage and is not relocated by
2510 GC. */
2511 XSETCAR (XIL ((EMACS_INT) msg.lParam), Qnil);
2512 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2513 emacs_abort ();
2514 break;
2515 case WM_EMACS_TOGGLE_LOCK_KEY:
2517 int vk_code = (int) msg.wParam;
2518 int cur_state = (GetKeyState (vk_code) & 1);
2519 Lisp_Object new_state = XIL ((EMACS_INT) msg.lParam);
2521 /* NB: This code must be thread-safe. It is safe to
2522 call NILP because symbols are not relocated by GC,
2523 and pointer here is not touched by GC (so the markbit
2524 can't be set). Numbers are safe because they are
2525 immediate values. */
2526 if (NILP (new_state)
2527 || (NUMBERP (new_state)
2528 && ((XUINT (new_state)) & 1) != cur_state))
2530 one_w32_display_info.faked_key = vk_code;
2532 keybd_event ((BYTE) vk_code,
2533 (BYTE) MapVirtualKey (vk_code, 0),
2534 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2535 keybd_event ((BYTE) vk_code,
2536 (BYTE) MapVirtualKey (vk_code, 0),
2537 KEYEVENTF_EXTENDEDKEY | 0, 0);
2538 keybd_event ((BYTE) vk_code,
2539 (BYTE) MapVirtualKey (vk_code, 0),
2540 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2541 cur_state = !cur_state;
2543 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2544 cur_state, 0))
2545 emacs_abort ();
2547 break;
2548 #ifdef MSG_DEBUG
2549 /* Broadcast messages make it here, so you need to be looking
2550 for something in particular for this to be useful. */
2551 default:
2552 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2553 #endif
2556 else
2558 if (w32_unicode_gui)
2559 DispatchMessageW (&msg);
2560 else
2561 DispatchMessageA (&msg);
2564 /* Exit nested loop when our deferred message has completed. */
2565 if (msg_buf->completed)
2566 break;
2570 deferred_msg * deferred_msg_head;
2572 static deferred_msg *
2573 find_deferred_msg (HWND hwnd, UINT msg)
2575 deferred_msg * item;
2577 /* Don't actually need synchronization for read access, since
2578 modification of single pointer is always atomic. */
2579 /* enter_crit (); */
2581 for (item = deferred_msg_head; item != NULL; item = item->next)
2582 if (item->w32msg.msg.hwnd == hwnd
2583 && item->w32msg.msg.message == msg)
2584 break;
2586 /* leave_crit (); */
2588 return item;
2591 static LRESULT
2592 send_deferred_msg (deferred_msg * msg_buf,
2593 HWND hwnd,
2594 UINT msg,
2595 WPARAM wParam,
2596 LPARAM lParam)
2598 /* Only input thread can send deferred messages. */
2599 if (GetCurrentThreadId () != dwWindowsThreadId)
2600 emacs_abort ();
2602 /* It is an error to send a message that is already deferred. */
2603 if (find_deferred_msg (hwnd, msg) != NULL)
2604 emacs_abort ();
2606 /* Enforced synchronization is not needed because this is the only
2607 function that alters deferred_msg_head, and the following critical
2608 section is guaranteed to only be serially reentered (since only the
2609 input thread can call us). */
2611 /* enter_crit (); */
2613 msg_buf->completed = 0;
2614 msg_buf->next = deferred_msg_head;
2615 deferred_msg_head = msg_buf;
2616 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2618 /* leave_crit (); */
2620 /* Start a new nested message loop to process other messages until
2621 this one is completed. */
2622 w32_msg_pump (msg_buf);
2624 deferred_msg_head = msg_buf->next;
2626 return msg_buf->result;
2629 void
2630 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2632 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2634 if (msg_buf == NULL)
2635 /* Message may have been canceled, so don't abort. */
2636 return;
2638 msg_buf->result = result;
2639 msg_buf->completed = 1;
2641 /* Ensure input thread is woken so it notices the completion. */
2642 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2645 static void
2646 cancel_all_deferred_msgs (void)
2648 deferred_msg * item;
2650 /* Don't actually need synchronization for read access, since
2651 modification of single pointer is always atomic. */
2652 /* enter_crit (); */
2654 for (item = deferred_msg_head; item != NULL; item = item->next)
2656 item->result = 0;
2657 item->completed = 1;
2660 /* leave_crit (); */
2662 /* Ensure input thread is woken so it notices the completion. */
2663 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2666 DWORD WINAPI
2667 w32_msg_worker (void *arg)
2669 MSG msg;
2670 deferred_msg dummy_buf;
2672 /* Ensure our message queue is created */
2674 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2676 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2677 emacs_abort ();
2679 memset (&dummy_buf, 0, sizeof (dummy_buf));
2680 dummy_buf.w32msg.msg.hwnd = NULL;
2681 dummy_buf.w32msg.msg.message = WM_NULL;
2683 /* This is the initial message loop which should only exit when the
2684 application quits. */
2685 w32_msg_pump (&dummy_buf);
2687 return 0;
2690 static void
2691 signal_user_input (void)
2693 /* Interrupt any lisp that wants to be interrupted by input. */
2694 if (!NILP (Vthrow_on_input))
2696 Vquit_flag = Vthrow_on_input;
2697 /* Doing a QUIT from this thread is a bad idea, since this
2698 unwinds the stack of the Lisp thread, and the Windows runtime
2699 rightfully barfs. Disabled. */
2700 #if 0
2701 /* If we're inside a function that wants immediate quits,
2702 do it now. */
2703 if (immediate_quit && NILP (Vinhibit_quit))
2705 immediate_quit = 0;
2706 QUIT;
2708 #endif
2713 static void
2714 post_character_message (HWND hwnd, UINT msg,
2715 WPARAM wParam, LPARAM lParam,
2716 DWORD modifiers)
2718 W32Msg wmsg;
2720 wmsg.dwModifiers = modifiers;
2722 /* Detect quit_char and set quit-flag directly. Note that we
2723 still need to post a message to ensure the main thread will be
2724 woken up if blocked in sys_select, but we do NOT want to post
2725 the quit_char message itself (because it will usually be as if
2726 the user had typed quit_char twice). Instead, we post a dummy
2727 message that has no particular effect. */
2729 int c = wParam;
2730 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2731 c = make_ctrl_char (c) & 0377;
2732 if (c == quit_char
2733 || (wmsg.dwModifiers == 0
2734 && w32_quit_key && wParam == w32_quit_key))
2736 Vquit_flag = Qt;
2738 /* The choice of message is somewhat arbitrary, as long as
2739 the main thread handler just ignores it. */
2740 msg = WM_NULL;
2742 /* Interrupt any blocking system calls. */
2743 signal_quit ();
2745 /* As a safety precaution, forcibly complete any deferred
2746 messages. This is a kludge, but I don't see any particularly
2747 clean way to handle the situation where a deferred message is
2748 "dropped" in the lisp thread, and will thus never be
2749 completed, eg. by the user trying to activate the menubar
2750 when the lisp thread is busy, and then typing C-g when the
2751 menubar doesn't open promptly (with the result that the
2752 menubar never responds at all because the deferred
2753 WM_INITMENU message is never completed). Another problem
2754 situation is when the lisp thread calls SendMessage (to send
2755 a window manager command) when a message has been deferred;
2756 the lisp thread gets blocked indefinitely waiting for the
2757 deferred message to be completed, which itself is waiting for
2758 the lisp thread to respond.
2760 Note that we don't want to block the input thread waiting for
2761 a response from the lisp thread (although that would at least
2762 solve the deadlock problem above), because we want to be able
2763 to receive C-g to interrupt the lisp thread. */
2764 cancel_all_deferred_msgs ();
2766 else
2767 signal_user_input ();
2770 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2773 /* Main window procedure */
2775 static LRESULT CALLBACK
2776 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2778 struct frame *f;
2779 struct w32_display_info *dpyinfo = &one_w32_display_info;
2780 W32Msg wmsg;
2781 int windows_translate;
2782 int key;
2784 /* Note that it is okay to call x_window_to_frame, even though we are
2785 not running in the main lisp thread, because frame deletion
2786 requires the lisp thread to synchronize with this thread. Thus, if
2787 a frame struct is returned, it can be used without concern that the
2788 lisp thread might make it disappear while we are using it.
2790 NB. Walking the frame list in this thread is safe (as long as
2791 writes of Lisp_Object slots are atomic, which they are on Windows).
2792 Although delete-frame can destructively modify the frame list while
2793 we are walking it, a garbage collection cannot occur until after
2794 delete-frame has synchronized with this thread.
2796 It is also safe to use functions that make GDI calls, such as
2797 w32_clear_rect, because these functions must obtain a DC handle
2798 from the frame struct using get_frame_dc which is thread-aware. */
2800 switch (msg)
2802 case WM_ERASEBKGND:
2803 f = x_window_to_frame (dpyinfo, hwnd);
2804 if (f)
2806 HDC hdc = get_frame_dc (f);
2807 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2808 w32_clear_rect (f, hdc, &wmsg.rect);
2809 release_frame_dc (f, hdc);
2811 #if defined (W32_DEBUG_DISPLAY)
2812 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2814 wmsg.rect.left, wmsg.rect.top,
2815 wmsg.rect.right, wmsg.rect.bottom));
2816 #endif /* W32_DEBUG_DISPLAY */
2818 return 1;
2819 case WM_PALETTECHANGED:
2820 /* ignore our own changes */
2821 if ((HWND)wParam != hwnd)
2823 f = x_window_to_frame (dpyinfo, hwnd);
2824 if (f)
2825 /* get_frame_dc will realize our palette and force all
2826 frames to be redrawn if needed. */
2827 release_frame_dc (f, get_frame_dc (f));
2829 return 0;
2830 case WM_PAINT:
2832 PAINTSTRUCT paintStruct;
2833 RECT update_rect;
2834 memset (&update_rect, 0, sizeof (update_rect));
2836 f = x_window_to_frame (dpyinfo, hwnd);
2837 if (f == 0)
2839 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2840 return 0;
2843 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2844 fails. Apparently this can happen under some
2845 circumstances. */
2846 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2848 enter_crit ();
2849 BeginPaint (hwnd, &paintStruct);
2851 /* The rectangles returned by GetUpdateRect and BeginPaint
2852 do not always match. Play it safe by assuming both areas
2853 are invalid. */
2854 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2856 #if defined (W32_DEBUG_DISPLAY)
2857 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2859 wmsg.rect.left, wmsg.rect.top,
2860 wmsg.rect.right, wmsg.rect.bottom));
2861 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2862 update_rect.left, update_rect.top,
2863 update_rect.right, update_rect.bottom));
2864 #endif
2865 EndPaint (hwnd, &paintStruct);
2866 leave_crit ();
2868 /* Change the message type to prevent Windows from
2869 combining WM_PAINT messages in the Lisp thread's queue,
2870 since Windows assumes that each message queue is
2871 dedicated to one frame and does not bother checking
2872 that hwnd matches before combining them. */
2873 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
2875 return 0;
2878 /* If GetUpdateRect returns 0 (meaning there is no update
2879 region), assume the whole window needs to be repainted. */
2880 GetClientRect (hwnd, &wmsg.rect);
2881 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2882 return 0;
2885 case WM_INPUTLANGCHANGE:
2886 /* Inform lisp thread of keyboard layout changes. */
2887 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2889 /* Clear dead keys in the keyboard state; for simplicity only
2890 preserve modifier key states. */
2892 int i;
2893 BYTE keystate[256];
2895 GetKeyboardState (keystate);
2896 for (i = 0; i < 256; i++)
2897 if (1
2898 && i != VK_SHIFT
2899 && i != VK_LSHIFT
2900 && i != VK_RSHIFT
2901 && i != VK_CAPITAL
2902 && i != VK_NUMLOCK
2903 && i != VK_SCROLL
2904 && i != VK_CONTROL
2905 && i != VK_LCONTROL
2906 && i != VK_RCONTROL
2907 && i != VK_MENU
2908 && i != VK_LMENU
2909 && i != VK_RMENU
2910 && i != VK_LWIN
2911 && i != VK_RWIN)
2912 keystate[i] = 0;
2913 SetKeyboardState (keystate);
2915 goto dflt;
2917 case WM_HOTKEY:
2918 /* Synchronize hot keys with normal input. */
2919 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2920 return (0);
2922 case WM_KEYUP:
2923 case WM_SYSKEYUP:
2924 record_keyup (wParam, lParam);
2925 goto dflt;
2927 case WM_KEYDOWN:
2928 case WM_SYSKEYDOWN:
2929 /* Ignore keystrokes we fake ourself; see below. */
2930 if (dpyinfo->faked_key == wParam)
2932 dpyinfo->faked_key = 0;
2933 /* Make sure TranslateMessage sees them though (as long as
2934 they don't produce WM_CHAR messages). This ensures that
2935 indicator lights are toggled promptly on Windows 9x, for
2936 example. */
2937 if (wParam < 256 && lispy_function_keys[wParam])
2939 windows_translate = 1;
2940 goto translate;
2942 return 0;
2945 /* Synchronize modifiers with current keystroke. */
2946 sync_modifiers ();
2947 record_keydown (wParam, lParam);
2948 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2950 windows_translate = 0;
2952 switch (wParam)
2954 case VK_LWIN:
2955 if (NILP (Vw32_pass_lwindow_to_system))
2957 /* Prevent system from acting on keyup (which opens the
2958 Start menu if no other key was pressed) by simulating a
2959 press of Space which we will ignore. */
2960 if (GetAsyncKeyState (wParam) & 1)
2962 if (NUMBERP (Vw32_phantom_key_code))
2963 key = XUINT (Vw32_phantom_key_code) & 255;
2964 else
2965 key = VK_SPACE;
2966 dpyinfo->faked_key = key;
2967 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2970 if (!NILP (Vw32_lwindow_modifier))
2971 return 0;
2972 break;
2973 case VK_RWIN:
2974 if (NILP (Vw32_pass_rwindow_to_system))
2976 if (GetAsyncKeyState (wParam) & 1)
2978 if (NUMBERP (Vw32_phantom_key_code))
2979 key = XUINT (Vw32_phantom_key_code) & 255;
2980 else
2981 key = VK_SPACE;
2982 dpyinfo->faked_key = key;
2983 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2986 if (!NILP (Vw32_rwindow_modifier))
2987 return 0;
2988 break;
2989 case VK_APPS:
2990 if (!NILP (Vw32_apps_modifier))
2991 return 0;
2992 break;
2993 case VK_MENU:
2994 if (NILP (Vw32_pass_alt_to_system))
2995 /* Prevent DefWindowProc from activating the menu bar if an
2996 Alt key is pressed and released by itself. */
2997 return 0;
2998 windows_translate = 1;
2999 break;
3000 case VK_CAPITAL:
3001 /* Decide whether to treat as modifier or function key. */
3002 if (NILP (Vw32_enable_caps_lock))
3003 goto disable_lock_key;
3004 windows_translate = 1;
3005 break;
3006 case VK_NUMLOCK:
3007 /* Decide whether to treat as modifier or function key. */
3008 if (NILP (Vw32_enable_num_lock))
3009 goto disable_lock_key;
3010 windows_translate = 1;
3011 break;
3012 case VK_SCROLL:
3013 /* Decide whether to treat as modifier or function key. */
3014 if (NILP (Vw32_scroll_lock_modifier))
3015 goto disable_lock_key;
3016 windows_translate = 1;
3017 break;
3018 disable_lock_key:
3019 /* Ensure the appropriate lock key state (and indicator light)
3020 remains in the same state. We do this by faking another
3021 press of the relevant key. Apparently, this really is the
3022 only way to toggle the state of the indicator lights. */
3023 dpyinfo->faked_key = wParam;
3024 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3025 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3026 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3027 KEYEVENTF_EXTENDEDKEY | 0, 0);
3028 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3029 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3030 /* Ensure indicator lights are updated promptly on Windows 9x
3031 (TranslateMessage apparently does this), after forwarding
3032 input event. */
3033 post_character_message (hwnd, msg, wParam, lParam,
3034 w32_get_key_modifiers (wParam, lParam));
3035 windows_translate = 1;
3036 break;
3037 case VK_CONTROL:
3038 case VK_SHIFT:
3039 case VK_PROCESSKEY: /* Generated by IME. */
3040 windows_translate = 1;
3041 break;
3042 case VK_CANCEL:
3043 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3044 which is confusing for purposes of key binding; convert
3045 VK_CANCEL events into VK_PAUSE events. */
3046 wParam = VK_PAUSE;
3047 break;
3048 case VK_PAUSE:
3049 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3050 for purposes of key binding; convert these back into
3051 VK_NUMLOCK events, at least when we want to see NumLock key
3052 presses. (Note that there is never any possibility that
3053 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3054 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3055 wParam = VK_NUMLOCK;
3056 break;
3057 default:
3058 /* If not defined as a function key, change it to a WM_CHAR message. */
3059 if (wParam > 255 || !lispy_function_keys[wParam])
3061 DWORD modifiers = construct_console_modifiers ();
3063 if (!NILP (Vw32_recognize_altgr)
3064 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3066 /* Always let TranslateMessage handle AltGr key chords;
3067 for some reason, ToAscii doesn't always process AltGr
3068 chords correctly. */
3069 windows_translate = 1;
3071 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3073 /* Handle key chords including any modifiers other
3074 than shift directly, in order to preserve as much
3075 modifier information as possible. */
3076 if ('A' <= wParam && wParam <= 'Z')
3078 /* Don't translate modified alphabetic keystrokes,
3079 so the user doesn't need to constantly switch
3080 layout to type control or meta keystrokes when
3081 the normal layout translates alphabetic
3082 characters to non-ascii characters. */
3083 if (!modifier_set (VK_SHIFT))
3084 wParam += ('a' - 'A');
3085 msg = WM_CHAR;
3087 else
3089 /* Try to handle other keystrokes by determining the
3090 base character (ie. translating the base key plus
3091 shift modifier). */
3092 int add;
3093 KEY_EVENT_RECORD key;
3095 key.bKeyDown = TRUE;
3096 key.wRepeatCount = 1;
3097 key.wVirtualKeyCode = wParam;
3098 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3099 key.uChar.AsciiChar = 0;
3100 key.dwControlKeyState = modifiers;
3102 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3103 /* 0 means an unrecognized keycode, negative means
3104 dead key. Ignore both. */
3105 while (--add >= 0)
3107 /* Forward asciified character sequence. */
3108 post_character_message
3109 (hwnd, WM_CHAR,
3110 (unsigned char) key.uChar.AsciiChar, lParam,
3111 w32_get_key_modifiers (wParam, lParam));
3112 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3114 return 0;
3117 else
3119 /* Let TranslateMessage handle everything else. */
3120 windows_translate = 1;
3125 translate:
3126 if (windows_translate)
3128 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3129 windows_msg.time = GetMessageTime ();
3130 TranslateMessage (&windows_msg);
3131 goto dflt;
3134 /* Fall through */
3136 case WM_SYSCHAR:
3137 case WM_CHAR:
3138 if (wParam > 255 )
3140 W32Msg wmsg;
3142 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3143 signal_user_input ();
3144 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3147 else
3148 post_character_message (hwnd, msg, wParam, lParam,
3149 w32_get_key_modifiers (wParam, lParam));
3150 break;
3152 case WM_UNICHAR:
3153 /* WM_UNICHAR looks promising from the docs, but the exact
3154 circumstances in which TranslateMessage sends it is one of those
3155 Microsoft secret API things that EU and US courts are supposed
3156 to have put a stop to already. Spy++ shows it being sent to Notepad
3157 and other MS apps, but never to Emacs.
3159 Some third party IMEs send it in accordance with the official
3160 documentation though, so handle it here.
3162 UNICODE_NOCHAR is used to test for support for this message.
3163 TRUE indicates that the message is supported. */
3164 if (wParam == UNICODE_NOCHAR)
3165 return TRUE;
3168 W32Msg wmsg;
3169 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3170 signal_user_input ();
3171 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3173 break;
3175 case WM_IME_CHAR:
3176 /* If we can't get the IME result as Unicode, use default processing,
3177 which will at least allow characters decodable in the system locale
3178 get through. */
3179 if (!get_composition_string_fn)
3180 goto dflt;
3182 else if (!ignore_ime_char)
3184 wchar_t * buffer;
3185 int size, i;
3186 W32Msg wmsg;
3187 HIMC context = get_ime_context_fn (hwnd);
3188 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3189 /* Get buffer size. */
3190 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3191 buffer = alloca (size);
3192 size = get_composition_string_fn (context, GCS_RESULTSTR,
3193 buffer, size);
3194 release_ime_context_fn (hwnd, context);
3196 signal_user_input ();
3197 for (i = 0; i < size / sizeof (wchar_t); i++)
3199 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3200 lParam);
3202 /* Ignore the messages for the rest of the
3203 characters in the string that was output above. */
3204 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3206 else
3207 ignore_ime_char--;
3209 break;
3211 case WM_IME_STARTCOMPOSITION:
3212 if (!set_ime_composition_window_fn)
3213 goto dflt;
3214 else
3216 COMPOSITIONFORM form;
3217 HIMC context;
3218 struct window *w;
3220 /* Implementation note: The code below does something that
3221 one shouldn't do: it accesses the window object from a
3222 separate thread, while the main (a.k.a. "Lisp") thread
3223 runs and can legitimately delete and even GC it. That is
3224 why we are extra careful not to futz with a window that
3225 is different from the one recorded when the system caret
3226 coordinates were last modified. That is also why we are
3227 careful not to move the IME window if the window
3228 described by W was deleted, as indicated by its buffer
3229 field being reset to nil. */
3230 f = x_window_to_frame (dpyinfo, hwnd);
3231 if (!(f && FRAME_LIVE_P (f)))
3232 break;
3233 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3234 /* Punt if someone changed the frame's selected window
3235 behind our back. */
3236 if (w != w32_system_caret_window)
3237 break;
3239 form.dwStyle = CFS_RECT;
3240 form.ptCurrentPos.x = w32_system_caret_x;
3241 form.ptCurrentPos.y = w32_system_caret_y;
3243 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3244 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3245 + w32_system_caret_hdr_height);
3246 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3247 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3248 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3249 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3250 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3251 - w32_system_caret_mode_height);
3253 /* Punt if the window was deleted behind our back. */
3254 if (!BUFFERP (w->contents))
3255 break;
3257 context = get_ime_context_fn (hwnd);
3259 if (!context)
3260 break;
3262 set_ime_composition_window_fn (context, &form);
3263 release_ime_context_fn (hwnd, context);
3265 break;
3267 case WM_IME_ENDCOMPOSITION:
3268 ignore_ime_char = 0;
3269 goto dflt;
3271 /* Simulate middle mouse button events when left and right buttons
3272 are used together, but only if user has two button mouse. */
3273 case WM_LBUTTONDOWN:
3274 case WM_RBUTTONDOWN:
3275 if (w32_num_mouse_buttons > 2)
3276 goto handle_plain_button;
3279 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3280 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3282 if (button_state & this)
3283 return 0;
3285 if (button_state == 0)
3286 SetCapture (hwnd);
3288 button_state |= this;
3290 if (button_state & other)
3292 if (mouse_button_timer)
3294 KillTimer (hwnd, mouse_button_timer);
3295 mouse_button_timer = 0;
3297 /* Generate middle mouse event instead. */
3298 msg = WM_MBUTTONDOWN;
3299 button_state |= MMOUSE;
3301 else if (button_state & MMOUSE)
3303 /* Ignore button event if we've already generated a
3304 middle mouse down event. This happens if the
3305 user releases and press one of the two buttons
3306 after we've faked a middle mouse event. */
3307 return 0;
3309 else
3311 /* Flush out saved message. */
3312 post_msg (&saved_mouse_button_msg);
3314 wmsg.dwModifiers = w32_get_modifiers ();
3315 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3316 signal_user_input ();
3318 /* Clear message buffer. */
3319 saved_mouse_button_msg.msg.hwnd = 0;
3321 else
3323 /* Hold onto message for now. */
3324 mouse_button_timer =
3325 SetTimer (hwnd, MOUSE_BUTTON_ID,
3326 w32_mouse_button_tolerance, NULL);
3327 saved_mouse_button_msg.msg.hwnd = hwnd;
3328 saved_mouse_button_msg.msg.message = msg;
3329 saved_mouse_button_msg.msg.wParam = wParam;
3330 saved_mouse_button_msg.msg.lParam = lParam;
3331 saved_mouse_button_msg.msg.time = GetMessageTime ();
3332 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3335 return 0;
3337 case WM_LBUTTONUP:
3338 case WM_RBUTTONUP:
3339 if (w32_num_mouse_buttons > 2)
3340 goto handle_plain_button;
3343 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3344 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3346 if ((button_state & this) == 0)
3347 return 0;
3349 button_state &= ~this;
3351 if (button_state & MMOUSE)
3353 /* Only generate event when second button is released. */
3354 if ((button_state & other) == 0)
3356 msg = WM_MBUTTONUP;
3357 button_state &= ~MMOUSE;
3359 if (button_state) emacs_abort ();
3361 else
3362 return 0;
3364 else
3366 /* Flush out saved message if necessary. */
3367 if (saved_mouse_button_msg.msg.hwnd)
3369 post_msg (&saved_mouse_button_msg);
3372 wmsg.dwModifiers = w32_get_modifiers ();
3373 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3374 signal_user_input ();
3376 /* Always clear message buffer and cancel timer. */
3377 saved_mouse_button_msg.msg.hwnd = 0;
3378 KillTimer (hwnd, mouse_button_timer);
3379 mouse_button_timer = 0;
3381 if (button_state == 0)
3382 ReleaseCapture ();
3384 return 0;
3386 case WM_XBUTTONDOWN:
3387 case WM_XBUTTONUP:
3388 if (w32_pass_extra_mouse_buttons_to_system)
3389 goto dflt;
3390 /* else fall through and process them. */
3391 case WM_MBUTTONDOWN:
3392 case WM_MBUTTONUP:
3393 handle_plain_button:
3395 BOOL up;
3396 int button;
3398 /* Ignore middle and extra buttons as long as the menu is active. */
3399 f = x_window_to_frame (dpyinfo, hwnd);
3400 if (f && f->output_data.w32->menubar_active)
3401 return 0;
3403 if (parse_button (msg, HIWORD (wParam), &button, &up))
3405 if (up) ReleaseCapture ();
3406 else SetCapture (hwnd);
3407 button = (button == 0) ? LMOUSE :
3408 ((button == 1) ? MMOUSE : RMOUSE);
3409 if (up)
3410 button_state &= ~button;
3411 else
3412 button_state |= button;
3416 wmsg.dwModifiers = w32_get_modifiers ();
3417 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3418 signal_user_input ();
3420 /* Need to return true for XBUTTON messages, false for others,
3421 to indicate that we processed the message. */
3422 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3424 case WM_MOUSEMOVE:
3425 /* Ignore mouse movements as long as the menu is active. These
3426 movements are processed by the window manager anyway, and
3427 it's wrong to handle them as if they happened on the
3428 underlying frame. */
3429 f = x_window_to_frame (dpyinfo, hwnd);
3430 if (f && f->output_data.w32->menubar_active)
3431 return 0;
3433 /* If the mouse has just moved into the frame, start tracking
3434 it, so we will be notified when it leaves the frame. Mouse
3435 tracking only works under W98 and NT4 and later. On earlier
3436 versions, there is no way of telling when the mouse leaves the
3437 frame, so we just have to put up with help-echo and mouse
3438 highlighting remaining while the frame is not active. */
3439 if (track_mouse_event_fn && !track_mouse_window
3440 /* If the menu bar is active, turning on tracking of mouse
3441 movement events might send these events to the tooltip
3442 frame, if the user happens to move the mouse pointer over
3443 the tooltip. But since we don't process events for
3444 tooltip frames, this causes Windows to present a
3445 hourglass cursor, which is ugly and unexpected. So don't
3446 enable tracking mouse events in this case; they will be
3447 restarted when the menu pops down. (Confusingly, the
3448 menubar_active member of f->output_data.w32, tested
3449 above, is only set when a menu was popped up _not_ from
3450 the frame's menu bar, but via x-popup-menu.) */
3451 && !menubar_in_use)
3453 TRACKMOUSEEVENT tme;
3454 tme.cbSize = sizeof (tme);
3455 tme.dwFlags = TME_LEAVE;
3456 tme.hwndTrack = hwnd;
3458 track_mouse_event_fn (&tme);
3459 track_mouse_window = hwnd;
3461 case WM_VSCROLL:
3462 if (w32_mouse_move_interval <= 0
3463 || (msg == WM_MOUSEMOVE && button_state == 0))
3465 wmsg.dwModifiers = w32_get_modifiers ();
3466 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3467 return 0;
3470 /* Hang onto mouse move and scroll messages for a bit, to avoid
3471 sending such events to Emacs faster than it can process them.
3472 If we get more events before the timer from the first message
3473 expires, we just replace the first message. */
3475 if (saved_mouse_move_msg.msg.hwnd == 0)
3476 mouse_move_timer =
3477 SetTimer (hwnd, MOUSE_MOVE_ID,
3478 w32_mouse_move_interval, NULL);
3480 /* Hold onto message for now. */
3481 saved_mouse_move_msg.msg.hwnd = hwnd;
3482 saved_mouse_move_msg.msg.message = msg;
3483 saved_mouse_move_msg.msg.wParam = wParam;
3484 saved_mouse_move_msg.msg.lParam = lParam;
3485 saved_mouse_move_msg.msg.time = GetMessageTime ();
3486 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3488 return 0;
3490 case WM_MOUSEWHEEL:
3491 case WM_DROPFILES:
3492 wmsg.dwModifiers = w32_get_modifiers ();
3493 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3494 signal_user_input ();
3495 return 0;
3497 case WM_APPCOMMAND:
3498 if (w32_pass_multimedia_buttons_to_system)
3499 goto dflt;
3500 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3501 case WM_MOUSEHWHEEL:
3502 wmsg.dwModifiers = w32_get_modifiers ();
3503 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3504 signal_user_input ();
3505 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3506 handled, to prevent the system trying to handle it by faking
3507 scroll bar events. */
3508 return 1;
3510 case WM_TIMER:
3511 /* Flush out saved messages if necessary. */
3512 if (wParam == mouse_button_timer)
3514 if (saved_mouse_button_msg.msg.hwnd)
3516 post_msg (&saved_mouse_button_msg);
3517 signal_user_input ();
3518 saved_mouse_button_msg.msg.hwnd = 0;
3520 KillTimer (hwnd, mouse_button_timer);
3521 mouse_button_timer = 0;
3523 else if (wParam == mouse_move_timer)
3525 if (saved_mouse_move_msg.msg.hwnd)
3527 post_msg (&saved_mouse_move_msg);
3528 saved_mouse_move_msg.msg.hwnd = 0;
3530 KillTimer (hwnd, mouse_move_timer);
3531 mouse_move_timer = 0;
3533 else if (wParam == menu_free_timer)
3535 KillTimer (hwnd, menu_free_timer);
3536 menu_free_timer = 0;
3537 f = x_window_to_frame (dpyinfo, hwnd);
3538 /* If a popup menu is active, don't wipe its strings. */
3539 if (menubar_in_use
3540 && current_popup_menu == NULL)
3542 /* Free memory used by owner-drawn and help-echo strings. */
3543 w32_free_menu_strings (hwnd);
3544 if (f)
3545 f->output_data.w32->menubar_active = 0;
3546 menubar_in_use = 0;
3549 return 0;
3551 case WM_NCACTIVATE:
3552 /* Windows doesn't send us focus messages when putting up and
3553 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3554 The only indication we get that something happened is receiving
3555 this message afterwards. So this is a good time to reset our
3556 keyboard modifiers' state. */
3557 reset_modifiers ();
3558 goto dflt;
3560 case WM_INITMENU:
3561 button_state = 0;
3562 ReleaseCapture ();
3563 /* We must ensure menu bar is fully constructed and up to date
3564 before allowing user interaction with it. To achieve this
3565 we send this message to the lisp thread and wait for a
3566 reply (whose value is not actually needed) to indicate that
3567 the menu bar is now ready for use, so we can now return.
3569 To remain responsive in the meantime, we enter a nested message
3570 loop that can process all other messages.
3572 However, we skip all this if the message results from calling
3573 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3574 thread a message because it is blocked on us at this point. We
3575 set menubar_active before calling TrackPopupMenu to indicate
3576 this (there is no possibility of confusion with real menubar
3577 being active). */
3579 f = x_window_to_frame (dpyinfo, hwnd);
3580 if (f
3581 && (f->output_data.w32->menubar_active
3582 /* We can receive this message even in the absence of a
3583 menubar (ie. when the system menu is activated) - in this
3584 case we do NOT want to forward the message, otherwise it
3585 will cause the menubar to suddenly appear when the user
3586 had requested it to be turned off! */
3587 || f->output_data.w32->menubar_widget == NULL))
3588 return 0;
3591 deferred_msg msg_buf;
3593 /* Detect if message has already been deferred; in this case
3594 we cannot return any sensible value to ignore this. */
3595 if (find_deferred_msg (hwnd, msg) != NULL)
3596 emacs_abort ();
3598 menubar_in_use = 1;
3600 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3603 case WM_EXITMENULOOP:
3604 f = x_window_to_frame (dpyinfo, hwnd);
3606 /* If a menu is still active, check again after a short delay,
3607 since Windows often (always?) sends the WM_EXITMENULOOP
3608 before the corresponding WM_COMMAND message.
3609 Don't do this if a popup menu is active, since it is only
3610 menubar menus that require cleaning up in this way.
3612 if (f && menubar_in_use && current_popup_menu == NULL)
3613 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3615 /* If hourglass cursor should be displayed, display it now. */
3616 if (f && f->output_data.w32->hourglass_p)
3617 SetCursor (f->output_data.w32->hourglass_cursor);
3619 goto dflt;
3621 case WM_MENUSELECT:
3622 /* Direct handling of help_echo in menus. Should be safe now
3623 that we generate the help_echo by placing a help event in the
3624 keyboard buffer. */
3626 HMENU menu = (HMENU) lParam;
3627 UINT menu_item = (UINT) LOWORD (wParam);
3628 UINT flags = (UINT) HIWORD (wParam);
3630 w32_menu_display_help (hwnd, menu, menu_item, flags);
3632 return 0;
3634 case WM_MEASUREITEM:
3635 f = x_window_to_frame (dpyinfo, hwnd);
3636 if (f)
3638 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3640 if (pMis->CtlType == ODT_MENU)
3642 /* Work out dimensions for popup menu titles. */
3643 char * title = (char *) pMis->itemData;
3644 HDC hdc = GetDC (hwnd);
3645 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3646 LOGFONT menu_logfont;
3647 HFONT old_font;
3648 SIZE size;
3650 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3651 menu_logfont.lfWeight = FW_BOLD;
3652 menu_font = CreateFontIndirect (&menu_logfont);
3653 old_font = SelectObject (hdc, menu_font);
3655 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3656 if (title)
3658 if (unicode_append_menu)
3659 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3660 wcslen ((WCHAR *) title),
3661 &size);
3662 else
3663 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3665 pMis->itemWidth = size.cx;
3666 if (pMis->itemHeight < size.cy)
3667 pMis->itemHeight = size.cy;
3669 else
3670 pMis->itemWidth = 0;
3672 SelectObject (hdc, old_font);
3673 DeleteObject (menu_font);
3674 ReleaseDC (hwnd, hdc);
3675 return TRUE;
3678 return 0;
3680 case WM_DRAWITEM:
3681 f = x_window_to_frame (dpyinfo, hwnd);
3682 if (f)
3684 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3686 if (pDis->CtlType == ODT_MENU)
3688 /* Draw popup menu title. */
3689 char * title = (char *) pDis->itemData;
3690 if (title)
3692 HDC hdc = pDis->hDC;
3693 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3694 LOGFONT menu_logfont;
3695 HFONT old_font;
3697 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3698 menu_logfont.lfWeight = FW_BOLD;
3699 menu_font = CreateFontIndirect (&menu_logfont);
3700 old_font = SelectObject (hdc, menu_font);
3702 /* Always draw title as if not selected. */
3703 if (unicode_append_menu)
3704 ExtTextOutW (hdc,
3705 pDis->rcItem.left
3706 + GetSystemMetrics (SM_CXMENUCHECK),
3707 pDis->rcItem.top,
3708 ETO_OPAQUE, &pDis->rcItem,
3709 (WCHAR *) title,
3710 wcslen ((WCHAR *) title), NULL);
3711 else
3712 ExtTextOut (hdc,
3713 pDis->rcItem.left
3714 + GetSystemMetrics (SM_CXMENUCHECK),
3715 pDis->rcItem.top,
3716 ETO_OPAQUE, &pDis->rcItem,
3717 title, strlen (title), NULL);
3719 SelectObject (hdc, old_font);
3720 DeleteObject (menu_font);
3722 return TRUE;
3725 return 0;
3727 #if 0
3728 /* Still not right - can't distinguish between clicks in the
3729 client area of the frame from clicks forwarded from the scroll
3730 bars - may have to hook WM_NCHITTEST to remember the mouse
3731 position and then check if it is in the client area ourselves. */
3732 case WM_MOUSEACTIVATE:
3733 /* Discard the mouse click that activates a frame, allowing the
3734 user to click anywhere without changing point (or worse!).
3735 Don't eat mouse clicks on scrollbars though!! */
3736 if (LOWORD (lParam) == HTCLIENT )
3737 return MA_ACTIVATEANDEAT;
3738 goto dflt;
3739 #endif
3741 case WM_MOUSELEAVE:
3742 /* No longer tracking mouse. */
3743 track_mouse_window = NULL;
3745 case WM_ACTIVATEAPP:
3746 case WM_ACTIVATE:
3747 case WM_WINDOWPOSCHANGED:
3748 case WM_SHOWWINDOW:
3749 /* Inform lisp thread that a frame might have just been obscured
3750 or exposed, so should recheck visibility of all frames. */
3751 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3752 goto dflt;
3754 case WM_SETFOCUS:
3755 dpyinfo->faked_key = 0;
3756 reset_modifiers ();
3757 register_hot_keys (hwnd);
3758 goto command;
3759 case WM_KILLFOCUS:
3760 unregister_hot_keys (hwnd);
3761 button_state = 0;
3762 ReleaseCapture ();
3763 /* Relinquish the system caret. */
3764 if (w32_system_caret_hwnd)
3766 w32_visible_system_caret_hwnd = NULL;
3767 w32_system_caret_hwnd = NULL;
3768 DestroyCaret ();
3770 goto command;
3771 case WM_COMMAND:
3772 menubar_in_use = 0;
3773 f = x_window_to_frame (dpyinfo, hwnd);
3774 if (f && HIWORD (wParam) == 0)
3776 if (menu_free_timer)
3778 KillTimer (hwnd, menu_free_timer);
3779 menu_free_timer = 0;
3782 case WM_MOVE:
3783 case WM_SIZE:
3784 command:
3785 wmsg.dwModifiers = w32_get_modifiers ();
3786 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3787 goto dflt;
3789 case WM_DESTROY:
3790 CoUninitialize ();
3791 return 0;
3793 case WM_CLOSE:
3794 wmsg.dwModifiers = w32_get_modifiers ();
3795 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3796 return 0;
3798 case WM_WINDOWPOSCHANGING:
3799 /* Don't restrict the sizing of tip frames. */
3800 if (frame_resize_pixelwise || hwnd == tip_window)
3801 return 0;
3803 /* Don't restrict the sizing of fullscreened frames, allowing them to be
3804 flush with the sides of the screen. */
3805 f = x_window_to_frame (dpyinfo, hwnd);
3806 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
3807 return 0;
3810 WINDOWPLACEMENT wp;
3811 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3813 wp.length = sizeof (WINDOWPLACEMENT);
3814 GetWindowPlacement (hwnd, &wp);
3816 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
3818 RECT rect;
3819 int wdiff;
3820 int hdiff;
3821 DWORD font_width;
3822 DWORD line_height;
3823 DWORD internal_border;
3824 DWORD scrollbar_extra;
3825 RECT wr;
3827 wp.length = sizeof (wp);
3828 GetWindowRect (hwnd, &wr);
3830 enter_crit ();
3832 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3833 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3834 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3835 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3837 leave_crit ();
3839 memset (&rect, 0, sizeof (rect));
3840 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3841 GetMenu (hwnd) != NULL);
3843 /* Force width and height of client area to be exact
3844 multiples of the character cell dimensions. */
3845 wdiff = (lppos->cx - (rect.right - rect.left)
3846 - 2 * internal_border - scrollbar_extra)
3847 % font_width;
3848 hdiff = (lppos->cy - (rect.bottom - rect.top)
3849 - 2 * internal_border)
3850 % line_height;
3852 if (wdiff || hdiff)
3854 /* For right/bottom sizing we can just fix the sizes.
3855 However for top/left sizing we will need to fix the X
3856 and Y positions as well. */
3858 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3859 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3861 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3862 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3864 if (wp.showCmd != SW_SHOWMAXIMIZED
3865 && (lppos->flags & SWP_NOMOVE) == 0)
3867 if (lppos->x != wr.left || lppos->y != wr.top)
3869 lppos->x += wdiff;
3870 lppos->y += hdiff;
3872 else
3874 lppos->flags |= SWP_NOMOVE;
3878 return 0;
3883 goto dflt;
3885 case WM_GETMINMAXINFO:
3886 /* Hack to allow resizing the Emacs frame above the screen size.
3887 Note that Windows 9x limits coordinates to 16-bits. */
3888 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3889 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3890 return 0;
3892 case WM_SETCURSOR:
3893 if (LOWORD (lParam) == HTCLIENT)
3895 f = x_window_to_frame (dpyinfo, hwnd);
3896 if (f && f->output_data.w32->hourglass_p
3897 && !menubar_in_use && !current_popup_menu)
3898 SetCursor (f->output_data.w32->hourglass_cursor);
3899 else if (f)
3900 SetCursor (f->output_data.w32->current_cursor);
3901 return 0;
3903 goto dflt;
3905 case WM_EMACS_SETCURSOR:
3907 Cursor cursor = (Cursor) wParam;
3908 f = x_window_to_frame (dpyinfo, hwnd);
3909 if (f && cursor)
3911 f->output_data.w32->current_cursor = cursor;
3912 if (!f->output_data.w32->hourglass_p)
3913 SetCursor (cursor);
3915 return 0;
3918 case WM_EMACS_CREATESCROLLBAR:
3919 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3920 (struct scroll_bar *) lParam);
3922 case WM_EMACS_SHOWWINDOW:
3923 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3925 case WM_EMACS_BRINGTOTOP:
3926 case WM_EMACS_SETFOREGROUND:
3928 HWND foreground_window;
3929 DWORD foreground_thread, retval;
3931 /* On NT 5.0, and apparently Windows 98, it is necessary to
3932 attach to the thread that currently has focus in order to
3933 pull the focus away from it. */
3934 foreground_window = GetForegroundWindow ();
3935 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3936 if (!foreground_window
3937 || foreground_thread == GetCurrentThreadId ()
3938 || !AttachThreadInput (GetCurrentThreadId (),
3939 foreground_thread, TRUE))
3940 foreground_thread = 0;
3942 retval = SetForegroundWindow ((HWND) wParam);
3943 if (msg == WM_EMACS_BRINGTOTOP)
3944 retval = BringWindowToTop ((HWND) wParam);
3946 /* Detach from the previous foreground thread. */
3947 if (foreground_thread)
3948 AttachThreadInput (GetCurrentThreadId (),
3949 foreground_thread, FALSE);
3951 return retval;
3954 case WM_EMACS_SETWINDOWPOS:
3956 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3957 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3958 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3961 case WM_EMACS_DESTROYWINDOW:
3962 DragAcceptFiles ((HWND) wParam, FALSE);
3963 return DestroyWindow ((HWND) wParam);
3965 case WM_EMACS_HIDE_CARET:
3966 return HideCaret (hwnd);
3968 case WM_EMACS_SHOW_CARET:
3969 return ShowCaret (hwnd);
3971 case WM_EMACS_DESTROY_CARET:
3972 w32_system_caret_hwnd = NULL;
3973 w32_visible_system_caret_hwnd = NULL;
3974 return DestroyCaret ();
3976 case WM_EMACS_TRACK_CARET:
3977 /* If there is currently no system caret, create one. */
3978 if (w32_system_caret_hwnd == NULL)
3980 /* Use the default caret width, and avoid changing it
3981 unnecessarily, as it confuses screen reader software. */
3982 w32_system_caret_hwnd = hwnd;
3983 CreateCaret (hwnd, NULL, 0,
3984 w32_system_caret_height);
3987 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3988 return 0;
3989 /* Ensure visible caret gets turned on when requested. */
3990 else if (w32_use_visible_system_caret
3991 && w32_visible_system_caret_hwnd != hwnd)
3993 w32_visible_system_caret_hwnd = hwnd;
3994 return ShowCaret (hwnd);
3996 /* Ensure visible caret gets turned off when requested. */
3997 else if (!w32_use_visible_system_caret
3998 && w32_visible_system_caret_hwnd)
4000 w32_visible_system_caret_hwnd = NULL;
4001 return HideCaret (hwnd);
4003 else
4004 return 1;
4006 case WM_EMACS_TRACKPOPUPMENU:
4008 UINT flags;
4009 POINT *pos;
4010 int retval;
4011 pos = (POINT *)lParam;
4012 flags = TPM_CENTERALIGN;
4013 if (button_state & LMOUSE)
4014 flags |= TPM_LEFTBUTTON;
4015 else if (button_state & RMOUSE)
4016 flags |= TPM_RIGHTBUTTON;
4018 /* Remember we did a SetCapture on the initial mouse down event,
4019 so for safety, we make sure the capture is canceled now. */
4020 ReleaseCapture ();
4021 button_state = 0;
4023 /* Use menubar_active to indicate that WM_INITMENU is from
4024 TrackPopupMenu below, and should be ignored. */
4025 f = x_window_to_frame (dpyinfo, hwnd);
4026 if (f)
4027 f->output_data.w32->menubar_active = 1;
4029 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4030 0, hwnd, NULL))
4032 MSG amsg;
4033 /* Eat any mouse messages during popupmenu */
4034 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4035 PM_REMOVE));
4036 /* Get the menu selection, if any */
4037 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4039 retval = LOWORD (amsg.wParam);
4041 else
4043 retval = 0;
4046 else
4048 retval = -1;
4051 return retval;
4053 case WM_EMACS_FILENOTIFY:
4054 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4055 return 1;
4057 default:
4058 /* Check for messages registered at runtime. */
4059 if (msg == msh_mousewheel)
4061 wmsg.dwModifiers = w32_get_modifiers ();
4062 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4063 signal_user_input ();
4064 return 0;
4067 dflt:
4068 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4071 /* The most common default return code for handled messages is 0. */
4072 return 0;
4075 static void
4076 my_create_window (struct frame * f)
4078 MSG msg;
4080 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4081 emacs_abort ();
4082 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4086 /* Create a tooltip window. Unlike my_create_window, we do not do this
4087 indirectly via the Window thread, as we do not need to process Window
4088 messages for the tooltip. Creating tooltips indirectly also creates
4089 deadlocks when tooltips are created for menu items. */
4090 static void
4091 my_create_tip_window (struct frame *f)
4093 RECT rect;
4095 rect.left = rect.top = 0;
4096 rect.right = FRAME_PIXEL_WIDTH (f);
4097 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4099 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4100 FRAME_EXTERNAL_MENU_BAR (f));
4102 tip_window = FRAME_W32_WINDOW (f)
4103 = CreateWindow (EMACS_CLASS,
4104 f->namebuf,
4105 f->output_data.w32->dwStyle,
4106 f->left_pos,
4107 f->top_pos,
4108 rect.right - rect.left,
4109 rect.bottom - rect.top,
4110 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4111 NULL,
4112 hinst,
4113 NULL);
4115 if (tip_window)
4117 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4118 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4119 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4120 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4122 /* Tip frames have no scrollbars. */
4123 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
4125 /* Do this to discard the default setting specified by our parent. */
4126 ShowWindow (tip_window, SW_HIDE);
4131 /* Create and set up the w32 window for frame F. */
4133 static void
4134 w32_window (struct frame *f, long window_prompting, int minibuffer_only)
4136 block_input ();
4138 /* Use the resource name as the top-level window name
4139 for looking up resources. Make a non-Lisp copy
4140 for the window manager, so GC relocation won't bother it.
4142 Elsewhere we specify the window name for the window manager. */
4143 f->namebuf = xstrdup (SSDATA (Vx_resource_name));
4145 my_create_window (f);
4147 validate_x_resource_name ();
4149 /* x_set_name normally ignores requests to set the name if the
4150 requested name is the same as the current name. This is the one
4151 place where that assumption isn't correct; f->name is set, but
4152 the server hasn't been told. */
4154 Lisp_Object name;
4155 int explicit = f->explicit_name;
4157 f->explicit_name = 0;
4158 name = f->name;
4159 fset_name (f, Qnil);
4160 x_set_name (f, name, explicit);
4163 unblock_input ();
4165 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4166 initialize_frame_menubar (f);
4168 if (FRAME_W32_WINDOW (f) == 0)
4169 error ("Unable to create window");
4172 /* Handle the icon stuff for this window. Perhaps later we might
4173 want an x_set_icon_position which can be called interactively as
4174 well. */
4176 static void
4177 x_icon (struct frame *f, Lisp_Object parms)
4179 Lisp_Object icon_x, icon_y;
4180 struct w32_display_info *dpyinfo = &one_w32_display_info;
4182 /* Set the position of the icon. Note that Windows 95 groups all
4183 icons in the tray. */
4184 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4185 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4186 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4188 CHECK_NUMBER (icon_x);
4189 CHECK_NUMBER (icon_y);
4191 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4192 error ("Both left and top icon corners of icon must be specified");
4194 block_input ();
4196 #if 0 /* TODO */
4197 /* Start up iconic or window? */
4198 x_wm_set_window_state
4199 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4200 ? IconicState
4201 : NormalState));
4203 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4204 ? f->icon_name
4205 : f->name)));
4206 #endif
4208 unblock_input ();
4212 static void
4213 x_make_gc (struct frame *f)
4215 XGCValues gc_values;
4217 block_input ();
4219 /* Create the GC's of this frame.
4220 Note that many default values are used. */
4222 /* Normal video */
4223 gc_values.font = FRAME_FONT (f);
4225 /* Cursor has cursor-color background, background-color foreground. */
4226 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4227 gc_values.background = f->output_data.w32->cursor_pixel;
4228 f->output_data.w32->cursor_gc
4229 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4230 (GCFont | GCForeground | GCBackground),
4231 &gc_values);
4233 /* Reliefs. */
4234 f->output_data.w32->white_relief.gc = 0;
4235 f->output_data.w32->black_relief.gc = 0;
4237 unblock_input ();
4241 /* Handler for signals raised during x_create_frame and
4242 x_create_tip_frame. FRAME is the frame which is partially
4243 constructed. */
4245 static Lisp_Object
4246 unwind_create_frame (Lisp_Object frame)
4248 struct frame *f = XFRAME (frame);
4250 /* If frame is ``official'', nothing to do. */
4251 if (NILP (Fmemq (frame, Vframe_list)))
4253 #ifdef GLYPH_DEBUG
4254 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4255 #endif
4257 x_free_frame_resources (f);
4258 free_glyphs (f);
4260 #ifdef GLYPH_DEBUG
4261 /* Check that reference counts are indeed correct. */
4262 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4263 eassert (dpyinfo->terminal->image_cache->refcount == image_cache_refcount);
4264 #endif
4265 return Qt;
4268 return Qnil;
4271 static void
4272 do_unwind_create_frame (Lisp_Object frame)
4274 unwind_create_frame (frame);
4277 static void
4278 unwind_create_frame_1 (Lisp_Object val)
4280 inhibit_lisp_code = val;
4283 static void
4284 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4286 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4287 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4288 RES_TYPE_STRING);
4289 Lisp_Object font;
4290 if (EQ (font_param, Qunbound))
4291 font_param = Qnil;
4292 font = !NILP (font_param) ? font_param
4293 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4295 if (!STRINGP (font))
4297 int i;
4298 static char *names[]
4299 = { "Courier New-10",
4300 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4301 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4302 "Fixedsys",
4303 NULL };
4305 for (i = 0; names[i]; i++)
4307 font = font_open_by_name (f, build_unibyte_string (names[i]));
4308 if (! NILP (font))
4309 break;
4311 if (NILP (font))
4312 error ("No suitable font was found");
4314 else if (!NILP (font_param))
4316 /* Remember the explicit font parameter, so we can re-apply it after
4317 we've applied the `default' face settings. */
4318 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4320 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4323 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4324 1, 1, 0,
4325 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4326 Return an Emacs frame object.
4327 PARAMETERS is an alist of frame parameters.
4328 If the parameters specify that the frame should not have a minibuffer,
4329 and do not specify a specific minibuffer window to use,
4330 then `default-minibuffer-frame' must be a frame whose minibuffer can
4331 be shared by the new frame.
4333 This function is an internal primitive--use `make-frame' instead. */)
4334 (Lisp_Object parameters)
4336 struct frame *f;
4337 Lisp_Object frame, tem;
4338 Lisp_Object name;
4339 int minibuffer_only = 0;
4340 long window_prompting = 0;
4341 int width, height;
4342 ptrdiff_t count = SPECPDL_INDEX ();
4343 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4344 Lisp_Object display;
4345 struct w32_display_info *dpyinfo = NULL;
4346 Lisp_Object parent;
4347 struct kboard *kb;
4349 if (!FRAME_W32_P (SELECTED_FRAME ())
4350 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4351 error ("Cannot create a GUI frame in a -nw session");
4353 /* Make copy of frame parameters because the original is in pure
4354 storage now. */
4355 parameters = Fcopy_alist (parameters);
4357 /* Use this general default value to start with
4358 until we know if this frame has a specified name. */
4359 Vx_resource_name = Vinvocation_name;
4361 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4362 if (EQ (display, Qunbound))
4363 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4364 if (EQ (display, Qunbound))
4365 display = Qnil;
4366 dpyinfo = check_x_display_info (display);
4367 kb = dpyinfo->terminal->kboard;
4369 if (!dpyinfo->terminal->name)
4370 error ("Terminal is not live, can't create new frames on it");
4372 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4373 if (!STRINGP (name)
4374 && ! EQ (name, Qunbound)
4375 && ! NILP (name))
4376 error ("Invalid frame name--not a string or nil");
4378 if (STRINGP (name))
4379 Vx_resource_name = name;
4381 /* See if parent window is specified. */
4382 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4383 if (EQ (parent, Qunbound))
4384 parent = Qnil;
4385 if (! NILP (parent))
4386 CHECK_NUMBER (parent);
4388 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4389 /* No need to protect DISPLAY because that's not used after passing
4390 it to make_frame_without_minibuffer. */
4391 frame = Qnil;
4392 GCPRO4 (parameters, parent, name, frame);
4393 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
4394 RES_TYPE_SYMBOL);
4395 if (EQ (tem, Qnone) || NILP (tem))
4396 f = make_frame_without_minibuffer (Qnil, kb, display);
4397 else if (EQ (tem, Qonly))
4399 f = make_minibuffer_frame ();
4400 minibuffer_only = 1;
4402 else if (WINDOWP (tem))
4403 f = make_frame_without_minibuffer (tem, kb, display);
4404 else
4405 f = make_frame (1);
4407 XSETFRAME (frame, f);
4409 /* By default, make scrollbars the system standard width. */
4410 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4412 f->terminal = dpyinfo->terminal;
4414 f->output_method = output_w32;
4415 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
4416 FRAME_FONTSET (f) = -1;
4418 fset_icon_name
4419 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
4420 RES_TYPE_STRING));
4421 if (! STRINGP (f->icon_name))
4422 fset_icon_name (f, Qnil);
4424 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
4426 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
4427 record_unwind_protect (do_unwind_create_frame, frame);
4429 /* Avoid calling window-configuration-change-hook; otherwise we could
4430 get into all kinds of nasty things like an infloop in next_frame or
4431 violating a (height >= 0) assertion in window_box_height. */
4432 record_unwind_protect (unwind_create_frame_1, inhibit_lisp_code);
4433 inhibit_lisp_code = Qt;
4435 #ifdef GLYPH_DEBUG
4436 image_cache_refcount =
4437 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
4438 dpyinfo_refcount = dpyinfo->reference_count;
4439 #endif /* GLYPH_DEBUG */
4441 /* Specify the parent under which to make this window. */
4443 if (!NILP (parent))
4445 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4446 f->output_data.w32->explicit_parent = 1;
4448 else
4450 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4451 f->output_data.w32->explicit_parent = 0;
4454 /* Set the name; the functions to which we pass f expect the name to
4455 be set. */
4456 if (EQ (name, Qunbound) || NILP (name))
4458 fset_name (f, build_string (dpyinfo->w32_id_name));
4459 f->explicit_name = 0;
4461 else
4463 fset_name (f, name);
4464 f->explicit_name = 1;
4465 /* use the frame's title when getting resources for this frame. */
4466 specbind (Qx_resource_name, name);
4469 if (uniscribe_available)
4470 register_font_driver (&uniscribe_font_driver, f);
4471 register_font_driver (&w32font_driver, f);
4473 x_default_parameter (f, parameters, Qfont_backend, Qnil,
4474 "fontBackend", "FontBackend", RES_TYPE_STRING);
4475 /* Extract the window parameters from the supplied values
4476 that are needed to determine window geometry. */
4477 x_default_font_parameter (f, parameters);
4478 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4479 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4481 /* We recognize either internalBorderWidth or internalBorder
4482 (which is what xterm calls it). */
4483 if (NILP (Fassq (Qinternal_border_width, parameters)))
4485 Lisp_Object value;
4487 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
4488 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4489 if (! EQ (value, Qunbound))
4490 parameters = Fcons (Fcons (Qinternal_border_width, value),
4491 parameters);
4493 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4494 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4495 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4496 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
4497 NULL, NULL, RES_TYPE_NUMBER);
4498 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
4499 NULL, NULL, RES_TYPE_NUMBER);
4500 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4501 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4503 /* Also do the stuff which must be set before the window exists. */
4504 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4505 "foreground", "Foreground", RES_TYPE_STRING);
4506 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4507 "background", "Background", RES_TYPE_STRING);
4508 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4509 "pointerColor", "Foreground", RES_TYPE_STRING);
4510 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4511 "borderColor", "BorderColor", RES_TYPE_STRING);
4512 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4513 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4514 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4515 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4516 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4517 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4518 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4519 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4521 /* Init faces before x_default_parameter is called for scroll-bar
4522 parameters because that function calls x_set_scroll_bar_width,
4523 which calls change_frame_size, which calls Fset_window_buffer,
4524 which runs hooks, which call Fvertical_motion. At the end, we
4525 end up in init_iterator with a null face cache, which should not
4526 happen. */
4527 init_frame_faces (f);
4529 /* The X resources controlling the menu-bar and tool-bar are
4530 processed specially at startup, and reflected in the mode
4531 variables; ignore them here. */
4532 x_default_parameter (f, parameters, Qmenu_bar_lines,
4533 NILP (Vmenu_bar_mode)
4534 ? make_number (0) : make_number (1),
4535 NULL, NULL, RES_TYPE_NUMBER);
4536 x_default_parameter (f, parameters, Qtool_bar_lines,
4537 NILP (Vtool_bar_mode)
4538 ? make_number (0) : make_number (1),
4539 NULL, NULL, RES_TYPE_NUMBER);
4541 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4542 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4543 x_default_parameter (f, parameters, Qtitle, Qnil,
4544 "title", "Title", RES_TYPE_STRING);
4545 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4546 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4548 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4549 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4551 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4552 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4553 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4554 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4555 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4556 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4557 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
4559 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
4561 window_prompting = x_figure_window_size (f, parameters, 1);
4563 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4564 f->no_split = minibuffer_only || EQ (tem, Qt);
4566 w32_window (f, window_prompting, minibuffer_only);
4567 x_icon (f, parameters);
4569 x_make_gc (f);
4571 /* Now consider the frame official. */
4572 f->terminal->reference_count++;
4573 FRAME_DISPLAY_INFO (f)->reference_count++;
4574 Vframe_list = Fcons (frame, Vframe_list);
4576 /* We need to do this after creating the window, so that the
4577 icon-creation functions can say whose icon they're describing. */
4578 x_default_parameter (f, parameters, Qicon_type, Qnil,
4579 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4581 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4582 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4583 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4584 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4585 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4586 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4587 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4588 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4589 x_default_parameter (f, parameters, Qalpha, Qnil,
4590 "alpha", "Alpha", RES_TYPE_NUMBER);
4592 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4593 Change will not be effected unless different from the current
4594 FRAME_LINES (f). */
4595 width = FRAME_TEXT_WIDTH (f);
4596 height = FRAME_TEXT_HEIGHT (f);
4597 FRAME_TEXT_HEIGHT (f) = 0;
4598 SET_FRAME_WIDTH (f, 0);
4599 change_frame_size (f, width, height, 1, 0, 0, 1);
4601 /* Tell the server what size and position, etc, we want, and how
4602 badly we want them. This should be done after we have the menu
4603 bar so that its size can be taken into account. */
4604 block_input ();
4605 x_wm_set_size_hint (f, window_prompting, 0);
4606 unblock_input ();
4608 /* Make the window appear on the frame and enable display, unless
4609 the caller says not to. However, with explicit parent, Emacs
4610 cannot control visibility, so don't try. */
4611 if (! f->output_data.w32->explicit_parent)
4613 Lisp_Object visibility;
4615 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4616 if (EQ (visibility, Qunbound))
4617 visibility = Qt;
4619 if (EQ (visibility, Qicon))
4620 x_iconify_frame (f);
4621 else if (! NILP (visibility))
4622 x_make_frame_visible (f);
4623 else
4624 /* Must have been Qnil. */
4628 /* Initialize `default-minibuffer-frame' in case this is the first
4629 frame on this terminal. */
4630 if (FRAME_HAS_MINIBUF_P (f)
4631 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
4632 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
4633 kset_default_minibuffer_frame (kb, frame);
4635 /* All remaining specified parameters, which have not been "used"
4636 by x_get_arg and friends, now go in the misc. alist of the frame. */
4637 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4638 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4639 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
4641 UNGCPRO;
4643 /* Make sure windows on this frame appear in calls to next-window
4644 and similar functions. */
4645 Vwindow_list = Qnil;
4647 return unbind_to (count, frame);
4650 /* FRAME is used only to get a handle on the X display. We don't pass the
4651 display info directly because we're called from frame.c, which doesn't
4652 know about that structure. */
4653 Lisp_Object
4654 x_get_focus_frame (struct frame *frame)
4656 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
4657 Lisp_Object xfocus;
4658 if (! dpyinfo->w32_focus_frame)
4659 return Qnil;
4661 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4662 return xfocus;
4665 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4666 doc: /* Internal function called by `color-defined-p', which see.
4667 \(Note that the Nextstep version of this function ignores FRAME.) */)
4668 (Lisp_Object color, Lisp_Object frame)
4670 XColor foo;
4671 struct frame *f = decode_window_system_frame (frame);
4673 CHECK_STRING (color);
4675 if (w32_defined_color (f, SDATA (color), &foo, 0))
4676 return Qt;
4677 else
4678 return Qnil;
4681 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
4682 doc: /* Internal function called by `color-values', which see. */)
4683 (Lisp_Object color, Lisp_Object frame)
4685 XColor foo;
4686 struct frame *f = decode_window_system_frame (frame);
4688 CHECK_STRING (color);
4690 if (w32_defined_color (f, SDATA (color), &foo, 0))
4691 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4692 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4693 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
4694 else
4695 return Qnil;
4698 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
4699 doc: /* Internal function called by `display-color-p', which see. */)
4700 (Lisp_Object display)
4702 struct w32_display_info *dpyinfo = check_x_display_info (display);
4704 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4705 return Qnil;
4707 return Qt;
4710 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4711 Sx_display_grayscale_p, 0, 1, 0,
4712 doc: /* Return t if DISPLAY supports shades of gray.
4713 Note that color displays do support shades of gray.
4714 The optional argument DISPLAY specifies which display to ask about.
4715 DISPLAY should be either a frame or a display name (a string).
4716 If omitted or nil, that stands for the selected frame's display. */)
4717 (Lisp_Object display)
4719 struct w32_display_info *dpyinfo = check_x_display_info (display);
4721 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4722 return Qnil;
4724 return Qt;
4727 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4728 Sx_display_pixel_width, 0, 1, 0,
4729 doc: /* Return the width in pixels of DISPLAY.
4730 The optional argument DISPLAY specifies which display to ask about.
4731 DISPLAY should be either a frame or a display name (a string).
4732 If omitted or nil, that stands for the selected frame's display.
4734 On \"multi-monitor\" setups this refers to the pixel width for all
4735 physical monitors associated with DISPLAY. To get information for
4736 each physical monitor, use `display-monitor-attributes-list'. */)
4737 (Lisp_Object display)
4739 struct w32_display_info *dpyinfo = check_x_display_info (display);
4741 return make_number (x_display_pixel_width (dpyinfo));
4744 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
4745 Sx_display_pixel_height, 0, 1, 0,
4746 doc: /* Return the height in pixels of DISPLAY.
4747 The optional argument DISPLAY specifies which display to ask about.
4748 DISPLAY should be either a frame or a display name (a string).
4749 If omitted or nil, that stands for the selected frame's display.
4751 On \"multi-monitor\" setups this refers to the pixel height for all
4752 physical monitors associated with DISPLAY. To get information for
4753 each physical monitor, use `display-monitor-attributes-list'. */)
4754 (Lisp_Object display)
4756 struct w32_display_info *dpyinfo = check_x_display_info (display);
4758 return make_number (x_display_pixel_height (dpyinfo));
4761 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
4762 0, 1, 0,
4763 doc: /* Return the number of bitplanes of DISPLAY.
4764 The optional argument DISPLAY specifies which display to ask about.
4765 DISPLAY should be either a frame or a display name (a string).
4766 If omitted or nil, that stands for the selected frame's display. */)
4767 (Lisp_Object display)
4769 struct w32_display_info *dpyinfo = check_x_display_info (display);
4771 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4774 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
4775 0, 1, 0,
4776 doc: /* Return the number of color cells of DISPLAY.
4777 The optional argument DISPLAY specifies which display to ask about.
4778 DISPLAY should be either a frame or a display name (a string).
4779 If omitted or nil, that stands for the selected frame's display. */)
4780 (Lisp_Object display)
4782 struct w32_display_info *dpyinfo = check_x_display_info (display);
4783 int cap;
4785 /* Don't use NCOLORS: it returns incorrect results under remote
4786 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4787 * overflow and because probably is more meaningful on Windows
4788 * anyway. */
4790 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
4791 return make_number (cap);
4794 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4795 Sx_server_max_request_size,
4796 0, 1, 0,
4797 doc: /* Return the maximum request size of the server of DISPLAY.
4798 The optional argument DISPLAY specifies which display to ask about.
4799 DISPLAY should be either a frame or a display name (a string).
4800 If omitted or nil, that stands for the selected frame's display. */)
4801 (Lisp_Object display)
4803 return make_number (1);
4806 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
4807 doc: /* Return the "vendor ID" string of the W32 system (Microsoft).
4808 The optional argument DISPLAY specifies which display to ask about.
4809 DISPLAY should be either a frame or a display name (a string).
4810 If omitted or nil, that stands for the selected frame's display. */)
4811 (Lisp_Object display)
4813 return build_string ("Microsoft Corp.");
4816 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
4817 doc: /* Return the version numbers of the server of DISPLAY.
4818 The value is a list of three integers: the major and minor
4819 version numbers of the X Protocol in use, and the distributor-specific
4820 release number. See also the function `x-server-vendor'.
4822 The optional argument DISPLAY specifies which display to ask about.
4823 DISPLAY should be either a frame or a display name (a string).
4824 If omitted or nil, that stands for the selected frame's display. */)
4825 (Lisp_Object display)
4827 return list3i (w32_major_version, w32_minor_version, w32_build_number);
4830 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
4831 doc: /* Return the number of screens on the server of DISPLAY.
4832 The optional argument DISPLAY specifies which display to ask about.
4833 DISPLAY should be either a frame or a display name (a string).
4834 If omitted or nil, that stands for the selected frame's display. */)
4835 (Lisp_Object display)
4837 return make_number (1);
4840 DEFUN ("x-display-mm-height", Fx_display_mm_height,
4841 Sx_display_mm_height, 0, 1, 0,
4842 doc: /* Return the height in millimeters of DISPLAY.
4843 The optional argument DISPLAY specifies which display to ask about.
4844 DISPLAY should be either a frame or a display name (a string).
4845 If omitted or nil, that stands for the selected frame's display.
4847 On \"multi-monitor\" setups this refers to the height in millimeters for
4848 all physical monitors associated with DISPLAY. To get information
4849 for each physical monitor, use `display-monitor-attributes-list'. */)
4850 (Lisp_Object display)
4852 struct w32_display_info *dpyinfo = check_x_display_info (display);
4853 HDC hdc;
4854 double mm_per_pixel;
4856 hdc = GetDC (NULL);
4857 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
4858 / GetDeviceCaps (hdc, VERTRES));
4859 ReleaseDC (NULL, hdc);
4861 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
4864 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
4865 doc: /* Return the width in millimeters of DISPLAY.
4866 The optional argument DISPLAY specifies which display to ask about.
4867 DISPLAY should be either a frame or a display name (a string).
4868 If omitted or nil, that stands for the selected frame's display.
4870 On \"multi-monitor\" setups this refers to the width in millimeters for
4871 all physical monitors associated with TERMINAL. To get information
4872 for each physical monitor, use `display-monitor-attributes-list'. */)
4873 (Lisp_Object display)
4875 struct w32_display_info *dpyinfo = check_x_display_info (display);
4876 HDC hdc;
4877 double mm_per_pixel;
4879 hdc = GetDC (NULL);
4880 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
4881 / GetDeviceCaps (hdc, HORZRES));
4882 ReleaseDC (NULL, hdc);
4884 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
4887 DEFUN ("x-display-backing-store", Fx_display_backing_store,
4888 Sx_display_backing_store, 0, 1, 0,
4889 doc: /* Return an indication of whether DISPLAY does backing store.
4890 The value may be `always', `when-mapped', or `not-useful'.
4891 The optional argument DISPLAY specifies which display to ask about.
4892 DISPLAY should be either a frame or a display name (a string).
4893 If omitted or nil, that stands for the selected frame's display. */)
4894 (Lisp_Object display)
4896 return intern ("not-useful");
4899 DEFUN ("x-display-visual-class", Fx_display_visual_class,
4900 Sx_display_visual_class, 0, 1, 0,
4901 doc: /* Return the visual class of DISPLAY.
4902 The value is one of the symbols `static-gray', `gray-scale',
4903 `static-color', `pseudo-color', `true-color', or `direct-color'.
4905 The optional argument DISPLAY specifies which display to ask about.
4906 DISPLAY should be either a frame or a display name (a string).
4907 If omitted or nil, that stands for the selected frame's display. */)
4908 (Lisp_Object display)
4910 struct w32_display_info *dpyinfo = check_x_display_info (display);
4911 Lisp_Object result = Qnil;
4913 if (dpyinfo->has_palette)
4914 result = intern ("pseudo-color");
4915 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
4916 result = intern ("static-grey");
4917 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
4918 result = intern ("static-color");
4919 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
4920 result = intern ("true-color");
4922 return result;
4925 DEFUN ("x-display-save-under", Fx_display_save_under,
4926 Sx_display_save_under, 0, 1, 0,
4927 doc: /* Return t if DISPLAY supports the save-under feature.
4928 The optional argument DISPLAY specifies which display to ask about.
4929 DISPLAY should be either a frame or a display name (a string).
4930 If omitted or nil, that stands for the selected frame's display. */)
4931 (Lisp_Object display)
4933 return Qnil;
4936 static BOOL CALLBACK
4937 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
4939 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
4941 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
4943 return TRUE;
4946 static Lisp_Object
4947 w32_display_monitor_attributes_list (void)
4949 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
4950 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
4951 int i, n_monitors;
4952 HMONITOR *monitors;
4953 struct gcpro gcpro1, gcpro2, gcpro3;
4955 if (!(enum_display_monitors_fn && get_monitor_info_fn
4956 && monitor_from_window_fn))
4957 return Qnil;
4959 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
4960 (LPARAM) &monitor_list)
4961 || NILP (monitor_list))
4962 return Qnil;
4964 n_monitors = 0;
4965 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
4966 n_monitors++;
4968 monitors = xmalloc (n_monitors * sizeof (*monitors));
4969 for (i = 0; i < n_monitors; i++)
4971 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
4972 monitor_list = XCDR (monitor_list);
4975 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
4976 FOR_EACH_FRAME (rest, frame)
4978 struct frame *f = XFRAME (frame);
4980 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
4982 HMONITOR monitor =
4983 monitor_from_window_fn (FRAME_W32_WINDOW (f),
4984 MONITOR_DEFAULT_TO_NEAREST);
4986 for (i = 0; i < n_monitors; i++)
4987 if (monitors[i] == monitor)
4988 break;
4990 if (i < n_monitors)
4991 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
4995 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
4997 for (i = 0; i < n_monitors; i++)
4999 Lisp_Object geometry, workarea, name, attributes = Qnil;
5000 HDC hdc;
5001 int width_mm, height_mm;
5002 struct MONITOR_INFO_EX mi;
5004 mi.cbSize = sizeof (mi);
5005 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5006 continue;
5008 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5009 if (hdc == NULL)
5010 continue;
5011 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5012 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5013 DeleteDC (hdc);
5015 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5016 attributes);
5018 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5020 attributes = Fcons (Fcons (Qname, name), attributes);
5022 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5023 attributes);
5025 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5026 mi.rcWork.right - mi.rcWork.left,
5027 mi.rcWork.bottom - mi.rcWork.top);
5028 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5030 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5031 mi.rcMonitor.right - mi.rcMonitor.left,
5032 mi.rcMonitor.bottom - mi.rcMonitor.top);
5033 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5035 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5036 primary_monitor_attributes = attributes;
5037 else
5038 attributes_list = Fcons (attributes, attributes_list);
5041 if (!NILP (primary_monitor_attributes))
5042 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5044 UNGCPRO;
5046 xfree (monitors);
5048 return attributes_list;
5051 static Lisp_Object
5052 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5054 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5055 HDC hdc;
5056 double mm_per_pixel;
5057 int pixel_width, pixel_height, width_mm, height_mm;
5058 RECT workarea_rect;
5060 /* Fallback: treat (possibly) multiple physical monitors as if they
5061 formed a single monitor as a whole. This should provide a
5062 consistent result at least on single monitor environments. */
5063 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5064 attributes);
5066 frames = Qnil;
5067 FOR_EACH_FRAME (rest, frame)
5069 struct frame *f = XFRAME (frame);
5071 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5072 frames = Fcons (frame, frames);
5074 attributes = Fcons (Fcons (Qframes, frames), attributes);
5076 pixel_width = x_display_pixel_width (dpyinfo);
5077 pixel_height = x_display_pixel_height (dpyinfo);
5079 hdc = GetDC (NULL);
5080 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5081 / GetDeviceCaps (hdc, HORZRES));
5082 width_mm = pixel_width * mm_per_pixel + 0.5;
5083 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5084 / GetDeviceCaps (hdc, VERTRES));
5085 height_mm = pixel_height * mm_per_pixel + 0.5;
5086 ReleaseDC (NULL, hdc);
5087 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5088 attributes);
5090 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5091 we don't care. */
5092 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5093 GetSystemMetrics (SM_YVIRTUALSCREEN),
5094 pixel_width, pixel_height);
5095 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5096 workarea = list4i (workarea_rect.left, workarea_rect.top,
5097 workarea_rect.right - workarea_rect.left,
5098 workarea_rect.bottom - workarea_rect.top);
5099 else
5100 workarea = geometry;
5101 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5103 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5105 return list1 (attributes);
5108 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5109 Sw32_display_monitor_attributes_list,
5110 0, 1, 0,
5111 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5113 The optional argument DISPLAY specifies which display to ask about.
5114 DISPLAY should be either a frame or a display name (a string).
5115 If omitted or nil, that stands for the selected frame's display.
5117 Internal use only, use `display-monitor-attributes-list' instead. */)
5118 (Lisp_Object display)
5120 struct w32_display_info *dpyinfo = check_x_display_info (display);
5121 Lisp_Object attributes_list;
5123 block_input ();
5124 attributes_list = w32_display_monitor_attributes_list ();
5125 if (NILP (attributes_list))
5126 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5127 unblock_input ();
5129 return attributes_list;
5132 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5133 doc: /* Set the sound generated when the bell is rung.
5134 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5135 to use the corresponding system sound for the bell. The 'silent sound
5136 prevents Emacs from making any sound at all.
5137 SOUND is nil to use the normal beep. */)
5138 (Lisp_Object sound)
5140 CHECK_SYMBOL (sound);
5142 if (NILP (sound))
5143 sound_type = 0xFFFFFFFF;
5144 else if (EQ (sound, intern ("asterisk")))
5145 sound_type = MB_ICONASTERISK;
5146 else if (EQ (sound, intern ("exclamation")))
5147 sound_type = MB_ICONEXCLAMATION;
5148 else if (EQ (sound, intern ("hand")))
5149 sound_type = MB_ICONHAND;
5150 else if (EQ (sound, intern ("question")))
5151 sound_type = MB_ICONQUESTION;
5152 else if (EQ (sound, intern ("ok")))
5153 sound_type = MB_OK;
5154 else if (EQ (sound, intern ("silent")))
5155 sound_type = MB_EMACS_SILENT;
5156 else
5157 sound_type = 0xFFFFFFFF;
5159 return sound;
5163 x_screen_planes (register struct frame *f)
5165 return FRAME_DISPLAY_INFO (f)->n_planes;
5168 /* Return the display structure for the display named NAME.
5169 Open a new connection if necessary. */
5171 struct w32_display_info *
5172 x_display_info_for_name (Lisp_Object name)
5174 struct w32_display_info *dpyinfo;
5176 CHECK_STRING (name);
5178 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5179 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5180 return dpyinfo;
5182 /* Use this general default value to start with. */
5183 Vx_resource_name = Vinvocation_name;
5185 validate_x_resource_name ();
5187 dpyinfo = w32_term_init (name, (unsigned char *)0,
5188 SSDATA (Vx_resource_name));
5190 if (dpyinfo == 0)
5191 error ("Cannot connect to server %s", SDATA (name));
5193 XSETFASTINT (Vwindow_system_version, w32_major_version);
5195 return dpyinfo;
5198 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5199 1, 3, 0, doc: /* Open a connection to a display server.
5200 DISPLAY is the name of the display to connect to.
5201 Optional second arg XRM-STRING is a string of resources in xrdb format.
5202 If the optional third arg MUST-SUCCEED is non-nil,
5203 terminate Emacs if we can't open the connection.
5204 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5205 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5207 unsigned char *xrm_option;
5208 struct w32_display_info *dpyinfo;
5210 CHECK_STRING (display);
5212 /* Signal an error in order to encourage correct use from callers.
5213 * If we ever support multiple window systems in the same Emacs,
5214 * we'll need callers to be precise about what window system they
5215 * want. */
5217 if (strcmp (SSDATA (display), "w32") != 0)
5218 error ("The name of the display in this Emacs must be \"w32\"");
5220 /* If initialization has already been done, return now to avoid
5221 overwriting critical parts of one_w32_display_info. */
5222 if (window_system_available (NULL))
5223 return Qnil;
5225 if (! NILP (xrm_string))
5226 CHECK_STRING (xrm_string);
5228 /* Allow color mapping to be defined externally; first look in user's
5229 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5231 Lisp_Object color_file;
5232 struct gcpro gcpro1;
5234 color_file = build_string ("~/rgb.txt");
5236 GCPRO1 (color_file);
5238 if (NILP (Ffile_readable_p (color_file)))
5239 color_file =
5240 Fexpand_file_name (build_string ("rgb.txt"),
5241 Fsymbol_value (intern ("data-directory")));
5243 Vw32_color_map = Fx_load_color_file (color_file);
5245 UNGCPRO;
5247 if (NILP (Vw32_color_map))
5248 Vw32_color_map = w32_default_color_map ();
5250 /* Merge in system logical colors. */
5251 add_system_logical_colors_to_map (&Vw32_color_map);
5253 if (! NILP (xrm_string))
5254 xrm_option = SDATA (xrm_string);
5255 else
5256 xrm_option = (unsigned char *) 0;
5258 /* Use this general default value to start with. */
5259 /* First remove .exe suffix from invocation-name - it looks ugly. */
5261 char basename[ MAX_PATH ], *str;
5263 strcpy (basename, SDATA (Vinvocation_name));
5264 str = strrchr (basename, '.');
5265 if (str) *str = 0;
5266 Vinvocation_name = build_string (basename);
5268 Vx_resource_name = Vinvocation_name;
5270 validate_x_resource_name ();
5272 /* This is what opens the connection and sets x_current_display.
5273 This also initializes many symbols, such as those used for input. */
5274 dpyinfo = w32_term_init (display, xrm_option,
5275 SSDATA (Vx_resource_name));
5277 if (dpyinfo == 0)
5279 if (!NILP (must_succeed))
5280 fatal ("Cannot connect to server %s.\n",
5281 SDATA (display));
5282 else
5283 error ("Cannot connect to server %s", SDATA (display));
5286 XSETFASTINT (Vwindow_system_version, w32_major_version);
5287 return Qnil;
5290 DEFUN ("x-close-connection", Fx_close_connection,
5291 Sx_close_connection, 1, 1, 0,
5292 doc: /* Close the connection to DISPLAY's server.
5293 For DISPLAY, specify either a frame or a display name (a string).
5294 If DISPLAY is nil, that stands for the selected frame's display. */)
5295 (Lisp_Object display)
5297 struct w32_display_info *dpyinfo = check_x_display_info (display);
5299 if (dpyinfo->reference_count > 0)
5300 error ("Display still has frames on it");
5302 block_input ();
5303 x_destroy_all_bitmaps (dpyinfo);
5305 x_delete_display (dpyinfo);
5306 unblock_input ();
5308 return Qnil;
5311 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5312 doc: /* Return the list of display names that Emacs has connections to. */)
5313 (void)
5315 Lisp_Object result = Qnil;
5316 struct w32_display_info *wdi;
5318 for (wdi = x_display_list; wdi; wdi = wdi->next)
5319 result = Fcons (XCAR (wdi->name_list_element), result);
5321 return result;
5324 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5325 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5326 This function only has an effect on X Windows. With MS Windows, it is
5327 defined but does nothing.
5329 If ON is nil, allow buffering of requests.
5330 Turning on synchronization prohibits the Xlib routines from buffering
5331 requests and seriously degrades performance, but makes debugging much
5332 easier.
5333 The optional second argument TERMINAL specifies which display to act on.
5334 TERMINAL should be a terminal object, a frame or a display name (a string).
5335 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5336 (Lisp_Object on, Lisp_Object display)
5338 return Qnil;
5343 /***********************************************************************
5344 Window properties
5345 ***********************************************************************/
5347 #if 0 /* TODO : port window properties to W32 */
5349 DEFUN ("x-change-window-property", Fx_change_window_property,
5350 Sx_change_window_property, 2, 6, 0,
5351 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5352 PROP must be a string. VALUE may be a string or a list of conses,
5353 numbers and/or strings. If an element in the list is a string, it is
5354 converted to an atom and the value of the Atom is used. If an element
5355 is a cons, it is converted to a 32 bit number where the car is the 16
5356 top bits and the cdr is the lower 16 bits.
5358 FRAME nil or omitted means use the selected frame.
5359 If TYPE is given and non-nil, it is the name of the type of VALUE.
5360 If TYPE is not given or nil, the type is STRING.
5361 FORMAT gives the size in bits of each element if VALUE is a list.
5362 It must be one of 8, 16 or 32.
5363 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
5364 If OUTER-P is non-nil, the property is changed for the outer X window of
5365 FRAME. Default is to change on the edit X window. */)
5366 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5367 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
5369 struct frame *f = decode_window_system_frame (frame);
5370 Atom prop_atom;
5372 CHECK_STRING (prop);
5373 CHECK_STRING (value);
5375 block_input ();
5376 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5377 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5378 prop_atom, XA_STRING, 8, PropModeReplace,
5379 SDATA (value), SCHARS (value));
5381 /* Make sure the property is set when we return. */
5382 XFlush (FRAME_W32_DISPLAY (f));
5383 unblock_input ();
5385 return value;
5389 DEFUN ("x-delete-window-property", Fx_delete_window_property,
5390 Sx_delete_window_property, 1, 2, 0,
5391 doc: /* Remove window property PROP from X window of FRAME.
5392 FRAME nil or omitted means use the selected frame. Value is PROP. */)
5393 (Lisp_Object prop, Lisp_Object frame)
5395 struct frame *f = decode_window_system_frame (frame);
5396 Atom prop_atom;
5398 CHECK_STRING (prop);
5399 block_input ();
5400 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5401 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
5403 /* Make sure the property is removed when we return. */
5404 XFlush (FRAME_W32_DISPLAY (f));
5405 unblock_input ();
5407 return prop;
5411 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
5412 1, 6, 0,
5413 doc: /* Value is the value of window property PROP on FRAME.
5414 If FRAME is nil or omitted, use the selected frame.
5416 On X Windows, the following optional arguments are also accepted:
5417 If TYPE is nil or omitted, get the property as a string.
5418 Otherwise TYPE is the name of the atom that denotes the type expected.
5419 If SOURCE is non-nil, get the property on that window instead of from
5420 FRAME. The number 0 denotes the root window.
5421 If DELETE-P is non-nil, delete the property after retrieving it.
5422 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5424 On MS Windows, this function accepts but ignores those optional arguments.
5426 Value is nil if FRAME hasn't a property with name PROP or if PROP has
5427 no value of TYPE (always string in the MS Windows case). */)
5428 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5429 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
5431 struct frame *f = decode_window_system_frame (frame);
5432 Atom prop_atom;
5433 int rc;
5434 Lisp_Object prop_value = Qnil;
5435 char *tmp_data = NULL;
5436 Atom actual_type;
5437 int actual_format;
5438 unsigned long actual_size, bytes_remaining;
5440 CHECK_STRING (prop);
5441 block_input ();
5442 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5443 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5444 prop_atom, 0, 0, False, XA_STRING,
5445 &actual_type, &actual_format, &actual_size,
5446 &bytes_remaining, (unsigned char **) &tmp_data);
5447 if (rc == Success)
5449 int size = bytes_remaining;
5451 XFree (tmp_data);
5452 tmp_data = NULL;
5454 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5455 prop_atom, 0, bytes_remaining,
5456 False, XA_STRING,
5457 &actual_type, &actual_format,
5458 &actual_size, &bytes_remaining,
5459 (unsigned char **) &tmp_data);
5460 if (rc == Success)
5461 prop_value = make_string (tmp_data, size);
5463 XFree (tmp_data);
5466 unblock_input ();
5468 return prop_value;
5470 return Qnil;
5473 #endif /* TODO */
5476 /***********************************************************************
5477 Busy cursor
5478 ***********************************************************************/
5480 void
5481 w32_note_current_window (void)
5483 struct frame * f = SELECTED_FRAME ();
5485 if (!FRAME_W32_P (f))
5486 return;
5488 hourglass_hwnd = FRAME_W32_WINDOW (f);
5491 void
5492 show_hourglass (struct atimer *timer)
5494 struct frame *f;
5496 hourglass_atimer = NULL;
5498 block_input ();
5499 f = x_window_to_frame (&one_w32_display_info,
5500 hourglass_hwnd);
5502 if (f)
5503 f->output_data.w32->hourglass_p = 0;
5504 else
5505 f = SELECTED_FRAME ();
5507 if (!FRAME_W32_P (f))
5509 unblock_input ();
5510 return;
5513 w32_show_hourglass (f);
5514 unblock_input ();
5517 void
5518 hide_hourglass (void)
5520 block_input ();
5521 w32_hide_hourglass ();
5522 unblock_input ();
5526 /* Display an hourglass cursor. Set the hourglass_p flag in display info
5527 to indicate that an hourglass cursor is shown. */
5529 static void
5530 w32_show_hourglass (struct frame *f)
5532 if (!hourglass_shown_p)
5534 f->output_data.w32->hourglass_p = 1;
5535 if (!menubar_in_use && !current_popup_menu)
5536 SetCursor (f->output_data.w32->hourglass_cursor);
5537 hourglass_shown_p = 1;
5542 /* Hide the hourglass cursor on all frames, if it is currently shown. */
5544 static void
5545 w32_hide_hourglass (void)
5547 if (hourglass_shown_p)
5549 struct frame *f = x_window_to_frame (&one_w32_display_info,
5550 hourglass_hwnd);
5551 if (f)
5552 f->output_data.w32->hourglass_p = 0;
5553 else
5554 /* If frame was deleted, restore to selected frame's cursor. */
5555 f = SELECTED_FRAME ();
5557 if (FRAME_W32_P (f))
5558 SetCursor (f->output_data.w32->current_cursor);
5559 else
5560 /* No cursors on non GUI frames - restore to stock arrow cursor. */
5561 SetCursor (w32_load_cursor (IDC_ARROW));
5563 hourglass_shown_p = 0;
5569 /***********************************************************************
5570 Tool tips
5571 ***********************************************************************/
5573 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5574 Lisp_Object, Lisp_Object);
5575 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5576 Lisp_Object, int, int, int *, int *);
5578 /* The frame of a currently visible tooltip. */
5580 Lisp_Object tip_frame;
5582 /* If non-nil, a timer started that hides the last tooltip when it
5583 fires. */
5585 Lisp_Object tip_timer;
5586 Window tip_window;
5588 /* If non-nil, a vector of 3 elements containing the last args
5589 with which x-show-tip was called. See there. */
5591 Lisp_Object last_show_tip_args;
5594 static void
5595 unwind_create_tip_frame (Lisp_Object frame)
5597 Lisp_Object deleted;
5599 deleted = unwind_create_frame (frame);
5600 if (EQ (deleted, Qt))
5602 tip_window = NULL;
5603 tip_frame = Qnil;
5608 /* Create a frame for a tooltip on the display described by DPYINFO.
5609 PARMS is a list of frame parameters. TEXT is the string to
5610 display in the tip frame. Value is the frame.
5612 Note that functions called here, esp. x_default_parameter can
5613 signal errors, for instance when a specified color name is
5614 undefined. We have to make sure that we're in a consistent state
5615 when this happens. */
5617 static Lisp_Object
5618 x_create_tip_frame (struct w32_display_info *dpyinfo,
5619 Lisp_Object parms, Lisp_Object text)
5621 struct frame *f;
5622 Lisp_Object frame;
5623 Lisp_Object name;
5624 long window_prompting = 0;
5625 int width, height;
5626 ptrdiff_t count = SPECPDL_INDEX ();
5627 struct gcpro gcpro1, gcpro2, gcpro3;
5628 struct kboard *kb;
5629 int face_change_count_before = face_change_count;
5630 Lisp_Object buffer;
5631 struct buffer *old_buffer;
5633 /* Use this general default value to start with until we know if
5634 this frame has a specified name. */
5635 Vx_resource_name = Vinvocation_name;
5637 kb = dpyinfo->terminal->kboard;
5639 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5640 avoid destructive changes behind our caller's back. */
5641 parms = Fcopy_alist (parms);
5643 /* Get the name of the frame to use for resource lookup. */
5644 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
5645 if (!STRINGP (name)
5646 && !EQ (name, Qunbound)
5647 && !NILP (name))
5648 error ("Invalid frame name--not a string or nil");
5649 Vx_resource_name = name;
5651 frame = Qnil;
5652 GCPRO3 (parms, name, frame);
5653 /* Make a frame without minibuffer nor mode-line. */
5654 f = make_frame (0);
5655 f->wants_modeline = 0;
5656 XSETFRAME (frame, f);
5658 buffer = Fget_buffer_create (build_string (" *tip*"));
5659 /* Use set_window_buffer instead of Fset_window_buffer (see
5660 discussion of bug#11984, bug#12025, bug#12026). */
5661 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, 0, 0);
5662 old_buffer = current_buffer;
5663 set_buffer_internal_1 (XBUFFER (buffer));
5664 bset_truncate_lines (current_buffer, Qnil);
5665 specbind (Qinhibit_read_only, Qt);
5666 specbind (Qinhibit_modification_hooks, Qt);
5667 Ferase_buffer ();
5668 Finsert (1, &text);
5669 set_buffer_internal_1 (old_buffer);
5671 record_unwind_protect (unwind_create_tip_frame, frame);
5673 /* By setting the output method, we're essentially saying that
5674 the frame is live, as per FRAME_LIVE_P. If we get a signal
5675 from this point on, x_destroy_window might screw up reference
5676 counts etc. */
5677 f->terminal = dpyinfo->terminal;
5678 f->output_method = output_w32;
5679 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5681 FRAME_FONTSET (f) = -1;
5682 fset_icon_name (f, Qnil);
5684 #ifdef GLYPH_DEBUG
5685 image_cache_refcount =
5686 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5687 dpyinfo_refcount = dpyinfo->reference_count;
5688 #endif /* GLYPH_DEBUG */
5689 FRAME_KBOARD (f) = kb;
5690 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5691 f->output_data.w32->explicit_parent = 0;
5693 /* Set the name; the functions to which we pass f expect the name to
5694 be set. */
5695 if (EQ (name, Qunbound) || NILP (name))
5697 fset_name (f, build_string (dpyinfo->w32_id_name));
5698 f->explicit_name = 0;
5700 else
5702 fset_name (f, name);
5703 f->explicit_name = 1;
5704 /* use the frame's title when getting resources for this frame. */
5705 specbind (Qx_resource_name, name);
5708 if (uniscribe_available)
5709 register_font_driver (&uniscribe_font_driver, f);
5710 register_font_driver (&w32font_driver, f);
5712 x_default_parameter (f, parms, Qfont_backend, Qnil,
5713 "fontBackend", "FontBackend", RES_TYPE_STRING);
5715 /* Extract the window parameters from the supplied values
5716 that are needed to determine window geometry. */
5717 x_default_font_parameter (f, parms);
5719 x_default_parameter (f, parms, Qborder_width, make_number (2),
5720 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5721 /* This defaults to 2 in order to match xterm. We recognize either
5722 internalBorderWidth or internalBorder (which is what xterm calls
5723 it). */
5724 if (NILP (Fassq (Qinternal_border_width, parms)))
5726 Lisp_Object value;
5728 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
5729 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5730 if (! EQ (value, Qunbound))
5731 parms = Fcons (Fcons (Qinternal_border_width, value),
5732 parms);
5734 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
5735 "internalBorderWidth", "internalBorderWidth",
5736 RES_TYPE_NUMBER);
5737 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5738 NULL, NULL, RES_TYPE_NUMBER);
5739 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5740 NULL, NULL, RES_TYPE_NUMBER);
5742 /* Also do the stuff which must be set before the window exists. */
5743 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5744 "foreground", "Foreground", RES_TYPE_STRING);
5745 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5746 "background", "Background", RES_TYPE_STRING);
5747 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5748 "pointerColor", "Foreground", RES_TYPE_STRING);
5749 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5750 "cursorColor", "Foreground", RES_TYPE_STRING);
5751 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5752 "borderColor", "BorderColor", RES_TYPE_STRING);
5754 /* Init faces before x_default_parameter is called for scroll-bar
5755 parameters because that function calls x_set_scroll_bar_width,
5756 which calls change_frame_size, which calls Fset_window_buffer,
5757 which runs hooks, which call Fvertical_motion. At the end, we
5758 end up in init_iterator with a null face cache, which should not
5759 happen. */
5760 init_frame_faces (f);
5762 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
5763 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5765 window_prompting = x_figure_window_size (f, parms, 0);
5767 /* No fringes on tip frame. */
5768 f->fringe_cols = 0;
5769 f->left_fringe_width = 0;
5770 f->right_fringe_width = 0;
5772 block_input ();
5773 my_create_tip_window (f);
5774 unblock_input ();
5776 x_make_gc (f);
5778 x_default_parameter (f, parms, Qauto_raise, Qnil,
5779 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5780 x_default_parameter (f, parms, Qauto_lower, Qnil,
5781 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5782 x_default_parameter (f, parms, Qcursor_type, Qbox,
5783 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5785 /* Dimensions, especially FRAME_LINES (f), must be done via
5786 change_frame_size. Change will not be effected unless different
5787 from the current FRAME_LINES (f). */
5788 width = FRAME_COLS (f);
5789 height = FRAME_LINES (f);
5790 FRAME_LINES (f) = 0;
5791 SET_FRAME_COLS (f, 0);
5792 change_frame_size (f, width, height, 1, 0, 0, 0);
5794 /* Add `tooltip' frame parameter's default value. */
5795 if (NILP (Fframe_parameter (frame, Qtooltip)))
5796 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
5798 /* Set up faces after all frame parameters are known. This call
5799 also merges in face attributes specified for new frames.
5801 Frame parameters may be changed if .Xdefaults contains
5802 specifications for the default font. For example, if there is an
5803 `Emacs.default.attributeBackground: pink', the `background-color'
5804 attribute of the frame get's set, which let's the internal border
5805 of the tooltip frame appear in pink. Prevent this. */
5807 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
5808 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5809 Lisp_Object colors = Qnil;
5811 /* Set tip_frame here, so that */
5812 tip_frame = frame;
5813 call2 (Qface_set_after_frame_default, frame, Qnil);
5815 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
5816 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5817 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5818 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5820 if (!NILP (colors))
5821 Fmodify_frame_parameters (frame, colors);
5824 f->no_split = 1;
5826 UNGCPRO;
5828 /* Now that the frame is official, it counts as a reference to
5829 its display. */
5830 FRAME_DISPLAY_INFO (f)->reference_count++;
5831 f->terminal->reference_count++;
5833 /* It is now ok to make the frame official even if we get an error
5834 below. And the frame needs to be on Vframe_list or making it
5835 visible won't work. */
5836 Vframe_list = Fcons (frame, Vframe_list);
5838 /* Setting attributes of faces of the tooltip frame from resources
5839 and similar will increment face_change_count, which leads to the
5840 clearing of all current matrices. Since this isn't necessary
5841 here, avoid it by resetting face_change_count to the value it
5842 had before we created the tip frame. */
5843 face_change_count = face_change_count_before;
5845 /* Discard the unwind_protect. */
5846 return unbind_to (count, frame);
5850 /* Compute where to display tip frame F. PARMS is the list of frame
5851 parameters for F. DX and DY are specified offsets from the current
5852 location of the mouse. WIDTH and HEIGHT are the width and height
5853 of the tooltip. Return coordinates relative to the root window of
5854 the display in *ROOT_X, and *ROOT_Y. */
5856 static void
5857 compute_tip_xy (struct frame *f,
5858 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5859 int width, int height, int *root_x, int *root_y)
5861 Lisp_Object left, top;
5862 int min_x, min_y, max_x, max_y;
5864 /* User-specified position? */
5865 left = Fcdr (Fassq (Qleft, parms));
5866 top = Fcdr (Fassq (Qtop, parms));
5868 /* Move the tooltip window where the mouse pointer is. Resize and
5869 show it. */
5870 if (!INTEGERP (left) || !INTEGERP (top))
5872 POINT pt;
5874 /* Default min and max values. */
5875 min_x = 0;
5876 min_y = 0;
5877 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5878 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
5880 block_input ();
5881 GetCursorPos (&pt);
5882 *root_x = pt.x;
5883 *root_y = pt.y;
5884 unblock_input ();
5886 /* If multiple monitor support is available, constrain the tip onto
5887 the current monitor. This improves the above by allowing negative
5888 co-ordinates if monitor positions are such that they are valid, and
5889 snaps a tooltip onto a single monitor if we are close to the edge
5890 where it would otherwise flow onto the other monitor (or into
5891 nothingness if there is a gap in the overlap). */
5892 if (monitor_from_point_fn && get_monitor_info_fn)
5894 struct MONITOR_INFO info;
5895 HMONITOR monitor
5896 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5897 info.cbSize = sizeof (info);
5899 if (get_monitor_info_fn (monitor, &info))
5901 min_x = info.rcWork.left;
5902 min_y = info.rcWork.top;
5903 max_x = info.rcWork.right;
5904 max_y = info.rcWork.bottom;
5909 if (INTEGERP (top))
5910 *root_y = XINT (top);
5911 else if (*root_y + XINT (dy) <= min_y)
5912 *root_y = min_y; /* Can happen for negative dy */
5913 else if (*root_y + XINT (dy) + height <= max_y)
5914 /* It fits below the pointer */
5915 *root_y += XINT (dy);
5916 else if (height + XINT (dy) + min_y <= *root_y)
5917 /* It fits above the pointer. */
5918 *root_y -= height + XINT (dy);
5919 else
5920 /* Put it on the top. */
5921 *root_y = min_y;
5923 if (INTEGERP (left))
5924 *root_x = XINT (left);
5925 else if (*root_x + XINT (dx) <= min_x)
5926 *root_x = 0; /* Can happen for negative dx */
5927 else if (*root_x + XINT (dx) + width <= max_x)
5928 /* It fits to the right of the pointer. */
5929 *root_x += XINT (dx);
5930 else if (width + XINT (dx) + min_x <= *root_x)
5931 /* It fits to the left of the pointer. */
5932 *root_x -= width + XINT (dx);
5933 else
5934 /* Put it left justified on the screen -- it ought to fit that way. */
5935 *root_x = min_x;
5939 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
5940 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
5941 A tooltip window is a small window displaying a string.
5943 This is an internal function; Lisp code should call `tooltip-show'.
5945 FRAME nil or omitted means use the selected frame.
5947 PARMS is an optional list of frame parameters which can be
5948 used to change the tooltip's appearance.
5950 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
5951 means use the default timeout of 5 seconds.
5953 If the list of frame parameters PARMS contains a `left' parameter,
5954 the tooltip is displayed at that x-position. Otherwise it is
5955 displayed at the mouse position, with offset DX added (default is 5 if
5956 DX isn't specified). Likewise for the y-position; if a `top' frame
5957 parameter is specified, it determines the y-position of the tooltip
5958 window, otherwise it is displayed at the mouse position, with offset
5959 DY added (default is -10).
5961 A tooltip's maximum size is specified by `x-max-tooltip-size'.
5962 Text larger than the specified size is clipped. */)
5963 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
5965 struct frame *f;
5966 struct window *w;
5967 int root_x, root_y;
5968 struct buffer *old_buffer;
5969 struct text_pos pos;
5970 int i, width, height, seen_reversed_p;
5971 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5972 int old_windows_or_buffers_changed = windows_or_buffers_changed;
5973 ptrdiff_t count = SPECPDL_INDEX ();
5975 specbind (Qinhibit_redisplay, Qt);
5977 GCPRO4 (string, parms, frame, timeout);
5979 CHECK_STRING (string);
5980 f = decode_window_system_frame (frame);
5981 if (NILP (timeout))
5982 timeout = make_number (5);
5983 else
5984 CHECK_NATNUM (timeout);
5986 if (NILP (dx))
5987 dx = make_number (5);
5988 else
5989 CHECK_NUMBER (dx);
5991 if (NILP (dy))
5992 dy = make_number (-10);
5993 else
5994 CHECK_NUMBER (dy);
5996 if (NILP (last_show_tip_args))
5997 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
5999 if (!NILP (tip_frame))
6001 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6002 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6003 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6005 if (EQ (frame, last_frame)
6006 && !NILP (Fequal (last_string, string))
6007 && !NILP (Fequal (last_parms, parms)))
6009 struct frame *f = XFRAME (tip_frame);
6011 /* Only DX and DY have changed. */
6012 if (!NILP (tip_timer))
6014 Lisp_Object timer = tip_timer;
6015 tip_timer = Qnil;
6016 call1 (Qcancel_timer, timer);
6019 block_input ();
6020 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6021 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6023 /* Put tooltip in topmost group and in position. */
6024 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6025 root_x, root_y, 0, 0,
6026 SWP_NOSIZE | SWP_NOACTIVATE);
6028 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6029 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6030 0, 0, 0, 0,
6031 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
6033 unblock_input ();
6034 goto start_timer;
6038 /* Hide a previous tip, if any. */
6039 Fx_hide_tip ();
6041 ASET (last_show_tip_args, 0, string);
6042 ASET (last_show_tip_args, 1, frame);
6043 ASET (last_show_tip_args, 2, parms);
6045 /* Add default values to frame parameters. */
6046 if (NILP (Fassq (Qname, parms)))
6047 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6048 if (NILP (Fassq (Qinternal_border_width, parms)))
6049 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6050 if (NILP (Fassq (Qright_divider_width, parms)))
6051 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6052 if (NILP (Fassq (Qbottom_divider_width, parms)))
6053 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6054 if (NILP (Fassq (Qborder_width, parms)))
6055 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6056 if (NILP (Fassq (Qborder_color, parms)))
6057 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6058 if (NILP (Fassq (Qbackground_color, parms)))
6059 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6060 parms);
6062 /* Block input until the tip has been fully drawn, to avoid crashes
6063 when drawing tips in menus. */
6064 block_input ();
6066 /* Create a frame for the tooltip, and record it in the global
6067 variable tip_frame. */
6068 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6069 f = XFRAME (frame);
6071 /* Set up the frame's root window. */
6072 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6073 w->left_col = 0;
6074 w->top_line = 0;
6075 w->pixel_left = 0;
6076 w->pixel_top = 0;
6078 if (CONSP (Vx_max_tooltip_size)
6079 && INTEGERP (XCAR (Vx_max_tooltip_size))
6080 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6081 && INTEGERP (XCDR (Vx_max_tooltip_size))
6082 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6084 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6085 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6087 else
6089 w->total_cols = 80;
6090 w->total_lines = 40;
6093 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6094 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6096 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6097 adjust_frame_glyphs (f);
6098 w->pseudo_window_p = 1;
6100 /* Display the tooltip text in a temporary buffer. */
6101 old_buffer = current_buffer;
6102 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6103 bset_truncate_lines (current_buffer, Qnil);
6104 clear_glyph_matrix (w->desired_matrix);
6105 clear_glyph_matrix (w->current_matrix);
6106 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6107 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6109 /* Compute width and height of the tooltip. */
6110 width = height = seen_reversed_p = 0;
6111 for (i = 0; i < w->desired_matrix->nrows; ++i)
6113 struct glyph_row *row = &w->desired_matrix->rows[i];
6114 struct glyph *last;
6115 int row_width;
6117 /* Stop at the first empty row at the end. */
6118 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6119 break;
6121 /* Let the row go over the full width of the frame. */
6122 row->full_width_p = 1;
6124 row_width = row->pixel_width;
6125 if (row->used[TEXT_AREA])
6127 if (!row->reversed_p)
6129 /* There's a glyph at the end of rows that is used to
6130 place the cursor there. Don't include the width of
6131 this glyph. */
6132 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6133 if (INTEGERP (last->object))
6134 row_width -= last->pixel_width;
6136 else
6138 /* There could be a stretch glyph at the beginning of R2L
6139 rows that is produced by extend_face_to_end_of_line.
6140 Don't count that glyph. */
6141 struct glyph *g = row->glyphs[TEXT_AREA];
6143 if (g->type == STRETCH_GLYPH && INTEGERP (g->object))
6145 row_width -= g->pixel_width;
6146 seen_reversed_p = 1;
6151 height += row->height;
6152 width = max (width, row_width);
6155 /* If we've seen partial-length R2L rows, we need to re-adjust the
6156 tool-tip frame width and redisplay it again, to avoid over-wide
6157 tips due to the stretch glyph that extends R2L lines to full
6158 width of the frame. */
6159 if (seen_reversed_p)
6161 /* PXW: Why do we do the pixel-to-cols conversion only if
6162 seen_reversed_p holds? Don't we have to set other fields of
6163 the window/frame structure?
6165 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6166 not in pixels. */
6167 w->pixel_width = width;
6168 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6169 w->total_cols = width;
6170 FRAME_TOTAL_COLS (f) = width;
6171 SET_FRAME_WIDTH (f, width);
6172 adjust_frame_glyphs (f);
6173 w->pseudo_window_p = 1;
6174 clear_glyph_matrix (w->desired_matrix);
6175 clear_glyph_matrix (w->current_matrix);
6176 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6177 width = height = 0;
6178 /* Recompute width and height of the tooltip. */
6179 for (i = 0; i < w->desired_matrix->nrows; ++i)
6181 struct glyph_row *row = &w->desired_matrix->rows[i];
6182 struct glyph *last;
6183 int row_width;
6185 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6186 break;
6187 row->full_width_p = 1;
6188 row_width = row->pixel_width;
6189 if (row->used[TEXT_AREA] && !row->reversed_p)
6191 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6192 if (INTEGERP (last->object))
6193 row_width -= last->pixel_width;
6196 height += row->height;
6197 width = max (width, row_width);
6201 /* Add the frame's internal border to the width and height the w32
6202 window should have. */
6203 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6204 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6206 /* Move the tooltip window where the mouse pointer is. Resize and
6207 show it.
6209 PXW: This should use the frame's pixel coordinates. */
6210 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6213 /* Adjust Window size to take border into account. */
6214 RECT rect;
6215 rect.left = rect.top = 0;
6216 rect.right = width;
6217 rect.bottom = height;
6218 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6219 FRAME_EXTERNAL_MENU_BAR (f));
6221 /* Position and size tooltip, and put it in the topmost group.
6222 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6223 peculiarity of w32 display: without it, some fonts cause the
6224 last character of the tip to be truncated or wrapped around to
6225 the next line. */
6226 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6227 root_x, root_y,
6228 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6229 rect.bottom - rect.top, SWP_NOACTIVATE);
6231 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6232 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6233 0, 0, 0, 0,
6234 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
6236 /* Let redisplay know that we have made the frame visible already. */
6237 SET_FRAME_VISIBLE (f, 1);
6239 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6242 /* Draw into the window. */
6243 w->must_be_updated_p = 1;
6244 update_single_window (w, 1);
6246 unblock_input ();
6248 /* Restore original current buffer. */
6249 set_buffer_internal_1 (old_buffer);
6250 windows_or_buffers_changed = old_windows_or_buffers_changed;
6252 start_timer:
6253 /* Let the tip disappear after timeout seconds. */
6254 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6255 intern ("x-hide-tip"));
6257 UNGCPRO;
6258 return unbind_to (count, Qnil);
6262 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6263 doc: /* Hide the current tooltip window, if there is any.
6264 Value is t if tooltip was open, nil otherwise. */)
6265 (void)
6267 ptrdiff_t count;
6268 Lisp_Object deleted, frame, timer;
6269 struct gcpro gcpro1, gcpro2;
6271 /* Return quickly if nothing to do. */
6272 if (NILP (tip_timer) && NILP (tip_frame))
6273 return Qnil;
6275 frame = tip_frame;
6276 timer = tip_timer;
6277 GCPRO2 (frame, timer);
6278 tip_frame = tip_timer = deleted = Qnil;
6280 count = SPECPDL_INDEX ();
6281 specbind (Qinhibit_redisplay, Qt);
6282 specbind (Qinhibit_quit, Qt);
6284 if (!NILP (timer))
6285 call1 (Qcancel_timer, timer);
6287 if (FRAMEP (frame))
6289 delete_frame (frame, Qnil);
6290 deleted = Qt;
6293 UNGCPRO;
6294 return unbind_to (count, deleted);
6297 /***********************************************************************
6298 File selection dialog
6299 ***********************************************************************/
6301 #define FILE_NAME_TEXT_FIELD edt1
6302 #define FILE_NAME_COMBO_BOX cmb13
6303 #define FILE_NAME_LIST lst1
6305 /* Callback for altering the behavior of the Open File dialog.
6306 Makes the Filename text field contain "Current Directory" and be
6307 read-only when "Directories" is selected in the filter. This
6308 allows us to work around the fact that the standard Open File
6309 dialog does not support directories. */
6310 static UINT_PTR CALLBACK
6311 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6313 if (msg == WM_NOTIFY)
6315 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6316 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6317 int dropdown_changed;
6318 int dir_index;
6319 #ifdef NTGUI_UNICODE
6320 const int use_unicode = 1;
6321 #else /* !NTGUI_UNICODE */
6322 int use_unicode = w32_unicode_filenames;
6323 #endif /* NTGUI_UNICODE */
6325 /* Detect when the Filter dropdown is changed. */
6326 if (use_unicode)
6327 dropdown_changed =
6328 notify_w->hdr.code == CDN_TYPECHANGE
6329 || notify_w->hdr.code == CDN_INITDONE;
6330 else
6331 dropdown_changed =
6332 notify_a->hdr.code == CDN_TYPECHANGE
6333 || notify_a->hdr.code == CDN_INITDONE;
6334 if (dropdown_changed)
6336 HWND dialog = GetParent (hwnd);
6337 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6338 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6339 int hdr_code;
6341 /* At least on Windows 7, the above attempt to get the window handle
6342 to the File Name Text Field fails. The following code does the
6343 job though. Note that this code is based on my examination of the
6344 window hierarchy using Microsoft Spy++. bk */
6345 if (edit_control == NULL)
6347 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6348 if (tmp)
6350 tmp = GetWindow (tmp, GW_CHILD);
6351 if (tmp)
6352 edit_control = GetWindow (tmp, GW_CHILD);
6356 /* Directories is in index 2. */
6357 if (use_unicode)
6359 dir_index = notify_w->lpOFN->nFilterIndex;
6360 hdr_code = notify_w->hdr.code;
6362 else
6364 dir_index = notify_a->lpOFN->nFilterIndex;
6365 hdr_code = notify_a->hdr.code;
6367 if (dir_index == 2)
6369 if (use_unicode)
6370 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6371 (LPARAM)L"Current Directory");
6372 else
6373 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6374 (LPARAM)"Current Directory");
6375 EnableWindow (edit_control, FALSE);
6376 /* Note that at least on Windows 7, the above call to EnableWindow
6377 disables the window that would ordinarily have focus. If we
6378 do not set focus to some other window here, focus will land in
6379 no man's land and the user will be unable to tab through the
6380 dialog box (pressing tab will only result in a beep).
6381 Avoid that problem by setting focus to the list here. */
6382 if (hdr_code == CDN_INITDONE)
6383 SetFocus (list);
6385 else
6387 /* Don't override default filename on init done. */
6388 if (hdr_code == CDN_TYPECHANGE)
6390 if (use_unicode)
6391 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6392 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6393 else
6394 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6395 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6397 EnableWindow (edit_control, TRUE);
6401 return 0;
6404 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6405 doc: /* Read file name, prompting with PROMPT in directory DIR.
6406 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6407 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6408 or directory must exist.
6410 This function is only defined on NS, MS Windows, and X Windows with the
6411 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6412 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories. */)
6413 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6415 /* Filter index: 1: All Files, 2: Directories only */
6416 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6417 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6419 Lisp_Object filename = default_filename;
6420 struct frame *f = SELECTED_FRAME ();
6421 BOOL file_opened = FALSE;
6422 Lisp_Object orig_dir = dir;
6423 Lisp_Object orig_prompt = prompt;
6425 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6426 compatibility) we end up with the old file dialogs. Define a big
6427 enough struct for the new dialog to trick GetOpenFileName into
6428 giving us the new dialogs on newer versions of Windows. */
6429 struct {
6430 OPENFILENAMEW details;
6431 #if _WIN32_WINNT < 0x500 /* < win2k */
6432 PVOID pvReserved;
6433 DWORD dwReserved;
6434 DWORD FlagsEx;
6435 #endif /* < win2k */
6436 } new_file_details_w;
6438 #ifdef NTGUI_UNICODE
6439 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6440 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6441 const int use_unicode = 1;
6442 #else /* not NTGUI_UNICODE */
6443 struct {
6444 OPENFILENAMEA details;
6445 #if _WIN32_WINNT < 0x500 /* < win2k */
6446 PVOID pvReserved;
6447 DWORD dwReserved;
6448 DWORD FlagsEx;
6449 #endif /* < win2k */
6450 } new_file_details_a;
6451 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6452 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6453 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6454 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6455 int use_unicode = w32_unicode_filenames;
6456 wchar_t *prompt_w;
6457 char *prompt_a;
6458 int len;
6459 char fname_ret[MAX_UTF8_PATH];
6460 #endif /* NTGUI_UNICODE */
6462 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
6463 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
6466 struct gcpro gcpro1, gcpro2;
6467 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
6469 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6470 system file encoding expected by the platform APIs (e.g. Cygwin's
6471 POSIX implementation) may not be the same as the encoding expected
6472 by the Windows "ANSI" APIs! */
6474 CHECK_STRING (prompt);
6475 CHECK_STRING (dir);
6477 dir = Fexpand_file_name (dir, Qnil);
6479 if (STRINGP (filename))
6480 filename = Ffile_name_nondirectory (filename);
6481 else
6482 filename = empty_unibyte_string;
6484 #ifdef CYGWIN
6485 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
6486 if (SCHARS (filename) > 0)
6487 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
6488 #endif
6490 CHECK_STRING (dir);
6491 CHECK_STRING (filename);
6493 /* The code in file_dialog_callback that attempts to set the text
6494 of the file name edit window when handling the CDN_INITDONE
6495 WM_NOTIFY message does not work. Setting filename to "Current
6496 Directory" in the only_dir_p case here does work however. */
6497 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6498 filename = build_string ("Current Directory");
6500 /* Convert the values we've computed so far to system form. */
6501 #ifdef NTGUI_UNICODE
6502 to_unicode (prompt, &prompt);
6503 to_unicode (dir, &dir);
6504 to_unicode (filename, &filename);
6505 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6506 report_file_error ("filename too long", default_filename);
6508 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
6509 #else /* !NTGUI_UNICODE */
6510 prompt = ENCODE_FILE (prompt);
6511 dir = ENCODE_FILE (dir);
6512 filename = ENCODE_FILE (filename);
6514 /* We modify these in-place, so make copies for safety. */
6515 dir = Fcopy_sequence (dir);
6516 unixtodos_filename (SDATA (dir));
6517 filename = Fcopy_sequence (filename);
6518 unixtodos_filename (SDATA (filename));
6519 if (SBYTES (filename) >= MAX_UTF8_PATH)
6520 report_file_error ("filename too long", default_filename);
6521 if (w32_unicode_filenames)
6523 filename_to_utf16 (SSDATA (dir), dir_w);
6524 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6526 /* filename_to_utf16 sets errno to ENOENT when the file
6527 name is too long or cannot be converted to UTF-16. */
6528 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6529 report_file_error ("filename too long", default_filename);
6531 len = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6532 SSDATA (prompt), -1, NULL, 0);
6533 if (len > 32768)
6534 len = 32768;
6535 prompt_w = alloca (len * sizeof (wchar_t));
6536 MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6537 SSDATA (prompt), -1, prompt_w, len);
6539 else
6541 filename_to_ansi (SSDATA (dir), dir_a);
6542 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6544 /* filename_to_ansi sets errno to ENOENT when the file
6545 name is too long or cannot be converted to UTF-16. */
6546 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6547 report_file_error ("filename too long", default_filename);
6549 len = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6550 SSDATA (prompt), -1, NULL, 0);
6551 if (len > 32768)
6552 len = 32768;
6553 prompt_w = alloca (len * sizeof (wchar_t));
6554 MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6555 SSDATA (prompt), -1, prompt_w, len);
6556 len = WideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
6557 if (len > 32768)
6558 len = 32768;
6559 prompt_a = alloca (len);
6560 WideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
6562 #endif /* NTGUI_UNICODE */
6564 /* Fill in the structure for the call to GetOpenFileName below.
6565 For NTGUI_UNICODE builds (which run only on NT), we just use
6566 the actual size of the structure. For non-NTGUI_UNICODE
6567 builds, we tell the OS we're using an old version of the
6568 structure if the OS isn't new enough to support the newer
6569 version. */
6570 if (use_unicode)
6572 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6573 if (w32_major_version > 4 && w32_major_version < 95)
6574 file_details_w->lStructSize = sizeof (new_file_details_w);
6575 else
6576 file_details_w->lStructSize = sizeof (*file_details_w);
6577 /* Set up the inout parameter for the selected file name. */
6578 file_details_w->lpstrFile = filename_buf_w;
6579 file_details_w->nMaxFile =
6580 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6581 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6582 /* Undocumented Bug in Common File Dialog:
6583 If a filter is not specified, shell links are not resolved. */
6584 file_details_w->lpstrFilter = filter_w;
6585 #ifdef NTGUI_UNICODE
6586 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
6587 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
6588 #else
6589 file_details_w->lpstrInitialDir = dir_w;
6590 file_details_w->lpstrTitle = prompt_w;
6591 #endif
6592 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6593 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6594 | OFN_EXPLORER | OFN_ENABLEHOOK);
6595 if (!NILP (mustmatch))
6597 /* Require that the path to the parent directory exists. */
6598 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6599 /* If we are looking for a file, require that it exists. */
6600 if (NILP (only_dir_p))
6601 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6604 #ifndef NTGUI_UNICODE
6605 else
6607 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6608 if (w32_major_version > 4 && w32_major_version < 95)
6609 file_details_a->lStructSize = sizeof (new_file_details_a);
6610 else
6611 file_details_a->lStructSize = sizeof (*file_details_a);
6612 file_details_a->lpstrFile = filename_buf_a;
6613 file_details_a->nMaxFile =
6614 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6615 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6616 file_details_a->lpstrFilter = filter_a;
6617 file_details_a->lpstrInitialDir = dir_a;
6618 file_details_a->lpstrTitle = prompt_a;
6619 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6620 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6621 | OFN_EXPLORER | OFN_ENABLEHOOK);
6622 if (!NILP (mustmatch))
6624 /* Require that the path to the parent directory exists. */
6625 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6626 /* If we are looking for a file, require that it exists. */
6627 if (NILP (only_dir_p))
6628 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6631 #endif /* !NTGUI_UNICODE */
6634 int count = SPECPDL_INDEX ();
6635 /* Prevent redisplay. */
6636 specbind (Qinhibit_redisplay, Qt);
6637 block_input ();
6638 if (use_unicode)
6640 file_details_w->lpfnHook = file_dialog_callback;
6642 file_opened = GetOpenFileNameW (file_details_w);
6644 #ifndef NTGUI_UNICODE
6645 else
6647 file_details_a->lpfnHook = file_dialog_callback;
6649 file_opened = GetOpenFileNameA (file_details_a);
6651 #endif /* !NTGUI_UNICODE */
6652 unblock_input ();
6653 unbind_to (count, Qnil);
6656 if (file_opened)
6658 /* Get an Emacs string from the value Windows gave us. */
6659 #ifdef NTGUI_UNICODE
6660 filename = from_unicode_buffer (filename_buf_w);
6661 #else /* !NTGUI_UNICODE */
6662 if (use_unicode)
6663 filename_from_utf16 (filename_buf_w, fname_ret);
6664 else
6665 filename_from_ansi (filename_buf_a, fname_ret);
6666 dostounix_filename (fname_ret);
6667 filename = DECODE_FILE (build_unibyte_string (fname_ret));
6668 #endif /* NTGUI_UNICODE */
6670 #ifdef CYGWIN
6671 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
6672 #endif /* CYGWIN */
6674 /* Strip the dummy filename off the end of the string if we
6675 added it to select a directory. */
6676 if ((use_unicode && file_details_w->nFilterIndex == 2)
6677 #ifndef NTGUI_UNICODE
6678 || (!use_unicode && file_details_a->nFilterIndex == 2)
6679 #endif
6681 filename = Ffile_name_directory (filename);
6683 /* User canceled the dialog without making a selection. */
6684 else if (!CommDlgExtendedError ())
6685 filename = Qnil;
6686 /* An error occurred, fallback on reading from the mini-buffer. */
6687 else
6688 filename = Fcompleting_read (
6689 orig_prompt,
6690 intern ("read-file-name-internal"),
6691 orig_dir,
6692 mustmatch,
6693 orig_dir,
6694 Qfile_name_history,
6695 default_filename,
6696 Qnil);
6698 UNGCPRO;
6701 /* Make "Cancel" equivalent to C-g. */
6702 if (NILP (filename))
6703 Fsignal (Qquit, Qnil);
6705 RETURN_UNGCPRO (filename);
6709 #ifdef WINDOWSNT
6710 /* Moving files to the system recycle bin.
6711 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6712 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6713 Ssystem_move_file_to_trash, 1, 1, 0,
6714 doc: /* Move file or directory named FILENAME to the recycle bin. */)
6715 (Lisp_Object filename)
6717 Lisp_Object handler;
6718 Lisp_Object encoded_file;
6719 Lisp_Object operation;
6721 operation = Qdelete_file;
6722 if (!NILP (Ffile_directory_p (filename))
6723 && NILP (Ffile_symlink_p (filename)))
6725 operation = intern ("delete-directory");
6726 filename = Fdirectory_file_name (filename);
6729 /* Must have fully qualified file names for moving files to Recycle
6730 Bin. */
6731 filename = Fexpand_file_name (filename, Qnil);
6733 handler = Ffind_file_name_handler (filename, operation);
6734 if (!NILP (handler))
6735 return call2 (handler, operation, filename);
6736 else
6738 const char * path;
6739 int result;
6741 encoded_file = ENCODE_FILE (filename);
6743 path = map_w32_filename (SDATA (encoded_file), NULL);
6745 /* The Unicode version of SHFileOperation is not supported on
6746 Windows 9X. */
6747 if (w32_unicode_filenames && os_subtype != OS_9X)
6749 SHFILEOPSTRUCTW file_op_w;
6750 /* We need one more element beyond MAX_PATH because this is
6751 a list of file names, with the last element double-null
6752 terminated. */
6753 wchar_t tmp_path_w[MAX_PATH + 1];
6755 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6756 filename_to_utf16 (path, tmp_path_w);
6758 /* On Windows, write permission is required to delete/move files. */
6759 _wchmod (tmp_path_w, 0666);
6761 memset (&file_op_w, 0, sizeof (file_op_w));
6762 file_op_w.hwnd = HWND_DESKTOP;
6763 file_op_w.wFunc = FO_DELETE;
6764 file_op_w.pFrom = tmp_path_w;
6765 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6766 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6767 file_op_w.fAnyOperationsAborted = FALSE;
6769 result = SHFileOperationW (&file_op_w);
6771 else
6773 SHFILEOPSTRUCTA file_op_a;
6774 char tmp_path_a[MAX_PATH + 1];
6776 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6777 filename_to_ansi (path, tmp_path_a);
6779 /* If a file cannot be represented in ANSI codepage, don't
6780 let them inadvertently delete other files because some
6781 characters are interpreted as a wildcards. */
6782 if (_mbspbrk (tmp_path_a, "?*"))
6783 result = ERROR_FILE_NOT_FOUND;
6784 else
6786 _chmod (tmp_path_a, 0666);
6788 memset (&file_op_a, 0, sizeof (file_op_a));
6789 file_op_a.hwnd = HWND_DESKTOP;
6790 file_op_a.wFunc = FO_DELETE;
6791 file_op_a.pFrom = tmp_path_a;
6792 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6793 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6794 file_op_a.fAnyOperationsAborted = FALSE;
6796 result = SHFileOperationA (&file_op_a);
6799 if (result != 0)
6800 report_file_error ("Removing old name", list1 (filename));
6802 return Qnil;
6805 #endif /* WINDOWSNT */
6808 /***********************************************************************
6809 w32 specialized functions
6810 ***********************************************************************/
6812 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6813 Sw32_send_sys_command, 1, 2, 0,
6814 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
6815 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
6816 to minimize), #xf120 to restore frame to original size, and #xf100
6817 to activate the menubar for keyboard access. #xf140 activates the
6818 screen saver if defined.
6820 If optional parameter FRAME is not specified, use selected frame. */)
6821 (Lisp_Object command, Lisp_Object frame)
6823 struct frame *f = decode_window_system_frame (frame);
6825 CHECK_NUMBER (command);
6827 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
6829 return Qnil;
6832 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
6833 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6834 This is a wrapper around the ShellExecute system function, which
6835 invokes the application registered to handle OPERATION for DOCUMENT.
6837 OPERATION is either nil or a string that names a supported operation.
6838 What operations can be used depends on the particular DOCUMENT and its
6839 handler application, but typically it is one of the following common
6840 operations:
6842 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6843 executable program. If it is an application, that
6844 application is launched in the current buffer's default
6845 directory. Otherwise, the application associated with
6846 DOCUMENT is launched in the buffer's default directory.
6847 \"print\" - print DOCUMENT, which must be a file
6848 \"explore\" - start the Windows Explorer on DOCUMENT
6849 \"edit\" - launch an editor and open DOCUMENT for editing; which
6850 editor is launched depends on the association for the
6851 specified DOCUMENT
6852 \"find\" - initiate search starting from DOCUMENT which must specify
6853 a directory
6854 \"runas\" - run DOCUMENT, which must be an excutable file, with
6855 elevated privileges (a.k.a. \"as Administrator\").
6856 nil - invoke the default OPERATION, or \"open\" if default is
6857 not defined or unavailable
6859 DOCUMENT is typically the name of a document file or a URL, but can
6860 also be a program executable to run, or a directory to open in the
6861 Windows Explorer. If it is a file, it must be a local one; this
6862 function does not support remote file names.
6864 If DOCUMENT is a program executable, the optional third arg PARAMETERS
6865 can be a string containing command line parameters that will be passed
6866 to the program; otherwise, PARAMETERS should be nil or unspecified.
6868 Optional fourth argument SHOW-FLAG can be used to control how the
6869 application will be displayed when it is invoked. If SHOW-FLAG is nil
6870 or unspecified, the application is displayed normally, otherwise it is
6871 an integer representing a ShowWindow flag:
6873 0 - start hidden
6874 1 - start normally
6875 3 - start maximized
6876 6 - start minimized */)
6877 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
6879 char *errstr;
6880 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6881 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
6882 intptr_t result;
6883 #ifndef CYGWIN
6884 int use_unicode = w32_unicode_filenames;
6885 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
6886 Lisp_Object absdoc;
6887 #endif
6889 CHECK_STRING (document);
6891 #ifdef CYGWIN
6892 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
6893 document = Fcygwin_convert_file_name_to_windows (document, Qt);
6895 /* Encode filename, current directory and parameters. */
6896 current_dir = GUI_ENCODE_FILE (current_dir);
6897 document = GUI_ENCODE_FILE (document);
6898 doc_w = GUI_SDATA (document);
6899 if (STRINGP (parameters))
6901 parameters = GUI_ENCODE_SYSTEM (parameters);
6902 params_w = GUI_SDATA (parameters);
6904 if (STRINGP (operation))
6906 operation = GUI_ENCODE_SYSTEM (operation);
6907 ops_w = GUI_SDATA (operation);
6909 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6910 GUI_SDATA (current_dir),
6911 (INTEGERP (show_flag)
6912 ? XINT (show_flag) : SW_SHOWDEFAULT));
6913 #else /* !CYGWIN */
6914 current_dir = ENCODE_FILE (current_dir);
6915 /* We have a situation here. If DOCUMENT is a relative file name,
6916 and is not in CURRENT_DIR, ShellExecute below will fail to find
6917 it. So we need to make the file name absolute. But DOCUMENT
6918 does not have to be a file, it can be a URL, for example. So we
6919 make it absolute only if it is an existing file; if it is a file
6920 that does not exist, tough. */
6921 absdoc = Fexpand_file_name (document, Qnil);
6922 if (!NILP (Ffile_exists_p (absdoc)))
6923 document = absdoc;
6924 document = ENCODE_FILE (document);
6925 if (use_unicode)
6927 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
6929 /* Encode filename, current directory and parameters, and
6930 convert operation to UTF-16. */
6931 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
6932 filename_to_utf16 (SSDATA (document), document_w);
6933 doc_w = document_w;
6934 if (STRINGP (parameters))
6936 int len;
6938 parameters = ENCODE_SYSTEM (parameters);
6939 len = MultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
6940 SSDATA (parameters), -1, NULL, 0);
6941 if (len > 32768)
6942 len = 32768;
6943 params_w = alloca (len * sizeof (wchar_t));
6944 MultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
6945 SSDATA (parameters), -1, params_w, len);
6947 if (STRINGP (operation))
6949 /* Assume OPERATION is pure ASCII. */
6950 const char *s = SSDATA (operation);
6951 wchar_t *d;
6952 int len = SBYTES (operation) + 1;
6954 if (len > 32768)
6955 len = 32768;
6956 d = ops_w = alloca (len * sizeof (wchar_t));
6957 while (d < ops_w + len - 1)
6958 *d++ = *s++;
6959 *d = 0;
6961 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6962 current_dir_w,
6963 (INTEGERP (show_flag)
6964 ? XINT (show_flag) : SW_SHOWDEFAULT));
6966 else
6968 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
6970 filename_to_ansi (SSDATA (current_dir), current_dir_a);
6971 filename_to_ansi (SSDATA (document), document_a);
6972 doc_a = document_a;
6973 if (STRINGP (parameters))
6975 parameters = ENCODE_SYSTEM (parameters);
6976 params_a = SSDATA (parameters);
6978 if (STRINGP (operation))
6980 /* Assume OPERATION is pure ASCII. */
6981 ops_a = SSDATA (operation);
6983 result = (intptr_t) ShellExecuteA (NULL, ops_a, doc_a, params_a,
6984 current_dir_a,
6985 (INTEGERP (show_flag)
6986 ? XINT (show_flag) : SW_SHOWDEFAULT));
6988 #endif /* !CYGWIN */
6990 if (result > 32)
6991 return Qt;
6993 switch (result)
6995 case SE_ERR_ACCESSDENIED:
6996 errstr = w32_strerror (ERROR_ACCESS_DENIED);
6997 break;
6998 case SE_ERR_ASSOCINCOMPLETE:
6999 case SE_ERR_NOASSOC:
7000 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7001 break;
7002 case SE_ERR_DDEBUSY:
7003 case SE_ERR_DDEFAIL:
7004 errstr = w32_strerror (ERROR_DDE_FAIL);
7005 break;
7006 case SE_ERR_DDETIMEOUT:
7007 errstr = w32_strerror (ERROR_TIMEOUT);
7008 break;
7009 case SE_ERR_DLLNOTFOUND:
7010 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7011 break;
7012 case SE_ERR_FNF:
7013 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7014 break;
7015 case SE_ERR_OOM:
7016 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7017 break;
7018 case SE_ERR_PNF:
7019 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7020 break;
7021 case SE_ERR_SHARE:
7022 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7023 break;
7024 default:
7025 errstr = w32_strerror (0);
7026 break;
7028 /* The error string might be encoded in the locale's encoding. */
7029 if (!NILP (Vlocale_coding_system))
7031 Lisp_Object decoded =
7032 code_convert_string_norecord (build_unibyte_string (errstr),
7033 Vlocale_coding_system, 0);
7034 errstr = SSDATA (decoded);
7036 error ("ShellExecute failed: %s", errstr);
7039 /* Lookup virtual keycode from string representing the name of a
7040 non-ascii keystroke into the corresponding virtual key, using
7041 lispy_function_keys. */
7042 static int
7043 lookup_vk_code (char *key)
7045 int i;
7047 for (i = 0; i < 256; i++)
7048 if (lispy_function_keys[i]
7049 && strcmp (lispy_function_keys[i], key) == 0)
7050 return i;
7052 return -1;
7055 /* Convert a one-element vector style key sequence to a hot key
7056 definition. */
7057 static Lisp_Object
7058 w32_parse_hot_key (Lisp_Object key)
7060 /* Copied from Fdefine_key and store_in_keymap. */
7061 register Lisp_Object c;
7062 int vk_code;
7063 int lisp_modifiers;
7064 int w32_modifiers;
7065 struct gcpro gcpro1;
7067 CHECK_VECTOR (key);
7069 if (ASIZE (key) != 1)
7070 return Qnil;
7072 GCPRO1 (key);
7074 c = AREF (key, 0);
7076 if (CONSP (c) && lucid_event_type_list_p (c))
7077 c = Fevent_convert_list (c);
7079 UNGCPRO;
7081 if (! INTEGERP (c) && ! SYMBOLP (c))
7082 error ("Key definition is invalid");
7084 /* Work out the base key and the modifiers. */
7085 if (SYMBOLP (c))
7087 c = parse_modifiers (c);
7088 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7089 c = Fcar (c);
7090 if (!SYMBOLP (c))
7091 emacs_abort ();
7092 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7094 else if (INTEGERP (c))
7096 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7097 /* Many ascii characters are their own virtual key code. */
7098 vk_code = XINT (c) & CHARACTERBITS;
7101 if (vk_code < 0 || vk_code > 255)
7102 return Qnil;
7104 if ((lisp_modifiers & meta_modifier) != 0
7105 && !NILP (Vw32_alt_is_meta))
7106 lisp_modifiers |= alt_modifier;
7108 /* Supply defs missing from mingw32. */
7109 #ifndef MOD_ALT
7110 #define MOD_ALT 0x0001
7111 #define MOD_CONTROL 0x0002
7112 #define MOD_SHIFT 0x0004
7113 #define MOD_WIN 0x0008
7114 #endif
7116 /* Convert lisp modifiers to Windows hot-key form. */
7117 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7118 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7119 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7120 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7122 return HOTKEY (vk_code, w32_modifiers);
7125 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7126 Sw32_register_hot_key, 1, 1, 0,
7127 doc: /* Register KEY as a hot-key combination.
7128 Certain key combinations like Alt-Tab are reserved for system use on
7129 Windows, and therefore are normally intercepted by the system. However,
7130 most of these key combinations can be received by registering them as
7131 hot-keys, overriding their special meaning.
7133 KEY must be a one element key definition in vector form that would be
7134 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7135 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7136 is always interpreted as the Windows modifier keys.
7138 The return value is the hotkey-id if registered, otherwise nil. */)
7139 (Lisp_Object key)
7141 key = w32_parse_hot_key (key);
7143 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7145 /* Reuse an empty slot if possible. */
7146 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7148 /* Safe to add new key to list, even if we have focus. */
7149 if (NILP (item))
7150 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7151 else
7152 XSETCAR (item, key);
7154 /* Notify input thread about new hot-key definition, so that it
7155 takes effect without needing to switch focus. */
7156 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7157 (WPARAM) XLI (key), 0);
7160 return key;
7163 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7164 Sw32_unregister_hot_key, 1, 1, 0,
7165 doc: /* Unregister KEY as a hot-key combination. */)
7166 (Lisp_Object key)
7168 Lisp_Object item;
7170 if (!INTEGERP (key))
7171 key = w32_parse_hot_key (key);
7173 item = Fmemq (key, w32_grabbed_keys);
7175 if (!NILP (item))
7177 /* Notify input thread about hot-key definition being removed, so
7178 that it takes effect without needing focus switch. */
7179 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7180 (WPARAM) XINT (XCAR (item)), (LPARAM) XLI (item)))
7182 MSG msg;
7183 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7185 return Qt;
7187 return Qnil;
7190 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7191 Sw32_registered_hot_keys, 0, 0, 0,
7192 doc: /* Return list of registered hot-key IDs. */)
7193 (void)
7195 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7198 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7199 Sw32_reconstruct_hot_key, 1, 1, 0,
7200 doc: /* Convert hot-key ID to a lisp key combination.
7201 usage: (w32-reconstruct-hot-key ID) */)
7202 (Lisp_Object hotkeyid)
7204 int vk_code, w32_modifiers;
7205 Lisp_Object key;
7207 CHECK_NUMBER (hotkeyid);
7209 vk_code = HOTKEY_VK_CODE (hotkeyid);
7210 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7212 if (vk_code < 256 && lispy_function_keys[vk_code])
7213 key = intern (lispy_function_keys[vk_code]);
7214 else
7215 key = make_number (vk_code);
7217 key = Fcons (key, Qnil);
7218 if (w32_modifiers & MOD_SHIFT)
7219 key = Fcons (Qshift, key);
7220 if (w32_modifiers & MOD_CONTROL)
7221 key = Fcons (Qctrl, key);
7222 if (w32_modifiers & MOD_ALT)
7223 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7224 if (w32_modifiers & MOD_WIN)
7225 key = Fcons (Qhyper, key);
7227 return key;
7230 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7231 Sw32_toggle_lock_key, 1, 2, 0,
7232 doc: /* Toggle the state of the lock key KEY.
7233 KEY can be `capslock', `kp-numlock', or `scroll'.
7234 If the optional parameter NEW-STATE is a number, then the state of KEY
7235 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
7236 (Lisp_Object key, Lisp_Object new_state)
7238 int vk_code;
7240 if (EQ (key, intern ("capslock")))
7241 vk_code = VK_CAPITAL;
7242 else if (EQ (key, intern ("kp-numlock")))
7243 vk_code = VK_NUMLOCK;
7244 else if (EQ (key, intern ("scroll")))
7245 vk_code = VK_SCROLL;
7246 else
7247 return Qnil;
7249 if (!dwWindowsThreadId)
7250 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7252 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7253 (WPARAM) vk_code, (LPARAM) XLI (new_state)))
7255 MSG msg;
7256 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7257 return make_number (msg.wParam);
7259 return Qnil;
7262 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7263 2, 2, 0,
7264 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7266 This is a direct interface to the Windows API FindWindow function. */)
7267 (Lisp_Object class, Lisp_Object name)
7269 HWND hnd;
7271 if (!NILP (class))
7272 CHECK_STRING (class);
7273 if (!NILP (name))
7274 CHECK_STRING (name);
7276 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7277 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7278 if (!hnd)
7279 return Qnil;
7280 return Qt;
7283 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7284 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7285 FRAME must be a live frame and defaults to the selected one.
7287 The boundary rectangle is a list of four elements, specifying the left,
7288 top, right and bottom screen coordinates of FRAME including menu and
7289 title bar and decorations. Optional argument CLIENT non-nil means to
7290 return the boundaries of the client rectangle which excludes menu and
7291 title bar and decorations. */)
7292 (Lisp_Object frame, Lisp_Object client)
7294 struct frame *f = decode_live_frame (frame);
7295 RECT rect;
7297 if (!NILP (client))
7298 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7299 else
7300 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7302 return list4 (make_number (rect.left), make_number (rect.top),
7303 make_number (rect.right), make_number (rect.bottom));
7306 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7307 doc: /* Get power status information from Windows system.
7309 The following %-sequences are provided:
7310 %L AC line status (verbose)
7311 %B Battery status (verbose)
7312 %b Battery status, empty means high, `-' means low,
7313 `!' means critical, and `+' means charging
7314 %p Battery load percentage
7315 %s Remaining time (to charge or discharge) in seconds
7316 %m Remaining time (to charge or discharge) in minutes
7317 %h Remaining time (to charge or discharge) in hours
7318 %t Remaining time (to charge or discharge) in the form `h:min' */)
7319 (void)
7321 Lisp_Object status = Qnil;
7323 SYSTEM_POWER_STATUS system_status;
7324 if (GetSystemPowerStatus (&system_status))
7326 Lisp_Object line_status, battery_status, battery_status_symbol;
7327 Lisp_Object load_percentage, seconds, minutes, hours, remain;
7329 long seconds_left = (long) system_status.BatteryLifeTime;
7331 if (system_status.ACLineStatus == 0)
7332 line_status = build_string ("off-line");
7333 else if (system_status.ACLineStatus == 1)
7334 line_status = build_string ("on-line");
7335 else
7336 line_status = build_string ("N/A");
7338 if (system_status.BatteryFlag & 128)
7340 battery_status = build_string ("N/A");
7341 battery_status_symbol = empty_unibyte_string;
7343 else if (system_status.BatteryFlag & 8)
7345 battery_status = build_string ("charging");
7346 battery_status_symbol = build_string ("+");
7347 if (system_status.BatteryFullLifeTime != -1L)
7348 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7350 else if (system_status.BatteryFlag & 4)
7352 battery_status = build_string ("critical");
7353 battery_status_symbol = build_string ("!");
7355 else if (system_status.BatteryFlag & 2)
7357 battery_status = build_string ("low");
7358 battery_status_symbol = build_string ("-");
7360 else if (system_status.BatteryFlag & 1)
7362 battery_status = build_string ("high");
7363 battery_status_symbol = empty_unibyte_string;
7365 else
7367 battery_status = build_string ("medium");
7368 battery_status_symbol = empty_unibyte_string;
7371 if (system_status.BatteryLifePercent > 100)
7372 load_percentage = build_string ("N/A");
7373 else
7375 char buffer[16];
7376 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
7377 load_percentage = build_string (buffer);
7380 if (seconds_left < 0)
7381 seconds = minutes = hours = remain = build_string ("N/A");
7382 else
7384 long m;
7385 float h;
7386 char buffer[16];
7387 snprintf (buffer, 16, "%ld", seconds_left);
7388 seconds = build_string (buffer);
7390 m = seconds_left / 60;
7391 snprintf (buffer, 16, "%ld", m);
7392 minutes = build_string (buffer);
7394 h = seconds_left / 3600.0;
7395 snprintf (buffer, 16, "%3.1f", h);
7396 hours = build_string (buffer);
7398 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
7399 remain = build_string (buffer);
7402 status = listn (CONSTYPE_HEAP, 8,
7403 Fcons (make_number ('L'), line_status),
7404 Fcons (make_number ('B'), battery_status),
7405 Fcons (make_number ('b'), battery_status_symbol),
7406 Fcons (make_number ('p'), load_percentage),
7407 Fcons (make_number ('s'), seconds),
7408 Fcons (make_number ('m'), minutes),
7409 Fcons (make_number ('h'), hours),
7410 Fcons (make_number ('t'), remain));
7412 return status;
7416 #ifdef WINDOWSNT
7417 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
7418 doc: /* Return storage information about the file system FILENAME is on.
7419 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7420 storage of the file system, FREE is the free storage, and AVAIL is the
7421 storage available to a non-superuser. All 3 numbers are in bytes.
7422 If the underlying system call fails, value is nil. */)
7423 (Lisp_Object filename)
7425 Lisp_Object encoded, value;
7427 CHECK_STRING (filename);
7428 filename = Fexpand_file_name (filename, Qnil);
7429 encoded = ENCODE_FILE (filename);
7431 value = Qnil;
7433 /* Determining the required information on Windows turns out, sadly,
7434 to be more involved than one would hope. The original Windows API
7435 call for this will return bogus information on some systems, but we
7436 must dynamically probe for the replacement api, since that was
7437 added rather late on. */
7439 HMODULE hKernel = GetModuleHandle ("kernel32");
7440 BOOL (*pfn_GetDiskFreeSpaceExW)
7441 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7442 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7443 BOOL (*pfn_GetDiskFreeSpaceExA)
7444 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7445 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
7446 bool have_pfn_GetDiskFreeSpaceEx =
7447 (w32_unicode_filenames && pfn_GetDiskFreeSpaceExW
7448 || !w32_unicode_filenames && pfn_GetDiskFreeSpaceExA);
7450 /* On Windows, we may need to specify the root directory of the
7451 volume holding FILENAME. */
7452 char rootname[MAX_UTF8_PATH];
7453 wchar_t rootname_w[MAX_PATH];
7454 char rootname_a[MAX_PATH];
7455 char *name = SDATA (encoded);
7456 BOOL result;
7458 /* find the root name of the volume if given */
7459 if (isalpha (name[0]) && name[1] == ':')
7461 rootname[0] = name[0];
7462 rootname[1] = name[1];
7463 rootname[2] = '\\';
7464 rootname[3] = 0;
7466 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7468 char *str = rootname;
7469 int slashes = 4;
7472 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7473 break;
7474 *str++ = *name++;
7476 while ( *name );
7478 *str++ = '\\';
7479 *str = 0;
7482 if (w32_unicode_filenames)
7483 filename_to_utf16 (rootname, rootname_w);
7484 else
7485 filename_to_ansi (rootname, rootname_a);
7487 if (have_pfn_GetDiskFreeSpaceEx)
7489 /* Unsigned large integers cannot be cast to double, so
7490 use signed ones instead. */
7491 LARGE_INTEGER availbytes;
7492 LARGE_INTEGER freebytes;
7493 LARGE_INTEGER totalbytes;
7495 if (w32_unicode_filenames)
7496 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7497 (ULARGE_INTEGER *)&availbytes,
7498 (ULARGE_INTEGER *)&totalbytes,
7499 (ULARGE_INTEGER *)&freebytes);
7500 else
7501 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7502 (ULARGE_INTEGER *)&availbytes,
7503 (ULARGE_INTEGER *)&totalbytes,
7504 (ULARGE_INTEGER *)&freebytes);
7505 if (result)
7506 value = list3 (make_float ((double) totalbytes.QuadPart),
7507 make_float ((double) freebytes.QuadPart),
7508 make_float ((double) availbytes.QuadPart));
7510 else
7512 DWORD sectors_per_cluster;
7513 DWORD bytes_per_sector;
7514 DWORD free_clusters;
7515 DWORD total_clusters;
7517 if (w32_unicode_filenames)
7518 result = GetDiskFreeSpaceW (rootname_w,
7519 &sectors_per_cluster,
7520 &bytes_per_sector,
7521 &free_clusters,
7522 &total_clusters);
7523 else
7524 result = GetDiskFreeSpaceA (rootname_a,
7525 &sectors_per_cluster,
7526 &bytes_per_sector,
7527 &free_clusters,
7528 &total_clusters);
7529 if (result)
7530 value = list3 (make_float ((double) total_clusters
7531 * sectors_per_cluster * bytes_per_sector),
7532 make_float ((double) free_clusters
7533 * sectors_per_cluster * bytes_per_sector),
7534 make_float ((double) free_clusters
7535 * sectors_per_cluster * bytes_per_sector));
7539 return value;
7541 #endif /* WINDOWSNT */
7544 #ifdef WINDOWSNT
7545 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7546 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
7547 (void)
7549 static char pname_buf[256];
7550 int err;
7551 HANDLE hPrn;
7552 PRINTER_INFO_2W *ppi2w = NULL;
7553 PRINTER_INFO_2A *ppi2a = NULL;
7554 DWORD dwNeeded = 0, dwReturned = 0;
7555 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7556 char port_name[MAX_UTF8_PATH];
7558 /* Retrieve the default string from Win.ini (the registry).
7559 * String will be in form "printername,drivername,portname".
7560 * This is the most portable way to get the default printer. */
7561 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7562 return Qnil;
7563 /* printername precedes first "," character */
7564 strtok (pname_buf, ",");
7565 /* We want to know more than the printer name */
7566 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7567 return Qnil;
7568 /* GetPrinterW is not supported by unicows.dll. */
7569 if (w32_unicode_filenames && os_subtype != OS_9X)
7570 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7571 else
7572 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
7573 if (dwNeeded == 0)
7575 ClosePrinter (hPrn);
7576 return Qnil;
7578 /* Call GetPrinter again with big enough memory block. */
7579 if (w32_unicode_filenames && os_subtype != OS_9X)
7581 /* Allocate memory for the PRINTER_INFO_2 struct. */
7582 ppi2w = xmalloc (dwNeeded);
7583 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
7584 ClosePrinter (hPrn);
7585 if (!err)
7587 xfree (ppi2w);
7588 return Qnil;
7591 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7592 && ppi2w->pServerName)
7594 filename_from_utf16 (ppi2w->pServerName, server_name);
7595 filename_from_utf16 (ppi2w->pShareName, share_name);
7597 else
7599 server_name[0] = '\0';
7600 filename_from_utf16 (ppi2w->pPortName, port_name);
7603 else
7605 ppi2a = xmalloc (dwNeeded);
7606 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7607 ClosePrinter (hPrn);
7608 if (!err)
7610 xfree (ppi2a);
7611 return Qnil;
7614 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7615 && ppi2a->pServerName)
7617 filename_from_ansi (ppi2a->pServerName, server_name);
7618 filename_from_ansi (ppi2a->pShareName, share_name);
7620 else
7622 server_name[0] = '\0';
7623 filename_from_ansi (ppi2a->pPortName, port_name);
7627 if (server_name[0])
7629 /* a remote printer */
7630 if (server_name[0] == '\\')
7631 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7632 share_name);
7633 else
7634 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7635 share_name);
7636 pname_buf[sizeof (pname_buf) - 1] = '\0';
7638 else
7640 /* a local printer */
7641 strncpy (pname_buf, port_name, sizeof (pname_buf));
7642 pname_buf[sizeof (pname_buf) - 1] = '\0';
7643 /* `pPortName' can include several ports, delimited by ','.
7644 * we only use the first one. */
7645 strtok (pname_buf, ",");
7648 return DECODE_FILE (build_unibyte_string (pname_buf));
7650 #endif /* WINDOWSNT */
7653 /* Equivalent of strerror for W32 error codes. */
7654 char *
7655 w32_strerror (int error_no)
7657 static char buf[500];
7658 DWORD ret;
7660 if (error_no == 0)
7661 error_no = GetLastError ();
7663 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7664 FORMAT_MESSAGE_IGNORE_INSERTS,
7665 NULL,
7666 error_no,
7667 0, /* choose most suitable language */
7668 buf, sizeof (buf), NULL);
7670 while (ret > 0 && (buf[ret - 1] == '\n' ||
7671 buf[ret - 1] == '\r' ))
7672 --ret;
7673 buf[ret] = '\0';
7674 if (!ret)
7675 sprintf (buf, "w32 error %u", error_no);
7677 return buf;
7680 /* For convenience when debugging. (You cannot call GetLastError
7681 directly from GDB: it will crash, because it uses the __stdcall
7682 calling convention, not the _cdecl convention assumed by GDB.) */
7683 DWORD
7684 w32_last_error (void)
7686 return GetLastError ();
7689 /* Cache information describing the NT system for later use. */
7690 void
7691 cache_system_info (void)
7693 union
7695 struct info
7697 char major;
7698 char minor;
7699 short platform;
7700 } info;
7701 DWORD data;
7702 } version;
7704 /* Cache the module handle of Emacs itself. */
7705 hinst = GetModuleHandle (NULL);
7707 /* Cache the version of the operating system. */
7708 version.data = GetVersion ();
7709 w32_major_version = version.info.major;
7710 w32_minor_version = version.info.minor;
7712 if (version.info.platform & 0x8000)
7713 os_subtype = OS_9X;
7714 else
7715 os_subtype = OS_NT;
7717 /* Cache page size, allocation unit, processor type, etc. */
7718 GetSystemInfo (&sysinfo_cache);
7719 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
7721 /* Cache os info. */
7722 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7723 GetVersionEx (&osinfo_cache);
7725 w32_build_number = osinfo_cache.dwBuildNumber;
7726 if (os_subtype == OS_9X)
7727 w32_build_number &= 0xffff;
7729 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
7732 #ifdef EMACSDEBUG
7733 void
7734 _DebPrint (const char *fmt, ...)
7736 char buf[1024];
7737 va_list args;
7739 va_start (args, fmt);
7740 vsprintf (buf, fmt, args);
7741 va_end (args);
7742 #if CYGWIN
7743 fprintf (stderr, "%s", buf);
7744 #endif
7745 OutputDebugString (buf);
7747 #endif
7750 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
7752 int cur_state = (GetKeyState (vk_code) & 1);
7754 if (NILP (new_state)
7755 || (NUMBERP (new_state)
7756 && ((XUINT (new_state)) & 1) != cur_state))
7758 #ifdef WINDOWSNT
7759 faked_key = vk_code;
7760 #endif /* WINDOWSNT */
7762 keybd_event ((BYTE) vk_code,
7763 (BYTE) MapVirtualKey (vk_code, 0),
7764 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7765 keybd_event ((BYTE) vk_code,
7766 (BYTE) MapVirtualKey (vk_code, 0),
7767 KEYEVENTF_EXTENDEDKEY | 0, 0);
7768 keybd_event ((BYTE) vk_code,
7769 (BYTE) MapVirtualKey (vk_code, 0),
7770 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7771 cur_state = !cur_state;
7774 return cur_state;
7777 /* Translate console modifiers to emacs modifiers.
7778 German keyboard support (Kai Morgan Zeise 2/18/95). */
7780 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
7782 int retval = 0;
7784 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
7785 pressed, first remove those modifiers. */
7786 if (!NILP (Vw32_recognize_altgr)
7787 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7788 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7789 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
7791 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
7792 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
7794 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7796 retval |= ctrl_modifier;
7797 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7798 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7799 retval |= meta_modifier;
7802 if (mods & LEFT_WIN_PRESSED)
7803 retval |= w32_key_to_modifier (VK_LWIN);
7804 if (mods & RIGHT_WIN_PRESSED)
7805 retval |= w32_key_to_modifier (VK_RWIN);
7806 if (mods & APPS_PRESSED)
7807 retval |= w32_key_to_modifier (VK_APPS);
7808 if (mods & SCROLLLOCK_ON)
7809 retval |= w32_key_to_modifier (VK_SCROLL);
7811 /* Just in case someone wanted the original behavior, make it
7812 optional by setting w32-capslock-is-shiftlock to t. */
7813 if (NILP (Vw32_capslock_is_shiftlock)
7814 /* Keys that should _not_ be affected by CapsLock. */
7815 && ( (key == VK_BACK)
7816 || (key == VK_TAB)
7817 || (key == VK_CLEAR)
7818 || (key == VK_RETURN)
7819 || (key == VK_ESCAPE)
7820 || ((key >= VK_SPACE) && (key <= VK_HELP))
7821 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
7822 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
7825 /* Only consider shift state. */
7826 if ((mods & SHIFT_PRESSED) != 0)
7827 retval |= shift_modifier;
7829 else
7831 /* Ignore CapsLock state if not enabled. */
7832 if (NILP (Vw32_enable_caps_lock))
7833 mods &= ~CAPSLOCK_ON;
7834 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
7835 retval |= shift_modifier;
7838 return retval;
7841 /* The return code indicates key code size. cpID is the codepage to
7842 use for translation to Unicode; -1 means use the current console
7843 input codepage. */
7845 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
7847 unsigned int key_code = event->wVirtualKeyCode;
7848 unsigned int mods = event->dwControlKeyState;
7849 BYTE keystate[256];
7850 static BYTE ansi_code[4];
7851 static int isdead = 0;
7853 if (isdead == 2)
7855 event->uChar.AsciiChar = ansi_code[2];
7856 isdead = 0;
7857 return 1;
7859 if (event->uChar.AsciiChar != 0)
7860 return 1;
7862 memset (keystate, 0, sizeof (keystate));
7863 keystate[key_code] = 0x80;
7864 if (mods & SHIFT_PRESSED)
7865 keystate[VK_SHIFT] = 0x80;
7866 if (mods & CAPSLOCK_ON)
7867 keystate[VK_CAPITAL] = 1;
7868 /* If we recognize right-alt and left-ctrl as AltGr, set the key
7869 states accordingly before invoking ToAscii. */
7870 if (!NILP (Vw32_recognize_altgr)
7871 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
7873 keystate[VK_CONTROL] = 0x80;
7874 keystate[VK_LCONTROL] = 0x80;
7875 keystate[VK_MENU] = 0x80;
7876 keystate[VK_RMENU] = 0x80;
7879 #if 0
7880 /* Because of an OS bug, ToAscii corrupts the stack when called to
7881 convert a dead key in console mode on NT4. Unfortunately, trying
7882 to check for dead keys using MapVirtualKey doesn't work either -
7883 these functions apparently use internal information about keyboard
7884 layout which doesn't get properly updated in console programs when
7885 changing layout (though apparently it gets partly updated,
7886 otherwise ToAscii wouldn't crash). */
7887 if (is_dead_key (event->wVirtualKeyCode))
7888 return 0;
7889 #endif
7891 /* On NT, call ToUnicode instead and then convert to the current
7892 console input codepage. */
7893 if (os_subtype == OS_NT)
7895 WCHAR buf[128];
7897 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
7898 keystate, buf, 128, 0);
7899 if (isdead > 0)
7901 /* When we are called from the GUI message processing code,
7902 we are passed the current keyboard codepage, a positive
7903 number, to use below. */
7904 if (cpId == -1)
7905 cpId = GetConsoleCP ();
7907 event->uChar.UnicodeChar = buf[isdead - 1];
7908 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
7909 ansi_code, 4, NULL, NULL);
7911 else
7912 isdead = 0;
7914 else
7916 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
7917 keystate, (LPWORD) ansi_code, 0);
7920 if (isdead == 0)
7921 return 0;
7922 event->uChar.AsciiChar = ansi_code[0];
7923 return isdead;
7927 void
7928 w32_sys_ring_bell (struct frame *f)
7930 if (sound_type == 0xFFFFFFFF)
7932 Beep (666, 100);
7934 else if (sound_type == MB_EMACS_SILENT)
7936 /* Do nothing. */
7938 else
7939 MessageBeep (sound_type);
7943 /***********************************************************************
7944 Initialization
7945 ***********************************************************************/
7947 /* Keep this list in the same order as frame_parms in frame.c.
7948 Use 0 for unsupported frame parameters. */
7950 frame_parm_handler w32_frame_parm_handlers[] =
7952 x_set_autoraise,
7953 x_set_autolower,
7954 x_set_background_color,
7955 x_set_border_color,
7956 x_set_border_width,
7957 x_set_cursor_color,
7958 x_set_cursor_type,
7959 x_set_font,
7960 x_set_foreground_color,
7961 x_set_icon_name,
7962 x_set_icon_type,
7963 x_set_internal_border_width,
7964 x_set_right_divider_width,
7965 x_set_bottom_divider_width,
7966 x_set_menu_bar_lines,
7967 x_set_mouse_color,
7968 x_explicitly_set_name,
7969 x_set_scroll_bar_width,
7970 x_set_title,
7971 x_set_unsplittable,
7972 x_set_vertical_scroll_bars,
7973 x_set_visibility,
7974 x_set_tool_bar_lines,
7975 0, /* x_set_scroll_bar_foreground, */
7976 0, /* x_set_scroll_bar_background, */
7977 x_set_screen_gamma,
7978 x_set_line_spacing,
7979 x_set_fringe_width,
7980 x_set_fringe_width,
7981 0, /* x_set_wait_for_wm, */
7982 x_set_fullscreen,
7983 x_set_font_backend,
7984 x_set_alpha,
7985 0, /* x_set_sticky */
7986 0, /* x_set_tool_bar_position */
7989 void
7990 syms_of_w32fns (void)
7992 globals_of_w32fns ();
7993 track_mouse_window = NULL;
7995 w32_visible_system_caret_hwnd = NULL;
7997 DEFSYM (Qsuppress_icon, "suppress-icon");
7998 DEFSYM (Qundefined_color, "undefined-color");
7999 DEFSYM (Qcancel_timer, "cancel-timer");
8000 DEFSYM (Qhyper, "hyper");
8001 DEFSYM (Qsuper, "super");
8002 DEFSYM (Qmeta, "meta");
8003 DEFSYM (Qalt, "alt");
8004 DEFSYM (Qctrl, "ctrl");
8005 DEFSYM (Qcontrol, "control");
8006 DEFSYM (Qshift, "shift");
8007 DEFSYM (Qfont_param, "font-parameter");
8008 DEFSYM (Qgeometry, "geometry");
8009 DEFSYM (Qworkarea, "workarea");
8010 DEFSYM (Qmm_size, "mm-size");
8011 DEFSYM (Qframes, "frames");
8012 /* This is the end of symbol initialization. */
8015 Fput (Qundefined_color, Qerror_conditions,
8016 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8017 Fput (Qundefined_color, Qerror_message,
8018 build_pure_c_string ("Undefined color"));
8020 staticpro (&w32_grabbed_keys);
8021 w32_grabbed_keys = Qnil;
8023 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8024 doc: /* An array of color name mappings for Windows. */);
8025 Vw32_color_map = Qnil;
8027 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8028 doc: /* Non-nil if Alt key presses are passed on to Windows.
8029 When non-nil, for example, Alt pressed and released and then space will
8030 open the System menu. When nil, Emacs processes the Alt key events, and
8031 then silently swallows them. */);
8032 Vw32_pass_alt_to_system = Qnil;
8034 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8035 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8036 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8037 Vw32_alt_is_meta = Qt;
8039 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8040 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8041 w32_quit_key = 0;
8043 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8044 Vw32_pass_lwindow_to_system,
8045 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8047 When non-nil, the Start menu is opened by tapping the key.
8048 If you set this to nil, the left \"Windows\" key is processed by Emacs
8049 according to the value of `w32-lwindow-modifier', which see.
8051 Note that some combinations of the left \"Windows\" key with other keys are
8052 caught by Windows at low level, and so binding them in Emacs will have no
8053 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8054 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8055 the doc string of `w32-phantom-key-code'. */);
8056 Vw32_pass_lwindow_to_system = Qt;
8058 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8059 Vw32_pass_rwindow_to_system,
8060 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8062 When non-nil, the Start menu is opened by tapping the key.
8063 If you set this to nil, the right \"Windows\" key is processed by Emacs
8064 according to the value of `w32-rwindow-modifier', which see.
8066 Note that some combinations of the right \"Windows\" key with other keys are
8067 caught by Windows at low level, and so binding them in Emacs will have no
8068 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8069 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8070 the doc string of `w32-phantom-key-code'. */);
8071 Vw32_pass_rwindow_to_system = Qt;
8073 DEFVAR_LISP ("w32-phantom-key-code",
8074 Vw32_phantom_key_code,
8075 doc: /* Virtual key code used to generate \"phantom\" key presses.
8076 Value is a number between 0 and 255.
8078 Phantom key presses are generated in order to stop the system from
8079 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8080 `w32-pass-rwindow-to-system' is nil. */);
8081 /* Although 255 is technically not a valid key code, it works and
8082 means that this hack won't interfere with any real key code. */
8083 XSETINT (Vw32_phantom_key_code, 255);
8085 DEFVAR_LISP ("w32-enable-num-lock",
8086 Vw32_enable_num_lock,
8087 doc: /* If non-nil, the Num Lock key acts normally.
8088 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8089 Vw32_enable_num_lock = Qt;
8091 DEFVAR_LISP ("w32-enable-caps-lock",
8092 Vw32_enable_caps_lock,
8093 doc: /* If non-nil, the Caps Lock key acts normally.
8094 Set to nil to handle Caps Lock as the `capslock' key. */);
8095 Vw32_enable_caps_lock = Qt;
8097 DEFVAR_LISP ("w32-scroll-lock-modifier",
8098 Vw32_scroll_lock_modifier,
8099 doc: /* Modifier to use for the Scroll Lock ON state.
8100 The value can be hyper, super, meta, alt, control or shift for the
8101 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8102 Any other value will cause the Scroll Lock key to be ignored. */);
8103 Vw32_scroll_lock_modifier = Qnil;
8105 DEFVAR_LISP ("w32-lwindow-modifier",
8106 Vw32_lwindow_modifier,
8107 doc: /* Modifier to use for the left \"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 `lwindow' key.
8110 Any other value will cause the key to be ignored. */);
8111 Vw32_lwindow_modifier = Qnil;
8113 DEFVAR_LISP ("w32-rwindow-modifier",
8114 Vw32_rwindow_modifier,
8115 doc: /* Modifier to use for the right \"Windows\" key.
8116 The value can be hyper, super, meta, alt, control or shift for the
8117 respective modifier, or nil to appear as the `rwindow' key.
8118 Any other value will cause the key to be ignored. */);
8119 Vw32_rwindow_modifier = Qnil;
8121 DEFVAR_LISP ("w32-apps-modifier",
8122 Vw32_apps_modifier,
8123 doc: /* Modifier to use for the \"Apps\" key.
8124 The value can be hyper, super, meta, alt, control or shift for the
8125 respective modifier, or nil to appear as the `apps' key.
8126 Any other value will cause the key to be ignored. */);
8127 Vw32_apps_modifier = Qnil;
8129 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
8130 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8131 w32_enable_synthesized_fonts = 0;
8133 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
8134 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8135 Vw32_enable_palette = Qt;
8137 DEFVAR_INT ("w32-mouse-button-tolerance",
8138 w32_mouse_button_tolerance,
8139 doc: /* Analogue of double click interval for faking middle mouse events.
8140 The value is the minimum time in milliseconds that must elapse between
8141 left and right button down events before they are considered distinct events.
8142 If both mouse buttons are depressed within this interval, a middle mouse
8143 button down event is generated instead. */);
8144 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8146 DEFVAR_INT ("w32-mouse-move-interval",
8147 w32_mouse_move_interval,
8148 doc: /* Minimum interval between mouse move events.
8149 The value is the minimum time in milliseconds that must elapse between
8150 successive mouse move (or scroll bar drag) events before they are
8151 reported as lisp events. */);
8152 w32_mouse_move_interval = 0;
8154 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8155 w32_pass_extra_mouse_buttons_to_system,
8156 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8157 Recent versions of Windows support mice with up to five buttons.
8158 Since most applications don't support these extra buttons, most mouse
8159 drivers will allow you to map them to functions at the system level.
8160 If this variable is non-nil, Emacs will pass them on, allowing the
8161 system to handle them. */);
8162 w32_pass_extra_mouse_buttons_to_system = 0;
8164 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8165 w32_pass_multimedia_buttons_to_system,
8166 doc: /* If non-nil, media buttons are passed to Windows.
8167 Some modern keyboards contain buttons for controlling media players, web
8168 browsers and other applications. Generally these buttons are handled on a
8169 system wide basis, but by setting this to nil they are made available
8170 to Emacs for binding. Depending on your keyboard, additional keys that
8171 may be available are:
8173 browser-back, browser-forward, browser-refresh, browser-stop,
8174 browser-search, browser-favorites, browser-home,
8175 mail, mail-reply, mail-forward, mail-send,
8176 app-1, app-2,
8177 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8178 spell-check, correction-list, toggle-dictate-command,
8179 media-next, media-previous, media-stop, media-play-pause, media-select,
8180 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8181 media-channel-up, media-channel-down,
8182 volume-mute, volume-up, volume-down,
8183 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8184 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8185 w32_pass_multimedia_buttons_to_system = 1;
8187 #if 0 /* TODO: Mouse cursor customization. */
8188 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
8189 doc: /* The shape of the pointer when over text.
8190 Changing the value does not affect existing frames
8191 unless you set the mouse color. */);
8192 Vx_pointer_shape = Qnil;
8194 Vx_nontext_pointer_shape = Qnil;
8196 Vx_mode_pointer_shape = Qnil;
8198 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
8199 doc: /* The shape of the pointer when Emacs is busy.
8200 This variable takes effect when you create a new frame
8201 or when you set the mouse color. */);
8202 Vx_hourglass_pointer_shape = Qnil;
8204 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8205 Vx_sensitive_text_pointer_shape,
8206 doc: /* The shape of the pointer when over mouse-sensitive text.
8207 This variable takes effect when you create a new frame
8208 or when you set the mouse color. */);
8209 Vx_sensitive_text_pointer_shape = Qnil;
8211 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8212 Vx_window_horizontal_drag_shape,
8213 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8214 This variable takes effect when you create a new frame
8215 or when you set the mouse color. */);
8216 Vx_window_horizontal_drag_shape = Qnil;
8218 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8219 Vx_window_vertical_drag_shape,
8220 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8221 This variable takes effect when you create a new frame
8222 or when you set the mouse color. */);
8223 Vx_window_vertical_drag_shape = Qnil;
8224 #endif
8226 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
8227 doc: /* A string indicating the foreground color of the cursor box. */);
8228 Vx_cursor_fore_pixel = Qnil;
8230 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
8231 doc: /* Maximum size for tooltips.
8232 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8233 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8235 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
8236 doc: /* Non-nil if no window manager is in use.
8237 Emacs doesn't try to figure this out; this is always nil
8238 unless you set it to something else. */);
8239 /* We don't have any way to find this out, so set it to nil
8240 and maybe the user would like to set it to t. */
8241 Vx_no_window_manager = Qnil;
8243 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8244 Vx_pixel_size_width_font_regexp,
8245 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8247 Since Emacs gets width of a font matching with this regexp from
8248 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8249 such a font. This is especially effective for such large fonts as
8250 Chinese, Japanese, and Korean. */);
8251 Vx_pixel_size_width_font_regexp = Qnil;
8253 DEFVAR_LISP ("w32-bdf-filename-alist",
8254 Vw32_bdf_filename_alist,
8255 doc: /* List of bdf fonts and their corresponding filenames. */);
8256 Vw32_bdf_filename_alist = Qnil;
8258 DEFVAR_BOOL ("w32-strict-fontnames",
8259 w32_strict_fontnames,
8260 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8261 Default is nil, which allows old fontnames that are not XLFD compliant,
8262 and allows third-party CJK display to work by specifying false charset
8263 fields to trick Emacs into translating to Big5, SJIS etc.
8264 Setting this to t will prevent wrong fonts being selected when
8265 fontsets are automatically created. */);
8266 w32_strict_fontnames = 0;
8268 DEFVAR_BOOL ("w32-strict-painting",
8269 w32_strict_painting,
8270 doc: /* Non-nil means use strict rules for repainting frames.
8271 Set this to nil to get the old behavior for repainting; this should
8272 only be necessary if the default setting causes problems. */);
8273 w32_strict_painting = 1;
8275 #if 0 /* TODO: Port to W32 */
8276 defsubr (&Sx_change_window_property);
8277 defsubr (&Sx_delete_window_property);
8278 defsubr (&Sx_window_property);
8279 #endif
8280 defsubr (&Sxw_display_color_p);
8281 defsubr (&Sx_display_grayscale_p);
8282 defsubr (&Sxw_color_defined_p);
8283 defsubr (&Sxw_color_values);
8284 defsubr (&Sx_server_max_request_size);
8285 defsubr (&Sx_server_vendor);
8286 defsubr (&Sx_server_version);
8287 defsubr (&Sx_display_pixel_width);
8288 defsubr (&Sx_display_pixel_height);
8289 defsubr (&Sx_display_mm_width);
8290 defsubr (&Sx_display_mm_height);
8291 defsubr (&Sx_display_screens);
8292 defsubr (&Sx_display_planes);
8293 defsubr (&Sx_display_color_cells);
8294 defsubr (&Sx_display_visual_class);
8295 defsubr (&Sx_display_backing_store);
8296 defsubr (&Sx_display_save_under);
8297 defsubr (&Sx_create_frame);
8298 defsubr (&Sx_open_connection);
8299 defsubr (&Sx_close_connection);
8300 defsubr (&Sx_display_list);
8301 defsubr (&Sx_synchronize);
8303 /* W32 specific functions */
8305 defsubr (&Sw32_define_rgb_color);
8306 defsubr (&Sw32_default_color_map);
8307 defsubr (&Sw32_display_monitor_attributes_list);
8308 defsubr (&Sw32_send_sys_command);
8309 defsubr (&Sw32_shell_execute);
8310 defsubr (&Sw32_register_hot_key);
8311 defsubr (&Sw32_unregister_hot_key);
8312 defsubr (&Sw32_registered_hot_keys);
8313 defsubr (&Sw32_reconstruct_hot_key);
8314 defsubr (&Sw32_toggle_lock_key);
8315 defsubr (&Sw32_window_exists_p);
8316 defsubr (&Sw32_frame_rect);
8317 defsubr (&Sw32_battery_status);
8319 #ifdef WINDOWSNT
8320 defsubr (&Sfile_system_info);
8321 defsubr (&Sdefault_printer_name);
8322 #endif
8324 defsubr (&Sset_message_beep);
8326 hourglass_hwnd = NULL;
8328 defsubr (&Sx_show_tip);
8329 defsubr (&Sx_hide_tip);
8330 tip_timer = Qnil;
8331 staticpro (&tip_timer);
8332 tip_frame = Qnil;
8333 staticpro (&tip_frame);
8335 last_show_tip_args = Qnil;
8336 staticpro (&last_show_tip_args);
8338 defsubr (&Sx_file_dialog);
8339 #ifdef WINDOWSNT
8340 defsubr (&Ssystem_move_file_to_trash);
8341 #endif
8346 /* Crashing and reporting backtrace. */
8348 #ifndef CYGWIN
8349 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8350 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8351 #endif
8352 static DWORD except_code;
8353 static PVOID except_addr;
8355 #ifndef CYGWIN
8356 /* This handler records the exception code and the address where it
8357 was triggered so that this info could be included in the backtrace.
8358 Without that, the backtrace in some cases has no information
8359 whatsoever about the offending code, and looks as if the top-level
8360 exception handler in the MinGW startup code di the one that
8361 crashed. */
8362 static LONG CALLBACK
8363 my_exception_handler (EXCEPTION_POINTERS * exception_data)
8365 except_code = exception_data->ExceptionRecord->ExceptionCode;
8366 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8368 if (prev_exception_handler)
8369 return prev_exception_handler (exception_data);
8370 return EXCEPTION_EXECUTE_HANDLER;
8372 #endif
8374 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8375 PULONG);
8377 #define BACKTRACE_LIMIT_MAX 62
8380 w32_backtrace (void **buffer, int limit)
8382 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8383 HMODULE hm_kernel32 = NULL;
8385 if (!s_pfn_CaptureStackBackTrace)
8387 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8388 s_pfn_CaptureStackBackTrace =
8389 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8390 "RtlCaptureStackBackTrace");
8392 if (s_pfn_CaptureStackBackTrace)
8393 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8394 buffer, NULL);
8395 return 0;
8398 void
8399 emacs_abort (void)
8401 int button;
8402 button = MessageBox (NULL,
8403 "A fatal error has occurred!\n\n"
8404 "Would you like to attach a debugger?\n\n"
8405 "Select:\n"
8406 "YES -- to debug Emacs, or\n"
8407 "NO -- to abort Emacs and produce a backtrace\n"
8408 " (emacs_backtrace.txt in current directory)."
8409 #if __GNUC__
8410 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8411 "\"continue\" inside GDB before clicking YES.)"
8412 #endif
8413 , "Emacs Abort Dialog",
8414 MB_ICONEXCLAMATION | MB_TASKMODAL
8415 | MB_SETFOREGROUND | MB_YESNO);
8416 switch (button)
8418 case IDYES:
8419 DebugBreak ();
8420 exit (2); /* tell the compiler we will never return */
8421 case IDNO:
8422 default:
8424 void *stack[BACKTRACE_LIMIT_MAX + 1];
8425 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8427 if (i)
8429 int errfile_fd = -1;
8430 int j;
8431 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
8432 /* The type below should really be 'void *', but
8433 INT_BUFSIZE_BOUND cannot handle that without
8434 triggering compiler warnings (under certain
8435 pedantic warning switches), it wants an
8436 integer type. */
8437 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
8438 #ifdef CYGWIN
8439 int stderr_fd = 2;
8440 #else
8441 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
8442 int stderr_fd = -1;
8444 if (errout && errout != INVALID_HANDLE_VALUE)
8445 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
8446 #endif
8448 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8449 but not on Windows 7. addr2line doesn't mind a missing
8450 "0x", but will be confused by an extra one. */
8451 if (except_addr)
8452 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8453 except_code, except_addr);
8454 if (stderr_fd >= 0)
8456 if (except_addr)
8457 write (stderr_fd, buf, strlen (buf));
8458 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8460 #ifdef CYGWIN
8461 #define _open open
8462 #endif
8463 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8464 if (errfile_fd >= 0)
8466 lseek (errfile_fd, 0L, SEEK_END);
8467 if (except_addr)
8468 write (errfile_fd, buf, strlen (buf));
8469 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8472 for (j = 0; j < i; j++)
8474 /* stack[] gives the return addresses, whereas we want
8475 the address of the call, so decrease each address
8476 by approximate size of 1 CALL instruction. */
8477 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
8478 if (stderr_fd >= 0)
8479 write (stderr_fd, buf, strlen (buf));
8480 if (errfile_fd >= 0)
8481 write (errfile_fd, buf, strlen (buf));
8483 if (i == BACKTRACE_LIMIT_MAX)
8485 if (stderr_fd >= 0)
8486 write (stderr_fd, "...\r\n", 5);
8487 if (errfile_fd >= 0)
8488 write (errfile_fd, "...\r\n", 5);
8490 if (errfile_fd >= 0)
8491 close (errfile_fd);
8493 abort ();
8494 break;
8501 /* Initialization. */
8504 globals_of_w32fns is used to initialize those global variables that
8505 must always be initialized on startup even when the global variable
8506 initialized is non zero (see the function main in emacs.c).
8507 globals_of_w32fns is called from syms_of_w32fns when the global
8508 variable initialized is 0 and directly from main when initialized
8509 is non zero.
8511 void
8512 globals_of_w32fns (void)
8514 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8516 TrackMouseEvent not available in all versions of Windows, so must load
8517 it dynamically. Do it once, here, instead of every time it is used.
8519 track_mouse_event_fn = (TrackMouseEvent_Proc)
8520 GetProcAddress (user32_lib, "TrackMouseEvent");
8522 monitor_from_point_fn = (MonitorFromPoint_Proc)
8523 GetProcAddress (user32_lib, "MonitorFromPoint");
8524 get_monitor_info_fn = (GetMonitorInfo_Proc)
8525 GetProcAddress (user32_lib, "GetMonitorInfoA");
8526 monitor_from_window_fn = (MonitorFromWindow_Proc)
8527 GetProcAddress (user32_lib, "MonitorFromWindow");
8528 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8529 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8532 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8533 get_composition_string_fn = (ImmGetCompositionString_Proc)
8534 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8535 get_ime_context_fn = (ImmGetContext_Proc)
8536 GetProcAddress (imm32_lib, "ImmGetContext");
8537 release_ime_context_fn = (ImmReleaseContext_Proc)
8538 GetProcAddress (imm32_lib, "ImmReleaseContext");
8539 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8540 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8543 except_code = 0;
8544 except_addr = 0;
8545 #ifndef CYGWIN
8546 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8547 #endif
8549 DEFVAR_INT ("w32-ansi-code-page",
8550 w32_ansi_code_page,
8551 doc: /* The ANSI code page used by the system. */);
8552 w32_ansi_code_page = GetACP ();
8554 if (os_subtype == OS_NT)
8555 w32_unicode_gui = 1;
8556 else
8557 w32_unicode_gui = 0;
8559 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8560 InitCommonControls ();
8562 syms_of_w32uniscribe ();
8565 #ifdef NTGUI_UNICODE
8567 Lisp_Object
8568 ntgui_encode_system (Lisp_Object str)
8570 Lisp_Object encoded;
8571 to_unicode (str, &encoded);
8572 return encoded;
8575 #endif /* NTGUI_UNICODE */