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