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