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