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