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