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