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