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