use dynwind_begin and dynwind_end
[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;
2bfa3d3e 4347 dynwind_begin ();
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
2bfa3d3e
BT
4670 dynwind_end ();
4671 return frame;
ee78dc32
GV
4672}
4673
4674/* FRAME is used only to get a handle on the X display. We don't pass the
4675 display info directly because we're called from frame.c, which doesn't
4676 know about that structure. */
4677Lisp_Object
b56ceb92 4678x_get_focus_frame (struct frame *frame)
ee78dc32 4679{
aad3612f 4680 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
ee78dc32 4681 Lisp_Object xfocus;
fbd6baed 4682 if (! dpyinfo->w32_focus_frame)
ee78dc32
GV
4683 return Qnil;
4684
fbd6baed 4685 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
ee78dc32
GV
4686 return xfocus;
4687}
1edf84e7 4688
6fc2811b 4689DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4f4f2973
GM
4690 doc: /* Internal function called by `color-defined-p', which see.
4691\(Note that the Nextstep version of this function ignores FRAME.) */)
5842a27b 4692 (Lisp_Object color, Lisp_Object frame)
6fc2811b
JR
4693{
4694 XColor foo;
a10c8269 4695 struct frame *f = decode_window_system_frame (frame);
ee78dc32 4696
b7826503 4697 CHECK_STRING (color);
ee78dc32 4698
d5db4077 4699 if (w32_defined_color (f, SDATA (color), &foo, 0))
6fc2811b
JR
4700 return Qt;
4701 else
4702 return Qnil;
4703}
ee78dc32 4704
2d764c78 4705DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
74e1aeec 4706 doc: /* Internal function called by `color-values', which see. */)
5842a27b 4707 (Lisp_Object color, Lisp_Object frame)
ee78dc32 4708{
6fc2811b 4709 XColor foo;
a10c8269 4710 struct frame *f = decode_window_system_frame (frame);
ee78dc32 4711
b7826503 4712 CHECK_STRING (color);
ee78dc32 4713
d5db4077 4714 if (w32_defined_color (f, SDATA (color), &foo, 0))
3de717bd
DA
4715 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4716 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4717 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
ee78dc32
GV
4718 else
4719 return Qnil;
4720}
4721
2d764c78 4722DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
74e1aeec 4723 doc: /* Internal function called by `display-color-p', which see. */)
5842a27b 4724 (Lisp_Object display)
ee78dc32 4725{
fbd6baed 4726 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
4727
4728 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4729 return Qnil;
4730
4731 return Qt;
4732}
4733
74e1aeec
JR
4734DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4735 Sx_display_grayscale_p, 0, 1, 0,
52deb19f 4736 doc: /* Return t if DISPLAY supports shades of gray.
74e1aeec
JR
4737Note that color displays do support shades of gray.
4738The optional argument DISPLAY specifies which display to ask about.
4739DISPLAY should be either a frame or a display name (a string).
4740If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4741 (Lisp_Object display)
ee78dc32 4742{
fbd6baed 4743 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
4744
4745 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4746 return Qnil;
4747
4748 return Qt;
4749}
4750
74e1aeec
JR
4751DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4752 Sx_display_pixel_width, 0, 1, 0,
36458ebd 4753 doc: /* Return the width in pixels of DISPLAY.
74e1aeec
JR
4754The optional argument DISPLAY specifies which display to ask about.
4755DISPLAY should be either a frame or a display name (a string).
cf13177e
YM
4756If omitted or nil, that stands for the selected frame's display.
4757
4758On \"multi-monitor\" setups this refers to the pixel width for all
4759physical monitors associated with DISPLAY. To get information for
4760each physical monitor, use `display-monitor-attributes-list'. */)
5842a27b 4761 (Lisp_Object display)
ee78dc32 4762{
fbd6baed 4763 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32 4764
05eb7cdc 4765 return make_number (x_display_pixel_width (dpyinfo));
ee78dc32
GV
4766}
4767
4768DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
74e1aeec 4769 Sx_display_pixel_height, 0, 1, 0,
36458ebd 4770 doc: /* Return the height in pixels of DISPLAY.
74e1aeec
JR
4771The optional argument DISPLAY specifies which display to ask about.
4772DISPLAY should be either a frame or a display name (a string).
cf13177e
YM
4773If omitted or nil, that stands for the selected frame's display.
4774
4775On \"multi-monitor\" setups this refers to the pixel height for all
4776physical monitors associated with DISPLAY. To get information for
4777each physical monitor, use `display-monitor-attributes-list'. */)
5842a27b 4778 (Lisp_Object display)
ee78dc32 4779{
fbd6baed 4780 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32 4781
05eb7cdc 4782 return make_number (x_display_pixel_height (dpyinfo));
ee78dc32
GV
4783}
4784
4785DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
74e1aeec 4786 0, 1, 0,
36458ebd 4787 doc: /* Return the number of bitplanes of DISPLAY.
74e1aeec
JR
4788The optional argument DISPLAY specifies which display to ask about.
4789DISPLAY should be either a frame or a display name (a string).
4790If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4791 (Lisp_Object display)
ee78dc32 4792{
fbd6baed 4793 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
4794
4795 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4796}
4797
4798DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
74e1aeec 4799 0, 1, 0,
36458ebd 4800 doc: /* Return the number of color cells of DISPLAY.
74e1aeec
JR
4801The optional argument DISPLAY specifies which display to ask about.
4802DISPLAY should be either a frame or a display name (a string).
4803If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4804 (Lisp_Object display)
ee78dc32 4805{
fbd6baed 4806 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
4807 int cap;
4808
821812e2
DC
4809 /* Don't use NCOLORS: it returns incorrect results under remote
4810 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4811 * overflow and because probably is more meaningful on Windows
4812 * anyway. */
7d0393cf 4813
821812e2 4814 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
ee78dc32
GV
4815 return make_number (cap);
4816}
4817
4818DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4819 Sx_server_max_request_size,
74e1aeec 4820 0, 1, 0,
36458ebd 4821 doc: /* Return the maximum request size of the server of DISPLAY.
74e1aeec
JR
4822The optional argument DISPLAY specifies which display to ask about.
4823DISPLAY should be either a frame or a display name (a string).
4824If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4825 (Lisp_Object display)
ee78dc32 4826{
ee78dc32
GV
4827 return make_number (1);
4828}
4829
4830DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
36458ebd 4831 doc: /* Return the "vendor ID" string of the W32 system (Microsoft).
74e1aeec
JR
4832The optional argument DISPLAY specifies which display to ask about.
4833DISPLAY should be either a frame or a display name (a string).
4834If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4835 (Lisp_Object display)
ee78dc32 4836{
dfff8a69 4837 return build_string ("Microsoft Corp.");
ee78dc32
GV
4838}
4839
4840DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
36458ebd 4841 doc: /* Return the version numbers of the server of DISPLAY.
74e1aeec 4842The value is a list of three integers: the major and minor
02b39a28
JB
4843version numbers of the X Protocol in use, and the distributor-specific
4844release number. See also the function `x-server-vendor'.
74e1aeec
JR
4845
4846The optional argument DISPLAY specifies which display to ask about.
4847DISPLAY should be either a frame or a display name (a string).
4848If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4849 (Lisp_Object display)
ee78dc32 4850{
3de717bd 4851 return list3i (w32_major_version, w32_minor_version, w32_build_number);
ee78dc32
GV
4852}
4853
4854DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
36458ebd 4855 doc: /* Return the number of screens on the server of DISPLAY.
74e1aeec
JR
4856The optional argument DISPLAY specifies which display to ask about.
4857DISPLAY should be either a frame or a display name (a string).
4858If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4859 (Lisp_Object display)
ee78dc32 4860{
ee78dc32
GV
4861 return make_number (1);
4862}
4863
74e1aeec
JR
4864DEFUN ("x-display-mm-height", Fx_display_mm_height,
4865 Sx_display_mm_height, 0, 1, 0,
36458ebd 4866 doc: /* Return the height in millimeters of DISPLAY.
74e1aeec
JR
4867The optional argument DISPLAY specifies which display to ask about.
4868DISPLAY should be either a frame or a display name (a string).
cf13177e
YM
4869If omitted or nil, that stands for the selected frame's display.
4870
4871On \"multi-monitor\" setups this refers to the height in millimeters for
4872all physical monitors associated with DISPLAY. To get information
4873for each physical monitor, use `display-monitor-attributes-list'. */)
5842a27b 4874 (Lisp_Object display)
ee78dc32 4875{
fbd6baed 4876 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32 4877 HDC hdc;
cf13177e 4878 double mm_per_pixel;
7d0393cf 4879
cf13177e
YM
4880 hdc = GetDC (NULL);
4881 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
4882 / GetDeviceCaps (hdc, VERTRES));
4883 ReleaseDC (NULL, hdc);
7d0393cf 4884
cf13177e 4885 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
ee78dc32
GV
4886}
4887
4888DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
36458ebd 4889 doc: /* Return the width in millimeters of DISPLAY.
74e1aeec
JR
4890The optional argument DISPLAY specifies which display to ask about.
4891DISPLAY should be either a frame or a display name (a string).
cf13177e
YM
4892If omitted or nil, that stands for the selected frame's display.
4893
4894On \"multi-monitor\" setups this refers to the width in millimeters for
4895all physical monitors associated with TERMINAL. To get information
4896for each physical monitor, use `display-monitor-attributes-list'. */)
5842a27b 4897 (Lisp_Object display)
ee78dc32 4898{
fbd6baed 4899 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32 4900 HDC hdc;
cf13177e 4901 double mm_per_pixel;
ee78dc32 4902
cf13177e
YM
4903 hdc = GetDC (NULL);
4904 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
4905 / GetDeviceCaps (hdc, HORZRES));
4906 ReleaseDC (NULL, hdc);
7d0393cf 4907
cf13177e 4908 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
ee78dc32
GV
4909}
4910
4911DEFUN ("x-display-backing-store", Fx_display_backing_store,
74e1aeec 4912 Sx_display_backing_store, 0, 1, 0,
36458ebd 4913 doc: /* Return an indication of whether DISPLAY does backing store.
74e1aeec
JR
4914The value may be `always', `when-mapped', or `not-useful'.
4915The optional argument DISPLAY specifies which display to ask about.
4916DISPLAY should be either a frame or a display name (a string).
4917If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4918 (Lisp_Object display)
ee78dc32
GV
4919{
4920 return intern ("not-useful");
4921}
4922
4923DEFUN ("x-display-visual-class", Fx_display_visual_class,
74e1aeec 4924 Sx_display_visual_class, 0, 1, 0,
36458ebd 4925 doc: /* Return the visual class of DISPLAY.
74e1aeec
JR
4926The value is one of the symbols `static-gray', `gray-scale',
4927`static-color', `pseudo-color', `true-color', or `direct-color'.
4928
4929The optional argument DISPLAY specifies which display to ask about.
4930DISPLAY should be either a frame or a display name (a string).
4931If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4932 (Lisp_Object display)
ee78dc32 4933{
fbd6baed 4934 struct w32_display_info *dpyinfo = check_x_display_info (display);
abf8c61b 4935 Lisp_Object result = Qnil;
ee78dc32 4936
abf8c61b
AI
4937 if (dpyinfo->has_palette)
4938 result = intern ("pseudo-color");
4939 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
4940 result = intern ("static-grey");
4941 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
4942 result = intern ("static-color");
4943 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
4944 result = intern ("true-color");
ee78dc32 4945
abf8c61b 4946 return result;
ee78dc32
GV
4947}
4948
4949DEFUN ("x-display-save-under", Fx_display_save_under,
74e1aeec 4950 Sx_display_save_under, 0, 1, 0,
02b39a28 4951 doc: /* Return t if DISPLAY supports the save-under feature.
74e1aeec
JR
4952The optional argument DISPLAY specifies which display to ask about.
4953DISPLAY should be either a frame or a display name (a string).
4954If omitted or nil, that stands for the selected frame's display. */)
5842a27b 4955 (Lisp_Object display)
ee78dc32 4956{
6fc2811b
JR
4957 return Qnil;
4958}
0fda9b75 4959
cf13177e
YM
4960static BOOL CALLBACK
4961w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
4962{
4963 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
4964
1396ac86 4965 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
cf13177e
YM
4966
4967 return TRUE;
4968}
4969
4970static Lisp_Object
4971w32_display_monitor_attributes_list (void)
4972{
4973 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
4974 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
4975 int i, n_monitors;
4976 HMONITOR *monitors;
4977 struct gcpro gcpro1, gcpro2, gcpro3;
4978
4979 if (!(enum_display_monitors_fn && get_monitor_info_fn
4980 && monitor_from_window_fn))
4981 return Qnil;
4982
4983 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
4984 (LPARAM) &monitor_list)
4985 || NILP (monitor_list))
4986 return Qnil;
4987
4988 n_monitors = 0;
4989 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
4990 n_monitors++;
4991
4992 monitors = xmalloc (n_monitors * sizeof (*monitors));
4993 for (i = 0; i < n_monitors; i++)
4994 {
4995 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
4996 monitor_list = XCDR (monitor_list);
4997 }
4998
4999 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5000 FOR_EACH_FRAME (rest, frame)
5001 {
5002 struct frame *f = XFRAME (frame);
5003
5004 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5005 {
5006 HMONITOR monitor =
5007 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5008 MONITOR_DEFAULT_TO_NEAREST);
5009
5010 for (i = 0; i < n_monitors; i++)
5011 if (monitors[i] == monitor)
5012 break;
5013
5014 if (i < n_monitors)
5015 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5016 }
5017 }
5018
5019 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5020
5021 for (i = 0; i < n_monitors; i++)
5022 {
5023 Lisp_Object geometry, workarea, name, attributes = Qnil;
5024 HDC hdc;
5025 int width_mm, height_mm;
5026 struct MONITOR_INFO_EX mi;
5027
5028 mi.cbSize = sizeof (mi);
5029 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5030 continue;
5031
5032 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5033 if (hdc == NULL)
5034 continue;
5035 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5036 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5037 DeleteDC (hdc);
5038
5039 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5040 attributes);
5041
309f24d1
DA
5042 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5043
cf13177e
YM
5044 attributes = Fcons (Fcons (Qname, name), attributes);
5045
5046 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5047 attributes);
5048
5049 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5050 mi.rcWork.right - mi.rcWork.left,
5051 mi.rcWork.bottom - mi.rcWork.top);
5052 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5053
5054 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5055 mi.rcMonitor.right - mi.rcMonitor.left,
5056 mi.rcMonitor.bottom - mi.rcMonitor.top);
5057 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5058
5059 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5060 primary_monitor_attributes = attributes;
5061 else
5062 attributes_list = Fcons (attributes, attributes_list);
5063 }
5064
5065 if (!NILP (primary_monitor_attributes))
5066 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5067
5068 UNGCPRO;
5069
5070 xfree (monitors);
5071
5072 return attributes_list;
5073}
5074
5075static Lisp_Object
5076w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5077{
5078 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5079 HDC hdc;
5080 double mm_per_pixel;
5081 int pixel_width, pixel_height, width_mm, height_mm;
5082 RECT workarea_rect;
5083
5084 /* Fallback: treat (possibly) multiple physical monitors as if they
5085 formed a single monitor as a whole. This should provide a
5086 consistent result at least on single monitor environments. */
5087 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5088 attributes);
5089
5090 frames = Qnil;
5091 FOR_EACH_FRAME (rest, frame)
5092 {
5093 struct frame *f = XFRAME (frame);
5094
5095 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5096 frames = Fcons (frame, frames);
5097 }
5098 attributes = Fcons (Fcons (Qframes, frames), attributes);
5099
5100 pixel_width = x_display_pixel_width (dpyinfo);
5101 pixel_height = x_display_pixel_height (dpyinfo);
5102
5103 hdc = GetDC (NULL);
5104 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5105 / GetDeviceCaps (hdc, HORZRES));
5106 width_mm = pixel_width * mm_per_pixel + 0.5;
5107 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5108 / GetDeviceCaps (hdc, VERTRES));
5109 height_mm = pixel_height * mm_per_pixel + 0.5;
5110 ReleaseDC (NULL, hdc);
5111 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5112 attributes);
5113
5114 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5115 we don't care. */
5116 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5117 GetSystemMetrics (SM_YVIRTUALSCREEN),
5118 pixel_width, pixel_height);
5119 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5120 workarea = list4i (workarea_rect.left, workarea_rect.top,
5121 workarea_rect.right - workarea_rect.left,
5122 workarea_rect.bottom - workarea_rect.top);
5123 else
5124 workarea = geometry;
5125 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5126
5127 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5128
5129 return list1 (attributes);
5130}
5131
5132DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5133 Sw32_display_monitor_attributes_list,
5134 0, 1, 0,
5135 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5136
5137The optional argument DISPLAY specifies which display to ask about.
5138DISPLAY should be either a frame or a display name (a string).
5139If omitted or nil, that stands for the selected frame's display.
5140
5141Internal use only, use `display-monitor-attributes-list' instead. */)
5142 (Lisp_Object display)
5143{
5144 struct w32_display_info *dpyinfo = check_x_display_info (display);
5145 Lisp_Object attributes_list;
5146
5147 block_input ();
5148 attributes_list = w32_display_monitor_attributes_list ();
5149 if (NILP (attributes_list))
5150 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5151 unblock_input ();
5152
5153 return attributes_list;
5154}
5155
0fda9b75
DC
5156DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5157 doc: /* Set the sound generated when the bell is rung.
5158SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5159to use the corresponding system sound for the bell. The 'silent sound
5160prevents Emacs from making any sound at all.
5161SOUND is nil to use the normal beep. */)
5162 (Lisp_Object sound)
5163{
5164 CHECK_SYMBOL (sound);
5165
5166 if (NILP (sound))
5167 sound_type = 0xFFFFFFFF;
5168 else if (EQ (sound, intern ("asterisk")))
5169 sound_type = MB_ICONASTERISK;
5170 else if (EQ (sound, intern ("exclamation")))
5171 sound_type = MB_ICONEXCLAMATION;
5172 else if (EQ (sound, intern ("hand")))
5173 sound_type = MB_ICONHAND;
5174 else if (EQ (sound, intern ("question")))
5175 sound_type = MB_ICONQUESTION;
5176 else if (EQ (sound, intern ("ok")))
5177 sound_type = MB_OK;
5178 else if (EQ (sound, intern ("silent")))
5179 sound_type = MB_EMACS_SILENT;
5180 else
5181 sound_type = 0xFFFFFFFF;
5182
5183 return sound;
5184}
5185
6fc2811b 5186int
b56ceb92 5187x_screen_planes (register struct frame *f)
6fc2811b 5188{
aad3612f 5189 return FRAME_DISPLAY_INFO (f)->n_planes;
6fc2811b
JR
5190}
5191\f
5192/* Return the display structure for the display named NAME.
5193 Open a new connection if necessary. */
5194
5195struct w32_display_info *
b56ceb92 5196x_display_info_for_name (Lisp_Object name)
6fc2811b 5197{
6fc2811b
JR
5198 struct w32_display_info *dpyinfo;
5199
b7826503 5200 CHECK_STRING (name);
6fc2811b 5201
d141d701
DA
5202 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5203 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5204 return dpyinfo;
6fc2811b
JR
5205
5206 /* Use this general default value to start with. */
5207 Vx_resource_name = Vinvocation_name;
5208
5209 validate_x_resource_name ();
5210
5211 dpyinfo = w32_term_init (name, (unsigned char *)0,
51b59d79 5212 SSDATA (Vx_resource_name));
6fc2811b
JR
5213
5214 if (dpyinfo == 0)
d5db4077 5215 error ("Cannot connect to server %s", SDATA (name));
6fc2811b 5216
d5272e33 5217 XSETFASTINT (Vwindow_system_version, w32_major_version);
6fc2811b
JR
5218
5219 return dpyinfo;
5220}
5221
5222DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
4f4f2973 5223 1, 3, 0, doc: /* Open a connection to a display server.
74e1aeec
JR
5224DISPLAY is the name of the display to connect to.
5225Optional second arg XRM-STRING is a string of resources in xrdb format.
5226If the optional third arg MUST-SUCCEED is non-nil,
4f4f2973
GM
5227terminate Emacs if we can't open the connection.
5228\(In the Nextstep version, the last two arguments are currently ignored.) */)
5842a27b 5229 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
6fc2811b
JR
5230{
5231 unsigned char *xrm_option;
5232 struct w32_display_info *dpyinfo;
5233
efc3dd3c
DC
5234 CHECK_STRING (display);
5235
5236 /* Signal an error in order to encourage correct use from callers.
5237 * If we ever support multiple window systems in the same Emacs,
5238 * we'll need callers to be precise about what window system they
5239 * want. */
5240
5241 if (strcmp (SSDATA (display), "w32") != 0)
5242 error ("The name of the display in this Emacs must be \"w32\"");
5243
74e1aeec
JR
5244 /* If initialization has already been done, return now to avoid
5245 overwriting critical parts of one_w32_display_info. */
7452b7bd 5246 if (window_system_available (NULL))
74e1aeec
JR
5247 return Qnil;
5248
6fc2811b 5249 if (! NILP (xrm_string))
b7826503 5250 CHECK_STRING (xrm_string);
6fc2811b 5251
6fc2811b
JR
5252 /* Allow color mapping to be defined externally; first look in user's
5253 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5254 {
5255 Lisp_Object color_file;
5256 struct gcpro gcpro1;
5257
74084731 5258 color_file = build_string ("~/rgb.txt");
6fc2811b
JR
5259
5260 GCPRO1 (color_file);
5261
5262 if (NILP (Ffile_readable_p (color_file)))
5263 color_file =
5264 Fexpand_file_name (build_string ("rgb.txt"),
5265 Fsymbol_value (intern ("data-directory")));
5266
7ded3383 5267 Vw32_color_map = Fx_load_color_file (color_file);
6fc2811b
JR
5268
5269 UNGCPRO;
5270 }
5271 if (NILP (Vw32_color_map))
5430d399 5272 Vw32_color_map = w32_default_color_map ();
6fc2811b 5273
5a8a15ec
JR
5274 /* Merge in system logical colors. */
5275 add_system_logical_colors_to_map (&Vw32_color_map);
5276
6fc2811b 5277 if (! NILP (xrm_string))
51b59d79 5278 xrm_option = SDATA (xrm_string);
6fc2811b
JR
5279 else
5280 xrm_option = (unsigned char *) 0;
5281
5282 /* Use this general default value to start with. */
5283 /* First remove .exe suffix from invocation-name - it looks ugly. */
5284 {
5285 char basename[ MAX_PATH ], *str;
5286
d5db4077 5287 strcpy (basename, SDATA (Vinvocation_name));
6fc2811b
JR
5288 str = strrchr (basename, '.');
5289 if (str) *str = 0;
5290 Vinvocation_name = build_string (basename);
5291 }
5292 Vx_resource_name = Vinvocation_name;
5293
5294 validate_x_resource_name ();
5295
5296 /* This is what opens the connection and sets x_current_display.
5297 This also initializes many symbols, such as those used for input. */
5298 dpyinfo = w32_term_init (display, xrm_option,
51b59d79 5299 SSDATA (Vx_resource_name));
6fc2811b
JR
5300
5301 if (dpyinfo == 0)
5302 {
5303 if (!NILP (must_succeed))
5304 fatal ("Cannot connect to server %s.\n",
d5db4077 5305 SDATA (display));
6fc2811b 5306 else
d5db4077 5307 error ("Cannot connect to server %s", SDATA (display));
6fc2811b
JR
5308 }
5309
d5272e33 5310 XSETFASTINT (Vwindow_system_version, w32_major_version);
6fc2811b
JR
5311 return Qnil;
5312}
5313
5314DEFUN ("x-close-connection", Fx_close_connection,
5315 Sx_close_connection, 1, 1, 0,
74e1aeec
JR
5316 doc: /* Close the connection to DISPLAY's server.
5317For DISPLAY, specify either a frame or a display name (a string).
5318If DISPLAY is nil, that stands for the selected frame's display. */)
5842a27b 5319 (Lisp_Object display)
6fc2811b
JR
5320{
5321 struct w32_display_info *dpyinfo = check_x_display_info (display);
6fc2811b
JR
5322
5323 if (dpyinfo->reference_count > 0)
5324 error ("Display still has frames on it");
5325
4d7e6e51 5326 block_input ();
6fc2811b
JR
5327 x_destroy_all_bitmaps (dpyinfo);
5328
5329 x_delete_display (dpyinfo);
4d7e6e51 5330 unblock_input ();
6fc2811b
JR
5331
5332 return Qnil;
5333}
5334
5335DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
74e1aeec 5336 doc: /* Return the list of display names that Emacs has connections to. */)
5842a27b 5337 (void)
6fc2811b 5338{
d141d701
DA
5339 Lisp_Object result = Qnil;
5340 struct w32_display_info *wdi;
6fc2811b 5341
d141d701
DA
5342 for (wdi = x_display_list; wdi; wdi = wdi->next)
5343 result = Fcons (XCAR (wdi->name_list_element), result);
6fc2811b
JR
5344
5345 return result;
5346}
5347
5348DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7c051dd8
GM
5349 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5350This function only has an effect on X Windows. With MS Windows, it is
5351defined but does nothing.
5352
5353If ON is nil, allow buffering of requests.
5354Turning on synchronization prohibits the Xlib routines from buffering
5355requests and seriously degrades performance, but makes debugging much
5356easier.
5357The optional second argument TERMINAL specifies which display to act on.
5358TERMINAL should be a terminal object, a frame or a display name (a string).
5359If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5842a27b 5360 (Lisp_Object on, Lisp_Object display)
6fc2811b 5361{
6fc2811b
JR
5362 return Qnil;
5363}
5364
6b61353c 5365
6fc2811b 5366\f
6fc2811b 5367/***********************************************************************
6b61353c 5368 Window properties
6fc2811b
JR
5369 ***********************************************************************/
5370
b124fd93
JB
5371#if 0 /* TODO : port window properties to W32 */
5372
6b61353c
KH
5373DEFUN ("x-change-window-property", Fx_change_window_property,
5374 Sx_change_window_property, 2, 6, 0,
5375 doc: /* Change window property PROP to VALUE on the X window of FRAME.
7c051dd8
GM
5376PROP must be a string. VALUE may be a string or a list of conses,
5377numbers and/or strings. If an element in the list is a string, it is
5378converted to an atom and the value of the Atom is used. If an element
5379is a cons, it is converted to a 32 bit number where the car is the 16
5380top bits and the cdr is the lower 16 bits.
5381
6b61353c
KH
5382FRAME nil or omitted means use the selected frame.
5383If TYPE is given and non-nil, it is the name of the type of VALUE.
5384If TYPE is not given or nil, the type is STRING.
5385FORMAT gives the size in bits of each element if VALUE is a list.
5386It must be one of 8, 16 or 32.
5387If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
fca8d6b6 5388If OUTER-P is non-nil, the property is changed for the outer X window of
7c051dd8 5389FRAME. Default is to change on the edit X window. */)
fca8d6b6
AS
5390 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5391 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6b61353c 5392{
7452b7bd 5393 struct frame *f = decode_window_system_frame (frame);
6b61353c 5394 Atom prop_atom;
6fc2811b 5395
6b61353c
KH
5396 CHECK_STRING (prop);
5397 CHECK_STRING (value);
6fc2811b 5398
4d7e6e51 5399 block_input ();
6b61353c
KH
5400 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5401 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5402 prop_atom, XA_STRING, 8, PropModeReplace,
5403 SDATA (value), SCHARS (value));
6fc2811b 5404
6b61353c
KH
5405 /* Make sure the property is set when we return. */
5406 XFlush (FRAME_W32_DISPLAY (f));
4d7e6e51 5407 unblock_input ();
6fc2811b 5408
6b61353c
KH
5409 return value;
5410}
dfff8a69 5411
6fc2811b 5412
6b61353c
KH
5413DEFUN ("x-delete-window-property", Fx_delete_window_property,
5414 Sx_delete_window_property, 1, 2, 0,
5415 doc: /* Remove window property PROP from X window of FRAME.
5416FRAME nil or omitted means use the selected frame. Value is PROP. */)
5842a27b 5417 (Lisp_Object prop, Lisp_Object frame)
6fc2811b 5418{
7452b7bd 5419 struct frame *f = decode_window_system_frame (frame);
6b61353c 5420 Atom prop_atom;
6fc2811b 5421
6b61353c 5422 CHECK_STRING (prop);
4d7e6e51 5423 block_input ();
6b61353c
KH
5424 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5425 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6fc2811b 5426
6b61353c
KH
5427 /* Make sure the property is removed when we return. */
5428 XFlush (FRAME_W32_DISPLAY (f));
4d7e6e51 5429 unblock_input ();
6fc2811b 5430
6b61353c 5431 return prop;
6fc2811b
JR
5432}
5433
5434
6b61353c 5435DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
ddadbc0e 5436 1, 6, 0,
6b61353c 5437 doc: /* Value is the value of window property PROP on FRAME.
7c051dd8
GM
5438If FRAME is nil or omitted, use the selected frame.
5439
7c051dd8
GM
5440On X Windows, the following optional arguments are also accepted:
5441If TYPE is nil or omitted, get the property as a string.
5442Otherwise TYPE is the name of the atom that denotes the type expected.
5443If SOURCE is non-nil, get the property on that window instead of from
5444FRAME. The number 0 denotes the root window.
ddadbc0e
AS
5445If DELETE-P is non-nil, delete the property after retrieving it.
5446If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5447
5448On MS Windows, this function accepts but ignores those optional arguments.
7c051dd8
GM
5449
5450Value is nil if FRAME hasn't a property with name PROP or if PROP has
5451no value of TYPE (always string in the MS Windows case). */)
ddadbc0e
AS
5452 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5453 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6fc2811b 5454{
7452b7bd 5455 struct frame *f = decode_window_system_frame (frame);
6b61353c
KH
5456 Atom prop_atom;
5457 int rc;
5458 Lisp_Object prop_value = Qnil;
5459 char *tmp_data = NULL;
5460 Atom actual_type;
5461 int actual_format;
5462 unsigned long actual_size, bytes_remaining;
7d0393cf 5463
6b61353c 5464 CHECK_STRING (prop);
4d7e6e51 5465 block_input ();
6b61353c
KH
5466 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5467 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5468 prop_atom, 0, 0, False, XA_STRING,
5469 &actual_type, &actual_format, &actual_size,
5470 &bytes_remaining, (unsigned char **) &tmp_data);
5471 if (rc == Success)
6fc2811b 5472 {
6b61353c 5473 int size = bytes_remaining;
3cf3436e 5474
6b61353c
KH
5475 XFree (tmp_data);
5476 tmp_data = NULL;
3cf3436e 5477
6b61353c
KH
5478 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5479 prop_atom, 0, bytes_remaining,
5480 False, XA_STRING,
5481 &actual_type, &actual_format,
5482 &actual_size, &bytes_remaining,
5483 (unsigned char **) &tmp_data);
5484 if (rc == Success)
5485 prop_value = make_string (tmp_data, size);
6fc2811b 5486
6b61353c
KH
5487 XFree (tmp_data);
5488 }
6fc2811b 5489
4d7e6e51 5490 unblock_input ();
6fc2811b 5491
6b61353c 5492 return prop_value;
6fc2811b 5493
6b61353c 5494 return Qnil;
6fc2811b
JR
5495}
5496
b124fd93 5497#endif /* TODO */
6fc2811b
JR
5498
5499\f
5500/***********************************************************************
6b61353c 5501 Busy cursor
6fc2811b
JR
5502 ***********************************************************************/
5503
6b61353c 5504void
c06c382a 5505w32_note_current_window (void)
6fc2811b 5506{
d148e14d 5507 struct frame * f = SELECTED_FRAME ();
6fc2811b 5508
30076589
JR
5509 if (!FRAME_W32_P (f))
5510 return;
5511
d148e14d 5512 hourglass_hwnd = FRAME_W32_WINDOW (f);
f79e6790
JR
5513}
5514
f79e6790 5515void
c06c382a 5516show_hourglass (struct atimer *timer)
f79e6790 5517{
c06c382a 5518 struct frame *f;
7d0393cf 5519
c06c382a
EZ
5520 hourglass_atimer = NULL;
5521
5522 block_input ();
5523 f = x_window_to_frame (&one_w32_display_info,
5524 hourglass_hwnd);
5525
5526 if (f)
5527 f->output_data.w32->hourglass_p = 0;
5528 else
5529 f = SELECTED_FRAME ();
5530
5531 if (!FRAME_W32_P (f))
f0177f86
EZ
5532 {
5533 unblock_input ();
5534 return;
5535 }
c06c382a
EZ
5536
5537 w32_show_hourglass (f);
5538 unblock_input ();
f79e6790
JR
5539}
5540
c06c382a
EZ
5541void
5542hide_hourglass (void)
5543{
5544 block_input ();
5545 w32_hide_hourglass ();
5546 unblock_input ();
5547}
f79e6790 5548
f79e6790 5549
c06c382a 5550/* Display an hourglass cursor. Set the hourglass_p flag in display info
d148e14d 5551 to indicate that an hourglass cursor is shown. */
f79e6790
JR
5552
5553static void
b56ceb92 5554w32_show_hourglass (struct frame *f)
6fc2811b 5555{
0af913d7 5556 if (!hourglass_shown_p)
6fc2811b 5557 {
d148e14d
JR
5558 f->output_data.w32->hourglass_p = 1;
5559 if (!menubar_in_use && !current_popup_menu)
5560 SetCursor (f->output_data.w32->hourglass_cursor);
0af913d7 5561 hourglass_shown_p = 1;
f79e6790 5562 }
6fc2811b
JR
5563}
5564
5565
0af913d7 5566/* Hide the hourglass cursor on all frames, if it is currently shown. */
6fc2811b 5567
f79e6790 5568static void
b56ceb92 5569w32_hide_hourglass (void)
f79e6790 5570{
0af913d7 5571 if (hourglass_shown_p)
6fc2811b 5572 {
d148e14d
JR
5573 struct frame *f = x_window_to_frame (&one_w32_display_info,
5574 hourglass_hwnd);
89e09428
JR
5575 if (f)
5576 f->output_data.w32->hourglass_p = 0;
5577 else
5578 /* If frame was deleted, restore to selected frame's cursor. */
5579 f = SELECTED_FRAME ();
5580
5581 if (FRAME_W32_P (f))
5582 SetCursor (f->output_data.w32->current_cursor);
5583 else
5584 /* No cursors on non GUI frames - restore to stock arrow cursor. */
5585 SetCursor (w32_load_cursor (IDC_ARROW));
6fc2811b 5586
0af913d7 5587 hourglass_shown_p = 0;
f79e6790 5588 }
6fc2811b
JR
5589}
5590
5591
5592\f
5593/***********************************************************************
5594 Tool tips
5595 ***********************************************************************/
5596
f57e2426
J
5597static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5598 Lisp_Object, Lisp_Object);
5599static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5600 Lisp_Object, int, int, int *, int *);
7d0393cf 5601
3cf3436e 5602/* The frame of a currently visible tooltip. */
6fc2811b 5603
937e601e 5604Lisp_Object tip_frame;
6fc2811b
JR
5605
5606/* If non-nil, a timer started that hides the last tooltip when it
5607 fires. */
5608
5609Lisp_Object tip_timer;
5610Window tip_window;
5611
3cf3436e
JR
5612/* If non-nil, a vector of 3 elements containing the last args
5613 with which x-show-tip was called. See there. */
5614
5615Lisp_Object last_show_tip_args;
5616
3cf3436e 5617
27e498e6 5618static void
b56ceb92 5619unwind_create_tip_frame (Lisp_Object frame)
937e601e 5620{
c844a81a
GM
5621 Lisp_Object deleted;
5622
5623 deleted = unwind_create_frame (frame);
5624 if (EQ (deleted, Qt))
5625 {
5626 tip_window = NULL;
5627 tip_frame = Qnil;
5628 }
937e601e
AI
5629}
5630
5631
6fc2811b 5632/* Create a frame for a tooltip on the display described by DPYINFO.
3cf3436e
JR
5633 PARMS is a list of frame parameters. TEXT is the string to
5634 display in the tip frame. Value is the frame.
937e601e
AI
5635
5636 Note that functions called here, esp. x_default_parameter can
5637 signal errors, for instance when a specified color name is
5638 undefined. We have to make sure that we're in a consistent state
5639 when this happens. */
6fc2811b
JR
5640
5641static Lisp_Object
b56ceb92
JB
5642x_create_tip_frame (struct w32_display_info *dpyinfo,
5643 Lisp_Object parms, Lisp_Object text)
6fc2811b 5644{
6fc2811b 5645 struct frame *f;
0f4a96b5 5646 Lisp_Object frame;
6fc2811b
JR
5647 Lisp_Object name;
5648 long window_prompting = 0;
5649 int width, height;
2bfa3d3e 5650 dynwind_begin ();
6fc2811b
JR
5651 struct gcpro gcpro1, gcpro2, gcpro3;
5652 struct kboard *kb;
3cf3436e
JR
5653 int face_change_count_before = face_change_count;
5654 Lisp_Object buffer;
5655 struct buffer *old_buffer;
6fc2811b 5656
6fc2811b
JR
5657 /* Use this general default value to start with until we know if
5658 this frame has a specified name. */
5659 Vx_resource_name = Vinvocation_name;
5660
fd142562 5661 kb = dpyinfo->terminal->kboard;
6fc2811b 5662
4a217bed
EZ
5663 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5664 avoid destructive changes behind our caller's back. */
5665 parms = Fcopy_alist (parms);
5666
6fc2811b 5667 /* Get the name of the frame to use for resource lookup. */
3faa984f 5668 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6fc2811b
JR
5669 if (!STRINGP (name)
5670 && !EQ (name, Qunbound)
5671 && !NILP (name))
5672 error ("Invalid frame name--not a string or nil");
5673 Vx_resource_name = name;
5674
5675 frame = Qnil;
5676 GCPRO3 (parms, name, frame);
9eb16b62
JR
5677 /* Make a frame without minibuffer nor mode-line. */
5678 f = make_frame (0);
5679 f->wants_modeline = 0;
6fc2811b 5680 XSETFRAME (frame, f);
3cf3436e
JR
5681
5682 buffer = Fget_buffer_create (build_string (" *tip*"));
08908aca
MR
5683 /* Use set_window_buffer instead of Fset_window_buffer (see
5684 discussion of bug#11984, bug#12025, bug#12026). */
5685 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, 0, 0);
3cf3436e
JR
5686 old_buffer = current_buffer;
5687 set_buffer_internal_1 (XBUFFER (buffer));
39eb03f1 5688 bset_truncate_lines (current_buffer, Qnil);
5c2a995d
KH
5689 specbind (Qinhibit_read_only, Qt);
5690 specbind (Qinhibit_modification_hooks, Qt);
3cf3436e
JR
5691 Ferase_buffer ();
5692 Finsert (1, &text);
5693 set_buffer_internal_1 (old_buffer);
7d0393cf 5694
937e601e 5695 record_unwind_protect (unwind_create_tip_frame, frame);
6fc2811b 5696
3cf3436e
JR
5697 /* By setting the output method, we're essentially saying that
5698 the frame is live, as per FRAME_LIVE_P. If we get a signal
5699 from this point on, x_destroy_window might screw up reference
5700 counts etc. */
ebbb61be 5701 f->terminal = dpyinfo->terminal;
d88c567c 5702 f->output_method = output_w32;
23f86fce 5703 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
ca56d953
JR
5704
5705 FRAME_FONTSET (f) = -1;
f00af5b1 5706 fset_icon_name (f, Qnil);
6fc2811b 5707
e509cfa6 5708#ifdef GLYPH_DEBUG
a06776b2 5709 image_cache_refcount =
784b56e2 5710 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
937e601e
AI
5711 dpyinfo_refcount = dpyinfo->reference_count;
5712#endif /* GLYPH_DEBUG */
6fc2811b 5713 FRAME_KBOARD (f) = kb;
aad3612f 5714 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6fc2811b
JR
5715 f->output_data.w32->explicit_parent = 0;
5716
5717 /* Set the name; the functions to which we pass f expect the name to
5718 be set. */
5719 if (EQ (name, Qunbound) || NILP (name))
5720 {
f00af5b1 5721 fset_name (f, build_string (dpyinfo->w32_id_name));
6fc2811b
JR
5722 f->explicit_name = 0;
5723 }
5724 else
5725 {
f00af5b1 5726 fset_name (f, name);
6fc2811b
JR
5727 f->explicit_name = 1;
5728 /* use the frame's title when getting resources for this frame. */
5729 specbind (Qx_resource_name, name);
5730 }
5731
fdb55376
JR
5732 if (uniscribe_available)
5733 register_font_driver (&uniscribe_font_driver, f);
1cc06b86 5734 register_font_driver (&w32font_driver, f);
a1fe5c00 5735
1cc06b86
KH
5736 x_default_parameter (f, parms, Qfont_backend, Qnil,
5737 "fontBackend", "FontBackend", RES_TYPE_STRING);
a1fe5c00 5738
6fc2811b
JR
5739 /* Extract the window parameters from the supplied values
5740 that are needed to determine window geometry. */
1cc06b86 5741 x_default_font_parameter (f, parms);
6fc2811b
JR
5742
5743 x_default_parameter (f, parms, Qborder_width, make_number (2),
5744 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6fc2811b
JR
5745 /* This defaults to 2 in order to match xterm. We recognize either
5746 internalBorderWidth or internalBorder (which is what xterm calls
5747 it). */
5748 if (NILP (Fassq (Qinternal_border_width, parms)))
5749 {
5750 Lisp_Object value;
5751
3faa984f 5752 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6fc2811b
JR
5753 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5754 if (! EQ (value, Qunbound))
5755 parms = Fcons (Fcons (Qinternal_border_width, value),
5756 parms);
5757 }
bfd6edcc 5758 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6fc2811b
JR
5759 "internalBorderWidth", "internalBorderWidth",
5760 RES_TYPE_NUMBER);
880e6158
MR
5761 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5762 NULL, NULL, RES_TYPE_NUMBER);
5763 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5764 NULL, NULL, RES_TYPE_NUMBER);
6fc2811b
JR
5765
5766 /* Also do the stuff which must be set before the window exists. */
5767 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5768 "foreground", "Foreground", RES_TYPE_STRING);
5769 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5770 "background", "Background", RES_TYPE_STRING);
5771 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5772 "pointerColor", "Foreground", RES_TYPE_STRING);
5773 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5774 "cursorColor", "Foreground", RES_TYPE_STRING);
5775 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5776 "borderColor", "BorderColor", RES_TYPE_STRING);
5777
5778 /* Init faces before x_default_parameter is called for scroll-bar
5779 parameters because that function calls x_set_scroll_bar_width,
5780 which calls change_frame_size, which calls Fset_window_buffer,
5781 which runs hooks, which call Fvertical_motion. At the end, we
5782 end up in init_iterator with a null face cache, which should not
5783 happen. */
5784 init_frame_faces (f);
ca56d953
JR
5785
5786 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
aad3612f 5787 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
9eb16b62 5788
6d906347 5789 window_prompting = x_figure_window_size (f, parms, 0);
6fc2811b 5790
9eb16b62 5791 /* No fringes on tip frame. */
be786000
KS
5792 f->fringe_cols = 0;
5793 f->left_fringe_width = 0;
5794 f->right_fringe_width = 0;
9eb16b62 5795
4d7e6e51 5796 block_input ();
ca56d953 5797 my_create_tip_window (f);
4d7e6e51 5798 unblock_input ();
6fc2811b
JR
5799
5800 x_make_gc (f);
5801
5802 x_default_parameter (f, parms, Qauto_raise, Qnil,
5803 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5804 x_default_parameter (f, parms, Qauto_lower, Qnil,
5805 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5806 x_default_parameter (f, parms, Qcursor_type, Qbox,
5807 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5808
880e6158
MR
5809 /* Dimensions, especially FRAME_LINES (f), must be done via
5810 change_frame_size. Change will not be effected unless different
5811 from the current FRAME_LINES (f). */
be786000
KS
5812 width = FRAME_COLS (f);
5813 height = FRAME_LINES (f);
5814 FRAME_LINES (f) = 0;
5815 SET_FRAME_COLS (f, 0);
880e6158 5816 change_frame_size (f, width, height, 1, 0, 0, 0);
6fc2811b 5817
cd1d850f 5818 /* Add `tooltip' frame parameter's default value. */
54ee7410
CY
5819 if (NILP (Fframe_parameter (frame, Qtooltip)))
5820 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
7d0393cf 5821
3cf3436e
JR
5822 /* Set up faces after all frame parameters are known. This call
5823 also merges in face attributes specified for new frames.
5824
5825 Frame parameters may be changed if .Xdefaults contains
5826 specifications for the default font. For example, if there is an
5827 `Emacs.default.attributeBackground: pink', the `background-color'
5828 attribute of the frame get's set, which let's the internal border
5829 of the tooltip frame appear in pink. Prevent this. */
5830 {
5831 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
601a9cf1
JB
5832 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5833 Lisp_Object colors = Qnil;
3cf3436e
JR
5834
5835 /* Set tip_frame here, so that */
5836 tip_frame = frame;
45cebfd9 5837 call2 (Qface_set_after_frame_default, frame, Qnil);
7d0393cf 5838
3cf3436e 5839 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
601a9cf1
JB
5840 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5841 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5842 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5843
5844 if (!NILP (colors))
5845 Fmodify_frame_parameters (frame, colors);
3cf3436e 5846 }
7d0393cf 5847
6fc2811b
JR
5848 f->no_split = 1;
5849
5850 UNGCPRO;
5851
a06776b2
EZ
5852 /* Now that the frame is official, it counts as a reference to
5853 its display. */
aad3612f 5854 FRAME_DISPLAY_INFO (f)->reference_count++;
a06776b2
EZ
5855 f->terminal->reference_count++;
5856
6fc2811b
JR
5857 /* It is now ok to make the frame official even if we get an error
5858 below. And the frame needs to be on Vframe_list or making it
5859 visible won't work. */
5860 Vframe_list = Fcons (frame, Vframe_list);
5861
3cf3436e
JR
5862 /* Setting attributes of faces of the tooltip frame from resources
5863 and similar will increment face_change_count, which leads to the
5864 clearing of all current matrices. Since this isn't necessary
5865 here, avoid it by resetting face_change_count to the value it
5866 had before we created the tip frame. */
5867 face_change_count = face_change_count_before;
5868
5869 /* Discard the unwind_protect. */
2bfa3d3e
BT
5870 dynwind_end ();
5871 return frame;
ee78dc32
GV
5872}
5873
3cf3436e
JR
5874
5875/* Compute where to display tip frame F. PARMS is the list of frame
5876 parameters for F. DX and DY are specified offsets from the current
5877 location of the mouse. WIDTH and HEIGHT are the width and height
5878 of the tooltip. Return coordinates relative to the root window of
5879 the display in *ROOT_X, and *ROOT_Y. */
5880
5881static void
b56ceb92
JB
5882compute_tip_xy (struct frame *f,
5883 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5884 int width, int height, int *root_x, int *root_y)
3cf3436e 5885{
3cf3436e 5886 Lisp_Object left, top;
64f0809d 5887 int min_x, min_y, max_x, max_y;
7d0393cf 5888
3cf3436e
JR
5889 /* User-specified position? */
5890 left = Fcdr (Fassq (Qleft, parms));
5891 top = Fcdr (Fassq (Qtop, parms));
7d0393cf 5892
3cf3436e
JR
5893 /* Move the tooltip window where the mouse pointer is. Resize and
5894 show it. */
ca56d953 5895 if (!INTEGERP (left) || !INTEGERP (top))
3cf3436e 5896 {
ca56d953
JR
5897 POINT pt;
5898
64f0809d
JR
5899 /* Default min and max values. */
5900 min_x = 0;
5901 min_y = 0;
aad3612f
DA
5902 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5903 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
64f0809d 5904
4d7e6e51 5905 block_input ();
ca56d953
JR
5906 GetCursorPos (&pt);
5907 *root_x = pt.x;
5908 *root_y = pt.y;
4d7e6e51 5909 unblock_input ();
64f0809d
JR
5910
5911 /* If multiple monitor support is available, constrain the tip onto
5912 the current monitor. This improves the above by allowing negative
5913 co-ordinates if monitor positions are such that they are valid, and
5914 snaps a tooltip onto a single monitor if we are close to the edge
5915 where it would otherwise flow onto the other monitor (or into
5916 nothingness if there is a gap in the overlap). */
5917 if (monitor_from_point_fn && get_monitor_info_fn)
5918 {
5919 struct MONITOR_INFO info;
5920 HMONITOR monitor
5921 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5922 info.cbSize = sizeof (info);
5923
5924 if (get_monitor_info_fn (monitor, &info))
5925 {
5926 min_x = info.rcWork.left;
5927 min_y = info.rcWork.top;
5928 max_x = info.rcWork.right;
5929 max_y = info.rcWork.bottom;
5930 }
5931 }
3cf3436e
JR
5932 }
5933
5934 if (INTEGERP (top))
5935 *root_y = XINT (top);
64f0809d
JR
5936 else if (*root_y + XINT (dy) <= min_y)
5937 *root_y = min_y; /* Can happen for negative dy */
5938 else if (*root_y + XINT (dy) + height <= max_y)
7e8410d1 5939 /* It fits below the pointer */
3cf3436e 5940 *root_y += XINT (dy);
64f0809d 5941 else if (height + XINT (dy) + min_y <= *root_y)
7e8410d1
JD
5942 /* It fits above the pointer. */
5943 *root_y -= height + XINT (dy);
5944 else
5945 /* Put it on the top. */
64f0809d 5946 *root_y = min_y;
3cf3436e
JR
5947
5948 if (INTEGERP (left))
5949 *root_x = XINT (left);
64f0809d 5950 else if (*root_x + XINT (dx) <= min_x)
bf63eb69 5951 *root_x = 0; /* Can happen for negative dx */
64f0809d 5952 else if (*root_x + XINT (dx) + width <= max_x)
72e4adef
JR
5953 /* It fits to the right of the pointer. */
5954 *root_x += XINT (dx);
64f0809d 5955 else if (width + XINT (dx) + min_x <= *root_x)
72e4adef 5956 /* It fits to the left of the pointer. */
3cf3436e
JR
5957 *root_x -= width + XINT (dx);
5958 else
72e4adef 5959 /* Put it left justified on the screen -- it ought to fit that way. */
64f0809d 5960 *root_x = min_x;
3cf3436e
JR
5961}
5962
5963
71eab8d1 5964DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
74e1aeec
JR
5965 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
5966A tooltip window is a small window displaying a string.
5967
87c891c7
EZ
5968This is an internal function; Lisp code should call `tooltip-show'.
5969
74e1aeec
JR
5970FRAME nil or omitted means use the selected frame.
5971
5972PARMS is an optional list of frame parameters which can be
5973used to change the tooltip's appearance.
5974
ca56d953
JR
5975Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
5976means use the default timeout of 5 seconds.
74e1aeec 5977
52deb19f 5978If the list of frame parameters PARMS contains a `left' parameter,
74e1aeec
JR
5979the tooltip is displayed at that x-position. Otherwise it is
5980displayed at the mouse position, with offset DX added (default is 5 if
5981DX isn't specified). Likewise for the y-position; if a `top' frame
5982parameter is specified, it determines the y-position of the tooltip
5983window, otherwise it is displayed at the mouse position, with offset
5984DY added (default is -10).
5985
5986A tooltip's maximum size is specified by `x-max-tooltip-size'.
5987Text larger than the specified size is clipped. */)
5842a27b 5988 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
ee78dc32 5989{
6fc2811b
JR
5990 struct frame *f;
5991 struct window *w;
3cf3436e 5992 int root_x, root_y;
6fc2811b
JR
5993 struct buffer *old_buffer;
5994 struct text_pos pos;
a971c0a7 5995 int i, width, height, seen_reversed_p;
6fc2811b
JR
5996 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5997 int old_windows_or_buffers_changed = windows_or_buffers_changed;
2bfa3d3e 5998 dynwind_begin ();
7d0393cf 5999
6fc2811b 6000 specbind (Qinhibit_redisplay, Qt);
ee78dc32 6001
dfff8a69 6002 GCPRO4 (string, parms, frame, timeout);
ee78dc32 6003
b7826503 6004 CHECK_STRING (string);
7452b7bd 6005 f = decode_window_system_frame (frame);
6fc2811b
JR
6006 if (NILP (timeout))
6007 timeout = make_number (5);
6008 else
b7826503 6009 CHECK_NATNUM (timeout);
ee78dc32 6010
71eab8d1
AI
6011 if (NILP (dx))
6012 dx = make_number (5);
6013 else
b7826503 6014 CHECK_NUMBER (dx);
7d0393cf 6015
71eab8d1 6016 if (NILP (dy))
dc220243 6017 dy = make_number (-10);
71eab8d1 6018 else
b7826503 6019 CHECK_NUMBER (dy);
71eab8d1 6020
dc220243
JR
6021 if (NILP (last_show_tip_args))
6022 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6023
6024 if (!NILP (tip_frame))
6025 {
6026 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6027 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6028 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6029
6030 if (EQ (frame, last_frame)
6031 && !NILP (Fequal (last_string, string))
6032 && !NILP (Fequal (last_parms, parms)))
6033 {
6034 struct frame *f = XFRAME (tip_frame);
7d0393cf 6035
dc220243
JR
6036 /* Only DX and DY have changed. */
6037 if (!NILP (tip_timer))
6038 {
6039 Lisp_Object timer = tip_timer;
6040 tip_timer = Qnil;
6041 call1 (Qcancel_timer, timer);
6042 }
6043
4d7e6e51 6044 block_input ();
be786000
KS
6045 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6046 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
d65a9cdc
JR
6047
6048 /* Put tooltip in topmost group and in position. */
ca56d953
JR
6049 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6050 root_x, root_y, 0, 0,
863f07de 6051 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
d65a9cdc
JR
6052
6053 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6054 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6055 0, 0, 0, 0,
863f07de
JC
6056 SWP_NOMOVE | SWP_NOSIZE
6057 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
d65a9cdc 6058
4d7e6e51 6059 unblock_input ();
dc220243
JR
6060 goto start_timer;
6061 }
6062 }
6063
6fc2811b
JR
6064 /* Hide a previous tip, if any. */
6065 Fx_hide_tip ();
ee78dc32 6066
dc220243
JR
6067 ASET (last_show_tip_args, 0, string);
6068 ASET (last_show_tip_args, 1, frame);
6069 ASET (last_show_tip_args, 2, parms);
6070
6fc2811b
JR
6071 /* Add default values to frame parameters. */
6072 if (NILP (Fassq (Qname, parms)))
6073 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6074 if (NILP (Fassq (Qinternal_border_width, parms)))
6075 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
880e6158
MR
6076 if (NILP (Fassq (Qright_divider_width, parms)))
6077 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6078 if (NILP (Fassq (Qbottom_divider_width, parms)))
6079 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6fc2811b
JR
6080 if (NILP (Fassq (Qborder_width, parms)))
6081 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6082 if (NILP (Fassq (Qborder_color, parms)))
6083 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6084 if (NILP (Fassq (Qbackground_color, parms)))
6085 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6086 parms);
6087
0e3fcdef
JR
6088 /* Block input until the tip has been fully drawn, to avoid crashes
6089 when drawing tips in menus. */
4d7e6e51 6090 block_input ();
0e3fcdef 6091
6fc2811b
JR
6092 /* Create a frame for the tooltip, and record it in the global
6093 variable tip_frame. */
aad3612f 6094 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
937e601e 6095 f = XFRAME (frame);
6fc2811b 6096
3cf3436e 6097 /* Set up the frame's root window. */
6fc2811b 6098 w = XWINDOW (FRAME_ROOT_WINDOW (f));
5f24fa51
DA
6099 w->left_col = 0;
6100 w->top_line = 0;
880e6158
MR
6101 w->pixel_left = 0;
6102 w->pixel_top = 0;
3cf3436e
JR
6103
6104 if (CONSP (Vx_max_tooltip_size)
6105 && INTEGERP (XCAR (Vx_max_tooltip_size))
6106 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6107 && INTEGERP (XCDR (Vx_max_tooltip_size))
6108 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6109 {
5f24fa51
DA
6110 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6111 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
3cf3436e
JR
6112 }
6113 else
6114 {
5f24fa51
DA
6115 w->total_cols = 80;
6116 w->total_lines = 40;
3cf3436e 6117 }
7d0393cf 6118
880e6158
MR
6119 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6120 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6121
21e930f8 6122 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
bd0443bb 6123 adjust_frame_glyphs (f);
6fc2811b
JR
6124 w->pseudo_window_p = 1;
6125
6126 /* Display the tooltip text in a temporary buffer. */
6fc2811b 6127 old_buffer = current_buffer;
e74aeda8 6128 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
39eb03f1 6129 bset_truncate_lines (current_buffer, Qnil);
6fc2811b
JR
6130 clear_glyph_matrix (w->desired_matrix);
6131 clear_glyph_matrix (w->current_matrix);
6132 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
39321b94 6133 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6fc2811b
JR
6134
6135 /* Compute width and height of the tooltip. */
a971c0a7 6136 width = height = seen_reversed_p = 0;
6fc2811b 6137 for (i = 0; i < w->desired_matrix->nrows; ++i)
ee78dc32 6138 {
6fc2811b
JR
6139 struct glyph_row *row = &w->desired_matrix->rows[i];
6140 struct glyph *last;
6141 int row_width;
6142
6143 /* Stop at the first empty row at the end. */
138c0ae8 6144 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6fc2811b
JR
6145 break;
6146
6147 /* Let the row go over the full width of the frame. */
6148 row->full_width_p = 1;
6149
a971c0a7 6150 row_width = row->pixel_width;
6fc2811b
JR
6151 if (row->used[TEXT_AREA])
6152 {
a971c0a7
EZ
6153 if (!row->reversed_p)
6154 {
a971c0a7
EZ
6155 /* There's a glyph at the end of rows that is used to
6156 place the cursor there. Don't include the width of
6157 this glyph. */
6158 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6159 if (INTEGERP (last->object))
6160 row_width -= last->pixel_width;
a971c0a7
EZ
6161 }
6162 else
6163 {
6164 /* There could be a stretch glyph at the beginning of R2L
6165 rows that is produced by extend_face_to_end_of_line.
6166 Don't count that glyph. */
6167 struct glyph *g = row->glyphs[TEXT_AREA];
6168
6169 if (g->type == STRETCH_GLYPH && INTEGERP (g->object))
6170 {
6171 row_width -= g->pixel_width;
6172 seen_reversed_p = 1;
6173 }
6174 }
6175 }
7d0393cf 6176
bfd6edcc 6177 height += row->height;
6fc2811b 6178 width = max (width, row_width);
ee78dc32
GV
6179 }
6180
a971c0a7
EZ
6181 /* If we've seen partial-length R2L rows, we need to re-adjust the
6182 tool-tip frame width and redisplay it again, to avoid over-wide
6183 tips due to the stretch glyph that extends R2L lines to full
6184 width of the frame. */
6185 if (seen_reversed_p)
6186 {
880e6158
MR
6187 /* PXW: Why do we do the pixel-to-cols conversion only if
6188 seen_reversed_p holds? Don't we have to set other fields of
f224e500 6189 the window/frame structure?
880e6158
MR
6190
6191 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
a971c0a7 6192 not in pixels. */
880e6158 6193 w->pixel_width = width;
a971c0a7 6194 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
5f24fa51 6195 w->total_cols = width;
a971c0a7 6196 FRAME_TOTAL_COLS (f) = width;
880e6158 6197 SET_FRAME_WIDTH (f, width);
bd0443bb 6198 adjust_frame_glyphs (f);
39321b94 6199 w->pseudo_window_p = 1;
a971c0a7
EZ
6200 clear_glyph_matrix (w->desired_matrix);
6201 clear_glyph_matrix (w->current_matrix);
39321b94 6202 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
a971c0a7
EZ
6203 width = height = 0;
6204 /* Recompute width and height of the tooltip. */
6205 for (i = 0; i < w->desired_matrix->nrows; ++i)
6206 {
6207 struct glyph_row *row = &w->desired_matrix->rows[i];
6208 struct glyph *last;
6209 int row_width;
6210
138c0ae8 6211 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
a971c0a7
EZ
6212 break;
6213 row->full_width_p = 1;
6214 row_width = row->pixel_width;
a971c0a7
EZ
6215 if (row->used[TEXT_AREA] && !row->reversed_p)
6216 {
6217 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6218 if (INTEGERP (last->object))
6219 row_width -= last->pixel_width;
6220 }
a971c0a7
EZ
6221
6222 height += row->height;
6223 width = max (width, row_width);
6224 }
6225 }
6226
39321b94 6227 /* Add the frame's internal border to the width and height the w32
6fc2811b
JR
6228 window should have. */
6229 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6230 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
ee78dc32 6231
6fc2811b 6232 /* Move the tooltip window where the mouse pointer is. Resize and
880e6158
MR
6233 show it.
6234
6235 PXW: This should use the frame's pixel coordinates. */
3cf3436e 6236 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
71eab8d1 6237
bfd6edcc
JR
6238 {
6239 /* Adjust Window size to take border into account. */
6240 RECT rect;
6241 rect.left = rect.top = 0;
6242 rect.right = width;
6243 rect.bottom = height;
6244 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6245 FRAME_EXTERNAL_MENU_BAR (f));
6246
1d79e521 6247 /* Position and size tooltip, and put it in the topmost group.
39321b94
EZ
6248 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6249 peculiarity of w32 display: without it, some fonts cause the
6250 last character of the tip to be truncated or wrapped around to
6251 the next line. */
bfd6edcc 6252 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
39321b94
EZ
6253 root_x, root_y,
6254 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
863f07de 6255 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
bfd6edcc 6256
d65a9cdc
JR
6257 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6258 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6259 0, 0, 0, 0,
863f07de
JC
6260 SWP_NOMOVE | SWP_NOSIZE
6261 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
d65a9cdc 6262
bfd6edcc 6263 /* Let redisplay know that we have made the frame visible already. */
edfa7fa0 6264 SET_FRAME_VISIBLE (f, 1);
bfd6edcc
JR
6265
6266 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6267 }
ee78dc32 6268
6fc2811b
JR
6269 /* Draw into the window. */
6270 w->must_be_updated_p = 1;
6271 update_single_window (w, 1);
ee78dc32 6272
4d7e6e51 6273 unblock_input ();
0e3fcdef 6274
6fc2811b
JR
6275 /* Restore original current buffer. */
6276 set_buffer_internal_1 (old_buffer);
6277 windows_or_buffers_changed = old_windows_or_buffers_changed;
ee78dc32 6278
dc220243 6279 start_timer:
6fc2811b
JR
6280 /* Let the tip disappear after timeout seconds. */
6281 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6282 intern ("x-hide-tip"));
ee78dc32 6283
dfff8a69 6284 UNGCPRO;
2bfa3d3e
BT
6285 dynwind_end ();
6286 return Qnil;
ee78dc32
GV
6287}
6288
ee78dc32 6289
6fc2811b 6290DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
74e1aeec
JR
6291 doc: /* Hide the current tooltip window, if there is any.
6292Value is t if tooltip was open, nil otherwise. */)
5842a27b 6293 (void)
6fc2811b 6294{
d311d28c 6295 ptrdiff_t count;
937e601e
AI
6296 Lisp_Object deleted, frame, timer;
6297 struct gcpro gcpro1, gcpro2;
6298
6299 /* Return quickly if nothing to do. */
6300 if (NILP (tip_timer) && NILP (tip_frame))
6301 return Qnil;
7d0393cf 6302
937e601e
AI
6303 frame = tip_frame;
6304 timer = tip_timer;
6305 GCPRO2 (frame, timer);
6306 tip_frame = tip_timer = deleted = Qnil;
7d0393cf 6307
2bfa3d3e 6308 dynwind_begin ();
6fc2811b 6309 specbind (Qinhibit_redisplay, Qt);
937e601e 6310 specbind (Qinhibit_quit, Qt);
7d0393cf 6311
937e601e 6312 if (!NILP (timer))
dc220243 6313 call1 (Qcancel_timer, timer);
ee78dc32 6314
937e601e 6315 if (FRAMEP (frame))
6fc2811b 6316 {
56f2de10 6317 delete_frame (frame, Qnil);
937e601e 6318 deleted = Qt;
6fc2811b 6319 }
1edf84e7 6320
937e601e 6321 UNGCPRO;
2bfa3d3e
BT
6322 dynwind_end ();
6323 return deleted;
6fc2811b 6324}
6fc2811b
JR
6325\f
6326/***********************************************************************
6327 File selection dialog
6328 ***********************************************************************/
6fc2811b 6329
0fda9b75
DC
6330#define FILE_NAME_TEXT_FIELD edt1
6331#define FILE_NAME_COMBO_BOX cmb13
6332#define FILE_NAME_LIST lst1
6333
fffa137c 6334/* Callback for altering the behavior of the Open File dialog.
1030b26b
JR
6335 Makes the Filename text field contain "Current Directory" and be
6336 read-only when "Directories" is selected in the filter. This
6337 allows us to work around the fact that the standard Open File
6338 dialog does not support directories. */
c7b36b95 6339static UINT_PTR CALLBACK
b56ceb92 6340file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1030b26b
JR
6341{
6342 if (msg == WM_NOTIFY)
6343 {
2d716d75
EZ
6344 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6345 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6346 int dropdown_changed;
6347 int dir_index;
0fda9b75 6348#ifdef NTGUI_UNICODE
eac30cd4 6349 const int use_unicode = 1;
0fda9b75 6350#else /* !NTGUI_UNICODE */
2d716d75 6351 int use_unicode = w32_unicode_filenames;
0fda9b75 6352#endif /* NTGUI_UNICODE */
2d716d75 6353
1030b26b 6354 /* Detect when the Filter dropdown is changed. */
2d716d75
EZ
6355 if (use_unicode)
6356 dropdown_changed =
6357 notify_w->hdr.code == CDN_TYPECHANGE
6358 || notify_w->hdr.code == CDN_INITDONE;
6359 else
6360 dropdown_changed =
6361 notify_a->hdr.code == CDN_TYPECHANGE
6362 || notify_a->hdr.code == CDN_INITDONE;
6363 if (dropdown_changed)
1030b26b
JR
6364 {
6365 HWND dialog = GetParent (hwnd);
6366 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7faeca66 6367 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
2d716d75 6368 int hdr_code;
1030b26b 6369
7faeca66
BK
6370 /* At least on Windows 7, the above attempt to get the window handle
6371 to the File Name Text Field fails. The following code does the
6372 job though. Note that this code is based on my examination of the
6373 window hierarchy using Microsoft Spy++. bk */
6374 if (edit_control == NULL)
6375 {
6376 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6377 if (tmp)
6378 {
6379 tmp = GetWindow (tmp, GW_CHILD);
6380 if (tmp)
6381 edit_control = GetWindow (tmp, GW_CHILD);
6382 }
6383 }
6384
6385 /* Directories is in index 2. */
2d716d75
EZ
6386 if (use_unicode)
6387 {
6388 dir_index = notify_w->lpOFN->nFilterIndex;
6389 hdr_code = notify_w->hdr.code;
6390 }
6391 else
6392 {
6393 dir_index = notify_a->lpOFN->nFilterIndex;
6394 hdr_code = notify_a->hdr.code;
6395 }
6396 if (dir_index == 2)
1030b26b 6397 {
2d716d75
EZ
6398 if (use_unicode)
6399 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6400 (LPARAM)L"Current Directory");
6401 else
6402 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6403 (LPARAM)"Current Directory");
1030b26b 6404 EnableWindow (edit_control, FALSE);
7faeca66
BK
6405 /* Note that at least on Windows 7, the above call to EnableWindow
6406 disables the window that would ordinarily have focus. If we
6407 do not set focus to some other window here, focus will land in
6408 no man's land and the user will be unable to tab through the
6409 dialog box (pressing tab will only result in a beep).
6410 Avoid that problem by setting focus to the list here. */
2d716d75 6411 if (hdr_code == CDN_INITDONE)
7faeca66 6412 SetFocus (list);
1030b26b
JR
6413 }
6414 else
6415 {
ef544dc8 6416 /* Don't override default filename on init done. */
2d716d75
EZ
6417 if (hdr_code == CDN_TYPECHANGE)
6418 {
6419 if (use_unicode)
6420 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6421 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6422 else
6423 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6424 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6425 }
1030b26b
JR
6426 EnableWindow (edit_control, TRUE);
6427 }
6428 }
6429 }
6430 return 0;
6431}
6432
f9d64bb3 6433DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
74e1aeec 6434 doc: /* Read file name, prompting with PROMPT in directory DIR.
7c051dd8
GM
6435Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6436selection box, if specified. If MUSTMATCH is non-nil, the returned file
6437or directory must exist.
6438
d7e642cc 6439This function is only defined on NS, MS Windows, and X Windows with the
7c051dd8
GM
6440Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6441Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories. */)
5842a27b 6442 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6fc2811b 6443{
0fda9b75 6444 /* Filter index: 1: All Files, 2: Directories only */
2d716d75
EZ
6445 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6446 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
0fda9b75
DC
6447
6448 Lisp_Object filename = default_filename;
6fc2811b 6449 struct frame *f = SELECTED_FRAME ();
0fda9b75
DC
6450 BOOL file_opened = FALSE;
6451 Lisp_Object orig_dir = dir;
6452 Lisp_Object orig_prompt = prompt;
6453
6454 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6455 compatibility) we end up with the old file dialogs. Define a big
6456 enough struct for the new dialog to trick GetOpenFileName into
6457 giving us the new dialogs on newer versions of Windows. */
6458 struct {
0fda9b75 6459 OPENFILENAMEW details;
0fda9b75
DC
6460#if _WIN32_WINNT < 0x500 /* < win2k */
6461 PVOID pvReserved;
6462 DWORD dwReserved;
6463 DWORD FlagsEx;
6464#endif /* < win2k */
2d716d75 6465 } new_file_details_w;
0fda9b75
DC
6466
6467#ifdef NTGUI_UNICODE
2d716d75
EZ
6468 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6469 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
eac30cd4 6470 const int use_unicode = 1;
0fda9b75 6471#else /* not NTGUI_UNICODE */
2d716d75
EZ
6472 struct {
6473 OPENFILENAMEA details;
6474#if _WIN32_WINNT < 0x500 /* < win2k */
6475 PVOID pvReserved;
6476 DWORD dwReserved;
6477 DWORD FlagsEx;
6478#endif /* < win2k */
6479 } new_file_details_a;
6480 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6481 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6482 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6483 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6484 int use_unicode = w32_unicode_filenames;
6485 wchar_t *prompt_w;
6486 char *prompt_a;
6487 int len;
6488 char fname_ret[MAX_UTF8_PATH];
0fda9b75
DC
6489#endif /* NTGUI_UNICODE */
6490
f9d64bb3 6491 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
0fda9b75 6492 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
5ac45f98 6493
0fda9b75
DC
6494 {
6495 struct gcpro gcpro1, gcpro2;
6496 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
5ac45f98 6497
0fda9b75
DC
6498 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6499 system file encoding expected by the platform APIs (e.g. Cygwin's
303cc1d1
EZ
6500 POSIX implementation) may not be the same as the encoding expected
6501 by the Windows "ANSI" APIs! */
ee78dc32 6502
0fda9b75
DC
6503 CHECK_STRING (prompt);
6504 CHECK_STRING (dir);
ee78dc32 6505
0fda9b75 6506 dir = Fexpand_file_name (dir, Qnil);
7faeca66 6507
0fda9b75
DC
6508 if (STRINGP (filename))
6509 filename = Ffile_name_nondirectory (filename);
6510 else
6511 filename = empty_unibyte_string;
21517c3d 6512
0fda9b75 6513#ifdef CYGWIN
6e9f7997 6514 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
0fda9b75 6515 if (SCHARS (filename) > 0)
6e9f7997 6516 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
0fda9b75 6517#endif
ee78dc32 6518
0fda9b75
DC
6519 CHECK_STRING (dir);
6520 CHECK_STRING (filename);
6521
6522 /* The code in file_dialog_callback that attempts to set the text
6523 of the file name edit window when handling the CDN_INITDONE
6524 WM_NOTIFY message does not work. Setting filename to "Current
6525 Directory" in the only_dir_p case here does work however. */
6526 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6527 filename = build_string ("Current Directory");
6528
6529 /* Convert the values we've computed so far to system form. */
6530#ifdef NTGUI_UNICODE
6531 to_unicode (prompt, &prompt);
6532 to_unicode (dir, &dir);
6533 to_unicode (filename, &filename);
2d716d75
EZ
6534 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6535 report_file_error ("filename too long", default_filename);
6536
6537 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
0fda9b75
DC
6538#else /* !NTGUI_UNICODE */
6539 prompt = ENCODE_FILE (prompt);
6540 dir = ENCODE_FILE (dir);
6541 filename = ENCODE_FILE (filename);
6542
6543 /* We modify these in-place, so make copies for safety. */
6544 dir = Fcopy_sequence (dir);
6545 unixtodos_filename (SDATA (dir));
6546 filename = Fcopy_sequence (filename);
6547 unixtodos_filename (SDATA (filename));
2d716d75
EZ
6548 if (SBYTES (filename) >= MAX_UTF8_PATH)
6549 report_file_error ("filename too long", default_filename);
6550 if (w32_unicode_filenames)
6551 {
6552 filename_to_utf16 (SSDATA (dir), dir_w);
6553 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6554 {
6555 /* filename_to_utf16 sets errno to ENOENT when the file
6556 name is too long or cannot be converted to UTF-16. */
6557 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6558 report_file_error ("filename too long", default_filename);
6559 }
829f4f22
EZ
6560 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6561 SSDATA (prompt), -1, NULL, 0);
ff0c63f2
EZ
6562 if (len > 32768)
6563 len = 32768;
2d716d75 6564 prompt_w = alloca (len * sizeof (wchar_t));
829f4f22
EZ
6565 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6566 SSDATA (prompt), -1, prompt_w, len);
2d716d75
EZ
6567 }
6568 else
6569 {
6570 filename_to_ansi (SSDATA (dir), dir_a);
6571 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6572 {
6573 /* filename_to_ansi sets errno to ENOENT when the file
6574 name is too long or cannot be converted to UTF-16. */
6575 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6576 report_file_error ("filename too long", default_filename);
6577 }
829f4f22
EZ
6578 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6579 SSDATA (prompt), -1, NULL, 0);
ff0c63f2
EZ
6580 if (len > 32768)
6581 len = 32768;
2d716d75 6582 prompt_w = alloca (len * sizeof (wchar_t));
829f4f22
EZ
6583 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6584 SSDATA (prompt), -1, prompt_w, len);
6585 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
ff0c63f2
EZ
6586 if (len > 32768)
6587 len = 32768;
2d716d75 6588 prompt_a = alloca (len);
829f4f22 6589 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
2d716d75 6590 }
0fda9b75
DC
6591#endif /* NTGUI_UNICODE */
6592
501199a3
DC
6593 /* Fill in the structure for the call to GetOpenFileName below.
6594 For NTGUI_UNICODE builds (which run only on NT), we just use
6595 the actual size of the structure. For non-NTGUI_UNICODE
6596 builds, we tell the OS we're using an old version of the
6597 structure if the OS isn't new enough to support the newer
6598 version. */
2d716d75
EZ
6599 if (use_unicode)
6600 {
6601 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6602 if (w32_major_version > 4 && w32_major_version < 95)
6603 file_details_w->lStructSize = sizeof (new_file_details_w);
6604 else
6605 file_details_w->lStructSize = sizeof (*file_details_w);
6606 /* Set up the inout parameter for the selected file name. */
6607 file_details_w->lpstrFile = filename_buf_w;
6608 file_details_w->nMaxFile =
6609 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6610 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6611 /* Undocumented Bug in Common File Dialog:
6612 If a filter is not specified, shell links are not resolved. */
6613 file_details_w->lpstrFilter = filter_w;
6614#ifdef NTGUI_UNICODE
6615 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
a5c9bbb3 6616 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
2d716d75
EZ
6617#else
6618 file_details_w->lpstrInitialDir = dir_w;
6619 file_details_w->lpstrTitle = prompt_w;
6620#endif
6621 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6622 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6623 | OFN_EXPLORER | OFN_ENABLEHOOK);
6624 if (!NILP (mustmatch))
6625 {
6626 /* Require that the path to the parent directory exists. */
6627 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6628 /* If we are looking for a file, require that it exists. */
6629 if (NILP (only_dir_p))
6630 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6631 }
6632 }
a5c9bbb3 6633#ifndef NTGUI_UNICODE
7f2b4738 6634 else
7f2b4738 6635 {
2d716d75
EZ
6636 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6637 if (w32_major_version > 4 && w32_major_version < 95)
6638 file_details_a->lStructSize = sizeof (new_file_details_a);
6639 else
6640 file_details_a->lStructSize = sizeof (*file_details_a);
6641 file_details_a->lpstrFile = filename_buf_a;
6642 file_details_a->nMaxFile =
6643 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6644 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6645 file_details_a->lpstrFilter = filter_a;
6646 file_details_a->lpstrInitialDir = dir_a;
6647 file_details_a->lpstrTitle = prompt_a;
6648 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6649 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6650 | OFN_EXPLORER | OFN_ENABLEHOOK);
6651 if (!NILP (mustmatch))
6652 {
6653 /* Require that the path to the parent directory exists. */
6654 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6655 /* If we are looking for a file, require that it exists. */
6656 if (NILP (only_dir_p))
6657 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6658 }
7f2b4738 6659 }
a5c9bbb3 6660#endif /* !NTGUI_UNICODE */
1030b26b 6661
0fda9b75 6662 {
2bfa3d3e 6663 dynwind_begin ();
303cc1d1 6664 /* Prevent redisplay. */
0fda9b75 6665 specbind (Qinhibit_redisplay, Qt);
36a305a7 6666 block_input ();
2d716d75
EZ
6667 if (use_unicode)
6668 {
6669 file_details_w->lpfnHook = file_dialog_callback;
6670
6671 file_opened = GetOpenFileNameW (file_details_w);
6672 }
8b55eeeb 6673#ifndef NTGUI_UNICODE
2d716d75
EZ
6674 else
6675 {
6676 file_details_a->lpfnHook = file_dialog_callback;
1030b26b 6677
2d716d75
EZ
6678 file_opened = GetOpenFileNameA (file_details_a);
6679 }
8b55eeeb 6680#endif /* !NTGUI_UNICODE */
36a305a7 6681 unblock_input ();
2bfa3d3e 6682 dynwind_end ();
0fda9b75 6683 }
ba6f3859
JR
6684
6685 if (file_opened)
1030b26b 6686 {
0fda9b75
DC
6687 /* Get an Emacs string from the value Windows gave us. */
6688#ifdef NTGUI_UNICODE
2d716d75 6689 filename = from_unicode_buffer (filename_buf_w);
0fda9b75 6690#else /* !NTGUI_UNICODE */
2d716d75
EZ
6691 if (use_unicode)
6692 filename_from_utf16 (filename_buf_w, fname_ret);
6693 else
6694 filename_from_ansi (filename_buf_a, fname_ret);
6695 dostounix_filename (fname_ret);
6696 filename = DECODE_FILE (build_unibyte_string (fname_ret));
0fda9b75
DC
6697#endif /* NTGUI_UNICODE */
6698
6699#ifdef CYGWIN
6e9f7997 6700 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
0fda9b75
DC
6701#endif /* CYGWIN */
6702
6703 /* Strip the dummy filename off the end of the string if we
6704 added it to select a directory. */
119f64db 6705 if ((use_unicode && file_details_w->nFilterIndex == 2)
893fcd38 6706#ifndef NTGUI_UNICODE
119f64db 6707 || (!use_unicode && file_details_a->nFilterIndex == 2)
893fcd38
EZ
6708#endif
6709 )
2d716d75 6710 filename = Ffile_name_directory (filename);
1030b26b 6711 }
c80e3b4a 6712 /* User canceled the dialog without making a selection. */
1030b26b 6713 else if (!CommDlgExtendedError ())
0fda9b75 6714 filename = Qnil;
1030b26b
JR
6715 /* An error occurred, fallback on reading from the mini-buffer. */
6716 else
0fda9b75
DC
6717 filename = Fcompleting_read (
6718 orig_prompt,
6719 intern ("read-file-name-internal"),
6720 orig_dir,
6721 mustmatch,
6722 orig_dir,
6723 Qfile_name_history,
6724 default_filename,
6725 Qnil);
1030b26b 6726
0fda9b75 6727 UNGCPRO;
1030b26b 6728 }
ee78dc32 6729
6fc2811b 6730 /* Make "Cancel" equivalent to C-g. */
0fda9b75 6731 if (NILP (filename))
6fc2811b 6732 Fsignal (Qquit, Qnil);
ee78dc32 6733
2bfa3d3e 6734 return filename;
6fc2811b 6735}
ee78dc32 6736
0fda9b75
DC
6737\f
6738#ifdef WINDOWSNT
6cf29fe8
JR
6739/* Moving files to the system recycle bin.
6740 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6741DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6742 Ssystem_move_file_to_trash, 1, 1, 0,
6743 doc: /* Move file or directory named FILENAME to the recycle bin. */)
5842a27b 6744 (Lisp_Object filename)
6cf29fe8
JR
6745{
6746 Lisp_Object handler;
6747 Lisp_Object encoded_file;
6748 Lisp_Object operation;
6749
6750 operation = Qdelete_file;
6751 if (!NILP (Ffile_directory_p (filename))
6752 && NILP (Ffile_symlink_p (filename)))
6753 {
e9a0aef8 6754 operation = intern ("delete-directory");
6cf29fe8
JR
6755 filename = Fdirectory_file_name (filename);
6756 }
2c47be65
EZ
6757
6758 /* Must have fully qualified file names for moving files to Recycle
6759 Bin. */
6cf29fe8
JR
6760 filename = Fexpand_file_name (filename, Qnil);
6761
6762 handler = Ffind_file_name_handler (filename, operation);
6763 if (!NILP (handler))
6764 return call2 (handler, operation, filename);
2c47be65
EZ
6765 else
6766 {
6767 const char * path;
6768 int result;
6cf29fe8 6769
2c47be65 6770 encoded_file = ENCODE_FILE (filename);
6cf29fe8 6771
2c47be65 6772 path = map_w32_filename (SDATA (encoded_file), NULL);
6cf29fe8 6773
2c47be65
EZ
6774 /* The Unicode version of SHFileOperation is not supported on
6775 Windows 9X. */
6776 if (w32_unicode_filenames && os_subtype != OS_9X)
6777 {
6778 SHFILEOPSTRUCTW file_op_w;
6779 /* We need one more element beyond MAX_PATH because this is
6780 a list of file names, with the last element double-null
6781 terminated. */
6782 wchar_t tmp_path_w[MAX_PATH + 1];
6783
6784 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6785 filename_to_utf16 (path, tmp_path_w);
6786
6787 /* On Windows, write permission is required to delete/move files. */
6788 _wchmod (tmp_path_w, 0666);
6789
6790 memset (&file_op_w, 0, sizeof (file_op_w));
6791 file_op_w.hwnd = HWND_DESKTOP;
6792 file_op_w.wFunc = FO_DELETE;
6793 file_op_w.pFrom = tmp_path_w;
6794 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6795 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6796 file_op_w.fAnyOperationsAborted = FALSE;
6797
6798 result = SHFileOperationW (&file_op_w);
6799 }
6800 else
6801 {
6802 SHFILEOPSTRUCTA file_op_a;
6803 char tmp_path_a[MAX_PATH + 1];
6cf29fe8 6804
2c47be65
EZ
6805 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6806 filename_to_ansi (path, tmp_path_a);
6cf29fe8 6807
2c47be65
EZ
6808 /* If a file cannot be represented in ANSI codepage, don't
6809 let them inadvertently delete other files because some
6810 characters are interpreted as a wildcards. */
6811 if (_mbspbrk (tmp_path_a, "?*"))
6812 result = ERROR_FILE_NOT_FOUND;
6813 else
6814 {
6815 _chmod (tmp_path_a, 0666);
6cf29fe8 6816
2c47be65
EZ
6817 memset (&file_op_a, 0, sizeof (file_op_a));
6818 file_op_a.hwnd = HWND_DESKTOP;
6819 file_op_a.wFunc = FO_DELETE;
6820 file_op_a.pFrom = tmp_path_a;
6821 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6822 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6823 file_op_a.fAnyOperationsAborted = FALSE;
6cf29fe8 6824
2c47be65
EZ
6825 result = SHFileOperationA (&file_op_a);
6826 }
6827 }
6828 if (result != 0)
6829 report_file_error ("Removing old name", list1 (filename));
6830 }
6cf29fe8
JR
6831 return Qnil;
6832}
6833
0fda9b75
DC
6834#endif /* WINDOWSNT */
6835
6fc2811b 6836\f
6fc2811b
JR
6837/***********************************************************************
6838 w32 specialized functions
6839 ***********************************************************************/
ee78dc32 6840
74e1aeec
JR
6841DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6842 Sw32_send_sys_command, 1, 2, 0,
6843 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
52deb19f 6844Some useful values for COMMAND are #xf030 to maximize frame (#xf020
d84b082d
JR
6845to minimize), #xf120 to restore frame to original size, and #xf100
6846to activate the menubar for keyboard access. #xf140 activates the
74e1aeec
JR
6847screen saver if defined.
6848
6849If optional parameter FRAME is not specified, use selected frame. */)
5842a27b 6850 (Lisp_Object command, Lisp_Object frame)
1edf84e7 6851{
a10c8269 6852 struct frame *f = decode_window_system_frame (frame);
1edf84e7 6853
b7826503 6854 CHECK_NUMBER (command);
1edf84e7 6855
ce6059da 6856 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
1edf84e7
GV
6857
6858 return Qnil;
6859}
6860
55dcfc15 6861DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
74e1aeec
JR
6862 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6863This is a wrapper around the ShellExecute system function, which
6864invokes the application registered to handle OPERATION for DOCUMENT.
74e1aeec 6865
1dccd454
EZ
6866OPERATION is either nil or a string that names a supported operation.
6867What operations can be used depends on the particular DOCUMENT and its
6868handler application, but typically it is one of the following common
6869operations:
6870
6871 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6d48053b
EZ
6872 executable program (application). If it is an application,
6873 that application is launched in the current buffer's default
1dccd454
EZ
6874 directory. Otherwise, the application associated with
6875 DOCUMENT is launched in the buffer's default directory.
6d48053b
EZ
6876 \"opennew\" - like \"open\", but instruct the application to open
6877 DOCUMENT in a new window.
6878 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
6879 \"print\" - print DOCUMENT, which must be a file.
6880 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
6881 The printer should be provided in PARAMETERS, see below.
6882 \"explore\" - start the Windows Explorer on DOCUMENT.
1dccd454
EZ
6883 \"edit\" - launch an editor and open DOCUMENT for editing; which
6884 editor is launched depends on the association for the
6d48053b
EZ
6885 specified DOCUMENT.
6886 \"find\" - initiate search starting from DOCUMENT, which must specify
6887 a directory.
6d731d41
EZ
6888 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
6889 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
6890 the clipboard.
6891 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
6892 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
6893 which must be a directory.
6894 \"pastelink\"
6895 - create a shortcut in DOCUMENT (which must be a directory)
6896 the file or directory whose name is in the clipboard.
ec6e26b8
EZ
6897 \"runas\" - run DOCUMENT, which must be an excutable file, with
6898 elevated privileges (a.k.a. \"as Administrator\").
6d48053b 6899 \"properties\"
33848c48 6900 - open the property sheet dialog for DOCUMENT.
1dccd454 6901 nil - invoke the default OPERATION, or \"open\" if default is
6d48053b 6902 not defined or unavailable.
1dccd454
EZ
6903
6904DOCUMENT is typically the name of a document file or a URL, but can
6d48053b 6905also be an executable program to run, or a directory to open in the
6d731d41
EZ
6906Windows Explorer. If it is a file or a directory, it must be a local
6907one; this function does not support remote file names.
1dccd454 6908
6d48053b 6909If DOCUMENT is an executable program, the optional third arg PARAMETERS
6d731d41
EZ
6910can be a string containing command line parameters, separated by blanks,
6911that will be passed to the program. Some values of OPERATION also require
6912parameters (e.g., \"printto\" requires the printer address). Otherwise,
6913PARAMETERS should be nil or unspecified. Note that double quote characters
6914in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
1dccd454 6915
02b39a28 6916Optional fourth argument SHOW-FLAG can be used to control how the
1dccd454 6917application will be displayed when it is invoked. If SHOW-FLAG is nil
6d48053b
EZ
6918or unspecified, the application is displayed as if SHOW-FLAG of 10 was
6919specified, otherwise it is an integer between 0 and 11 representing
6920a ShowWindow flag:
74e1aeec
JR
6921
6922 0 - start hidden
6d48053b
EZ
6923 1 - start as normal-size window
6924 3 - start in a maximized window
6925 6 - start in a minimized window
6926 10 - start as the application itself specifies; this is the default. */)
5842a27b 6927 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
55dcfc15 6928{
5cba3209 6929 char *errstr;
ff0c63f2
EZ
6930 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6931 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
17bf44f8 6932#ifdef CYGWIN
a5c9bbb3 6933 intptr_t result;
17bf44f8 6934#else
ff0c63f2
EZ
6935 int use_unicode = w32_unicode_filenames;
6936 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
cb13e9a8 6937 Lisp_Object absdoc, handler;
6d731d41 6938 BOOL success;
cb13e9a8 6939 struct gcpro gcpro1;
ff0c63f2 6940#endif
55dcfc15 6941
b7826503 6942 CHECK_STRING (document);
55dcfc15 6943
819e2da9
DC
6944#ifdef CYGWIN
6945 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
ec6e26b8 6946 document = Fcygwin_convert_file_name_to_windows (document, Qt);
819e2da9 6947
ff0c63f2 6948 /* Encode filename, current directory and parameters. */
819e2da9 6949 current_dir = GUI_ENCODE_FILE (current_dir);
ec6e26b8
EZ
6950 document = GUI_ENCODE_FILE (document);
6951 doc_w = GUI_SDATA (document);
3bc143eb 6952 if (STRINGP (parameters))
ff0c63f2
EZ
6953 {
6954 parameters = GUI_ENCODE_SYSTEM (parameters);
6955 params_w = GUI_SDATA (parameters);
6956 }
6957 if (STRINGP (operation))
6958 {
6959 operation = GUI_ENCODE_SYSTEM (operation);
6960 ops_w = GUI_SDATA (operation);
6961 }
a5c9bbb3
EZ
6962 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6963 GUI_SDATA (current_dir),
6964 (INTEGERP (show_flag)
6965 ? XINT (show_flag) : SW_SHOWDEFAULT));
6d731d41
EZ
6966
6967 if (result > 32)
6968 return Qt;
6969
6970 switch (result)
6971 {
6972 case SE_ERR_ACCESSDENIED:
6973 errstr = w32_strerror (ERROR_ACCESS_DENIED);
6974 break;
6975 case SE_ERR_ASSOCINCOMPLETE:
6976 case SE_ERR_NOASSOC:
6977 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
6978 break;
6979 case SE_ERR_DDEBUSY:
6980 case SE_ERR_DDEFAIL:
6981 errstr = w32_strerror (ERROR_DDE_FAIL);
6982 break;
6983 case SE_ERR_DDETIMEOUT:
6984 errstr = w32_strerror (ERROR_TIMEOUT);
6985 break;
6986 case SE_ERR_DLLNOTFOUND:
6987 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
6988 break;
6989 case SE_ERR_FNF:
6990 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
6991 break;
6992 case SE_ERR_OOM:
6993 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
6994 break;
6995 case SE_ERR_PNF:
6996 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
6997 break;
6998 case SE_ERR_SHARE:
6999 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7000 break;
7001 default:
7002 errstr = w32_strerror (0);
7003 break;
7004 }
7005
ff0c63f2 7006#else /* !CYGWIN */
6d731d41 7007
ec6e26b8 7008 current_dir = ENCODE_FILE (current_dir);
9ab3ce4d 7009 /* We have a situation here. If DOCUMENT is a relative file name,
8101203a
EZ
7010 but its name includes leading directories, i.e. it lives not in
7011 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7012 will fail to find it. So we need to make the file name is
7013 absolute. But DOCUMENT does not have to be a file, it can be a
7014 URL, for example. So we make it absolute only if it is an
7015 existing file; if it is a file that does not exist, tough. */
cb13e9a8 7016 GCPRO1 (absdoc);
9ab3ce4d 7017 absdoc = Fexpand_file_name (document, Qnil);
cb13e9a8
EZ
7018 /* Don't call file handlers for file-exists-p, since they might
7019 attempt to access the file, which could fail or produce undesired
7020 consequences, see bug#16558 for an example. */
7021 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7022 if (NILP (handler))
7023 {
7024 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7025
7026 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7027 document = absdoc_encoded;
7028 else
7029 document = ENCODE_FILE (document);
7030 }
7031 else
7032 document = ENCODE_FILE (document);
7033 UNGCPRO;
ff0c63f2
EZ
7034 if (use_unicode)
7035 {
7036 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
6d731d41 7037 SHELLEXECUTEINFOW shexinfo_w;
ff0c63f2
EZ
7038
7039 /* Encode filename, current directory and parameters, and
7040 convert operation to UTF-16. */
ff0c63f2 7041 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
ec6e26b8
EZ
7042 filename_to_utf16 (SSDATA (document), document_w);
7043 doc_w = document_w;
ff0c63f2
EZ
7044 if (STRINGP (parameters))
7045 {
9f9974b4
EZ
7046 int len;
7047
7048 parameters = ENCODE_SYSTEM (parameters);
829f4f22
EZ
7049 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7050 SSDATA (parameters), -1, NULL, 0);
ff0c63f2
EZ
7051 if (len > 32768)
7052 len = 32768;
7053 params_w = alloca (len * sizeof (wchar_t));
829f4f22
EZ
7054 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7055 SSDATA (parameters), -1, params_w, len);
ff0c63f2
EZ
7056 }
7057 if (STRINGP (operation))
7058 {
7059 /* Assume OPERATION is pure ASCII. */
7060 const char *s = SSDATA (operation);
7061 wchar_t *d;
9f9974b4 7062 int len = SBYTES (operation) + 1;
ff0c63f2
EZ
7063
7064 if (len > 32768)
7065 len = 32768;
7066 d = ops_w = alloca (len * sizeof (wchar_t));
7067 while (d < ops_w + len - 1)
7068 *d++ = *s++;
7069 *d = 0;
7070 }
6d731d41
EZ
7071
7072 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7073 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7074 able to invoke verbs from shortcut menu extensions, not just
7075 static verbs listed in the Registry. */
7076 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7077 shexinfo_w.cbSize = sizeof (shexinfo_w);
7078 shexinfo_w.fMask =
7079 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7080 shexinfo_w.hwnd = NULL;
7081 shexinfo_w.lpVerb = ops_w;
7082 shexinfo_w.lpFile = doc_w;
7083 shexinfo_w.lpParameters = params_w;
7084 shexinfo_w.lpDirectory = current_dir_w;
7085 shexinfo_w.nShow =
7086 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7087 success = ShellExecuteExW (&shexinfo_w);
ff0c63f2
EZ
7088 }
7089 else
7090 {
7091 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
6d731d41 7092 SHELLEXECUTEINFOA shexinfo_a;
ff0c63f2 7093
ff0c63f2 7094 filename_to_ansi (SSDATA (current_dir), current_dir_a);
ec6e26b8
EZ
7095 filename_to_ansi (SSDATA (document), document_a);
7096 doc_a = document_a;
ff0c63f2
EZ
7097 if (STRINGP (parameters))
7098 {
9f9974b4
EZ
7099 parameters = ENCODE_SYSTEM (parameters);
7100 params_a = SSDATA (parameters);
ff0c63f2
EZ
7101 }
7102 if (STRINGP (operation))
7103 {
7104 /* Assume OPERATION is pure ASCII. */
7105 ops_a = SSDATA (operation);
7106 }
6d731d41
EZ
7107 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7108 shexinfo_a.cbSize = sizeof (shexinfo_a);
7109 shexinfo_a.fMask =
7110 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7111 shexinfo_a.hwnd = NULL;
7112 shexinfo_a.lpVerb = ops_a;
7113 shexinfo_a.lpFile = doc_a;
7114 shexinfo_a.lpParameters = params_a;
7115 shexinfo_a.lpDirectory = current_dir_a;
7116 shexinfo_a.nShow =
7117 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7118 success = ShellExecuteExA (&shexinfo_a);
ff0c63f2 7119 }
ff0c63f2 7120
6d731d41 7121 if (success)
55dcfc15 7122 return Qt;
ff0c63f2 7123
6d731d41
EZ
7124 errstr = w32_strerror (0);
7125
7126#endif /* !CYGWIN */
7127
5cba3209
EZ
7128 /* The error string might be encoded in the locale's encoding. */
7129 if (!NILP (Vlocale_coding_system))
7130 {
7131 Lisp_Object decoded =
d7ea76b4 7132 code_convert_string_norecord (build_unibyte_string (errstr),
5cba3209 7133 Vlocale_coding_system, 0);
51b59d79 7134 errstr = SSDATA (decoded);
5cba3209
EZ
7135 }
7136 error ("ShellExecute failed: %s", errstr);
55dcfc15
AI
7137}
7138
ccc2d29c
GV
7139/* Lookup virtual keycode from string representing the name of a
7140 non-ascii keystroke into the corresponding virtual key, using
7141 lispy_function_keys. */
7142static int
7143lookup_vk_code (char *key)
7144{
7145 int i;
7146
7147 for (i = 0; i < 256; i++)
bf254037 7148 if (lispy_function_keys[i]
ccc2d29c
GV
7149 && strcmp (lispy_function_keys[i], key) == 0)
7150 return i;
7151
7152 return -1;
7153}
7154
7155/* Convert a one-element vector style key sequence to a hot key
7156 definition. */
2ba49441 7157static Lisp_Object
b56ceb92 7158w32_parse_hot_key (Lisp_Object key)
ccc2d29c
GV
7159{
7160 /* Copied from Fdefine_key and store_in_keymap. */
7161 register Lisp_Object c;
7162 int vk_code;
7163 int lisp_modifiers;
7164 int w32_modifiers;
7165 struct gcpro gcpro1;
7166
b7826503 7167 CHECK_VECTOR (key);
ccc2d29c 7168
9a9d91d9 7169 if (ASIZE (key) != 1)
ccc2d29c
GV
7170 return Qnil;
7171
7172 GCPRO1 (key);
7173
9a9d91d9 7174 c = AREF (key, 0);
ccc2d29c
GV
7175
7176 if (CONSP (c) && lucid_event_type_list_p (c))
7177 c = Fevent_convert_list (c);
7178
7179 UNGCPRO;
7180
7181 if (! INTEGERP (c) && ! SYMBOLP (c))
7182 error ("Key definition is invalid");
7183
7184 /* Work out the base key and the modifiers. */
7185 if (SYMBOLP (c))
7186 {
7187 c = parse_modifiers (c);
2ba49441 7188 lisp_modifiers = XINT (Fcar (Fcdr (c)));
ccc2d29c
GV
7189 c = Fcar (c);
7190 if (!SYMBOLP (c))
1088b922 7191 emacs_abort ();
d5db4077 7192 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
ccc2d29c
GV
7193 }
7194 else if (INTEGERP (c))
7195 {
7196 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7197 /* Many ascii characters are their own virtual key code. */
7198 vk_code = XINT (c) & CHARACTERBITS;
7199 }
7200
7201 if (vk_code < 0 || vk_code > 255)
7202 return Qnil;
7203
7204 if ((lisp_modifiers & meta_modifier) != 0
7205 && !NILP (Vw32_alt_is_meta))
7206 lisp_modifiers |= alt_modifier;
7207
71eab8d1
AI
7208 /* Supply defs missing from mingw32. */
7209#ifndef MOD_ALT
7210#define MOD_ALT 0x0001
7211#define MOD_CONTROL 0x0002
7212#define MOD_SHIFT 0x0004
7213#define MOD_WIN 0x0008
7214#endif
7215
ccc2d29c
GV
7216 /* Convert lisp modifiers to Windows hot-key form. */
7217 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7218 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7219 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7220 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7221
7222 return HOTKEY (vk_code, w32_modifiers);
7223}
7224
74e1aeec
JR
7225DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7226 Sw32_register_hot_key, 1, 1, 0,
7227 doc: /* Register KEY as a hot-key combination.
7228Certain key combinations like Alt-Tab are reserved for system use on
7229Windows, and therefore are normally intercepted by the system. However,
7230most of these key combinations can be received by registering them as
7231hot-keys, overriding their special meaning.
7232
7233KEY must be a one element key definition in vector form that would be
7234acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7235modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7236is always interpreted as the Windows modifier keys.
7237
7238The return value is the hotkey-id if registered, otherwise nil. */)
5842a27b 7239 (Lisp_Object key)
ccc2d29c
GV
7240{
7241 key = w32_parse_hot_key (key);
7242
fb053a1f 7243 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
ccc2d29c
GV
7244 {
7245 /* Reuse an empty slot if possible. */
7246 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7247
7248 /* Safe to add new key to list, even if we have focus. */
7249 if (NILP (item))
7250 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7251 else
f3fbd155 7252 XSETCAR (item, key);
ccc2d29c
GV
7253
7254 /* Notify input thread about new hot-key definition, so that it
7255 takes effect without needing to switch focus. */
2ba49441 7256 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
646b5f55 7257 (WPARAM) XLI (key), 0);
ccc2d29c
GV
7258 }
7259
7260 return key;
7261}
7262
74e1aeec
JR
7263DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7264 Sw32_unregister_hot_key, 1, 1, 0,
52deb19f 7265 doc: /* Unregister KEY as a hot-key combination. */)
5842a27b 7266 (Lisp_Object key)
ccc2d29c
GV
7267{
7268 Lisp_Object item;
7269
7270 if (!INTEGERP (key))
7271 key = w32_parse_hot_key (key);
7272
7273 item = Fmemq (key, w32_grabbed_keys);
7274
7275 if (!NILP (item))
7276 {
7277 /* Notify input thread about hot-key definition being removed, so
7278 that it takes effect without needing focus switch. */
7279 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
646b5f55 7280 (WPARAM) XINT (XCAR (item)), (LPARAM) XLI (item)))
ccc2d29c
GV
7281 {
7282 MSG msg;
7283 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7284 }
7285 return Qt;
7286 }
7287 return Qnil;
7288}
7289
74e1aeec
JR
7290DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7291 Sw32_registered_hot_keys, 0, 0, 0,
7292 doc: /* Return list of registered hot-key IDs. */)
5842a27b 7293 (void)
ccc2d29c 7294{
74084731 7295 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
ccc2d29c
GV
7296}
7297
74e1aeec
JR
7298DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7299 Sw32_reconstruct_hot_key, 1, 1, 0,
52deb19f
JB
7300 doc: /* Convert hot-key ID to a lisp key combination.
7301usage: (w32-reconstruct-hot-key ID) */)
5842a27b 7302 (Lisp_Object hotkeyid)
ccc2d29c
GV
7303{
7304 int vk_code, w32_modifiers;
7305 Lisp_Object key;
7306
b7826503 7307 CHECK_NUMBER (hotkeyid);
ccc2d29c
GV
7308
7309 vk_code = HOTKEY_VK_CODE (hotkeyid);
7310 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7311
bf254037 7312 if (vk_code < 256 && lispy_function_keys[vk_code])
ccc2d29c
GV
7313 key = intern (lispy_function_keys[vk_code]);
7314 else
7315 key = make_number (vk_code);
7316
7317 key = Fcons (key, Qnil);
7318 if (w32_modifiers & MOD_SHIFT)
3ef68e6b 7319 key = Fcons (Qshift, key);
ccc2d29c 7320 if (w32_modifiers & MOD_CONTROL)
3ef68e6b 7321 key = Fcons (Qctrl, key);
ccc2d29c 7322 if (w32_modifiers & MOD_ALT)
3ef68e6b 7323 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
ccc2d29c 7324 if (w32_modifiers & MOD_WIN)
3ef68e6b 7325 key = Fcons (Qhyper, key);
ccc2d29c
GV
7326
7327 return key;
7328}
adcc3809 7329
74e1aeec
JR
7330DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7331 Sw32_toggle_lock_key, 1, 2, 0,
7332 doc: /* Toggle the state of the lock key KEY.
7333KEY can be `capslock', `kp-numlock', or `scroll'.
7334If the optional parameter NEW-STATE is a number, then the state of KEY
7335is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
5842a27b 7336 (Lisp_Object key, Lisp_Object new_state)
adcc3809
GV
7337{
7338 int vk_code;
adcc3809
GV
7339
7340 if (EQ (key, intern ("capslock")))
7341 vk_code = VK_CAPITAL;
7342 else if (EQ (key, intern ("kp-numlock")))
7343 vk_code = VK_NUMLOCK;
7344 else if (EQ (key, intern ("scroll")))
7345 vk_code = VK_SCROLL;
7346 else
7347 return Qnil;
7348
7349 if (!dwWindowsThreadId)
7350 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7351
7352 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
646b5f55 7353 (WPARAM) vk_code, (LPARAM) XLI (new_state)))
adcc3809
GV
7354 {
7355 MSG msg;
7356 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7357 return make_number (msg.wParam);
7358 }
7359 return Qnil;
7360}
a01763cb
EZ
7361
7362DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7363 2, 2, 0,
7364 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7365
7366This is a direct interface to the Windows API FindWindow function. */)
5842a27b 7367 (Lisp_Object class, Lisp_Object name)
a01763cb
EZ
7368{
7369 HWND hnd;
7370
7371 if (!NILP (class))
7372 CHECK_STRING (class);
7373 if (!NILP (name))
7374 CHECK_STRING (name);
7375
7376 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7377 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7378 if (!hnd)
7379 return Qnil;
7380 return Qt;
7381}
7382
880e6158
MR
7383DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7384 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7385FRAME must be a live frame and defaults to the selected one.
7386
7387The boundary rectangle is a list of four elements, specifying the left,
7388top, right and bottom screen coordinates of FRAME including menu and
7389title bar and decorations. Optional argument CLIENT non-nil means to
7390return the boundaries of the client rectangle which excludes menu and
7391title bar and decorations. */)
7392 (Lisp_Object frame, Lisp_Object client)
7393{
7394 struct frame *f = decode_live_frame (frame);
7395 RECT rect;
7396
7397 if (!NILP (client))
7398 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7399 else
7400 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7401
7402 return list4 (make_number (rect.left), make_number (rect.top),
7403 make_number (rect.right), make_number (rect.bottom));
7404}
7405
2c2279c6
JR
7406DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7407 doc: /* Get power status information from Windows system.
7408
7409The following %-sequences are provided:
7410%L AC line status (verbose)
7411%B Battery status (verbose)
7412%b Battery status, empty means high, `-' means low,
7413 `!' means critical, and `+' means charging
7414%p Battery load percentage
7415%s Remaining time (to charge or discharge) in seconds
7416%m Remaining time (to charge or discharge) in minutes
7417%h Remaining time (to charge or discharge) in hours
7418%t Remaining time (to charge or discharge) in the form `h:min' */)
5842a27b 7419 (void)
2c2279c6
JR
7420{
7421 Lisp_Object status = Qnil;
7422
7423 SYSTEM_POWER_STATUS system_status;
7424 if (GetSystemPowerStatus (&system_status))
7425 {
7426 Lisp_Object line_status, battery_status, battery_status_symbol;
7427 Lisp_Object load_percentage, seconds, minutes, hours, remain;
2c2279c6
JR
7428
7429 long seconds_left = (long) system_status.BatteryLifeTime;
7430
7431 if (system_status.ACLineStatus == 0)
7432 line_status = build_string ("off-line");
7433 else if (system_status.ACLineStatus == 1)
7434 line_status = build_string ("on-line");
7435 else
7436 line_status = build_string ("N/A");
7437
7438 if (system_status.BatteryFlag & 128)
7439 {
7440 battery_status = build_string ("N/A");
fff4e459 7441 battery_status_symbol = empty_unibyte_string;
2c2279c6
JR
7442 }
7443 else if (system_status.BatteryFlag & 8)
7444 {
7445 battery_status = build_string ("charging");
7446 battery_status_symbol = build_string ("+");
7447 if (system_status.BatteryFullLifeTime != -1L)
7448 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7449 }
7450 else if (system_status.BatteryFlag & 4)
7451 {
7452 battery_status = build_string ("critical");
7453 battery_status_symbol = build_string ("!");
7454 }
7455 else if (system_status.BatteryFlag & 2)
7456 {
7457 battery_status = build_string ("low");
7458 battery_status_symbol = build_string ("-");
7459 }
7460 else if (system_status.BatteryFlag & 1)
7461 {
7462 battery_status = build_string ("high");
fff4e459 7463 battery_status_symbol = empty_unibyte_string;
2c2279c6
JR
7464 }
7465 else
7466 {
7467 battery_status = build_string ("medium");
fff4e459 7468 battery_status_symbol = empty_unibyte_string;
2c2279c6
JR
7469 }
7470
7471 if (system_status.BatteryLifePercent > 100)
7472 load_percentage = build_string ("N/A");
7473 else
7474 {
7475 char buffer[16];
0fda9b75 7476 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
2c2279c6
JR
7477 load_percentage = build_string (buffer);
7478 }
7479
7480 if (seconds_left < 0)
7481 seconds = minutes = hours = remain = build_string ("N/A");
7482 else
7483 {
7484 long m;
7485 float h;
7486 char buffer[16];
0fda9b75 7487 snprintf (buffer, 16, "%ld", seconds_left);
2c2279c6
JR
7488 seconds = build_string (buffer);
7489
7490 m = seconds_left / 60;
0fda9b75 7491 snprintf (buffer, 16, "%ld", m);
2c2279c6
JR
7492 minutes = build_string (buffer);
7493
7494 h = seconds_left / 3600.0;
0fda9b75 7495 snprintf (buffer, 16, "%3.1f", h);
2c2279c6
JR
7496 hours = build_string (buffer);
7497
0fda9b75 7498 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
2c2279c6
JR
7499 remain = build_string (buffer);
7500 }
694b6c97 7501
3438fe21 7502 status = listn (CONSTYPE_HEAP, 8,
694b6c97
DA
7503 Fcons (make_number ('L'), line_status),
7504 Fcons (make_number ('B'), battery_status),
7505 Fcons (make_number ('b'), battery_status_symbol),
7506 Fcons (make_number ('p'), load_percentage),
7507 Fcons (make_number ('s'), seconds),
7508 Fcons (make_number ('m'), minutes),
7509 Fcons (make_number ('h'), hours),
7510 Fcons (make_number ('t'), remain));
2c2279c6
JR
7511 }
7512 return status;
7513}
a01763cb 7514
ee78dc32 7515\f
819e2da9 7516#ifdef WINDOWSNT
2254bcde 7517DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
74e1aeec
JR
7518 doc: /* Return storage information about the file system FILENAME is on.
7519Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7520storage of the file system, FREE is the free storage, and AVAIL is the
7521storage available to a non-superuser. All 3 numbers are in bytes.
7522If the underlying system call fails, value is nil. */)
5842a27b 7523 (Lisp_Object filename)
2254bcde
AI
7524{
7525 Lisp_Object encoded, value;
7526
b7826503 7527 CHECK_STRING (filename);
2254bcde
AI
7528 filename = Fexpand_file_name (filename, Qnil);
7529 encoded = ENCODE_FILE (filename);
7530
7531 value = Qnil;
7532
7533 /* Determining the required information on Windows turns out, sadly,
b46a6a83 7534 to be more involved than one would hope. The original Windows API
2254bcde
AI
7535 call for this will return bogus information on some systems, but we
7536 must dynamically probe for the replacement api, since that was
7537 added rather late on. */
7538 {
7539 HMODULE hKernel = GetModuleHandle ("kernel32");
28e6cee8 7540 BOOL (WINAPI *pfn_GetDiskFreeSpaceExW)
577c8624 7541 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
28e6cee8
EZ
7542 = GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7543 BOOL (WINAPI *pfn_GetDiskFreeSpaceExA)
2254bcde 7544 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
28e6cee8 7545 = GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
577c8624 7546 bool have_pfn_GetDiskFreeSpaceEx =
5af73b0f
JB
7547 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
7548 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
2254bcde
AI
7549
7550 /* On Windows, we may need to specify the root directory of the
7551 volume holding FILENAME. */
577c8624
EZ
7552 char rootname[MAX_UTF8_PATH];
7553 wchar_t rootname_w[MAX_PATH];
7554 char rootname_a[MAX_PATH];
d5db4077 7555 char *name = SDATA (encoded);
577c8624 7556 BOOL result;
2254bcde
AI
7557
7558 /* find the root name of the volume if given */
7559 if (isalpha (name[0]) && name[1] == ':')
7560 {
7561 rootname[0] = name[0];
7562 rootname[1] = name[1];
7563 rootname[2] = '\\';
7564 rootname[3] = 0;
7565 }
7566 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7567 {
7568 char *str = rootname;
7569 int slashes = 4;
7570 do
7571 {
7572 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7573 break;
7574 *str++ = *name++;
7575 }
7576 while ( *name );
7577
7578 *str++ = '\\';
7579 *str = 0;
7580 }
7581
577c8624
EZ
7582 if (w32_unicode_filenames)
7583 filename_to_utf16 (rootname, rootname_w);
7584 else
7585 filename_to_ansi (rootname, rootname_a);
7586
7587 if (have_pfn_GetDiskFreeSpaceEx)
2254bcde 7588 {
ac849ba4
JR
7589 /* Unsigned large integers cannot be cast to double, so
7590 use signed ones instead. */
2254bcde
AI
7591 LARGE_INTEGER availbytes;
7592 LARGE_INTEGER freebytes;
7593 LARGE_INTEGER totalbytes;
7594
577c8624
EZ
7595 if (w32_unicode_filenames)
7596 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7597 (ULARGE_INTEGER *)&availbytes,
7598 (ULARGE_INTEGER *)&totalbytes,
7599 (ULARGE_INTEGER *)&freebytes);
7600 else
7601 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7602 (ULARGE_INTEGER *)&availbytes,
7603 (ULARGE_INTEGER *)&totalbytes,
7604 (ULARGE_INTEGER *)&freebytes);
7605 if (result)
2254bcde
AI
7606 value = list3 (make_float ((double) totalbytes.QuadPart),
7607 make_float ((double) freebytes.QuadPart),
7608 make_float ((double) availbytes.QuadPart));
7609 }
7610 else
7611 {
7612 DWORD sectors_per_cluster;
7613 DWORD bytes_per_sector;
7614 DWORD free_clusters;
7615 DWORD total_clusters;
7616
577c8624
EZ
7617 if (w32_unicode_filenames)
7618 result = GetDiskFreeSpaceW (rootname_w,
7619 &sectors_per_cluster,
7620 &bytes_per_sector,
7621 &free_clusters,
7622 &total_clusters);
7623 else
7624 result = GetDiskFreeSpaceA (rootname_a,
7625 &sectors_per_cluster,
7626 &bytes_per_sector,
7627 &free_clusters,
7628 &total_clusters);
7629 if (result)
2254bcde
AI
7630 value = list3 (make_float ((double) total_clusters
7631 * sectors_per_cluster * bytes_per_sector),
7632 make_float ((double) free_clusters
7633 * sectors_per_cluster * bytes_per_sector),
7634 make_float ((double) free_clusters
7635 * sectors_per_cluster * bytes_per_sector));
7636 }
7637 }
7638
7639 return value;
7640}
819e2da9
DC
7641#endif /* WINDOWSNT */
7642
2254bcde 7643\f
a5c9bbb3 7644#ifdef WINDOWSNT
6b61353c
KH
7645DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7646 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
5842a27b 7647 (void)
6b61353c
KH
7648{
7649 static char pname_buf[256];
7650 int err;
7651 HANDLE hPrn;
080fd649
EZ
7652 PRINTER_INFO_2W *ppi2w = NULL;
7653 PRINTER_INFO_2A *ppi2a = NULL;
6b61353c 7654 DWORD dwNeeded = 0, dwReturned = 0;
080fd649
EZ
7655 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7656 char port_name[MAX_UTF8_PATH];
6b61353c
KH
7657
7658 /* Retrieve the default string from Win.ini (the registry).
7659 * String will be in form "printername,drivername,portname".
7660 * This is the most portable way to get the default printer. */
7661 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7662 return Qnil;
7663 /* printername precedes first "," character */
7664 strtok (pname_buf, ",");
7665 /* We want to know more than the printer name */
7666 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7667 return Qnil;
080fd649
EZ
7668 /* GetPrinterW is not supported by unicows.dll. */
7669 if (w32_unicode_filenames && os_subtype != OS_9X)
7670 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7671 else
7672 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
6b61353c
KH
7673 if (dwNeeded == 0)
7674 {
7675 ClosePrinter (hPrn);
7676 return Qnil;
7677 }
080fd649
EZ
7678 /* Call GetPrinter again with big enough memory block. */
7679 if (w32_unicode_filenames && os_subtype != OS_9X)
6b61353c 7680 {
080fd649
EZ
7681 /* Allocate memory for the PRINTER_INFO_2 struct. */
7682 ppi2w = xmalloc (dwNeeded);
7683 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
6b61353c 7684 ClosePrinter (hPrn);
080fd649
EZ
7685 if (!err)
7686 {
7687 xfree (ppi2w);
7688 return Qnil;
7689 }
7690
7691 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7692 && ppi2w->pServerName)
7693 {
7694 filename_from_utf16 (ppi2w->pServerName, server_name);
7695 filename_from_utf16 (ppi2w->pShareName, share_name);
7696 }
7697 else
7698 {
7699 server_name[0] = '\0';
7700 filename_from_utf16 (ppi2w->pPortName, port_name);
7701 }
6b61353c 7702 }
080fd649 7703 else
6b61353c 7704 {
080fd649
EZ
7705 ppi2a = xmalloc (dwNeeded);
7706 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7707 ClosePrinter (hPrn);
7708 if (!err)
7709 {
7710 xfree (ppi2a);
7711 return Qnil;
7712 }
6b61353c 7713
080fd649
EZ
7714 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7715 && ppi2a->pServerName)
7716 {
7717 filename_from_ansi (ppi2a->pServerName, server_name);
7718 filename_from_ansi (ppi2a->pShareName, share_name);
6b61353c
KH
7719 }
7720 else
080fd649
EZ
7721 {
7722 server_name[0] = '\0';
7723 filename_from_ansi (ppi2a->pPortName, port_name);
6b61353c 7724 }
6b61353c
KH
7725 }
7726
080fd649
EZ
7727 if (server_name[0])
7728 {
7729 /* a remote printer */
7730 if (server_name[0] == '\\')
7731 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7732 share_name);
7733 else
7734 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7735 share_name);
7736 pname_buf[sizeof (pname_buf) - 1] = '\0';
7737 }
7738 else
7739 {
7740 /* a local printer */
7741 strncpy (pname_buf, port_name, sizeof (pname_buf));
7742 pname_buf[sizeof (pname_buf) - 1] = '\0';
7743 /* `pPortName' can include several ports, delimited by ','.
7744 * we only use the first one. */
7745 strtok (pname_buf, ",");
7746 }
7747
7748 return DECODE_FILE (build_unibyte_string (pname_buf));
6b61353c 7749}
a5c9bbb3 7750#endif /* WINDOWSNT */
6b61353c 7751\f
0fda9b75
DC
7752
7753/* Equivalent of strerror for W32 error codes. */
7754char *
7755w32_strerror (int error_no)
7756{
7757 static char buf[500];
7758 DWORD ret;
7759
7760 if (error_no == 0)
7761 error_no = GetLastError ();
7762
7763 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7764 FORMAT_MESSAGE_IGNORE_INSERTS,
7765 NULL,
7766 error_no,
7767 0, /* choose most suitable language */
7768 buf, sizeof (buf), NULL);
7769
7770 while (ret > 0 && (buf[ret - 1] == '\n' ||
7771 buf[ret - 1] == '\r' ))
7772 --ret;
7773 buf[ret] = '\0';
7774 if (!ret)
7775 sprintf (buf, "w32 error %u", error_no);
7776
7777 return buf;
7778}
7779
b15736e6
EZ
7780/* For convenience when debugging. (You cannot call GetLastError
7781 directly from GDB: it will crash, because it uses the __stdcall
7782 calling convention, not the _cdecl convention assumed by GDB.) */
7783DWORD
0fda9b75
DC
7784w32_last_error (void)
7785{
7786 return GetLastError ();
7787}
7788
7789/* Cache information describing the NT system for later use. */
7790void
7791cache_system_info (void)
7792{
7793 union
7794 {
7795 struct info
7796 {
7797 char major;
7798 char minor;
7799 short platform;
7800 } info;
7801 DWORD data;
7802 } version;
7803
1cf1bbd5
DC
7804 /* Cache the module handle of Emacs itself. */
7805 hinst = GetModuleHandle (NULL);
7806
0fda9b75
DC
7807 /* Cache the version of the operating system. */
7808 version.data = GetVersion ();
7809 w32_major_version = version.info.major;
7810 w32_minor_version = version.info.minor;
7811
7812 if (version.info.platform & 0x8000)
7813 os_subtype = OS_9X;
7814 else
7815 os_subtype = OS_NT;
7816
7817 /* Cache page size, allocation unit, processor type, etc. */
7818 GetSystemInfo (&sysinfo_cache);
cb576b5c 7819 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
0fda9b75
DC
7820
7821 /* Cache os info. */
7822 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7823 GetVersionEx (&osinfo_cache);
7824
7825 w32_build_number = osinfo_cache.dwBuildNumber;
7826 if (os_subtype == OS_9X)
7827 w32_build_number &= 0xffff;
7828
7829 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
7830}
7831
7832#ifdef EMACSDEBUG
7833void
7834_DebPrint (const char *fmt, ...)
7835{
7836 char buf[1024];
7837 va_list args;
7838
7839 va_start (args, fmt);
7840 vsprintf (buf, fmt, args);
7841 va_end (args);
7842#if CYGWIN
7843 fprintf (stderr, "%s", buf);
7844#endif
7845 OutputDebugString (buf);
7846}
7847#endif
7848
7849int
7850w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
7851{
7852 int cur_state = (GetKeyState (vk_code) & 1);
7853
7854 if (NILP (new_state)
7855 || (NUMBERP (new_state)
7856 && ((XUINT (new_state)) & 1) != cur_state))
7857 {
7858#ifdef WINDOWSNT
7859 faked_key = vk_code;
7860#endif /* WINDOWSNT */
7861
7862 keybd_event ((BYTE) vk_code,
7863 (BYTE) MapVirtualKey (vk_code, 0),
7864 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7865 keybd_event ((BYTE) vk_code,
7866 (BYTE) MapVirtualKey (vk_code, 0),
7867 KEYEVENTF_EXTENDEDKEY | 0, 0);
7868 keybd_event ((BYTE) vk_code,
7869 (BYTE) MapVirtualKey (vk_code, 0),
7870 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7871 cur_state = !cur_state;
7872 }
7873
7874 return cur_state;
7875}
7876
7877/* Translate console modifiers to emacs modifiers.
7878 German keyboard support (Kai Morgan Zeise 2/18/95). */
7879int
7880w32_kbd_mods_to_emacs (DWORD mods, WORD key)
7881{
7882 int retval = 0;
7883
7884 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
7885 pressed, first remove those modifiers. */
7886 if (!NILP (Vw32_recognize_altgr)
7887 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7888 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7889 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
7890
7891 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
7892 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
7893
7894 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7895 {
7896 retval |= ctrl_modifier;
7897 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7898 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7899 retval |= meta_modifier;
7900 }
7901
7902 if (mods & LEFT_WIN_PRESSED)
7903 retval |= w32_key_to_modifier (VK_LWIN);
7904 if (mods & RIGHT_WIN_PRESSED)
7905 retval |= w32_key_to_modifier (VK_RWIN);
7906 if (mods & APPS_PRESSED)
7907 retval |= w32_key_to_modifier (VK_APPS);
7908 if (mods & SCROLLLOCK_ON)
7909 retval |= w32_key_to_modifier (VK_SCROLL);
7910
7911 /* Just in case someone wanted the original behavior, make it
7912 optional by setting w32-capslock-is-shiftlock to t. */
7913 if (NILP (Vw32_capslock_is_shiftlock)
7914 /* Keys that should _not_ be affected by CapsLock. */
7915 && ( (key == VK_BACK)
7916 || (key == VK_TAB)
7917 || (key == VK_CLEAR)
7918 || (key == VK_RETURN)
7919 || (key == VK_ESCAPE)
7920 || ((key >= VK_SPACE) && (key <= VK_HELP))
7921 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
7922 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
7923 ))
7924 {
7925 /* Only consider shift state. */
7926 if ((mods & SHIFT_PRESSED) != 0)
7927 retval |= shift_modifier;
7928 }
7929 else
7930 {
7931 /* Ignore CapsLock state if not enabled. */
7932 if (NILP (Vw32_enable_caps_lock))
7933 mods &= ~CAPSLOCK_ON;
7934 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
7935 retval |= shift_modifier;
7936 }
7937
7938 return retval;
7939}
7940
7941/* The return code indicates key code size. cpID is the codepage to
7942 use for translation to Unicode; -1 means use the current console
7943 input codepage. */
7944int
7945w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
7946{
7947 unsigned int key_code = event->wVirtualKeyCode;
7948 unsigned int mods = event->dwControlKeyState;
7949 BYTE keystate[256];
7950 static BYTE ansi_code[4];
7951 static int isdead = 0;
7952
7953 if (isdead == 2)
7954 {
7955 event->uChar.AsciiChar = ansi_code[2];
7956 isdead = 0;
7957 return 1;
7958 }
7959 if (event->uChar.AsciiChar != 0)
7960 return 1;
7961
7962 memset (keystate, 0, sizeof (keystate));
7963 keystate[key_code] = 0x80;
7964 if (mods & SHIFT_PRESSED)
7965 keystate[VK_SHIFT] = 0x80;
7966 if (mods & CAPSLOCK_ON)
7967 keystate[VK_CAPITAL] = 1;
7968 /* If we recognize right-alt and left-ctrl as AltGr, set the key
7969 states accordingly before invoking ToAscii. */
7970 if (!NILP (Vw32_recognize_altgr)
7971 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
7972 {
7973 keystate[VK_CONTROL] = 0x80;
7974 keystate[VK_LCONTROL] = 0x80;
7975 keystate[VK_MENU] = 0x80;
7976 keystate[VK_RMENU] = 0x80;
7977 }
7978
7979#if 0
7980 /* Because of an OS bug, ToAscii corrupts the stack when called to
7981 convert a dead key in console mode on NT4. Unfortunately, trying
7982 to check for dead keys using MapVirtualKey doesn't work either -
7983 these functions apparently use internal information about keyboard
7984 layout which doesn't get properly updated in console programs when
7985 changing layout (though apparently it gets partly updated,
7986 otherwise ToAscii wouldn't crash). */
7987 if (is_dead_key (event->wVirtualKeyCode))
7988 return 0;
7989#endif
7990
7991 /* On NT, call ToUnicode instead and then convert to the current
7992 console input codepage. */
7993 if (os_subtype == OS_NT)
7994 {
7995 WCHAR buf[128];
7996
7997 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
7998 keystate, buf, 128, 0);
7999 if (isdead > 0)
8000 {
8001 /* When we are called from the GUI message processing code,
8002 we are passed the current keyboard codepage, a positive
8003 number, to use below. */
8004 if (cpId == -1)
8005 cpId = GetConsoleCP ();
8006
8007 event->uChar.UnicodeChar = buf[isdead - 1];
8008 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8009 ansi_code, 4, NULL, NULL);
8010 }
8011 else
8012 isdead = 0;
8013 }
8014 else
8015 {
8016 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8017 keystate, (LPWORD) ansi_code, 0);
8018 }
8019
8020 if (isdead == 0)
8021 return 0;
8022 event->uChar.AsciiChar = ansi_code[0];
8023 return isdead;
8024}
8025
8026
8027void
8028w32_sys_ring_bell (struct frame *f)
8029{
8030 if (sound_type == 0xFFFFFFFF)
8031 {
8032 Beep (666, 100);
8033 }
8034 else if (sound_type == MB_EMACS_SILENT)
8035 {
8036 /* Do nothing. */
8037 }
8038 else
8039 MessageBeep (sound_type);
8040}
8041
8042\f
0e3fcdef
JR
8043/***********************************************************************
8044 Initialization
8045 ***********************************************************************/
8046
52deb19f 8047/* Keep this list in the same order as frame_parms in frame.c.
6d906347
KS
8048 Use 0 for unsupported frame parameters. */
8049
8050frame_parm_handler w32_frame_parm_handlers[] =
8051{
8052 x_set_autoraise,
8053 x_set_autolower,
8054 x_set_background_color,
8055 x_set_border_color,
8056 x_set_border_width,
8057 x_set_cursor_color,
8058 x_set_cursor_type,
8059 x_set_font,
8060 x_set_foreground_color,
8061 x_set_icon_name,
8062 x_set_icon_type,
8063 x_set_internal_border_width,
880e6158
MR
8064 x_set_right_divider_width,
8065 x_set_bottom_divider_width,
6d906347
KS
8066 x_set_menu_bar_lines,
8067 x_set_mouse_color,
8068 x_explicitly_set_name,
8069 x_set_scroll_bar_width,
8070 x_set_title,
8071 x_set_unsplittable,
8072 x_set_vertical_scroll_bars,
8073 x_set_visibility,
8074 x_set_tool_bar_lines,
8075 0, /* x_set_scroll_bar_foreground, */
8076 0, /* x_set_scroll_bar_background, */
8077 x_set_screen_gamma,
8078 x_set_line_spacing,
8079 x_set_fringe_width,
8080 x_set_fringe_width,
8081 0, /* x_set_wait_for_wm, */
8082 x_set_fullscreen,
a2979e8e 8083 x_set_font_backend,
cad9ef74
JD
8084 x_set_alpha,
8085 0, /* x_set_sticky */
0cc56427 8086 0, /* x_set_tool_bar_position */
6d906347
KS
8087};
8088
0e3fcdef 8089void
b56ceb92 8090syms_of_w32fns (void)
ee78dc32 8091{
fe6aa7a1
BT
8092#include "w32fns.x"
8093
afc390dc 8094 globals_of_w32fns ();
9eb16b62
JR
8095 track_mouse_window = NULL;
8096
d285988b
JR
8097 w32_visible_system_caret_hwnd = NULL;
8098
4f5b288c
JR
8099 DEFSYM (Qundefined_color, "undefined-color");
8100 DEFSYM (Qcancel_timer, "cancel-timer");
8101 DEFSYM (Qhyper, "hyper");
8102 DEFSYM (Qsuper, "super");
8103 DEFSYM (Qmeta, "meta");
8104 DEFSYM (Qalt, "alt");
8105 DEFSYM (Qctrl, "ctrl");
8106 DEFSYM (Qcontrol, "control");
8107 DEFSYM (Qshift, "shift");
27129af9 8108 DEFSYM (Qfont_param, "font-parameter");
cf13177e
YM
8109 DEFSYM (Qgeometry, "geometry");
8110 DEFSYM (Qworkarea, "workarea");
8111 DEFSYM (Qmm_size, "mm-size");
8112 DEFSYM (Qframes, "frames");
6fc2811b 8113
ee78dc32 8114 Fput (Qundefined_color, Qerror_conditions,
3438fe21 8115 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
ee78dc32 8116 Fput (Qundefined_color, Qerror_message,
2a0213a6 8117 build_pure_c_string ("Undefined color"));
ee78dc32 8118
ccc2d29c
GV
8119 staticpro (&w32_grabbed_keys);
8120 w32_grabbed_keys = Qnil;
8121
29208e82 8122 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
52deb19f 8123 doc: /* An array of color name mappings for Windows. */);
fbd6baed 8124 Vw32_color_map = Qnil;
ee78dc32 8125
29208e82 8126 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
1133f8e7
EZ
8127 doc: /* Non-nil if Alt key presses are passed on to Windows.
8128When non-nil, for example, Alt pressed and released and then space will
8129open the System menu. When nil, Emacs processes the Alt key events, and
8130then silently swallows them. */);
fbd6baed 8131 Vw32_pass_alt_to_system = Qnil;
da36a4d6 8132
29208e82 8133 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
1133f8e7
EZ
8134 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8135When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
fbd6baed 8136 Vw32_alt_is_meta = Qt;
8c205c63 8137
29208e82 8138 DEFVAR_INT ("w32-quit-key", w32_quit_key,
2ba49441
JR
8139 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8140 w32_quit_key = 0;
7d081355 8141
7d0393cf 8142 DEFVAR_LISP ("w32-pass-lwindow-to-system",
29208e82 8143 Vw32_pass_lwindow_to_system,
1133f8e7
EZ
8144 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8145
8146When non-nil, the Start menu is opened by tapping the key.
8147If you set this to nil, the left \"Windows\" key is processed by Emacs
8148according to the value of `w32-lwindow-modifier', which see.
8149
8150Note that some combinations of the left \"Windows\" key with other keys are
8151caught by Windows at low level, and so binding them in Emacs will have no
8152effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8153<lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8154the doc string of `w32-phantom-key-code'. */);
ccc2d29c
GV
8155 Vw32_pass_lwindow_to_system = Qt;
8156
7d0393cf 8157 DEFVAR_LISP ("w32-pass-rwindow-to-system",
29208e82 8158 Vw32_pass_rwindow_to_system,
1133f8e7
EZ
8159 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8160
8161When non-nil, the Start menu is opened by tapping the key.
8162If you set this to nil, the right \"Windows\" key is processed by Emacs
8163according to the value of `w32-rwindow-modifier', which see.
8164
8165Note that some combinations of the right \"Windows\" key with other keys are
8166caught by Windows at low level, and so binding them in Emacs will have no
8167effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8168<rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8169the doc string of `w32-phantom-key-code'. */);
ccc2d29c
GV
8170 Vw32_pass_rwindow_to_system = Qt;
8171
2ba49441 8172 DEFVAR_LISP ("w32-phantom-key-code",
29208e82 8173 Vw32_phantom_key_code,
2ba49441 8174 doc: /* Virtual key code used to generate \"phantom\" key presses.
74e1aeec
JR
8175Value is a number between 0 and 255.
8176
8177Phantom key presses are generated in order to stop the system from
8178acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8179`w32-pass-rwindow-to-system' is nil. */);
ce6059da
AI
8180 /* Although 255 is technically not a valid key code, it works and
8181 means that this hack won't interfere with any real key code. */
2ba49441 8182 XSETINT (Vw32_phantom_key_code, 255);
adcc3809 8183
7d0393cf 8184 DEFVAR_LISP ("w32-enable-num-lock",
29208e82 8185 Vw32_enable_num_lock,
1133f8e7
EZ
8186 doc: /* If non-nil, the Num Lock key acts normally.
8187Set to nil to handle Num Lock as the `kp-numlock' key. */);
ccc2d29c
GV
8188 Vw32_enable_num_lock = Qt;
8189
7d0393cf 8190 DEFVAR_LISP ("w32-enable-caps-lock",
29208e82 8191 Vw32_enable_caps_lock,
1133f8e7
EZ
8192 doc: /* If non-nil, the Caps Lock key acts normally.
8193Set to nil to handle Caps Lock as the `capslock' key. */);
ccc2d29c
GV
8194 Vw32_enable_caps_lock = Qt;
8195
8196 DEFVAR_LISP ("w32-scroll-lock-modifier",
29208e82 8197 Vw32_scroll_lock_modifier,
1133f8e7 8198 doc: /* Modifier to use for the Scroll Lock ON state.
74e1aeec 8199The value can be hyper, super, meta, alt, control or shift for the
1133f8e7
EZ
8200respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8201Any other value will cause the Scroll Lock key to be ignored. */);
47e0e0e4 8202 Vw32_scroll_lock_modifier = Qnil;
ccc2d29c
GV
8203
8204 DEFVAR_LISP ("w32-lwindow-modifier",
29208e82 8205 Vw32_lwindow_modifier,
74e1aeec
JR
8206 doc: /* Modifier to use for the left \"Windows\" key.
8207The value can be hyper, super, meta, alt, control or shift for the
1133f8e7 8208respective modifier, or nil to appear as the `lwindow' key.
74e1aeec 8209Any other value will cause the key to be ignored. */);
ccc2d29c
GV
8210 Vw32_lwindow_modifier = Qnil;
8211
8212 DEFVAR_LISP ("w32-rwindow-modifier",
29208e82 8213 Vw32_rwindow_modifier,
74e1aeec
JR
8214 doc: /* Modifier to use for the right \"Windows\" key.
8215The value can be hyper, super, meta, alt, control or shift for the
1133f8e7 8216respective modifier, or nil to appear as the `rwindow' key.
74e1aeec 8217Any other value will cause the key to be ignored. */);
ccc2d29c
GV
8218 Vw32_rwindow_modifier = Qnil;
8219
8220 DEFVAR_LISP ("w32-apps-modifier",
29208e82 8221 Vw32_apps_modifier,
74e1aeec
JR
8222 doc: /* Modifier to use for the \"Apps\" key.
8223The value can be hyper, super, meta, alt, control or shift for the
1133f8e7 8224respective modifier, or nil to appear as the `apps' key.
74e1aeec 8225Any other value will cause the key to be ignored. */);
ccc2d29c 8226 Vw32_apps_modifier = Qnil;
da36a4d6 8227
29208e82 8228 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
74e1aeec 8229 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
d84b082d 8230 w32_enable_synthesized_fonts = 0;
5ac45f98 8231
29208e82 8232 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
74e1aeec 8233 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
fbd6baed 8234 Vw32_enable_palette = Qt;
5ac45f98 8235
fbd6baed 8236 DEFVAR_INT ("w32-mouse-button-tolerance",
29208e82 8237 w32_mouse_button_tolerance,
74e1aeec
JR
8238 doc: /* Analogue of double click interval for faking middle mouse events.
8239The value is the minimum time in milliseconds that must elapse between
1133f8e7 8240left and right button down events before they are considered distinct events.
74e1aeec
JR
8241If both mouse buttons are depressed within this interval, a middle mouse
8242button down event is generated instead. */);
2ba49441 8243 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
5ac45f98 8244
fbd6baed 8245 DEFVAR_INT ("w32-mouse-move-interval",
29208e82 8246 w32_mouse_move_interval,
74e1aeec
JR
8247 doc: /* Minimum interval between mouse move events.
8248The value is the minimum time in milliseconds that must elapse between
8249successive mouse move (or scroll bar drag) events before they are
8250reported as lisp events. */);
2ba49441 8251 w32_mouse_move_interval = 0;
84fb1139 8252
74214547 8253 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
29208e82 8254 w32_pass_extra_mouse_buttons_to_system,
1133f8e7 8255 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
74214547
JR
8256Recent versions of Windows support mice with up to five buttons.
8257Since most applications don't support these extra buttons, most mouse
8258drivers will allow you to map them to functions at the system level.
8259If this variable is non-nil, Emacs will pass them on, allowing the
8260system to handle them. */);
8261 w32_pass_extra_mouse_buttons_to_system = 0;
8262
0b151762 8263 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
29208e82 8264 w32_pass_multimedia_buttons_to_system,
0b151762
JR
8265 doc: /* If non-nil, media buttons are passed to Windows.
8266Some modern keyboards contain buttons for controlling media players, web
74084731 8267browsers and other applications. Generally these buttons are handled on a
0b151762
JR
8268system wide basis, but by setting this to nil they are made available
8269to Emacs for binding. Depending on your keyboard, additional keys that
8270may be available are:
8271
8272browser-back, browser-forward, browser-refresh, browser-stop,
8273browser-search, browser-favorites, browser-home,
8274mail, mail-reply, mail-forward, mail-send,
8275app-1, app-2,
8276help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8277spell-check, correction-list, toggle-dictate-command,
8278media-next, media-previous, media-stop, media-play-pause, media-select,
8279media-play, media-pause, media-record, media-fast-forward, media-rewind,
8280media-channel-up, media-channel-down,
8281volume-mute, volume-up, volume-down,
8282mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
74084731 8283bass-down, bass-boost, bass-up, treble-down, treble-up */);
0b151762
JR
8284 w32_pass_multimedia_buttons_to_system = 1;
8285
5f004711 8286#if 0 /* TODO: Mouse cursor customization. */
29208e82 8287 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
74e1aeec
JR
8288 doc: /* The shape of the pointer when over text.
8289Changing the value does not affect existing frames
8290unless you set the mouse color. */);
ee78dc32
GV
8291 Vx_pointer_shape = Qnil;
8292
ee78dc32
GV
8293 Vx_nontext_pointer_shape = Qnil;
8294
8295 Vx_mode_pointer_shape = Qnil;
8296
29208e82 8297 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
74e1aeec
JR
8298 doc: /* The shape of the pointer when Emacs is busy.
8299This variable takes effect when you create a new frame
8300or when you set the mouse color. */);
0af913d7 8301 Vx_hourglass_pointer_shape = Qnil;
6fc2811b 8302
6fc2811b 8303 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
29208e82 8304 Vx_sensitive_text_pointer_shape,
74e1aeec
JR
8305 doc: /* The shape of the pointer when over mouse-sensitive text.
8306This variable takes effect when you create a new frame
8307or when you set the mouse color. */);
ee78dc32
GV
8308 Vx_sensitive_text_pointer_shape = Qnil;
8309
4694d762 8310 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
29208e82 8311 Vx_window_horizontal_drag_shape,
74e1aeec
JR
8312 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8313This variable takes effect when you create a new frame
8314or when you set the mouse color. */);
4694d762 8315 Vx_window_horizontal_drag_shape = Qnil;
880e6158
MR
8316
8317 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8318 Vx_window_vertical_drag_shape,
8319 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8320This variable takes effect when you create a new frame
8321or when you set the mouse color. */);
8322 Vx_window_vertical_drag_shape = Qnil;
5f004711 8323#endif
4694d762 8324
29208e82 8325 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
74e1aeec 8326 doc: /* A string indicating the foreground color of the cursor box. */);
ee78dc32
GV
8327 Vx_cursor_fore_pixel = Qnil;
8328
29208e82 8329 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
b3700ae7 8330 doc: /* Maximum size for tooltips.
f5f6c0e0 8331Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
3cf3436e 8332 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
7d0393cf 8333
29208e82 8334 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
74e1aeec
JR
8335 doc: /* Non-nil if no window manager is in use.
8336Emacs doesn't try to figure this out; this is always nil
8337unless you set it to something else. */);
ee78dc32
GV
8338 /* We don't have any way to find this out, so set it to nil
8339 and maybe the user would like to set it to t. */
8340 Vx_no_window_manager = Qnil;
8341
4587b026 8342 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
29208e82 8343 Vx_pixel_size_width_font_regexp,
74e1aeec
JR
8344 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8345
8346Since Emacs gets width of a font matching with this regexp from
8347PIXEL_SIZE field of the name, font finding mechanism gets faster for
8348such a font. This is especially effective for such large fonts as
8349Chinese, Japanese, and Korean. */);
4587b026
GV
8350 Vx_pixel_size_width_font_regexp = Qnil;
8351
33d52f9c 8352 DEFVAR_LISP ("w32-bdf-filename-alist",
29208e82 8353 Vw32_bdf_filename_alist,
74e1aeec 8354 doc: /* List of bdf fonts and their corresponding filenames. */);
33d52f9c
GV
8355 Vw32_bdf_filename_alist = Qnil;
8356
1075afa9 8357 DEFVAR_BOOL ("w32-strict-fontnames",
29208e82 8358 w32_strict_fontnames,
74e1aeec
JR
8359 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8360Default is nil, which allows old fontnames that are not XLFD compliant,
8361and allows third-party CJK display to work by specifying false charset
8362fields to trick Emacs into translating to Big5, SJIS etc.
8363Setting this to t will prevent wrong fonts being selected when
8364fontsets are automatically created. */);
1075afa9
GV
8365 w32_strict_fontnames = 0;
8366
c0611964 8367 DEFVAR_BOOL ("w32-strict-painting",
29208e82 8368 w32_strict_painting,
74e1aeec 8369 doc: /* Non-nil means use strict rules for repainting frames.
a8ab3e96 8370Set this to nil to get the old behavior for repainting; this should
74e1aeec 8371only be necessary if the default setting causes problems. */);
c0611964
AI
8372 w32_strict_painting = 1;
8373
d148e14d 8374 hourglass_hwnd = NULL;
1885ab29 8375
6fc2811b 8376 tip_timer = Qnil;
57fa2774
JR
8377 staticpro (&tip_timer);
8378 tip_frame = Qnil;
8379 staticpro (&tip_frame);
6fc2811b 8380
ca56d953
JR
8381 last_show_tip_args = Qnil;
8382 staticpro (&last_show_tip_args);
6fc2811b
JR
8383}
8384
21bf394d 8385\f
c922a224 8386
21bf394d 8387/* Crashing and reporting backtrace. */
60860eb3 8388
21bf394d
EZ
8389#ifndef CYGWIN
8390static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8391static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8392#endif
8393static DWORD except_code;
8394static PVOID except_addr;
cbfedb1c 8395
21bf394d
EZ
8396#ifndef CYGWIN
8397/* This handler records the exception code and the address where it
8398 was triggered so that this info could be included in the backtrace.
8399 Without that, the backtrace in some cases has no information
8400 whatsoever about the offending code, and looks as if the top-level
8401 exception handler in the MinGW startup code di the one that
8402 crashed. */
8403static LONG CALLBACK
8404my_exception_handler (EXCEPTION_POINTERS * exception_data)
8405{
8406 except_code = exception_data->ExceptionRecord->ExceptionCode;
8407 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8408
8409 if (prev_exception_handler)
8410 return prev_exception_handler (exception_data);
8411 return EXCEPTION_EXECUTE_HANDLER;
9785d95b 8412}
21bf394d 8413#endif
6fc2811b 8414
1005b4b9
EZ
8415typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8416 PULONG);
8417
8418#define BACKTRACE_LIMIT_MAX 62
8419
8420int
8421w32_backtrace (void **buffer, int limit)
8422{
8423 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8424 HMODULE hm_kernel32 = NULL;
8425
8426 if (!s_pfn_CaptureStackBackTrace)
8427 {
8428 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8429 s_pfn_CaptureStackBackTrace =
8430 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8431 "RtlCaptureStackBackTrace");
8432 }
8433 if (s_pfn_CaptureStackBackTrace)
8434 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8435 buffer, NULL);
8436 return 0;
8437}
8438
7d0393cf 8439void
1088b922 8440emacs_abort (void)
ee78dc32 8441{
5ac45f98
GV
8442 int button;
8443 button = MessageBox (NULL,
8444 "A fatal error has occurred!\n\n"
c52e1638 8445 "Would you like to attach a debugger?\n\n"
1005b4b9
EZ
8446 "Select:\n"
8447 "YES -- to debug Emacs, or\n"
8448 "NO -- to abort Emacs and produce a backtrace\n"
8449 " (emacs_backtrace.txt in current directory)."
cb91d111
EZ
8450#if __GNUC__
8451 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8452 "\"continue\" inside GDB before clicking YES.)"
8453#endif
8454 , "Emacs Abort Dialog",
5ac45f98 8455 MB_ICONEXCLAMATION | MB_TASKMODAL
c52e1638 8456 | MB_SETFOREGROUND | MB_YESNO);
5ac45f98
GV
8457 switch (button)
8458 {
c52e1638 8459 case IDYES:
5ac45f98 8460 DebugBreak ();
c52e1638
EZ
8461 exit (2); /* tell the compiler we will never return */
8462 case IDNO:
5ac45f98 8463 default:
1005b4b9
EZ
8464 {
8465 void *stack[BACKTRACE_LIMIT_MAX + 1];
8466 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8467
8468 if (i)
8469 {
21bf394d
EZ
8470 int errfile_fd = -1;
8471 int j;
8472 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
39e896c1
EZ
8473 /* The type below should really be 'void *', but
8474 INT_BUFSIZE_BOUND cannot handle that without
8475 triggering compiler warnings (under certain
8476 pedantic warning switches), it wants an
8477 integer type. */
8478 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
c8e3a9c3
EZ
8479#ifdef CYGWIN
8480 int stderr_fd = 2;
8481#else
1005b4b9 8482 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
c8e3a9c3 8483 int stderr_fd = -1;
1005b4b9
EZ
8484
8485 if (errout && errout != INVALID_HANDLE_VALUE)
8486 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
c8e3a9c3 8487#endif
21bf394d
EZ
8488
8489 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8490 but not on Windows 7. addr2line doesn't mind a missing
8491 "0x", but will be confused by an extra one. */
8492 if (except_addr)
8493 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8494 except_code, except_addr);
1005b4b9 8495 if (stderr_fd >= 0)
21bf394d
EZ
8496 {
8497 if (except_addr)
8498 write (stderr_fd, buf, strlen (buf));
8499 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8500 }
789b5e9a
KB
8501#ifdef CYGWIN
8502#define _open open
8503#endif
1005b4b9
EZ
8504 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8505 if (errfile_fd >= 0)
8506 {
8507 lseek (errfile_fd, 0L, SEEK_END);
21bf394d
EZ
8508 if (except_addr)
8509 write (errfile_fd, buf, strlen (buf));
1005b4b9
EZ
8510 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8511 }
8512
8513 for (j = 0; j < i; j++)
8514 {
1005b4b9
EZ
8515 /* stack[] gives the return addresses, whereas we want
8516 the address of the call, so decrease each address
8517 by approximate size of 1 CALL instruction. */
21bf394d 8518 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
1005b4b9
EZ
8519 if (stderr_fd >= 0)
8520 write (stderr_fd, buf, strlen (buf));
8521 if (errfile_fd >= 0)
8522 write (errfile_fd, buf, strlen (buf));
8523 }
8524 if (i == BACKTRACE_LIMIT_MAX)
8525 {
8526 if (stderr_fd >= 0)
8527 write (stderr_fd, "...\r\n", 5);
8528 if (errfile_fd >= 0)
8529 write (errfile_fd, "...\r\n", 5);
8530 }
8531 if (errfile_fd >= 0)
8532 close (errfile_fd);
8533 }
8534 abort ();
8535 break;
8536 }
5ac45f98 8537 }
ee78dc32 8538}
819e2da9 8539
21bf394d
EZ
8540\f
8541
8542/* Initialization. */
8543
8544/*
8545 globals_of_w32fns is used to initialize those global variables that
8546 must always be initialized on startup even when the global variable
8547 initialized is non zero (see the function main in emacs.c).
8548 globals_of_w32fns is called from syms_of_w32fns when the global
8549 variable initialized is 0 and directly from main when initialized
8550 is non zero.
8551 */
8552void
8553globals_of_w32fns (void)
8554{
8555 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8556 /*
8557 TrackMouseEvent not available in all versions of Windows, so must load
8558 it dynamically. Do it once, here, instead of every time it is used.
8559 */
8560 track_mouse_event_fn = (TrackMouseEvent_Proc)
8561 GetProcAddress (user32_lib, "TrackMouseEvent");
8562
8563 monitor_from_point_fn = (MonitorFromPoint_Proc)
8564 GetProcAddress (user32_lib, "MonitorFromPoint");
8565 get_monitor_info_fn = (GetMonitorInfo_Proc)
8566 GetProcAddress (user32_lib, "GetMonitorInfoA");
8567 monitor_from_window_fn = (MonitorFromWindow_Proc)
8568 GetProcAddress (user32_lib, "MonitorFromWindow");
8569 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8570 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8571
8572 {
8573 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8574 get_composition_string_fn = (ImmGetCompositionString_Proc)
8575 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8576 get_ime_context_fn = (ImmGetContext_Proc)
8577 GetProcAddress (imm32_lib, "ImmGetContext");
8578 release_ime_context_fn = (ImmReleaseContext_Proc)
8579 GetProcAddress (imm32_lib, "ImmReleaseContext");
8580 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8581 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8582 }
8583
8584 except_code = 0;
8585 except_addr = 0;
8586#ifndef CYGWIN
8587 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8588#endif
8589
8590 DEFVAR_INT ("w32-ansi-code-page",
8591 w32_ansi_code_page,
8592 doc: /* The ANSI code page used by the system. */);
8593 w32_ansi_code_page = GetACP ();
8594
8595 if (os_subtype == OS_NT)
8596 w32_unicode_gui = 1;
8597 else
8598 w32_unicode_gui = 0;
8599
8600 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8601 InitCommonControls ();
8602
8603 syms_of_w32uniscribe ();
8604}
8605
819e2da9
DC
8606#ifdef NTGUI_UNICODE
8607
8608Lisp_Object
8609ntgui_encode_system (Lisp_Object str)
8610{
8611 Lisp_Object encoded;
8612 to_unicode (str, &encoded);
8613 return encoded;
8614}
8615
8616#endif /* NTGUI_UNICODE */