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