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