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