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