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