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