*** empty log message ***
[emacs.git] / src / w32fns.c
blobba1fe88f82463b125637cb7aaab53b6c55a6f54a
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
23 /* Added by Kevin Gallo */
25 #include <config.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <limits.h>
30 #include <errno.h>
31 #include <math.h>
33 #include "lisp.h"
34 #include "charset.h"
35 #include "dispextern.h"
36 #include "w32term.h"
37 #include "keyboard.h"
38 #include "frame.h"
39 #include "window.h"
40 #include "buffer.h"
41 #include "fontset.h"
42 #include "intervals.h"
43 #include "blockinput.h"
44 #include "epaths.h"
45 #include "w32heap.h"
46 #include "termhooks.h"
47 #include "coding.h"
48 #include "ccl.h"
49 #include "systime.h"
51 #include "bitmaps/gray.xbm"
53 #include <commctrl.h>
54 #include <commdlg.h>
55 #include <shellapi.h>
56 #include <ctype.h>
57 #include <winspool.h>
58 #include <objbase.h>
60 #include <dlgs.h>
61 #define FILE_NAME_TEXT_FIELD edt1
63 void syms_of_w32fns ();
64 void globals_of_w32fns ();
66 extern void free_frame_menubar ();
67 extern double atof ();
68 extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
69 extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
70 extern void w32_free_menu_strings P_ ((HWND));
71 extern XCharStruct *w32_per_char_metric P_ ((XFontStruct *, wchar_t *, int));
73 extern int quit_char;
75 extern char *lispy_function_keys[];
77 /* The colormap for converting color names to RGB values */
78 Lisp_Object Vw32_color_map;
80 /* Non nil if alt key presses are passed on to Windows. */
81 Lisp_Object Vw32_pass_alt_to_system;
83 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
84 to alt_modifier. */
85 Lisp_Object Vw32_alt_is_meta;
87 /* If non-zero, the windows virtual key code for an alternative quit key. */
88 int w32_quit_key;
90 /* Non nil if left window key events are passed on to Windows (this only
91 affects whether "tapping" the key opens the Start menu). */
92 Lisp_Object Vw32_pass_lwindow_to_system;
94 /* Non nil if right window key events are passed on to Windows (this
95 only affects whether "tapping" the key opens the Start menu). */
96 Lisp_Object Vw32_pass_rwindow_to_system;
98 /* Virtual key code used to generate "phantom" key presses in order
99 to stop system from acting on Windows key events. */
100 Lisp_Object Vw32_phantom_key_code;
102 /* Modifier associated with the left "Windows" key, or nil to act as a
103 normal key. */
104 Lisp_Object Vw32_lwindow_modifier;
106 /* Modifier associated with the right "Windows" key, or nil to act as a
107 normal key. */
108 Lisp_Object Vw32_rwindow_modifier;
110 /* Modifier associated with the "Apps" key, or nil to act as a normal
111 key. */
112 Lisp_Object Vw32_apps_modifier;
114 /* Value is nil if Num Lock acts as a function key. */
115 Lisp_Object Vw32_enable_num_lock;
117 /* Value is nil if Caps Lock acts as a function key. */
118 Lisp_Object Vw32_enable_caps_lock;
120 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
121 Lisp_Object Vw32_scroll_lock_modifier;
123 /* Switch to control whether we inhibit requests for synthesized bold
124 and italic versions of fonts. */
125 int w32_enable_synthesized_fonts;
127 /* Enable palette management. */
128 Lisp_Object Vw32_enable_palette;
130 /* Control how close left/right button down events must be to
131 be converted to a middle button down event. */
132 int w32_mouse_button_tolerance;
134 /* Minimum interval between mouse movement (and scroll bar drag)
135 events that are passed on to the event loop. */
136 int w32_mouse_move_interval;
138 /* Flag to indicate if XBUTTON events should be passed on to Windows. */
139 int w32_pass_extra_mouse_buttons_to_system;
141 /* Non nil if no window manager is in use. */
142 Lisp_Object Vx_no_window_manager;
144 /* Non-zero means we're allowed to display a hourglass pointer. */
146 int display_hourglass_p;
148 /* The background and shape of the mouse pointer, and shape when not
149 over text or in the modeline. */
151 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
152 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
154 /* The shape when over mouse-sensitive text. */
156 Lisp_Object Vx_sensitive_text_pointer_shape;
158 #ifndef IDC_HAND
159 #define IDC_HAND MAKEINTRESOURCE(32649)
160 #endif
162 /* Color of chars displayed in cursor box. */
164 Lisp_Object Vx_cursor_fore_pixel;
166 /* Nonzero if using Windows. */
168 static int w32_in_use;
170 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
172 Lisp_Object Vx_pixel_size_width_font_regexp;
174 /* Alist of bdf fonts and the files that define them. */
175 Lisp_Object Vw32_bdf_filename_alist;
177 /* A flag to control whether fonts are matched strictly or not. */
178 int w32_strict_fontnames;
180 /* A flag to control whether we should only repaint if GetUpdateRect
181 indicates there is an update region. */
182 int w32_strict_painting;
184 /* Associative list linking character set strings to Windows codepages. */
185 Lisp_Object Vw32_charset_info_alist;
187 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
188 #ifndef VIETNAMESE_CHARSET
189 #define VIETNAMESE_CHARSET 163
190 #endif
192 Lisp_Object Qnone;
193 Lisp_Object Qsuppress_icon;
194 Lisp_Object Qundefined_color;
195 Lisp_Object Qcancel_timer;
196 Lisp_Object Qhyper;
197 Lisp_Object Qsuper;
198 Lisp_Object Qmeta;
199 Lisp_Object Qalt;
200 Lisp_Object Qctrl;
201 Lisp_Object Qcontrol;
202 Lisp_Object Qshift;
204 Lisp_Object Qw32_charset_ansi;
205 Lisp_Object Qw32_charset_default;
206 Lisp_Object Qw32_charset_symbol;
207 Lisp_Object Qw32_charset_shiftjis;
208 Lisp_Object Qw32_charset_hangeul;
209 Lisp_Object Qw32_charset_gb2312;
210 Lisp_Object Qw32_charset_chinesebig5;
211 Lisp_Object Qw32_charset_oem;
213 #ifndef JOHAB_CHARSET
214 #define JOHAB_CHARSET 130
215 #endif
216 #ifdef JOHAB_CHARSET
217 Lisp_Object Qw32_charset_easteurope;
218 Lisp_Object Qw32_charset_turkish;
219 Lisp_Object Qw32_charset_baltic;
220 Lisp_Object Qw32_charset_russian;
221 Lisp_Object Qw32_charset_arabic;
222 Lisp_Object Qw32_charset_greek;
223 Lisp_Object Qw32_charset_hebrew;
224 Lisp_Object Qw32_charset_vietnamese;
225 Lisp_Object Qw32_charset_thai;
226 Lisp_Object Qw32_charset_johab;
227 Lisp_Object Qw32_charset_mac;
228 #endif
230 #ifdef UNICODE_CHARSET
231 Lisp_Object Qw32_charset_unicode;
232 #endif
234 /* The ANSI codepage. */
235 int w32_ansi_code_page;
237 /* Prefix for system colors. */
238 #define SYSTEM_COLOR_PREFIX "System"
239 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
241 /* State variables for emulating a three button mouse. */
242 #define LMOUSE 1
243 #define MMOUSE 2
244 #define RMOUSE 4
246 static int button_state = 0;
247 static W32Msg saved_mouse_button_msg;
248 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
249 static W32Msg saved_mouse_move_msg;
250 static unsigned mouse_move_timer = 0;
252 /* Window that is tracking the mouse. */
253 static HWND track_mouse_window;
255 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
256 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
258 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
259 ClipboardSequence_Proc clipboard_sequence_fn = NULL;
260 extern AppendMenuW_Proc unicode_append_menu;
262 /* W95 mousewheel handler */
263 unsigned int msh_mousewheel = 0;
265 /* Timers */
266 #define MOUSE_BUTTON_ID 1
267 #define MOUSE_MOVE_ID 2
268 #define MENU_FREE_ID 3
269 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
270 is received. */
271 #define MENU_FREE_DELAY 1000
272 static unsigned menu_free_timer = 0;
274 /* The below are defined in frame.c. */
276 extern Lisp_Object Vwindow_system_version;
278 #ifdef GLYPH_DEBUG
279 int image_cache_refcount, dpyinfo_refcount;
280 #endif
283 /* From w32term.c. */
284 extern int w32_num_mouse_buttons;
285 extern Lisp_Object Vw32_recognize_altgr;
287 extern HWND w32_system_caret_hwnd;
289 extern int w32_system_caret_height;
290 extern int w32_system_caret_x;
291 extern int w32_system_caret_y;
292 extern int w32_use_visible_system_caret;
294 static HWND w32_visible_system_caret_hwnd;
296 /* From w32menu.c */
297 extern HMENU current_popup_menu;
298 static int menubar_in_use = 0;
301 /* Error if we are not connected to MS-Windows. */
302 void
303 check_w32 ()
305 if (! w32_in_use)
306 error ("MS-Windows not in use or not initialized");
309 /* Nonzero if we can use mouse menus.
310 You should not call this unless HAVE_MENUS is defined. */
313 have_menus_p ()
315 return w32_in_use;
318 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
319 and checking validity for W32. */
321 FRAME_PTR
322 check_x_frame (frame)
323 Lisp_Object frame;
325 FRAME_PTR f;
327 if (NILP (frame))
328 frame = selected_frame;
329 CHECK_LIVE_FRAME (frame);
330 f = XFRAME (frame);
331 if (! FRAME_W32_P (f))
332 error ("Non-W32 frame used");
333 return f;
336 /* Let the user specify a display with a frame.
337 nil stands for the selected frame--or, if that is not a w32 frame,
338 the first display on the list. */
340 struct w32_display_info *
341 check_x_display_info (frame)
342 Lisp_Object frame;
344 if (NILP (frame))
346 struct frame *sf = XFRAME (selected_frame);
348 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
349 return FRAME_W32_DISPLAY_INFO (sf);
350 else
351 return &one_w32_display_info;
353 else if (STRINGP (frame))
354 return x_display_info_for_name (frame);
355 else
357 FRAME_PTR f;
359 CHECK_LIVE_FRAME (frame);
360 f = XFRAME (frame);
361 if (! FRAME_W32_P (f))
362 error ("Non-W32 frame used");
363 return FRAME_W32_DISPLAY_INFO (f);
367 /* Return the Emacs frame-object corresponding to an w32 window.
368 It could be the frame's main window or an icon window. */
370 /* This function can be called during GC, so use GC_xxx type test macros. */
372 struct frame *
373 x_window_to_frame (dpyinfo, wdesc)
374 struct w32_display_info *dpyinfo;
375 HWND wdesc;
377 Lisp_Object tail, frame;
378 struct frame *f;
380 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
382 frame = XCAR (tail);
383 if (!GC_FRAMEP (frame))
384 continue;
385 f = XFRAME (frame);
386 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
387 continue;
388 if (f->output_data.w32->hourglass_window == wdesc)
389 return f;
391 if (FRAME_W32_WINDOW (f) == wdesc)
392 return f;
394 return 0;
398 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
399 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
400 static void my_create_window P_ ((struct frame *));
401 static void my_create_tip_window P_ ((struct frame *));
403 /* TODO: Native Input Method support; see x_create_im. */
404 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
405 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
406 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
407 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
408 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
409 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
410 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
411 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
412 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
413 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
414 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
415 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
416 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
417 Lisp_Object));
422 /* Store the screen positions of frame F into XPTR and YPTR.
423 These are the positions of the containing window manager window,
424 not Emacs's own window. */
426 void
427 x_real_positions (f, xptr, yptr)
428 FRAME_PTR f;
429 int *xptr, *yptr;
431 POINT pt;
432 RECT rect;
434 /* Get the bounds of the WM window. */
435 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
437 pt.x = 0;
438 pt.y = 0;
440 /* Convert (0, 0) in the client area to screen co-ordinates. */
441 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
443 /* Remember x_pixels_diff and y_pixels_diff. */
444 f->x_pixels_diff = pt.x - rect.left;
445 f->y_pixels_diff = pt.y - rect.top;
447 *xptr = rect.left;
448 *yptr = rect.top;
453 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
454 Sw32_define_rgb_color, 4, 4, 0,
455 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
456 This adds or updates a named color to `w32-color-map', making it
457 available for use. The original entry's RGB ref is returned, or nil
458 if the entry is new. */)
459 (red, green, blue, name)
460 Lisp_Object red, green, blue, name;
462 Lisp_Object rgb;
463 Lisp_Object oldrgb = Qnil;
464 Lisp_Object entry;
466 CHECK_NUMBER (red);
467 CHECK_NUMBER (green);
468 CHECK_NUMBER (blue);
469 CHECK_STRING (name);
471 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
473 BLOCK_INPUT;
475 /* replace existing entry in w32-color-map or add new entry. */
476 entry = Fassoc (name, Vw32_color_map);
477 if (NILP (entry))
479 entry = Fcons (name, rgb);
480 Vw32_color_map = Fcons (entry, Vw32_color_map);
482 else
484 oldrgb = Fcdr (entry);
485 Fsetcdr (entry, rgb);
488 UNBLOCK_INPUT;
490 return (oldrgb);
493 DEFUN ("w32-load-color-file", Fw32_load_color_file,
494 Sw32_load_color_file, 1, 1, 0,
495 doc: /* Create an alist of color entries from an external file.
496 Assign this value to `w32-color-map' to replace the existing color map.
498 The file should define one named RGB color per line like so:
499 R G B name
500 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
501 (filename)
502 Lisp_Object filename;
504 FILE *fp;
505 Lisp_Object cmap = Qnil;
506 Lisp_Object abspath;
508 CHECK_STRING (filename);
509 abspath = Fexpand_file_name (filename, Qnil);
511 fp = fopen (SDATA (filename), "rt");
512 if (fp)
514 char buf[512];
515 int red, green, blue;
516 int num;
518 BLOCK_INPUT;
520 while (fgets (buf, sizeof (buf), fp) != NULL) {
521 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
523 char *name = buf + num;
524 num = strlen (name) - 1;
525 if (name[num] == '\n')
526 name[num] = 0;
527 cmap = Fcons (Fcons (build_string (name),
528 make_number (RGB (red, green, blue))),
529 cmap);
532 fclose (fp);
534 UNBLOCK_INPUT;
537 return cmap;
540 /* The default colors for the w32 color map */
541 typedef struct colormap_t
543 char *name;
544 COLORREF colorref;
545 } colormap_t;
547 colormap_t w32_color_map[] =
549 {"snow" , PALETTERGB (255,250,250)},
550 {"ghost white" , PALETTERGB (248,248,255)},
551 {"GhostWhite" , PALETTERGB (248,248,255)},
552 {"white smoke" , PALETTERGB (245,245,245)},
553 {"WhiteSmoke" , PALETTERGB (245,245,245)},
554 {"gainsboro" , PALETTERGB (220,220,220)},
555 {"floral white" , PALETTERGB (255,250,240)},
556 {"FloralWhite" , PALETTERGB (255,250,240)},
557 {"old lace" , PALETTERGB (253,245,230)},
558 {"OldLace" , PALETTERGB (253,245,230)},
559 {"linen" , PALETTERGB (250,240,230)},
560 {"antique white" , PALETTERGB (250,235,215)},
561 {"AntiqueWhite" , PALETTERGB (250,235,215)},
562 {"papaya whip" , PALETTERGB (255,239,213)},
563 {"PapayaWhip" , PALETTERGB (255,239,213)},
564 {"blanched almond" , PALETTERGB (255,235,205)},
565 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
566 {"bisque" , PALETTERGB (255,228,196)},
567 {"peach puff" , PALETTERGB (255,218,185)},
568 {"PeachPuff" , PALETTERGB (255,218,185)},
569 {"navajo white" , PALETTERGB (255,222,173)},
570 {"NavajoWhite" , PALETTERGB (255,222,173)},
571 {"moccasin" , PALETTERGB (255,228,181)},
572 {"cornsilk" , PALETTERGB (255,248,220)},
573 {"ivory" , PALETTERGB (255,255,240)},
574 {"lemon chiffon" , PALETTERGB (255,250,205)},
575 {"LemonChiffon" , PALETTERGB (255,250,205)},
576 {"seashell" , PALETTERGB (255,245,238)},
577 {"honeydew" , PALETTERGB (240,255,240)},
578 {"mint cream" , PALETTERGB (245,255,250)},
579 {"MintCream" , PALETTERGB (245,255,250)},
580 {"azure" , PALETTERGB (240,255,255)},
581 {"alice blue" , PALETTERGB (240,248,255)},
582 {"AliceBlue" , PALETTERGB (240,248,255)},
583 {"lavender" , PALETTERGB (230,230,250)},
584 {"lavender blush" , PALETTERGB (255,240,245)},
585 {"LavenderBlush" , PALETTERGB (255,240,245)},
586 {"misty rose" , PALETTERGB (255,228,225)},
587 {"MistyRose" , PALETTERGB (255,228,225)},
588 {"white" , PALETTERGB (255,255,255)},
589 {"black" , PALETTERGB ( 0, 0, 0)},
590 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
591 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
592 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
593 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
594 {"dim gray" , PALETTERGB (105,105,105)},
595 {"DimGray" , PALETTERGB (105,105,105)},
596 {"dim grey" , PALETTERGB (105,105,105)},
597 {"DimGrey" , PALETTERGB (105,105,105)},
598 {"slate gray" , PALETTERGB (112,128,144)},
599 {"SlateGray" , PALETTERGB (112,128,144)},
600 {"slate grey" , PALETTERGB (112,128,144)},
601 {"SlateGrey" , PALETTERGB (112,128,144)},
602 {"light slate gray" , PALETTERGB (119,136,153)},
603 {"LightSlateGray" , PALETTERGB (119,136,153)},
604 {"light slate grey" , PALETTERGB (119,136,153)},
605 {"LightSlateGrey" , PALETTERGB (119,136,153)},
606 {"gray" , PALETTERGB (190,190,190)},
607 {"grey" , PALETTERGB (190,190,190)},
608 {"light grey" , PALETTERGB (211,211,211)},
609 {"LightGrey" , PALETTERGB (211,211,211)},
610 {"light gray" , PALETTERGB (211,211,211)},
611 {"LightGray" , PALETTERGB (211,211,211)},
612 {"midnight blue" , PALETTERGB ( 25, 25,112)},
613 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
614 {"navy" , PALETTERGB ( 0, 0,128)},
615 {"navy blue" , PALETTERGB ( 0, 0,128)},
616 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
617 {"cornflower blue" , PALETTERGB (100,149,237)},
618 {"CornflowerBlue" , PALETTERGB (100,149,237)},
619 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
620 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
621 {"slate blue" , PALETTERGB (106, 90,205)},
622 {"SlateBlue" , PALETTERGB (106, 90,205)},
623 {"medium slate blue" , PALETTERGB (123,104,238)},
624 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
625 {"light slate blue" , PALETTERGB (132,112,255)},
626 {"LightSlateBlue" , PALETTERGB (132,112,255)},
627 {"medium blue" , PALETTERGB ( 0, 0,205)},
628 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
629 {"royal blue" , PALETTERGB ( 65,105,225)},
630 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
631 {"blue" , PALETTERGB ( 0, 0,255)},
632 {"dodger blue" , PALETTERGB ( 30,144,255)},
633 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
634 {"deep sky blue" , PALETTERGB ( 0,191,255)},
635 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
636 {"sky blue" , PALETTERGB (135,206,235)},
637 {"SkyBlue" , PALETTERGB (135,206,235)},
638 {"light sky blue" , PALETTERGB (135,206,250)},
639 {"LightSkyBlue" , PALETTERGB (135,206,250)},
640 {"steel blue" , PALETTERGB ( 70,130,180)},
641 {"SteelBlue" , PALETTERGB ( 70,130,180)},
642 {"light steel blue" , PALETTERGB (176,196,222)},
643 {"LightSteelBlue" , PALETTERGB (176,196,222)},
644 {"light blue" , PALETTERGB (173,216,230)},
645 {"LightBlue" , PALETTERGB (173,216,230)},
646 {"powder blue" , PALETTERGB (176,224,230)},
647 {"PowderBlue" , PALETTERGB (176,224,230)},
648 {"pale turquoise" , PALETTERGB (175,238,238)},
649 {"PaleTurquoise" , PALETTERGB (175,238,238)},
650 {"dark turquoise" , PALETTERGB ( 0,206,209)},
651 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
652 {"medium turquoise" , PALETTERGB ( 72,209,204)},
653 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
654 {"turquoise" , PALETTERGB ( 64,224,208)},
655 {"cyan" , PALETTERGB ( 0,255,255)},
656 {"light cyan" , PALETTERGB (224,255,255)},
657 {"LightCyan" , PALETTERGB (224,255,255)},
658 {"cadet blue" , PALETTERGB ( 95,158,160)},
659 {"CadetBlue" , PALETTERGB ( 95,158,160)},
660 {"medium aquamarine" , PALETTERGB (102,205,170)},
661 {"MediumAquamarine" , PALETTERGB (102,205,170)},
662 {"aquamarine" , PALETTERGB (127,255,212)},
663 {"dark green" , PALETTERGB ( 0,100, 0)},
664 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
665 {"dark olive green" , PALETTERGB ( 85,107, 47)},
666 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
667 {"dark sea green" , PALETTERGB (143,188,143)},
668 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
669 {"sea green" , PALETTERGB ( 46,139, 87)},
670 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
671 {"medium sea green" , PALETTERGB ( 60,179,113)},
672 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
673 {"light sea green" , PALETTERGB ( 32,178,170)},
674 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
675 {"pale green" , PALETTERGB (152,251,152)},
676 {"PaleGreen" , PALETTERGB (152,251,152)},
677 {"spring green" , PALETTERGB ( 0,255,127)},
678 {"SpringGreen" , PALETTERGB ( 0,255,127)},
679 {"lawn green" , PALETTERGB (124,252, 0)},
680 {"LawnGreen" , PALETTERGB (124,252, 0)},
681 {"green" , PALETTERGB ( 0,255, 0)},
682 {"chartreuse" , PALETTERGB (127,255, 0)},
683 {"medium spring green" , PALETTERGB ( 0,250,154)},
684 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
685 {"green yellow" , PALETTERGB (173,255, 47)},
686 {"GreenYellow" , PALETTERGB (173,255, 47)},
687 {"lime green" , PALETTERGB ( 50,205, 50)},
688 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
689 {"yellow green" , PALETTERGB (154,205, 50)},
690 {"YellowGreen" , PALETTERGB (154,205, 50)},
691 {"forest green" , PALETTERGB ( 34,139, 34)},
692 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
693 {"olive drab" , PALETTERGB (107,142, 35)},
694 {"OliveDrab" , PALETTERGB (107,142, 35)},
695 {"dark khaki" , PALETTERGB (189,183,107)},
696 {"DarkKhaki" , PALETTERGB (189,183,107)},
697 {"khaki" , PALETTERGB (240,230,140)},
698 {"pale goldenrod" , PALETTERGB (238,232,170)},
699 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
700 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
701 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
702 {"light yellow" , PALETTERGB (255,255,224)},
703 {"LightYellow" , PALETTERGB (255,255,224)},
704 {"yellow" , PALETTERGB (255,255, 0)},
705 {"gold" , PALETTERGB (255,215, 0)},
706 {"light goldenrod" , PALETTERGB (238,221,130)},
707 {"LightGoldenrod" , PALETTERGB (238,221,130)},
708 {"goldenrod" , PALETTERGB (218,165, 32)},
709 {"dark goldenrod" , PALETTERGB (184,134, 11)},
710 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
711 {"rosy brown" , PALETTERGB (188,143,143)},
712 {"RosyBrown" , PALETTERGB (188,143,143)},
713 {"indian red" , PALETTERGB (205, 92, 92)},
714 {"IndianRed" , PALETTERGB (205, 92, 92)},
715 {"saddle brown" , PALETTERGB (139, 69, 19)},
716 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
717 {"sienna" , PALETTERGB (160, 82, 45)},
718 {"peru" , PALETTERGB (205,133, 63)},
719 {"burlywood" , PALETTERGB (222,184,135)},
720 {"beige" , PALETTERGB (245,245,220)},
721 {"wheat" , PALETTERGB (245,222,179)},
722 {"sandy brown" , PALETTERGB (244,164, 96)},
723 {"SandyBrown" , PALETTERGB (244,164, 96)},
724 {"tan" , PALETTERGB (210,180,140)},
725 {"chocolate" , PALETTERGB (210,105, 30)},
726 {"firebrick" , PALETTERGB (178,34, 34)},
727 {"brown" , PALETTERGB (165,42, 42)},
728 {"dark salmon" , PALETTERGB (233,150,122)},
729 {"DarkSalmon" , PALETTERGB (233,150,122)},
730 {"salmon" , PALETTERGB (250,128,114)},
731 {"light salmon" , PALETTERGB (255,160,122)},
732 {"LightSalmon" , PALETTERGB (255,160,122)},
733 {"orange" , PALETTERGB (255,165, 0)},
734 {"dark orange" , PALETTERGB (255,140, 0)},
735 {"DarkOrange" , PALETTERGB (255,140, 0)},
736 {"coral" , PALETTERGB (255,127, 80)},
737 {"light coral" , PALETTERGB (240,128,128)},
738 {"LightCoral" , PALETTERGB (240,128,128)},
739 {"tomato" , PALETTERGB (255, 99, 71)},
740 {"orange red" , PALETTERGB (255, 69, 0)},
741 {"OrangeRed" , PALETTERGB (255, 69, 0)},
742 {"red" , PALETTERGB (255, 0, 0)},
743 {"hot pink" , PALETTERGB (255,105,180)},
744 {"HotPink" , PALETTERGB (255,105,180)},
745 {"deep pink" , PALETTERGB (255, 20,147)},
746 {"DeepPink" , PALETTERGB (255, 20,147)},
747 {"pink" , PALETTERGB (255,192,203)},
748 {"light pink" , PALETTERGB (255,182,193)},
749 {"LightPink" , PALETTERGB (255,182,193)},
750 {"pale violet red" , PALETTERGB (219,112,147)},
751 {"PaleVioletRed" , PALETTERGB (219,112,147)},
752 {"maroon" , PALETTERGB (176, 48, 96)},
753 {"medium violet red" , PALETTERGB (199, 21,133)},
754 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
755 {"violet red" , PALETTERGB (208, 32,144)},
756 {"VioletRed" , PALETTERGB (208, 32,144)},
757 {"magenta" , PALETTERGB (255, 0,255)},
758 {"violet" , PALETTERGB (238,130,238)},
759 {"plum" , PALETTERGB (221,160,221)},
760 {"orchid" , PALETTERGB (218,112,214)},
761 {"medium orchid" , PALETTERGB (186, 85,211)},
762 {"MediumOrchid" , PALETTERGB (186, 85,211)},
763 {"dark orchid" , PALETTERGB (153, 50,204)},
764 {"DarkOrchid" , PALETTERGB (153, 50,204)},
765 {"dark violet" , PALETTERGB (148, 0,211)},
766 {"DarkViolet" , PALETTERGB (148, 0,211)},
767 {"blue violet" , PALETTERGB (138, 43,226)},
768 {"BlueViolet" , PALETTERGB (138, 43,226)},
769 {"purple" , PALETTERGB (160, 32,240)},
770 {"medium purple" , PALETTERGB (147,112,219)},
771 {"MediumPurple" , PALETTERGB (147,112,219)},
772 {"thistle" , PALETTERGB (216,191,216)},
773 {"gray0" , PALETTERGB ( 0, 0, 0)},
774 {"grey0" , PALETTERGB ( 0, 0, 0)},
775 {"dark grey" , PALETTERGB (169,169,169)},
776 {"DarkGrey" , PALETTERGB (169,169,169)},
777 {"dark gray" , PALETTERGB (169,169,169)},
778 {"DarkGray" , PALETTERGB (169,169,169)},
779 {"dark blue" , PALETTERGB ( 0, 0,139)},
780 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
781 {"dark cyan" , PALETTERGB ( 0,139,139)},
782 {"DarkCyan" , PALETTERGB ( 0,139,139)},
783 {"dark magenta" , PALETTERGB (139, 0,139)},
784 {"DarkMagenta" , PALETTERGB (139, 0,139)},
785 {"dark red" , PALETTERGB (139, 0, 0)},
786 {"DarkRed" , PALETTERGB (139, 0, 0)},
787 {"light green" , PALETTERGB (144,238,144)},
788 {"LightGreen" , PALETTERGB (144,238,144)},
791 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
792 0, 0, 0, doc: /* Return the default color map. */)
795 int i;
796 colormap_t *pc = w32_color_map;
797 Lisp_Object cmap;
799 BLOCK_INPUT;
801 cmap = Qnil;
803 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
804 pc++, i++)
805 cmap = Fcons (Fcons (build_string (pc->name),
806 make_number (pc->colorref)),
807 cmap);
809 UNBLOCK_INPUT;
811 return (cmap);
814 Lisp_Object
815 w32_to_x_color (rgb)
816 Lisp_Object rgb;
818 Lisp_Object color;
820 CHECK_NUMBER (rgb);
822 BLOCK_INPUT;
824 color = Frassq (rgb, Vw32_color_map);
826 UNBLOCK_INPUT;
828 if (!NILP (color))
829 return (Fcar (color));
830 else
831 return Qnil;
834 static Lisp_Object
835 w32_color_map_lookup (colorname)
836 char *colorname;
838 Lisp_Object tail, ret = Qnil;
840 BLOCK_INPUT;
842 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
844 register Lisp_Object elt, tem;
846 elt = Fcar (tail);
847 if (!CONSP (elt)) continue;
849 tem = Fcar (elt);
851 if (lstrcmpi (SDATA (tem), colorname) == 0)
853 ret = Fcdr (elt);
854 break;
857 QUIT;
861 UNBLOCK_INPUT;
863 return ret;
867 static void
868 add_system_logical_colors_to_map (system_colors)
869 Lisp_Object *system_colors;
871 HKEY colors_key;
873 /* Other registry operations are done with input blocked. */
874 BLOCK_INPUT;
876 /* Look for "Control Panel/Colors" under User and Machine registry
877 settings. */
878 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
879 KEY_READ, &colors_key) == ERROR_SUCCESS
880 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
881 KEY_READ, &colors_key) == ERROR_SUCCESS)
883 /* List all keys. */
884 char color_buffer[64];
885 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
886 int index = 0;
887 DWORD name_size, color_size;
888 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
890 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
891 color_size = sizeof (color_buffer);
893 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
895 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
896 NULL, NULL, color_buffer, &color_size)
897 == ERROR_SUCCESS)
899 int r, g, b;
900 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
901 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
902 make_number (RGB (r, g, b))),
903 *system_colors);
905 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
906 color_size = sizeof (color_buffer);
907 index++;
909 RegCloseKey (colors_key);
912 UNBLOCK_INPUT;
916 static Lisp_Object
917 x_to_w32_color (colorname)
918 char * colorname;
920 register Lisp_Object ret = Qnil;
922 BLOCK_INPUT;
924 if (colorname[0] == '#')
926 /* Could be an old-style RGB Device specification. */
927 char *color;
928 int size;
929 color = colorname + 1;
931 size = strlen (color);
932 if (size == 3 || size == 6 || size == 9 || size == 12)
934 UINT colorval;
935 int i, pos;
936 pos = 0;
937 size /= 3;
938 colorval = 0;
940 for (i = 0; i < 3; i++)
942 char *end;
943 char t;
944 unsigned long value;
946 /* The check for 'x' in the following conditional takes into
947 account the fact that strtol allows a "0x" in front of
948 our numbers, and we don't. */
949 if (!isxdigit (color[0]) || color[1] == 'x')
950 break;
951 t = color[size];
952 color[size] = '\0';
953 value = strtoul (color, &end, 16);
954 color[size] = t;
955 if (errno == ERANGE || end - color != size)
956 break;
957 switch (size)
959 case 1:
960 value = value * 0x10;
961 break;
962 case 2:
963 break;
964 case 3:
965 value /= 0x10;
966 break;
967 case 4:
968 value /= 0x100;
969 break;
971 colorval |= (value << pos);
972 pos += 0x8;
973 if (i == 2)
975 UNBLOCK_INPUT;
976 XSETINT (ret, colorval);
977 return ret;
979 color = end;
983 else if (strnicmp (colorname, "rgb:", 4) == 0)
985 char *color;
986 UINT colorval;
987 int i, pos;
988 pos = 0;
990 colorval = 0;
991 color = colorname + 4;
992 for (i = 0; i < 3; i++)
994 char *end;
995 unsigned long value;
997 /* The check for 'x' in the following conditional takes into
998 account the fact that strtol allows a "0x" in front of
999 our numbers, and we don't. */
1000 if (!isxdigit (color[0]) || color[1] == 'x')
1001 break;
1002 value = strtoul (color, &end, 16);
1003 if (errno == ERANGE)
1004 break;
1005 switch (end - color)
1007 case 1:
1008 value = value * 0x10 + value;
1009 break;
1010 case 2:
1011 break;
1012 case 3:
1013 value /= 0x10;
1014 break;
1015 case 4:
1016 value /= 0x100;
1017 break;
1018 default:
1019 value = ULONG_MAX;
1021 if (value == ULONG_MAX)
1022 break;
1023 colorval |= (value << pos);
1024 pos += 0x8;
1025 if (i == 2)
1027 if (*end != '\0')
1028 break;
1029 UNBLOCK_INPUT;
1030 XSETINT (ret, colorval);
1031 return ret;
1033 if (*end != '/')
1034 break;
1035 color = end + 1;
1038 else if (strnicmp (colorname, "rgbi:", 5) == 0)
1040 /* This is an RGB Intensity specification. */
1041 char *color;
1042 UINT colorval;
1043 int i, pos;
1044 pos = 0;
1046 colorval = 0;
1047 color = colorname + 5;
1048 for (i = 0; i < 3; i++)
1050 char *end;
1051 double value;
1052 UINT val;
1054 value = strtod (color, &end);
1055 if (errno == ERANGE)
1056 break;
1057 if (value < 0.0 || value > 1.0)
1058 break;
1059 val = (UINT)(0x100 * value);
1060 /* We used 0x100 instead of 0xFF to give a continuous
1061 range between 0.0 and 1.0 inclusive. The next statement
1062 fixes the 1.0 case. */
1063 if (val == 0x100)
1064 val = 0xFF;
1065 colorval |= (val << pos);
1066 pos += 0x8;
1067 if (i == 2)
1069 if (*end != '\0')
1070 break;
1071 UNBLOCK_INPUT;
1072 XSETINT (ret, colorval);
1073 return ret;
1075 if (*end != '/')
1076 break;
1077 color = end + 1;
1080 /* I am not going to attempt to handle any of the CIE color schemes
1081 or TekHVC, since I don't know the algorithms for conversion to
1082 RGB. */
1084 /* If we fail to lookup the color name in w32_color_map, then check the
1085 colorname to see if it can be crudely approximated: If the X color
1086 ends in a number (e.g., "darkseagreen2"), strip the number and
1087 return the result of looking up the base color name. */
1088 ret = w32_color_map_lookup (colorname);
1089 if (NILP (ret))
1091 int len = strlen (colorname);
1093 if (isdigit (colorname[len - 1]))
1095 char *ptr, *approx = alloca (len + 1);
1097 strcpy (approx, colorname);
1098 ptr = &approx[len - 1];
1099 while (ptr > approx && isdigit (*ptr))
1100 *ptr-- = '\0';
1102 ret = w32_color_map_lookup (approx);
1106 UNBLOCK_INPUT;
1107 return ret;
1110 void
1111 w32_regenerate_palette (FRAME_PTR f)
1113 struct w32_palette_entry * list;
1114 LOGPALETTE * log_palette;
1115 HPALETTE new_palette;
1116 int i;
1118 /* don't bother trying to create palette if not supported */
1119 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1120 return;
1122 log_palette = (LOGPALETTE *)
1123 alloca (sizeof (LOGPALETTE) +
1124 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1125 log_palette->palVersion = 0x300;
1126 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1128 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1129 for (i = 0;
1130 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1131 i++, list = list->next)
1132 log_palette->palPalEntry[i] = list->entry;
1134 new_palette = CreatePalette (log_palette);
1136 enter_crit ();
1138 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1139 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1140 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1142 /* Realize display palette and garbage all frames. */
1143 release_frame_dc (f, get_frame_dc (f));
1145 leave_crit ();
1148 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1149 #define SET_W32_COLOR(pe, color) \
1150 do \
1152 pe.peRed = GetRValue (color); \
1153 pe.peGreen = GetGValue (color); \
1154 pe.peBlue = GetBValue (color); \
1155 pe.peFlags = 0; \
1156 } while (0)
1158 #if 0
1159 /* Keep these around in case we ever want to track color usage. */
1160 void
1161 w32_map_color (FRAME_PTR f, COLORREF color)
1163 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1165 if (NILP (Vw32_enable_palette))
1166 return;
1168 /* check if color is already mapped */
1169 while (list)
1171 if (W32_COLOR (list->entry) == color)
1173 ++list->refcount;
1174 return;
1176 list = list->next;
1179 /* not already mapped, so add to list and recreate Windows palette */
1180 list = (struct w32_palette_entry *)
1181 xmalloc (sizeof (struct w32_palette_entry));
1182 SET_W32_COLOR (list->entry, color);
1183 list->refcount = 1;
1184 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1185 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1186 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1188 /* set flag that palette must be regenerated */
1189 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1192 void
1193 w32_unmap_color (FRAME_PTR f, COLORREF color)
1195 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1196 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1198 if (NILP (Vw32_enable_palette))
1199 return;
1201 /* check if color is already mapped */
1202 while (list)
1204 if (W32_COLOR (list->entry) == color)
1206 if (--list->refcount == 0)
1208 *prev = list->next;
1209 xfree (list);
1210 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1211 break;
1213 else
1214 return;
1216 prev = &list->next;
1217 list = list->next;
1220 /* set flag that palette must be regenerated */
1221 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1223 #endif
1226 /* Gamma-correct COLOR on frame F. */
1228 void
1229 gamma_correct (f, color)
1230 struct frame *f;
1231 COLORREF *color;
1233 if (f->gamma)
1235 *color = PALETTERGB (
1236 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1237 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1238 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1243 /* Decide if color named COLOR is valid for the display associated with
1244 the selected frame; if so, return the rgb values in COLOR_DEF.
1245 If ALLOC is nonzero, allocate a new colormap cell. */
1248 w32_defined_color (f, color, color_def, alloc)
1249 FRAME_PTR f;
1250 char *color;
1251 XColor *color_def;
1252 int alloc;
1254 register Lisp_Object tem;
1255 COLORREF w32_color_ref;
1257 tem = x_to_w32_color (color);
1259 if (!NILP (tem))
1261 if (f)
1263 /* Apply gamma correction. */
1264 w32_color_ref = XUINT (tem);
1265 gamma_correct (f, &w32_color_ref);
1266 XSETINT (tem, w32_color_ref);
1269 /* Map this color to the palette if it is enabled. */
1270 if (!NILP (Vw32_enable_palette))
1272 struct w32_palette_entry * entry =
1273 one_w32_display_info.color_list;
1274 struct w32_palette_entry ** prev =
1275 &one_w32_display_info.color_list;
1277 /* check if color is already mapped */
1278 while (entry)
1280 if (W32_COLOR (entry->entry) == XUINT (tem))
1281 break;
1282 prev = &entry->next;
1283 entry = entry->next;
1286 if (entry == NULL && alloc)
1288 /* not already mapped, so add to list */
1289 entry = (struct w32_palette_entry *)
1290 xmalloc (sizeof (struct w32_palette_entry));
1291 SET_W32_COLOR (entry->entry, XUINT (tem));
1292 entry->next = NULL;
1293 *prev = entry;
1294 one_w32_display_info.num_colors++;
1296 /* set flag that palette must be regenerated */
1297 one_w32_display_info.regen_palette = TRUE;
1300 /* Ensure COLORREF value is snapped to nearest color in (default)
1301 palette by simulating the PALETTERGB macro. This works whether
1302 or not the display device has a palette. */
1303 w32_color_ref = XUINT (tem) | 0x2000000;
1305 color_def->pixel = w32_color_ref;
1306 color_def->red = GetRValue (w32_color_ref) * 256;
1307 color_def->green = GetGValue (w32_color_ref) * 256;
1308 color_def->blue = GetBValue (w32_color_ref) * 256;
1310 return 1;
1312 else
1314 return 0;
1318 /* Given a string ARG naming a color, compute a pixel value from it
1319 suitable for screen F.
1320 If F is not a color screen, return DEF (default) regardless of what
1321 ARG says. */
1324 x_decode_color (f, arg, def)
1325 FRAME_PTR f;
1326 Lisp_Object arg;
1327 int def;
1329 XColor cdef;
1331 CHECK_STRING (arg);
1333 if (strcmp (SDATA (arg), "black") == 0)
1334 return BLACK_PIX_DEFAULT (f);
1335 else if (strcmp (SDATA (arg), "white") == 0)
1336 return WHITE_PIX_DEFAULT (f);
1338 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1339 return def;
1341 /* w32_defined_color is responsible for coping with failures
1342 by looking for a near-miss. */
1343 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1344 return cdef.pixel;
1346 /* defined_color failed; return an ultimate default. */
1347 return def;
1352 /* Functions called only from `x_set_frame_param'
1353 to set individual parameters.
1355 If FRAME_W32_WINDOW (f) is 0,
1356 the frame is being created and its window does not exist yet.
1357 In that case, just record the parameter's new value
1358 in the standard place; do not attempt to change the window. */
1360 void
1361 x_set_foreground_color (f, arg, oldval)
1362 struct frame *f;
1363 Lisp_Object arg, oldval;
1365 struct w32_output *x = f->output_data.w32;
1366 PIX_TYPE fg, old_fg;
1368 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1369 old_fg = FRAME_FOREGROUND_PIXEL (f);
1370 FRAME_FOREGROUND_PIXEL (f) = fg;
1372 if (FRAME_W32_WINDOW (f) != 0)
1374 if (x->cursor_pixel == old_fg)
1375 x->cursor_pixel = fg;
1377 update_face_from_frame_parameter (f, Qforeground_color, arg);
1378 if (FRAME_VISIBLE_P (f))
1379 redraw_frame (f);
1383 void
1384 x_set_background_color (f, arg, oldval)
1385 struct frame *f;
1386 Lisp_Object arg, oldval;
1388 FRAME_BACKGROUND_PIXEL (f)
1389 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1391 if (FRAME_W32_WINDOW (f) != 0)
1393 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1394 FRAME_BACKGROUND_PIXEL (f));
1396 update_face_from_frame_parameter (f, Qbackground_color, arg);
1398 if (FRAME_VISIBLE_P (f))
1399 redraw_frame (f);
1403 void
1404 x_set_mouse_color (f, arg, oldval)
1405 struct frame *f;
1406 Lisp_Object arg, oldval;
1408 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1409 int count;
1410 int mask_color;
1412 if (!EQ (Qnil, arg))
1413 f->output_data.w32->mouse_pixel
1414 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1415 mask_color = FRAME_BACKGROUND_PIXEL (f);
1417 /* Don't let pointers be invisible. */
1418 if (mask_color == f->output_data.w32->mouse_pixel
1419 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1420 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1422 #if 0 /* TODO : cursor changes */
1423 BLOCK_INPUT;
1425 /* It's not okay to crash if the user selects a screwy cursor. */
1426 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1428 if (!EQ (Qnil, Vx_pointer_shape))
1430 CHECK_NUMBER (Vx_pointer_shape);
1431 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1433 else
1434 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1435 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1437 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1439 CHECK_NUMBER (Vx_nontext_pointer_shape);
1440 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1441 XINT (Vx_nontext_pointer_shape));
1443 else
1444 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1445 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1447 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1449 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1450 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1451 XINT (Vx_hourglass_pointer_shape));
1453 else
1454 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1455 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1457 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1458 if (!EQ (Qnil, Vx_mode_pointer_shape))
1460 CHECK_NUMBER (Vx_mode_pointer_shape);
1461 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1462 XINT (Vx_mode_pointer_shape));
1464 else
1465 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1466 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1468 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1470 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1471 hand_cursor
1472 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1473 XINT (Vx_sensitive_text_pointer_shape));
1475 else
1476 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1478 if (!NILP (Vx_window_horizontal_drag_shape))
1480 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1481 horizontal_drag_cursor
1482 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1483 XINT (Vx_window_horizontal_drag_shape));
1485 else
1486 horizontal_drag_cursor
1487 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1489 /* Check and report errors with the above calls. */
1490 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1491 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1494 XColor fore_color, back_color;
1496 fore_color.pixel = f->output_data.w32->mouse_pixel;
1497 back_color.pixel = mask_color;
1498 XQueryColor (FRAME_W32_DISPLAY (f),
1499 DefaultColormap (FRAME_W32_DISPLAY (f),
1500 DefaultScreen (FRAME_W32_DISPLAY (f))),
1501 &fore_color);
1502 XQueryColor (FRAME_W32_DISPLAY (f),
1503 DefaultColormap (FRAME_W32_DISPLAY (f),
1504 DefaultScreen (FRAME_W32_DISPLAY (f))),
1505 &back_color);
1506 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1507 &fore_color, &back_color);
1508 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1509 &fore_color, &back_color);
1510 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1511 &fore_color, &back_color);
1512 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1513 &fore_color, &back_color);
1514 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1515 &fore_color, &back_color);
1518 if (FRAME_W32_WINDOW (f) != 0)
1519 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1521 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1522 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1523 f->output_data.w32->text_cursor = cursor;
1525 if (nontext_cursor != f->output_data.w32->nontext_cursor
1526 && f->output_data.w32->nontext_cursor != 0)
1527 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1528 f->output_data.w32->nontext_cursor = nontext_cursor;
1530 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1531 && f->output_data.w32->hourglass_cursor != 0)
1532 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1533 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1535 if (mode_cursor != f->output_data.w32->modeline_cursor
1536 && f->output_data.w32->modeline_cursor != 0)
1537 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1538 f->output_data.w32->modeline_cursor = mode_cursor;
1540 if (hand_cursor != f->output_data.w32->hand_cursor
1541 && f->output_data.w32->hand_cursor != 0)
1542 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1543 f->output_data.w32->hand_cursor = hand_cursor;
1545 XFlush (FRAME_W32_DISPLAY (f));
1546 UNBLOCK_INPUT;
1548 update_face_from_frame_parameter (f, Qmouse_color, arg);
1549 #endif /* TODO */
1552 void
1553 x_set_cursor_color (f, arg, oldval)
1554 struct frame *f;
1555 Lisp_Object arg, oldval;
1557 unsigned long fore_pixel, pixel;
1559 if (!NILP (Vx_cursor_fore_pixel))
1560 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1561 WHITE_PIX_DEFAULT (f));
1562 else
1563 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1565 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1567 /* Make sure that the cursor color differs from the background color. */
1568 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1570 pixel = f->output_data.w32->mouse_pixel;
1571 if (pixel == fore_pixel)
1572 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1575 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1576 f->output_data.w32->cursor_pixel = pixel;
1578 if (FRAME_W32_WINDOW (f) != 0)
1580 BLOCK_INPUT;
1581 /* Update frame's cursor_gc. */
1582 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1583 f->output_data.w32->cursor_gc->background = pixel;
1585 UNBLOCK_INPUT;
1587 if (FRAME_VISIBLE_P (f))
1589 x_update_cursor (f, 0);
1590 x_update_cursor (f, 1);
1594 update_face_from_frame_parameter (f, Qcursor_color, arg);
1597 /* Set the border-color of frame F to pixel value PIX.
1598 Note that this does not fully take effect if done before
1599 F has a window. */
1601 void
1602 x_set_border_pixel (f, pix)
1603 struct frame *f;
1604 int pix;
1607 f->output_data.w32->border_pixel = pix;
1609 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1611 if (FRAME_VISIBLE_P (f))
1612 redraw_frame (f);
1616 /* Set the border-color of frame F to value described by ARG.
1617 ARG can be a string naming a color.
1618 The border-color is used for the border that is drawn by the server.
1619 Note that this does not fully take effect if done before
1620 F has a window; it must be redone when the window is created. */
1622 void
1623 x_set_border_color (f, arg, oldval)
1624 struct frame *f;
1625 Lisp_Object arg, oldval;
1627 int pix;
1629 CHECK_STRING (arg);
1630 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1631 x_set_border_pixel (f, pix);
1632 update_face_from_frame_parameter (f, Qborder_color, arg);
1636 void
1637 x_set_cursor_type (f, arg, oldval)
1638 FRAME_PTR f;
1639 Lisp_Object arg, oldval;
1641 set_frame_cursor_types (f, arg);
1643 /* Make sure the cursor gets redrawn. */
1644 cursor_type_changed = 1;
1647 void
1648 x_set_icon_type (f, arg, oldval)
1649 struct frame *f;
1650 Lisp_Object arg, oldval;
1652 int result;
1654 if (NILP (arg) && NILP (oldval))
1655 return;
1657 if (STRINGP (arg) && STRINGP (oldval)
1658 && EQ (Fstring_equal (oldval, arg), Qt))
1659 return;
1661 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1662 return;
1664 BLOCK_INPUT;
1666 result = x_bitmap_icon (f, arg);
1667 if (result)
1669 UNBLOCK_INPUT;
1670 error ("No icon window available");
1673 UNBLOCK_INPUT;
1676 void
1677 x_set_icon_name (f, arg, oldval)
1678 struct frame *f;
1679 Lisp_Object arg, oldval;
1681 if (STRINGP (arg))
1683 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1684 return;
1686 else if (!NILP (arg) || NILP (oldval))
1687 return;
1689 f->icon_name = arg;
1691 #if 0
1692 if (f->output_data.w32->icon_bitmap != 0)
1693 return;
1695 BLOCK_INPUT;
1697 result = x_text_icon (f,
1698 (char *) SDATA ((!NILP (f->icon_name)
1699 ? f->icon_name
1700 : !NILP (f->title)
1701 ? f->title
1702 : f->name)));
1704 if (result)
1706 UNBLOCK_INPUT;
1707 error ("No icon window available");
1710 /* If the window was unmapped (and its icon was mapped),
1711 the new icon is not mapped, so map the window in its stead. */
1712 if (FRAME_VISIBLE_P (f))
1714 #ifdef USE_X_TOOLKIT
1715 XtPopup (f->output_data.w32->widget, XtGrabNone);
1716 #endif
1717 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1720 XFlush (FRAME_W32_DISPLAY (f));
1721 UNBLOCK_INPUT;
1722 #endif
1726 void
1727 x_set_menu_bar_lines (f, value, oldval)
1728 struct frame *f;
1729 Lisp_Object value, oldval;
1731 int nlines;
1732 int olines = FRAME_MENU_BAR_LINES (f);
1734 /* Right now, menu bars don't work properly in minibuf-only frames;
1735 most of the commands try to apply themselves to the minibuffer
1736 frame itself, and get an error because you can't switch buffers
1737 in or split the minibuffer window. */
1738 if (FRAME_MINIBUF_ONLY_P (f))
1739 return;
1741 if (INTEGERP (value))
1742 nlines = XINT (value);
1743 else
1744 nlines = 0;
1746 FRAME_MENU_BAR_LINES (f) = 0;
1747 if (nlines)
1748 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1749 else
1751 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1752 free_frame_menubar (f);
1753 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1755 /* Adjust the frame size so that the client (text) dimensions
1756 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1757 set correctly. */
1758 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
1759 do_pending_window_change (0);
1761 adjust_glyphs (f);
1765 /* Set the number of lines used for the tool bar of frame F to VALUE.
1766 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
1767 is the old number of tool bar lines. This function changes the
1768 height of all windows on frame F to match the new tool bar height.
1769 The frame's height doesn't change. */
1771 void
1772 x_set_tool_bar_lines (f, value, oldval)
1773 struct frame *f;
1774 Lisp_Object value, oldval;
1776 int delta, nlines, root_height;
1777 Lisp_Object root_window;
1779 /* Treat tool bars like menu bars. */
1780 if (FRAME_MINIBUF_ONLY_P (f))
1781 return;
1783 /* Use VALUE only if an integer >= 0. */
1784 if (INTEGERP (value) && XINT (value) >= 0)
1785 nlines = XFASTINT (value);
1786 else
1787 nlines = 0;
1789 /* Make sure we redisplay all windows in this frame. */
1790 ++windows_or_buffers_changed;
1792 delta = nlines - FRAME_TOOL_BAR_LINES (f);
1794 /* Don't resize the tool-bar to more than we have room for. */
1795 root_window = FRAME_ROOT_WINDOW (f);
1796 root_height = WINDOW_TOTAL_LINES (XWINDOW (root_window));
1797 if (root_height - delta < 1)
1799 delta = root_height - 1;
1800 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
1803 FRAME_TOOL_BAR_LINES (f) = nlines;
1804 change_window_heights (root_window, delta);
1805 adjust_glyphs (f);
1807 /* We also have to make sure that the internal border at the top of
1808 the frame, below the menu bar or tool bar, is redrawn when the
1809 tool bar disappears. This is so because the internal border is
1810 below the tool bar if one is displayed, but is below the menu bar
1811 if there isn't a tool bar. The tool bar draws into the area
1812 below the menu bar. */
1813 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
1815 updating_frame = f;
1816 clear_frame ();
1817 clear_current_matrices (f);
1818 updating_frame = NULL;
1821 /* If the tool bar gets smaller, the internal border below it
1822 has to be cleared. It was formerly part of the display
1823 of the larger tool bar, and updating windows won't clear it. */
1824 if (delta < 0)
1826 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1827 int width = FRAME_PIXEL_WIDTH (f);
1828 int y = nlines * FRAME_LINE_HEIGHT (f);
1830 BLOCK_INPUT;
1832 HDC hdc = get_frame_dc (f);
1833 w32_clear_area (f, hdc, 0, y, width, height);
1834 release_frame_dc (f, hdc);
1836 UNBLOCK_INPUT;
1838 if (WINDOWP (f->tool_bar_window))
1839 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1844 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1845 w32_id_name.
1847 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1848 name; if NAME is a string, set F's name to NAME and set
1849 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1851 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1852 suggesting a new name, which lisp code should override; if
1853 F->explicit_name is set, ignore the new name; otherwise, set it. */
1855 void
1856 x_set_name (f, name, explicit)
1857 struct frame *f;
1858 Lisp_Object name;
1859 int explicit;
1861 /* Make sure that requests from lisp code override requests from
1862 Emacs redisplay code. */
1863 if (explicit)
1865 /* If we're switching from explicit to implicit, we had better
1866 update the mode lines and thereby update the title. */
1867 if (f->explicit_name && NILP (name))
1868 update_mode_lines = 1;
1870 f->explicit_name = ! NILP (name);
1872 else if (f->explicit_name)
1873 return;
1875 /* If NAME is nil, set the name to the w32_id_name. */
1876 if (NILP (name))
1878 /* Check for no change needed in this very common case
1879 before we do any consing. */
1880 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
1881 SDATA (f->name)))
1882 return;
1883 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
1885 else
1886 CHECK_STRING (name);
1888 /* Don't change the name if it's already NAME. */
1889 if (! NILP (Fstring_equal (name, f->name)))
1890 return;
1892 f->name = name;
1894 /* For setting the frame title, the title parameter should override
1895 the name parameter. */
1896 if (! NILP (f->title))
1897 name = f->title;
1899 if (FRAME_W32_WINDOW (f))
1901 if (STRING_MULTIBYTE (name))
1902 name = ENCODE_SYSTEM (name);
1904 BLOCK_INPUT;
1905 SetWindowText (FRAME_W32_WINDOW (f), SDATA (name));
1906 UNBLOCK_INPUT;
1910 /* This function should be called when the user's lisp code has
1911 specified a name for the frame; the name will override any set by the
1912 redisplay code. */
1913 void
1914 x_explicitly_set_name (f, arg, oldval)
1915 FRAME_PTR f;
1916 Lisp_Object arg, oldval;
1918 x_set_name (f, arg, 1);
1921 /* This function should be called by Emacs redisplay code to set the
1922 name; names set this way will never override names set by the user's
1923 lisp code. */
1924 void
1925 x_implicitly_set_name (f, arg, oldval)
1926 FRAME_PTR f;
1927 Lisp_Object arg, oldval;
1929 x_set_name (f, arg, 0);
1932 /* Change the title of frame F to NAME.
1933 If NAME is nil, use the frame name as the title. */
1935 void
1936 x_set_title (f, name, old_name)
1937 struct frame *f;
1938 Lisp_Object name, old_name;
1940 /* Don't change the title if it's already NAME. */
1941 if (EQ (name, f->title))
1942 return;
1944 update_mode_lines = 1;
1946 f->title = name;
1948 if (NILP (name))
1949 name = f->name;
1951 if (FRAME_W32_WINDOW (f))
1953 if (STRING_MULTIBYTE (name))
1954 name = ENCODE_SYSTEM (name);
1956 BLOCK_INPUT;
1957 SetWindowText (FRAME_W32_WINDOW (f), SDATA (name));
1958 UNBLOCK_INPUT;
1963 void x_set_scroll_bar_default_width (f)
1964 struct frame *f;
1966 int wid = FRAME_COLUMN_WIDTH (f);
1968 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1969 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
1970 wid - 1) / wid;
1974 /* Subroutines of creating a frame. */
1977 /* Return the value of parameter PARAM.
1979 First search ALIST, then Vdefault_frame_alist, then the X defaults
1980 database, using ATTRIBUTE as the attribute name and CLASS as its class.
1982 Convert the resource to the type specified by desired_type.
1984 If no default is specified, return Qunbound. If you call
1985 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
1986 and don't let it get stored in any Lisp-visible variables! */
1988 static Lisp_Object
1989 w32_get_arg (alist, param, attribute, class, type)
1990 Lisp_Object alist, param;
1991 char *attribute;
1992 char *class;
1993 enum resource_types type;
1995 return x_get_arg (check_x_display_info (Qnil),
1996 alist, param, attribute, class, type);
2000 Cursor
2001 w32_load_cursor (LPCTSTR name)
2003 /* Try first to load cursor from application resource. */
2004 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
2005 name, IMAGE_CURSOR, 0, 0,
2006 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2007 if (!cursor)
2009 /* Then try to load a shared predefined cursor. */
2010 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
2011 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2013 return cursor;
2016 extern LRESULT CALLBACK w32_wnd_proc ();
2018 BOOL
2019 w32_init_class (hinst)
2020 HINSTANCE hinst;
2022 WNDCLASS wc;
2024 wc.style = CS_HREDRAW | CS_VREDRAW;
2025 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
2026 wc.cbClsExtra = 0;
2027 wc.cbWndExtra = WND_EXTRA_BYTES;
2028 wc.hInstance = hinst;
2029 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
2030 wc.hCursor = w32_load_cursor (IDC_ARROW);
2031 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
2032 wc.lpszMenuName = NULL;
2033 wc.lpszClassName = EMACS_CLASS;
2035 return (RegisterClass (&wc));
2038 HWND
2039 w32_createscrollbar (f, bar)
2040 struct frame *f;
2041 struct scroll_bar * bar;
2043 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2044 /* Position and size of scroll bar. */
2045 XINT (bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
2046 XINT (bar->top),
2047 XINT (bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
2048 XINT (bar->height),
2049 FRAME_W32_WINDOW (f),
2050 NULL,
2051 hinst,
2052 NULL));
2055 void
2056 w32_createwindow (f)
2057 struct frame *f;
2059 HWND hwnd;
2060 RECT rect;
2061 Lisp_Object top = Qunbound;
2062 Lisp_Object left = Qunbound;
2064 rect.left = rect.top = 0;
2065 rect.right = FRAME_PIXEL_WIDTH (f);
2066 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2068 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2069 FRAME_EXTERNAL_MENU_BAR (f));
2071 /* Do first time app init */
2073 if (!hprevinst)
2075 w32_init_class (hinst);
2078 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2080 XSETINT (left, f->left_pos);
2081 XSETINT (top, f->top_pos);
2083 else if (EQ (left, Qunbound) && EQ (top, Qunbound))
2085 /* When called with RES_TYPE_NUMBER, w32_get_arg will return zero
2086 for anything that is not a number and is not Qunbound. */
2087 left = w32_get_arg (Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
2088 top = w32_get_arg (Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
2091 FRAME_W32_WINDOW (f) = hwnd
2092 = CreateWindow (EMACS_CLASS,
2093 f->namebuf,
2094 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2095 EQ (left, Qunbound) ? CW_USEDEFAULT : XINT (left),
2096 EQ (top, Qunbound) ? CW_USEDEFAULT : XINT (top),
2097 rect.right - rect.left,
2098 rect.bottom - rect.top,
2099 NULL,
2100 NULL,
2101 hinst,
2102 NULL);
2104 if (hwnd)
2106 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2107 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2108 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2109 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->scroll_bar_actual_width);
2110 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2112 /* Enable drag-n-drop. */
2113 DragAcceptFiles (hwnd, TRUE);
2115 /* Do this to discard the default setting specified by our parent. */
2116 ShowWindow (hwnd, SW_HIDE);
2118 /* Update frame positions. */
2119 GetWindowRect (hwnd, &rect);
2120 f->left_pos = rect.left;
2121 f->top_pos = rect.top;
2125 void
2126 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
2127 W32Msg * wmsg;
2128 HWND hwnd;
2129 UINT msg;
2130 WPARAM wParam;
2131 LPARAM lParam;
2133 wmsg->msg.hwnd = hwnd;
2134 wmsg->msg.message = msg;
2135 wmsg->msg.wParam = wParam;
2136 wmsg->msg.lParam = lParam;
2137 wmsg->msg.time = GetMessageTime ();
2139 post_msg (wmsg);
2142 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2143 between left and right keys as advertised. We test for this
2144 support dynamically, and set a flag when the support is absent. If
2145 absent, we keep track of the left and right control and alt keys
2146 ourselves. This is particularly necessary on keyboards that rely
2147 upon the AltGr key, which is represented as having the left control
2148 and right alt keys pressed. For these keyboards, we need to know
2149 when the left alt key has been pressed in addition to the AltGr key
2150 so that we can properly support M-AltGr-key sequences (such as M-@
2151 on Swedish keyboards). */
2153 #define EMACS_LCONTROL 0
2154 #define EMACS_RCONTROL 1
2155 #define EMACS_LMENU 2
2156 #define EMACS_RMENU 3
2158 static int modifiers[4];
2159 static int modifiers_recorded;
2160 static int modifier_key_support_tested;
2162 static void
2163 test_modifier_support (unsigned int wparam)
2165 unsigned int l, r;
2167 if (wparam != VK_CONTROL && wparam != VK_MENU)
2168 return;
2169 if (wparam == VK_CONTROL)
2171 l = VK_LCONTROL;
2172 r = VK_RCONTROL;
2174 else
2176 l = VK_LMENU;
2177 r = VK_RMENU;
2179 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2180 modifiers_recorded = 1;
2181 else
2182 modifiers_recorded = 0;
2183 modifier_key_support_tested = 1;
2186 static void
2187 record_keydown (unsigned int wparam, unsigned int lparam)
2189 int i;
2191 if (!modifier_key_support_tested)
2192 test_modifier_support (wparam);
2194 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2195 return;
2197 if (wparam == VK_CONTROL)
2198 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2199 else
2200 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2202 modifiers[i] = 1;
2205 static void
2206 record_keyup (unsigned int wparam, unsigned int lparam)
2208 int i;
2210 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2211 return;
2213 if (wparam == VK_CONTROL)
2214 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2215 else
2216 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2218 modifiers[i] = 0;
2221 /* Emacs can lose focus while a modifier key has been pressed. When
2222 it regains focus, be conservative and clear all modifiers since
2223 we cannot reconstruct the left and right modifier state. */
2224 static void
2225 reset_modifiers ()
2227 SHORT ctrl, alt;
2229 if (GetFocus () == NULL)
2230 /* Emacs doesn't have keyboard focus. Do nothing. */
2231 return;
2233 ctrl = GetAsyncKeyState (VK_CONTROL);
2234 alt = GetAsyncKeyState (VK_MENU);
2236 if (!(ctrl & 0x08000))
2237 /* Clear any recorded control modifier state. */
2238 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2240 if (!(alt & 0x08000))
2241 /* Clear any recorded alt modifier state. */
2242 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2244 /* Update the state of all modifier keys, because modifiers used in
2245 hot-key combinations can get stuck on if Emacs loses focus as a
2246 result of a hot-key being pressed. */
2248 BYTE keystate[256];
2250 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2252 GetKeyboardState (keystate);
2253 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2254 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2255 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2256 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2257 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2258 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2259 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2260 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2261 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2262 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2263 SetKeyboardState (keystate);
2267 /* Synchronize modifier state with what is reported with the current
2268 keystroke. Even if we cannot distinguish between left and right
2269 modifier keys, we know that, if no modifiers are set, then neither
2270 the left or right modifier should be set. */
2271 static void
2272 sync_modifiers ()
2274 if (!modifiers_recorded)
2275 return;
2277 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2278 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2280 if (!(GetKeyState (VK_MENU) & 0x8000))
2281 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2284 static int
2285 modifier_set (int vkey)
2287 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
2288 return (GetKeyState (vkey) & 0x1);
2289 if (!modifiers_recorded)
2290 return (GetKeyState (vkey) & 0x8000);
2292 switch (vkey)
2294 case VK_LCONTROL:
2295 return modifiers[EMACS_LCONTROL];
2296 case VK_RCONTROL:
2297 return modifiers[EMACS_RCONTROL];
2298 case VK_LMENU:
2299 return modifiers[EMACS_LMENU];
2300 case VK_RMENU:
2301 return modifiers[EMACS_RMENU];
2303 return (GetKeyState (vkey) & 0x8000);
2306 /* Convert between the modifier bits W32 uses and the modifier bits
2307 Emacs uses. */
2309 unsigned int
2310 w32_key_to_modifier (int key)
2312 Lisp_Object key_mapping;
2314 switch (key)
2316 case VK_LWIN:
2317 key_mapping = Vw32_lwindow_modifier;
2318 break;
2319 case VK_RWIN:
2320 key_mapping = Vw32_rwindow_modifier;
2321 break;
2322 case VK_APPS:
2323 key_mapping = Vw32_apps_modifier;
2324 break;
2325 case VK_SCROLL:
2326 key_mapping = Vw32_scroll_lock_modifier;
2327 break;
2328 default:
2329 key_mapping = Qnil;
2332 /* NB. This code runs in the input thread, asychronously to the lisp
2333 thread, so we must be careful to ensure access to lisp data is
2334 thread-safe. The following code is safe because the modifier
2335 variable values are updated atomically from lisp and symbols are
2336 not relocated by GC. Also, we don't have to worry about seeing GC
2337 markbits here. */
2338 if (EQ (key_mapping, Qhyper))
2339 return hyper_modifier;
2340 if (EQ (key_mapping, Qsuper))
2341 return super_modifier;
2342 if (EQ (key_mapping, Qmeta))
2343 return meta_modifier;
2344 if (EQ (key_mapping, Qalt))
2345 return alt_modifier;
2346 if (EQ (key_mapping, Qctrl))
2347 return ctrl_modifier;
2348 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2349 return ctrl_modifier;
2350 if (EQ (key_mapping, Qshift))
2351 return shift_modifier;
2353 /* Don't generate any modifier if not explicitly requested. */
2354 return 0;
2357 unsigned int
2358 w32_get_modifiers ()
2360 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2361 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2362 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2363 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2364 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2365 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2366 (modifier_set (VK_MENU) ?
2367 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2370 /* We map the VK_* modifiers into console modifier constants
2371 so that we can use the same routines to handle both console
2372 and window input. */
2374 static int
2375 construct_console_modifiers ()
2377 int mods;
2379 mods = 0;
2380 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2381 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2382 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2383 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2384 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2385 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2386 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2387 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2388 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2389 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2390 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2392 return mods;
2395 static int
2396 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2398 int mods;
2400 /* Convert to emacs modifiers. */
2401 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2403 return mods;
2406 unsigned int
2407 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2409 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2410 return virt_key;
2412 if (virt_key == VK_RETURN)
2413 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2415 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2416 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2418 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2419 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2421 if (virt_key == VK_CLEAR)
2422 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2424 return virt_key;
2427 /* List of special key combinations which w32 would normally capture,
2428 but Emacs should grab instead. Not directly visible to lisp, to
2429 simplify synchronization. Each item is an integer encoding a virtual
2430 key code and modifier combination to capture. */
2431 Lisp_Object w32_grabbed_keys;
2433 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2434 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2435 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2436 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2438 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2439 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2440 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2442 /* Register hot-keys for reserved key combinations when Emacs has
2443 keyboard focus, since this is the only way Emacs can receive key
2444 combinations like Alt-Tab which are used by the system. */
2446 static void
2447 register_hot_keys (hwnd)
2448 HWND hwnd;
2450 Lisp_Object keylist;
2452 /* Use GC_CONSP, since we are called asynchronously. */
2453 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2455 Lisp_Object key = XCAR (keylist);
2457 /* Deleted entries get set to nil. */
2458 if (!INTEGERP (key))
2459 continue;
2461 RegisterHotKey (hwnd, HOTKEY_ID (key),
2462 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2466 static void
2467 unregister_hot_keys (hwnd)
2468 HWND hwnd;
2470 Lisp_Object keylist;
2472 /* Use GC_CONSP, since we are called asynchronously. */
2473 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2475 Lisp_Object key = XCAR (keylist);
2477 if (!INTEGERP (key))
2478 continue;
2480 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2484 /* Main message dispatch loop. */
2486 static void
2487 w32_msg_pump (deferred_msg * msg_buf)
2489 MSG msg;
2490 int result;
2491 HWND focus_window;
2493 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2495 while (GetMessage (&msg, NULL, 0, 0))
2497 if (msg.hwnd == NULL)
2499 switch (msg.message)
2501 case WM_NULL:
2502 /* Produced by complete_deferred_msg; just ignore. */
2503 break;
2504 case WM_EMACS_CREATEWINDOW:
2505 /* Initialize COM for this window. Even though we don't use it,
2506 some third party shell extensions can cause it to be used in
2507 system dialogs, which causes a crash if it is not initialized.
2508 This is a known bug in Windows, which was fixed long ago, but
2509 the patch for XP is not publically available until XP SP3,
2510 and older versions will never be patched. */
2511 CoInitialize (NULL);
2512 w32_createwindow ((struct frame *) msg.wParam);
2513 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2514 abort ();
2515 break;
2516 case WM_EMACS_SETLOCALE:
2517 SetThreadLocale (msg.wParam);
2518 /* Reply is not expected. */
2519 break;
2520 case WM_EMACS_SETKEYBOARDLAYOUT:
2521 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2522 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2523 result, 0))
2524 abort ();
2525 break;
2526 case WM_EMACS_REGISTER_HOT_KEY:
2527 focus_window = GetFocus ();
2528 if (focus_window != NULL)
2529 RegisterHotKey (focus_window,
2530 RAW_HOTKEY_ID (msg.wParam),
2531 RAW_HOTKEY_MODIFIERS (msg.wParam),
2532 RAW_HOTKEY_VK_CODE (msg.wParam));
2533 /* Reply is not expected. */
2534 break;
2535 case WM_EMACS_UNREGISTER_HOT_KEY:
2536 focus_window = GetFocus ();
2537 if (focus_window != NULL)
2538 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2539 /* Mark item as erased. NB: this code must be
2540 thread-safe. The next line is okay because the cons
2541 cell is never made into garbage and is not relocated by
2542 GC. */
2543 XSETCAR ((Lisp_Object) ((EMACS_INT) msg.lParam), Qnil);
2544 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2545 abort ();
2546 break;
2547 case WM_EMACS_TOGGLE_LOCK_KEY:
2549 int vk_code = (int) msg.wParam;
2550 int cur_state = (GetKeyState (vk_code) & 1);
2551 Lisp_Object new_state = (Lisp_Object) ((EMACS_INT) msg.lParam);
2553 /* NB: This code must be thread-safe. It is safe to
2554 call NILP because symbols are not relocated by GC,
2555 and pointer here is not touched by GC (so the markbit
2556 can't be set). Numbers are safe because they are
2557 immediate values. */
2558 if (NILP (new_state)
2559 || (NUMBERP (new_state)
2560 && ((XUINT (new_state)) & 1) != cur_state))
2562 one_w32_display_info.faked_key = vk_code;
2564 keybd_event ((BYTE) vk_code,
2565 (BYTE) MapVirtualKey (vk_code, 0),
2566 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2567 keybd_event ((BYTE) vk_code,
2568 (BYTE) MapVirtualKey (vk_code, 0),
2569 KEYEVENTF_EXTENDEDKEY | 0, 0);
2570 keybd_event ((BYTE) vk_code,
2571 (BYTE) MapVirtualKey (vk_code, 0),
2572 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2573 cur_state = !cur_state;
2575 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2576 cur_state, 0))
2577 abort ();
2579 break;
2580 default:
2581 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2584 else
2586 DispatchMessage (&msg);
2589 /* Exit nested loop when our deferred message has completed. */
2590 if (msg_buf->completed)
2591 break;
2595 deferred_msg * deferred_msg_head;
2597 static deferred_msg *
2598 find_deferred_msg (HWND hwnd, UINT msg)
2600 deferred_msg * item;
2602 /* Don't actually need synchronization for read access, since
2603 modification of single pointer is always atomic. */
2604 /* enter_crit (); */
2606 for (item = deferred_msg_head; item != NULL; item = item->next)
2607 if (item->w32msg.msg.hwnd == hwnd
2608 && item->w32msg.msg.message == msg)
2609 break;
2611 /* leave_crit (); */
2613 return item;
2616 static LRESULT
2617 send_deferred_msg (deferred_msg * msg_buf,
2618 HWND hwnd,
2619 UINT msg,
2620 WPARAM wParam,
2621 LPARAM lParam)
2623 /* Only input thread can send deferred messages. */
2624 if (GetCurrentThreadId () != dwWindowsThreadId)
2625 abort ();
2627 /* It is an error to send a message that is already deferred. */
2628 if (find_deferred_msg (hwnd, msg) != NULL)
2629 abort ();
2631 /* Enforced synchronization is not needed because this is the only
2632 function that alters deferred_msg_head, and the following critical
2633 section is guaranteed to only be serially reentered (since only the
2634 input thread can call us). */
2636 /* enter_crit (); */
2638 msg_buf->completed = 0;
2639 msg_buf->next = deferred_msg_head;
2640 deferred_msg_head = msg_buf;
2641 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2643 /* leave_crit (); */
2645 /* Start a new nested message loop to process other messages until
2646 this one is completed. */
2647 w32_msg_pump (msg_buf);
2649 deferred_msg_head = msg_buf->next;
2651 return msg_buf->result;
2654 void
2655 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2657 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2659 if (msg_buf == NULL)
2660 /* Message may have been cancelled, so don't abort. */
2661 return;
2663 msg_buf->result = result;
2664 msg_buf->completed = 1;
2666 /* Ensure input thread is woken so it notices the completion. */
2667 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2670 void
2671 cancel_all_deferred_msgs ()
2673 deferred_msg * item;
2675 /* Don't actually need synchronization for read access, since
2676 modification of single pointer is always atomic. */
2677 /* enter_crit (); */
2679 for (item = deferred_msg_head; item != NULL; item = item->next)
2681 item->result = 0;
2682 item->completed = 1;
2685 /* leave_crit (); */
2687 /* Ensure input thread is woken so it notices the completion. */
2688 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2691 DWORD WINAPI
2692 w32_msg_worker (void *arg)
2694 MSG msg;
2695 deferred_msg dummy_buf;
2697 /* Ensure our message queue is created */
2699 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2701 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2702 abort ();
2704 memset (&dummy_buf, 0, sizeof (dummy_buf));
2705 dummy_buf.w32msg.msg.hwnd = NULL;
2706 dummy_buf.w32msg.msg.message = WM_NULL;
2708 /* This is the inital message loop which should only exit when the
2709 application quits. */
2710 w32_msg_pump (&dummy_buf);
2712 return 0;
2715 static void
2716 signal_user_input ()
2718 /* Interrupt any lisp that wants to be interrupted by input. */
2719 if (!NILP (Vthrow_on_input))
2721 Vquit_flag = Vthrow_on_input;
2722 /* If we're inside a function that wants immediate quits,
2723 do it now. */
2724 if (immediate_quit && NILP (Vinhibit_quit))
2726 immediate_quit = 0;
2727 QUIT;
2733 static void
2734 post_character_message (hwnd, msg, wParam, lParam, modifiers)
2735 HWND hwnd;
2736 UINT msg;
2737 WPARAM wParam;
2738 LPARAM lParam;
2739 DWORD modifiers;
2742 W32Msg wmsg;
2744 wmsg.dwModifiers = modifiers;
2746 /* Detect quit_char and set quit-flag directly. Note that we
2747 still need to post a message to ensure the main thread will be
2748 woken up if blocked in sys_select, but we do NOT want to post
2749 the quit_char message itself (because it will usually be as if
2750 the user had typed quit_char twice). Instead, we post a dummy
2751 message that has no particular effect. */
2753 int c = wParam;
2754 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2755 c = make_ctrl_char (c) & 0377;
2756 if (c == quit_char
2757 || (wmsg.dwModifiers == 0 &&
2758 w32_quit_key && wParam == w32_quit_key))
2760 Vquit_flag = Qt;
2762 /* The choice of message is somewhat arbitrary, as long as
2763 the main thread handler just ignores it. */
2764 msg = WM_NULL;
2766 /* Interrupt any blocking system calls. */
2767 signal_quit ();
2769 /* As a safety precaution, forcibly complete any deferred
2770 messages. This is a kludge, but I don't see any particularly
2771 clean way to handle the situation where a deferred message is
2772 "dropped" in the lisp thread, and will thus never be
2773 completed, eg. by the user trying to activate the menubar
2774 when the lisp thread is busy, and then typing C-g when the
2775 menubar doesn't open promptly (with the result that the
2776 menubar never responds at all because the deferred
2777 WM_INITMENU message is never completed). Another problem
2778 situation is when the lisp thread calls SendMessage (to send
2779 a window manager command) when a message has been deferred;
2780 the lisp thread gets blocked indefinitely waiting for the
2781 deferred message to be completed, which itself is waiting for
2782 the lisp thread to respond.
2784 Note that we don't want to block the input thread waiting for
2785 a reponse from the lisp thread (although that would at least
2786 solve the deadlock problem above), because we want to be able
2787 to receive C-g to interrupt the lisp thread. */
2788 cancel_all_deferred_msgs ();
2790 else
2791 signal_user_input ();
2794 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2797 /* Main window procedure */
2799 LRESULT CALLBACK
2800 w32_wnd_proc (hwnd, msg, wParam, lParam)
2801 HWND hwnd;
2802 UINT msg;
2803 WPARAM wParam;
2804 LPARAM lParam;
2806 struct frame *f;
2807 struct w32_display_info *dpyinfo = &one_w32_display_info;
2808 W32Msg wmsg;
2809 int windows_translate;
2810 int key;
2812 /* Note that it is okay to call x_window_to_frame, even though we are
2813 not running in the main lisp thread, because frame deletion
2814 requires the lisp thread to synchronize with this thread. Thus, if
2815 a frame struct is returned, it can be used without concern that the
2816 lisp thread might make it disappear while we are using it.
2818 NB. Walking the frame list in this thread is safe (as long as
2819 writes of Lisp_Object slots are atomic, which they are on Windows).
2820 Although delete-frame can destructively modify the frame list while
2821 we are walking it, a garbage collection cannot occur until after
2822 delete-frame has synchronized with this thread.
2824 It is also safe to use functions that make GDI calls, such as
2825 w32_clear_rect, because these functions must obtain a DC handle
2826 from the frame struct using get_frame_dc which is thread-aware. */
2828 switch (msg)
2830 case WM_ERASEBKGND:
2831 f = x_window_to_frame (dpyinfo, hwnd);
2832 if (f)
2834 HDC hdc = get_frame_dc (f);
2835 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2836 w32_clear_rect (f, hdc, &wmsg.rect);
2837 release_frame_dc (f, hdc);
2839 #if defined (W32_DEBUG_DISPLAY)
2840 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2842 wmsg.rect.left, wmsg.rect.top,
2843 wmsg.rect.right, wmsg.rect.bottom));
2844 #endif /* W32_DEBUG_DISPLAY */
2846 return 1;
2847 case WM_PALETTECHANGED:
2848 /* ignore our own changes */
2849 if ((HWND)wParam != hwnd)
2851 f = x_window_to_frame (dpyinfo, hwnd);
2852 if (f)
2853 /* get_frame_dc will realize our palette and force all
2854 frames to be redrawn if needed. */
2855 release_frame_dc (f, get_frame_dc (f));
2857 return 0;
2858 case WM_PAINT:
2860 PAINTSTRUCT paintStruct;
2861 RECT update_rect;
2862 bzero (&update_rect, sizeof (update_rect));
2864 f = x_window_to_frame (dpyinfo, hwnd);
2865 if (f == 0)
2867 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2868 return 0;
2871 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2872 fails. Apparently this can happen under some
2873 circumstances. */
2874 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2876 enter_crit ();
2877 BeginPaint (hwnd, &paintStruct);
2879 /* The rectangles returned by GetUpdateRect and BeginPaint
2880 do not always match. Play it safe by assuming both areas
2881 are invalid. */
2882 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2884 #if defined (W32_DEBUG_DISPLAY)
2885 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2887 wmsg.rect.left, wmsg.rect.top,
2888 wmsg.rect.right, wmsg.rect.bottom));
2889 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2890 update_rect.left, update_rect.top,
2891 update_rect.right, update_rect.bottom));
2892 #endif
2893 EndPaint (hwnd, &paintStruct);
2894 leave_crit ();
2896 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2898 return 0;
2901 /* If GetUpdateRect returns 0 (meaning there is no update
2902 region), assume the whole window needs to be repainted. */
2903 GetClientRect (hwnd, &wmsg.rect);
2904 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2905 return 0;
2908 case WM_INPUTLANGCHANGE:
2909 /* Inform lisp thread of keyboard layout changes. */
2910 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2912 /* Clear dead keys in the keyboard state; for simplicity only
2913 preserve modifier key states. */
2915 int i;
2916 BYTE keystate[256];
2918 GetKeyboardState (keystate);
2919 for (i = 0; i < 256; i++)
2920 if (1
2921 && i != VK_SHIFT
2922 && i != VK_LSHIFT
2923 && i != VK_RSHIFT
2924 && i != VK_CAPITAL
2925 && i != VK_NUMLOCK
2926 && i != VK_SCROLL
2927 && i != VK_CONTROL
2928 && i != VK_LCONTROL
2929 && i != VK_RCONTROL
2930 && i != VK_MENU
2931 && i != VK_LMENU
2932 && i != VK_RMENU
2933 && i != VK_LWIN
2934 && i != VK_RWIN)
2935 keystate[i] = 0;
2936 SetKeyboardState (keystate);
2938 goto dflt;
2940 case WM_HOTKEY:
2941 /* Synchronize hot keys with normal input. */
2942 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2943 return (0);
2945 case WM_KEYUP:
2946 case WM_SYSKEYUP:
2947 record_keyup (wParam, lParam);
2948 goto dflt;
2950 case WM_KEYDOWN:
2951 case WM_SYSKEYDOWN:
2952 /* Ignore keystrokes we fake ourself; see below. */
2953 if (dpyinfo->faked_key == wParam)
2955 dpyinfo->faked_key = 0;
2956 /* Make sure TranslateMessage sees them though (as long as
2957 they don't produce WM_CHAR messages). This ensures that
2958 indicator lights are toggled promptly on Windows 9x, for
2959 example. */
2960 if (wParam < 256 && lispy_function_keys[wParam])
2962 windows_translate = 1;
2963 goto translate;
2965 return 0;
2968 /* Synchronize modifiers with current keystroke. */
2969 sync_modifiers ();
2970 record_keydown (wParam, lParam);
2971 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2973 windows_translate = 0;
2975 switch (wParam)
2977 case VK_LWIN:
2978 if (NILP (Vw32_pass_lwindow_to_system))
2980 /* Prevent system from acting on keyup (which opens the
2981 Start menu if no other key was pressed) by simulating a
2982 press of Space which we will ignore. */
2983 if (GetAsyncKeyState (wParam) & 1)
2985 if (NUMBERP (Vw32_phantom_key_code))
2986 key = XUINT (Vw32_phantom_key_code) & 255;
2987 else
2988 key = VK_SPACE;
2989 dpyinfo->faked_key = key;
2990 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2993 if (!NILP (Vw32_lwindow_modifier))
2994 return 0;
2995 break;
2996 case VK_RWIN:
2997 if (NILP (Vw32_pass_rwindow_to_system))
2999 if (GetAsyncKeyState (wParam) & 1)
3001 if (NUMBERP (Vw32_phantom_key_code))
3002 key = XUINT (Vw32_phantom_key_code) & 255;
3003 else
3004 key = VK_SPACE;
3005 dpyinfo->faked_key = key;
3006 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3009 if (!NILP (Vw32_rwindow_modifier))
3010 return 0;
3011 break;
3012 case VK_APPS:
3013 if (!NILP (Vw32_apps_modifier))
3014 return 0;
3015 break;
3016 case VK_MENU:
3017 if (NILP (Vw32_pass_alt_to_system))
3018 /* Prevent DefWindowProc from activating the menu bar if an
3019 Alt key is pressed and released by itself. */
3020 return 0;
3021 windows_translate = 1;
3022 break;
3023 case VK_CAPITAL:
3024 /* Decide whether to treat as modifier or function key. */
3025 if (NILP (Vw32_enable_caps_lock))
3026 goto disable_lock_key;
3027 windows_translate = 1;
3028 break;
3029 case VK_NUMLOCK:
3030 /* Decide whether to treat as modifier or function key. */
3031 if (NILP (Vw32_enable_num_lock))
3032 goto disable_lock_key;
3033 windows_translate = 1;
3034 break;
3035 case VK_SCROLL:
3036 /* Decide whether to treat as modifier or function key. */
3037 if (NILP (Vw32_scroll_lock_modifier))
3038 goto disable_lock_key;
3039 windows_translate = 1;
3040 break;
3041 disable_lock_key:
3042 /* Ensure the appropriate lock key state (and indicator light)
3043 remains in the same state. We do this by faking another
3044 press of the relevant key. Apparently, this really is the
3045 only way to toggle the state of the indicator lights. */
3046 dpyinfo->faked_key = wParam;
3047 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3048 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3049 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3050 KEYEVENTF_EXTENDEDKEY | 0, 0);
3051 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3052 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3053 /* Ensure indicator lights are updated promptly on Windows 9x
3054 (TranslateMessage apparently does this), after forwarding
3055 input event. */
3056 post_character_message (hwnd, msg, wParam, lParam,
3057 w32_get_key_modifiers (wParam, lParam));
3058 windows_translate = 1;
3059 break;
3060 case VK_CONTROL:
3061 case VK_SHIFT:
3062 case VK_PROCESSKEY: /* Generated by IME. */
3063 windows_translate = 1;
3064 break;
3065 case VK_CANCEL:
3066 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3067 which is confusing for purposes of key binding; convert
3068 VK_CANCEL events into VK_PAUSE events. */
3069 wParam = VK_PAUSE;
3070 break;
3071 case VK_PAUSE:
3072 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3073 for purposes of key binding; convert these back into
3074 VK_NUMLOCK events, at least when we want to see NumLock key
3075 presses. (Note that there is never any possibility that
3076 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3077 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3078 wParam = VK_NUMLOCK;
3079 break;
3080 default:
3081 /* If not defined as a function key, change it to a WM_CHAR message. */
3082 if (wParam > 255 || !lispy_function_keys[wParam])
3084 DWORD modifiers = construct_console_modifiers ();
3086 if (!NILP (Vw32_recognize_altgr)
3087 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3089 /* Always let TranslateMessage handle AltGr key chords;
3090 for some reason, ToAscii doesn't always process AltGr
3091 chords correctly. */
3092 windows_translate = 1;
3094 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3096 /* Handle key chords including any modifiers other
3097 than shift directly, in order to preserve as much
3098 modifier information as possible. */
3099 if ('A' <= wParam && wParam <= 'Z')
3101 /* Don't translate modified alphabetic keystrokes,
3102 so the user doesn't need to constantly switch
3103 layout to type control or meta keystrokes when
3104 the normal layout translates alphabetic
3105 characters to non-ascii characters. */
3106 if (!modifier_set (VK_SHIFT))
3107 wParam += ('a' - 'A');
3108 msg = WM_CHAR;
3110 else
3112 /* Try to handle other keystrokes by determining the
3113 base character (ie. translating the base key plus
3114 shift modifier). */
3115 int add;
3116 int isdead = 0;
3117 KEY_EVENT_RECORD key;
3119 key.bKeyDown = TRUE;
3120 key.wRepeatCount = 1;
3121 key.wVirtualKeyCode = wParam;
3122 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3123 key.uChar.AsciiChar = 0;
3124 key.dwControlKeyState = modifiers;
3126 add = w32_kbd_patch_key (&key);
3127 /* 0 means an unrecognised keycode, negative means
3128 dead key. Ignore both. */
3129 while (--add >= 0)
3131 /* Forward asciified character sequence. */
3132 post_character_message
3133 (hwnd, WM_CHAR,
3134 (unsigned char) key.uChar.AsciiChar, lParam,
3135 w32_get_key_modifiers (wParam, lParam));
3136 w32_kbd_patch_key (&key);
3138 return 0;
3141 else
3143 /* Let TranslateMessage handle everything else. */
3144 windows_translate = 1;
3149 translate:
3150 if (windows_translate)
3152 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3154 windows_msg.time = GetMessageTime ();
3155 TranslateMessage (&windows_msg);
3156 goto dflt;
3159 /* Fall through */
3161 case WM_SYSCHAR:
3162 case WM_CHAR:
3163 post_character_message (hwnd, msg, wParam, lParam,
3164 w32_get_key_modifiers (wParam, lParam));
3165 break;
3167 /* Simulate middle mouse button events when left and right buttons
3168 are used together, but only if user has two button mouse. */
3169 case WM_LBUTTONDOWN:
3170 case WM_RBUTTONDOWN:
3171 if (w32_num_mouse_buttons > 2)
3172 goto handle_plain_button;
3175 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3176 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3178 if (button_state & this)
3179 return 0;
3181 if (button_state == 0)
3182 SetCapture (hwnd);
3184 button_state |= this;
3186 if (button_state & other)
3188 if (mouse_button_timer)
3190 KillTimer (hwnd, mouse_button_timer);
3191 mouse_button_timer = 0;
3193 /* Generate middle mouse event instead. */
3194 msg = WM_MBUTTONDOWN;
3195 button_state |= MMOUSE;
3197 else if (button_state & MMOUSE)
3199 /* Ignore button event if we've already generated a
3200 middle mouse down event. This happens if the
3201 user releases and press one of the two buttons
3202 after we've faked a middle mouse event. */
3203 return 0;
3205 else
3207 /* Flush out saved message. */
3208 post_msg (&saved_mouse_button_msg);
3210 wmsg.dwModifiers = w32_get_modifiers ();
3211 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3212 signal_user_input ();
3214 /* Clear message buffer. */
3215 saved_mouse_button_msg.msg.hwnd = 0;
3217 else
3219 /* Hold onto message for now. */
3220 mouse_button_timer =
3221 SetTimer (hwnd, MOUSE_BUTTON_ID,
3222 w32_mouse_button_tolerance, NULL);
3223 saved_mouse_button_msg.msg.hwnd = hwnd;
3224 saved_mouse_button_msg.msg.message = msg;
3225 saved_mouse_button_msg.msg.wParam = wParam;
3226 saved_mouse_button_msg.msg.lParam = lParam;
3227 saved_mouse_button_msg.msg.time = GetMessageTime ();
3228 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3231 return 0;
3233 case WM_LBUTTONUP:
3234 case WM_RBUTTONUP:
3235 if (w32_num_mouse_buttons > 2)
3236 goto handle_plain_button;
3239 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3240 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3242 if ((button_state & this) == 0)
3243 return 0;
3245 button_state &= ~this;
3247 if (button_state & MMOUSE)
3249 /* Only generate event when second button is released. */
3250 if ((button_state & other) == 0)
3252 msg = WM_MBUTTONUP;
3253 button_state &= ~MMOUSE;
3255 if (button_state) abort ();
3257 else
3258 return 0;
3260 else
3262 /* Flush out saved message if necessary. */
3263 if (saved_mouse_button_msg.msg.hwnd)
3265 post_msg (&saved_mouse_button_msg);
3268 wmsg.dwModifiers = w32_get_modifiers ();
3269 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3270 signal_user_input ();
3272 /* Always clear message buffer and cancel timer. */
3273 saved_mouse_button_msg.msg.hwnd = 0;
3274 KillTimer (hwnd, mouse_button_timer);
3275 mouse_button_timer = 0;
3277 if (button_state == 0)
3278 ReleaseCapture ();
3280 return 0;
3282 case WM_XBUTTONDOWN:
3283 case WM_XBUTTONUP:
3284 if (w32_pass_extra_mouse_buttons_to_system)
3285 goto dflt;
3286 /* else fall through and process them. */
3287 case WM_MBUTTONDOWN:
3288 case WM_MBUTTONUP:
3289 handle_plain_button:
3291 BOOL up;
3292 int button;
3294 /* Ignore middle and extra buttons as long as the menu is active. */
3295 f = x_window_to_frame (dpyinfo, hwnd);
3296 if (f && f->output_data.w32->menubar_active)
3297 return 0;
3299 if (parse_button (msg, HIWORD (wParam), &button, &up))
3301 if (up) ReleaseCapture ();
3302 else SetCapture (hwnd);
3303 button = (button == 0) ? LMOUSE :
3304 ((button == 1) ? MMOUSE : RMOUSE);
3305 if (up)
3306 button_state &= ~button;
3307 else
3308 button_state |= button;
3312 wmsg.dwModifiers = w32_get_modifiers ();
3313 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3314 signal_user_input ();
3316 /* Need to return true for XBUTTON messages, false for others,
3317 to indicate that we processed the message. */
3318 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3320 case WM_MOUSEMOVE:
3321 /* Ignore mouse movements as long as the menu is active. These
3322 movements are processed by the window manager anyway, and
3323 it's wrong to handle them as if they happened on the
3324 underlying frame. */
3325 f = x_window_to_frame (dpyinfo, hwnd);
3326 if (f && f->output_data.w32->menubar_active)
3327 return 0;
3329 /* If the mouse has just moved into the frame, start tracking
3330 it, so we will be notified when it leaves the frame. Mouse
3331 tracking only works under W98 and NT4 and later. On earlier
3332 versions, there is no way of telling when the mouse leaves the
3333 frame, so we just have to put up with help-echo and mouse
3334 highlighting remaining while the frame is not active. */
3335 if (track_mouse_event_fn && !track_mouse_window)
3337 TRACKMOUSEEVENT tme;
3338 tme.cbSize = sizeof (tme);
3339 tme.dwFlags = TME_LEAVE;
3340 tme.hwndTrack = hwnd;
3342 track_mouse_event_fn (&tme);
3343 track_mouse_window = hwnd;
3345 case WM_VSCROLL:
3346 if (w32_mouse_move_interval <= 0
3347 || (msg == WM_MOUSEMOVE && button_state == 0))
3349 wmsg.dwModifiers = w32_get_modifiers ();
3350 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3351 return 0;
3354 /* Hang onto mouse move and scroll messages for a bit, to avoid
3355 sending such events to Emacs faster than it can process them.
3356 If we get more events before the timer from the first message
3357 expires, we just replace the first message. */
3359 if (saved_mouse_move_msg.msg.hwnd == 0)
3360 mouse_move_timer =
3361 SetTimer (hwnd, MOUSE_MOVE_ID,
3362 w32_mouse_move_interval, NULL);
3364 /* Hold onto message for now. */
3365 saved_mouse_move_msg.msg.hwnd = hwnd;
3366 saved_mouse_move_msg.msg.message = msg;
3367 saved_mouse_move_msg.msg.wParam = wParam;
3368 saved_mouse_move_msg.msg.lParam = lParam;
3369 saved_mouse_move_msg.msg.time = GetMessageTime ();
3370 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3372 return 0;
3374 case WM_MOUSEWHEEL:
3375 wmsg.dwModifiers = w32_get_modifiers ();
3376 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3377 signal_user_input ();
3378 return 0;
3380 case WM_DROPFILES:
3381 wmsg.dwModifiers = w32_get_modifiers ();
3382 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3383 signal_user_input ();
3384 return 0;
3386 case WM_TIMER:
3387 /* Flush out saved messages if necessary. */
3388 if (wParam == mouse_button_timer)
3390 if (saved_mouse_button_msg.msg.hwnd)
3392 post_msg (&saved_mouse_button_msg);
3393 signal_user_input ();
3394 saved_mouse_button_msg.msg.hwnd = 0;
3396 KillTimer (hwnd, mouse_button_timer);
3397 mouse_button_timer = 0;
3399 else if (wParam == mouse_move_timer)
3401 if (saved_mouse_move_msg.msg.hwnd)
3403 post_msg (&saved_mouse_move_msg);
3404 saved_mouse_move_msg.msg.hwnd = 0;
3406 KillTimer (hwnd, mouse_move_timer);
3407 mouse_move_timer = 0;
3409 else if (wParam == menu_free_timer)
3411 KillTimer (hwnd, menu_free_timer);
3412 menu_free_timer = 0;
3413 f = x_window_to_frame (dpyinfo, hwnd);
3414 /* If a popup menu is active, don't wipe its strings. */
3415 if (menubar_in_use
3416 && current_popup_menu == NULL)
3418 /* Free memory used by owner-drawn and help-echo strings. */
3419 w32_free_menu_strings (hwnd);
3420 f->output_data.w32->menubar_active = 0;
3421 menubar_in_use = 0;
3424 return 0;
3426 case WM_NCACTIVATE:
3427 /* Windows doesn't send us focus messages when putting up and
3428 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3429 The only indication we get that something happened is receiving
3430 this message afterwards. So this is a good time to reset our
3431 keyboard modifiers' state. */
3432 reset_modifiers ();
3433 goto dflt;
3435 case WM_INITMENU:
3436 button_state = 0;
3437 ReleaseCapture ();
3438 /* We must ensure menu bar is fully constructed and up to date
3439 before allowing user interaction with it. To achieve this
3440 we send this message to the lisp thread and wait for a
3441 reply (whose value is not actually needed) to indicate that
3442 the menu bar is now ready for use, so we can now return.
3444 To remain responsive in the meantime, we enter a nested message
3445 loop that can process all other messages.
3447 However, we skip all this if the message results from calling
3448 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3449 thread a message because it is blocked on us at this point. We
3450 set menubar_active before calling TrackPopupMenu to indicate
3451 this (there is no possibility of confusion with real menubar
3452 being active). */
3454 f = x_window_to_frame (dpyinfo, hwnd);
3455 if (f
3456 && (f->output_data.w32->menubar_active
3457 /* We can receive this message even in the absence of a
3458 menubar (ie. when the system menu is activated) - in this
3459 case we do NOT want to forward the message, otherwise it
3460 will cause the menubar to suddenly appear when the user
3461 had requested it to be turned off! */
3462 || f->output_data.w32->menubar_widget == NULL))
3463 return 0;
3466 deferred_msg msg_buf;
3468 /* Detect if message has already been deferred; in this case
3469 we cannot return any sensible value to ignore this. */
3470 if (find_deferred_msg (hwnd, msg) != NULL)
3471 abort ();
3473 menubar_in_use = 1;
3475 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3478 case WM_EXITMENULOOP:
3479 f = x_window_to_frame (dpyinfo, hwnd);
3481 /* If a menu is still active, check again after a short delay,
3482 since Windows often (always?) sends the WM_EXITMENULOOP
3483 before the corresponding WM_COMMAND message.
3484 Don't do this if a popup menu is active, since it is only
3485 menubar menus that require cleaning up in this way.
3487 if (f && menubar_in_use && current_popup_menu == NULL)
3488 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3489 goto dflt;
3491 case WM_MENUSELECT:
3492 /* Direct handling of help_echo in menus. Should be safe now
3493 that we generate the help_echo by placing a help event in the
3494 keyboard buffer. */
3496 HMENU menu = (HMENU) lParam;
3497 UINT menu_item = (UINT) LOWORD (wParam);
3498 UINT flags = (UINT) HIWORD (wParam);
3500 w32_menu_display_help (hwnd, menu, menu_item, flags);
3502 return 0;
3504 case WM_MEASUREITEM:
3505 f = x_window_to_frame (dpyinfo, hwnd);
3506 if (f)
3508 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3510 if (pMis->CtlType == ODT_MENU)
3512 /* Work out dimensions for popup menu titles. */
3513 char * title = (char *) pMis->itemData;
3514 HDC hdc = GetDC (hwnd);
3515 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3516 LOGFONT menu_logfont;
3517 HFONT old_font;
3518 SIZE size;
3520 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3521 menu_logfont.lfWeight = FW_BOLD;
3522 menu_font = CreateFontIndirect (&menu_logfont);
3523 old_font = SelectObject (hdc, menu_font);
3525 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3526 if (title)
3528 if (unicode_append_menu)
3529 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3530 wcslen ((WCHAR *) title),
3531 &size);
3532 else
3533 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3535 pMis->itemWidth = size.cx;
3536 if (pMis->itemHeight < size.cy)
3537 pMis->itemHeight = size.cy;
3539 else
3540 pMis->itemWidth = 0;
3542 SelectObject (hdc, old_font);
3543 DeleteObject (menu_font);
3544 ReleaseDC (hwnd, hdc);
3545 return TRUE;
3548 return 0;
3550 case WM_DRAWITEM:
3551 f = x_window_to_frame (dpyinfo, hwnd);
3552 if (f)
3554 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3556 if (pDis->CtlType == ODT_MENU)
3558 /* Draw popup menu title. */
3559 char * title = (char *) pDis->itemData;
3560 if (title)
3562 HDC hdc = pDis->hDC;
3563 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3564 LOGFONT menu_logfont;
3565 HFONT old_font;
3567 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3568 menu_logfont.lfWeight = FW_BOLD;
3569 menu_font = CreateFontIndirect (&menu_logfont);
3570 old_font = SelectObject (hdc, menu_font);
3572 /* Always draw title as if not selected. */
3573 if (unicode_append_menu)
3574 ExtTextOutW (hdc,
3575 pDis->rcItem.left
3576 + GetSystemMetrics (SM_CXMENUCHECK),
3577 pDis->rcItem.top,
3578 ETO_OPAQUE, &pDis->rcItem,
3579 (WCHAR *) title,
3580 wcslen ((WCHAR *) title), NULL);
3581 else
3582 ExtTextOut (hdc,
3583 pDis->rcItem.left
3584 + GetSystemMetrics (SM_CXMENUCHECK),
3585 pDis->rcItem.top,
3586 ETO_OPAQUE, &pDis->rcItem,
3587 title, strlen (title), NULL);
3589 SelectObject (hdc, old_font);
3590 DeleteObject (menu_font);
3592 return TRUE;
3595 return 0;
3597 #if 0
3598 /* Still not right - can't distinguish between clicks in the
3599 client area of the frame from clicks forwarded from the scroll
3600 bars - may have to hook WM_NCHITTEST to remember the mouse
3601 position and then check if it is in the client area ourselves. */
3602 case WM_MOUSEACTIVATE:
3603 /* Discard the mouse click that activates a frame, allowing the
3604 user to click anywhere without changing point (or worse!).
3605 Don't eat mouse clicks on scrollbars though!! */
3606 if (LOWORD (lParam) == HTCLIENT )
3607 return MA_ACTIVATEANDEAT;
3608 goto dflt;
3609 #endif
3611 case WM_MOUSELEAVE:
3612 /* No longer tracking mouse. */
3613 track_mouse_window = NULL;
3615 case WM_ACTIVATEAPP:
3616 case WM_ACTIVATE:
3617 case WM_WINDOWPOSCHANGED:
3618 case WM_SHOWWINDOW:
3619 /* Inform lisp thread that a frame might have just been obscured
3620 or exposed, so should recheck visibility of all frames. */
3621 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3622 goto dflt;
3624 case WM_SETFOCUS:
3625 dpyinfo->faked_key = 0;
3626 reset_modifiers ();
3627 register_hot_keys (hwnd);
3628 goto command;
3629 case WM_KILLFOCUS:
3630 unregister_hot_keys (hwnd);
3631 button_state = 0;
3632 ReleaseCapture ();
3633 /* Relinquish the system caret. */
3634 if (w32_system_caret_hwnd)
3636 w32_visible_system_caret_hwnd = NULL;
3637 w32_system_caret_hwnd = NULL;
3638 DestroyCaret ();
3640 goto command;
3641 case WM_COMMAND:
3642 menubar_in_use = 0;
3643 f = x_window_to_frame (dpyinfo, hwnd);
3644 if (f && HIWORD (wParam) == 0)
3646 if (menu_free_timer)
3648 KillTimer (hwnd, menu_free_timer);
3649 menu_free_timer = 0;
3652 case WM_MOVE:
3653 case WM_SIZE:
3654 command:
3655 wmsg.dwModifiers = w32_get_modifiers ();
3656 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3657 goto dflt;
3659 case WM_DESTROY:
3660 CoUninitialize ();
3661 return 0;
3663 case WM_CLOSE:
3664 wmsg.dwModifiers = w32_get_modifiers ();
3665 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3666 return 0;
3668 case WM_WINDOWPOSCHANGING:
3669 /* Don't restrict the sizing of tip frames. */
3670 if (hwnd == tip_window)
3671 return 0;
3673 WINDOWPLACEMENT wp;
3674 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3676 wp.length = sizeof (WINDOWPLACEMENT);
3677 GetWindowPlacement (hwnd, &wp);
3679 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
3681 RECT rect;
3682 int wdiff;
3683 int hdiff;
3684 DWORD font_width;
3685 DWORD line_height;
3686 DWORD internal_border;
3687 DWORD scrollbar_extra;
3688 RECT wr;
3690 wp.length = sizeof (wp);
3691 GetWindowRect (hwnd, &wr);
3693 enter_crit ();
3695 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3696 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3697 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3698 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3700 leave_crit ();
3702 memset (&rect, 0, sizeof (rect));
3703 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3704 GetMenu (hwnd) != NULL);
3706 /* Force width and height of client area to be exact
3707 multiples of the character cell dimensions. */
3708 wdiff = (lppos->cx - (rect.right - rect.left)
3709 - 2 * internal_border - scrollbar_extra)
3710 % font_width;
3711 hdiff = (lppos->cy - (rect.bottom - rect.top)
3712 - 2 * internal_border)
3713 % line_height;
3715 if (wdiff || hdiff)
3717 /* For right/bottom sizing we can just fix the sizes.
3718 However for top/left sizing we will need to fix the X
3719 and Y positions as well. */
3721 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3722 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3724 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3725 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3727 if (wp.showCmd != SW_SHOWMAXIMIZED
3728 && (lppos->flags & SWP_NOMOVE) == 0)
3730 if (lppos->x != wr.left || lppos->y != wr.top)
3732 lppos->x += wdiff;
3733 lppos->y += hdiff;
3735 else
3737 lppos->flags |= SWP_NOMOVE;
3741 return 0;
3746 goto dflt;
3748 case WM_GETMINMAXINFO:
3749 /* Hack to allow resizing the Emacs frame above the screen size.
3750 Note that Windows 9x limits coordinates to 16-bits. */
3751 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3752 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3753 return 0;
3755 case WM_SETCURSOR:
3756 if (LOWORD (lParam) == HTCLIENT)
3757 return 0;
3759 goto dflt;
3761 case WM_EMACS_SETCURSOR:
3763 Cursor cursor = (Cursor) wParam;
3764 if (cursor)
3765 SetCursor (cursor);
3766 return 0;
3769 case WM_EMACS_CREATESCROLLBAR:
3770 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3771 (struct scroll_bar *) lParam);
3773 case WM_EMACS_SHOWWINDOW:
3774 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3776 case WM_EMACS_SETFOREGROUND:
3778 HWND foreground_window;
3779 DWORD foreground_thread, retval;
3781 /* On NT 5.0, and apparently Windows 98, it is necessary to
3782 attach to the thread that currently has focus in order to
3783 pull the focus away from it. */
3784 foreground_window = GetForegroundWindow ();
3785 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3786 if (!foreground_window
3787 || foreground_thread == GetCurrentThreadId ()
3788 || !AttachThreadInput (GetCurrentThreadId (),
3789 foreground_thread, TRUE))
3790 foreground_thread = 0;
3792 retval = SetForegroundWindow ((HWND) wParam);
3794 /* Detach from the previous foreground thread. */
3795 if (foreground_thread)
3796 AttachThreadInput (GetCurrentThreadId (),
3797 foreground_thread, FALSE);
3799 return retval;
3802 case WM_EMACS_SETWINDOWPOS:
3804 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3805 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3806 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3809 case WM_EMACS_DESTROYWINDOW:
3810 DragAcceptFiles ((HWND) wParam, FALSE);
3811 return DestroyWindow ((HWND) wParam);
3813 case WM_EMACS_HIDE_CARET:
3814 return HideCaret (hwnd);
3816 case WM_EMACS_SHOW_CARET:
3817 return ShowCaret (hwnd);
3819 case WM_EMACS_DESTROY_CARET:
3820 w32_system_caret_hwnd = NULL;
3821 w32_visible_system_caret_hwnd = NULL;
3822 return DestroyCaret ();
3824 case WM_EMACS_TRACK_CARET:
3825 /* If there is currently no system caret, create one. */
3826 if (w32_system_caret_hwnd == NULL)
3828 /* Use the default caret width, and avoid changing it
3829 unneccesarily, as it confuses screen reader software. */
3830 w32_system_caret_hwnd = hwnd;
3831 CreateCaret (hwnd, NULL, 0,
3832 w32_system_caret_height);
3835 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3836 return 0;
3837 /* Ensure visible caret gets turned on when requested. */
3838 else if (w32_use_visible_system_caret
3839 && w32_visible_system_caret_hwnd != hwnd)
3841 w32_visible_system_caret_hwnd = hwnd;
3842 return ShowCaret (hwnd);
3844 /* Ensure visible caret gets turned off when requested. */
3845 else if (!w32_use_visible_system_caret
3846 && w32_visible_system_caret_hwnd)
3848 w32_visible_system_caret_hwnd = NULL;
3849 return HideCaret (hwnd);
3851 else
3852 return 1;
3854 case WM_EMACS_TRACKPOPUPMENU:
3856 UINT flags;
3857 POINT *pos;
3858 int retval;
3859 pos = (POINT *)lParam;
3860 flags = TPM_CENTERALIGN;
3861 if (button_state & LMOUSE)
3862 flags |= TPM_LEFTBUTTON;
3863 else if (button_state & RMOUSE)
3864 flags |= TPM_RIGHTBUTTON;
3866 /* Remember we did a SetCapture on the initial mouse down event,
3867 so for safety, we make sure the capture is cancelled now. */
3868 ReleaseCapture ();
3869 button_state = 0;
3871 /* Use menubar_active to indicate that WM_INITMENU is from
3872 TrackPopupMenu below, and should be ignored. */
3873 f = x_window_to_frame (dpyinfo, hwnd);
3874 if (f)
3875 f->output_data.w32->menubar_active = 1;
3877 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
3878 0, hwnd, NULL))
3880 MSG amsg;
3881 /* Eat any mouse messages during popupmenu */
3882 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
3883 PM_REMOVE));
3884 /* Get the menu selection, if any */
3885 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
3887 retval = LOWORD (amsg.wParam);
3889 else
3891 retval = 0;
3894 else
3896 retval = -1;
3899 return retval;
3902 default:
3903 /* Check for messages registered at runtime. */
3904 if (msg == msh_mousewheel)
3906 wmsg.dwModifiers = w32_get_modifiers ();
3907 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3908 signal_user_input ();
3909 return 0;
3912 dflt:
3913 return DefWindowProc (hwnd, msg, wParam, lParam);
3917 /* The most common default return code for handled messages is 0. */
3918 return 0;
3921 static void
3922 my_create_window (f)
3923 struct frame * f;
3925 MSG msg;
3927 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
3928 abort ();
3929 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
3933 /* Create a tooltip window. Unlike my_create_window, we do not do this
3934 indirectly via the Window thread, as we do not need to process Window
3935 messages for the tooltip. Creating tooltips indirectly also creates
3936 deadlocks when tooltips are created for menu items. */
3937 static void
3938 my_create_tip_window (f)
3939 struct frame *f;
3941 RECT rect;
3943 rect.left = rect.top = 0;
3944 rect.right = FRAME_PIXEL_WIDTH (f);
3945 rect.bottom = FRAME_PIXEL_HEIGHT (f);
3947 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3948 FRAME_EXTERNAL_MENU_BAR (f));
3950 tip_window = FRAME_W32_WINDOW (f)
3951 = CreateWindow (EMACS_CLASS,
3952 f->namebuf,
3953 f->output_data.w32->dwStyle,
3954 f->left_pos,
3955 f->top_pos,
3956 rect.right - rect.left,
3957 rect.bottom - rect.top,
3958 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
3959 NULL,
3960 hinst,
3961 NULL);
3963 if (tip_window)
3965 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
3966 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
3967 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
3968 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3970 /* Tip frames have no scrollbars. */
3971 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
3973 /* Do this to discard the default setting specified by our parent. */
3974 ShowWindow (tip_window, SW_HIDE);
3979 /* Create and set up the w32 window for frame F. */
3981 static void
3982 w32_window (f, window_prompting, minibuffer_only)
3983 struct frame *f;
3984 long window_prompting;
3985 int minibuffer_only;
3987 BLOCK_INPUT;
3989 /* Use the resource name as the top-level window name
3990 for looking up resources. Make a non-Lisp copy
3991 for the window manager, so GC relocation won't bother it.
3993 Elsewhere we specify the window name for the window manager. */
3996 char *str = (char *) SDATA (Vx_resource_name);
3997 f->namebuf = (char *) xmalloc (strlen (str) + 1);
3998 strcpy (f->namebuf, str);
4001 my_create_window (f);
4003 validate_x_resource_name ();
4005 /* x_set_name normally ignores requests to set the name if the
4006 requested name is the same as the current name. This is the one
4007 place where that assumption isn't correct; f->name is set, but
4008 the server hasn't been told. */
4010 Lisp_Object name;
4011 int explicit = f->explicit_name;
4013 f->explicit_name = 0;
4014 name = f->name;
4015 f->name = Qnil;
4016 x_set_name (f, name, explicit);
4019 UNBLOCK_INPUT;
4021 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4022 initialize_frame_menubar (f);
4024 if (FRAME_W32_WINDOW (f) == 0)
4025 error ("Unable to create window");
4028 /* Handle the icon stuff for this window. Perhaps later we might
4029 want an x_set_icon_position which can be called interactively as
4030 well. */
4032 static void
4033 x_icon (f, parms)
4034 struct frame *f;
4035 Lisp_Object parms;
4037 Lisp_Object icon_x, icon_y;
4039 /* Set the position of the icon. Note that Windows 95 groups all
4040 icons in the tray. */
4041 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4042 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4043 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4045 CHECK_NUMBER (icon_x);
4046 CHECK_NUMBER (icon_y);
4048 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4049 error ("Both left and top icon corners of icon must be specified");
4051 BLOCK_INPUT;
4053 if (! EQ (icon_x, Qunbound))
4054 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4056 #if 0 /* TODO */
4057 /* Start up iconic or window? */
4058 x_wm_set_window_state
4059 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4060 ? IconicState
4061 : NormalState));
4063 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
4064 ? f->icon_name
4065 : f->name)));
4066 #endif
4068 UNBLOCK_INPUT;
4072 static void
4073 x_make_gc (f)
4074 struct frame *f;
4076 XGCValues gc_values;
4078 BLOCK_INPUT;
4080 /* Create the GC's of this frame.
4081 Note that many default values are used. */
4083 /* Normal video */
4084 gc_values.font = FRAME_FONT (f);
4086 /* Cursor has cursor-color background, background-color foreground. */
4087 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4088 gc_values.background = f->output_data.w32->cursor_pixel;
4089 f->output_data.w32->cursor_gc
4090 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4091 (GCFont | GCForeground | GCBackground),
4092 &gc_values);
4094 /* Reliefs. */
4095 f->output_data.w32->white_relief.gc = 0;
4096 f->output_data.w32->black_relief.gc = 0;
4098 UNBLOCK_INPUT;
4102 /* Handler for signals raised during x_create_frame and
4103 x_create_top_frame. FRAME is the frame which is partially
4104 constructed. */
4106 static Lisp_Object
4107 unwind_create_frame (frame)
4108 Lisp_Object frame;
4110 struct frame *f = XFRAME (frame);
4112 /* If frame is ``official'', nothing to do. */
4113 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
4115 #ifdef GLYPH_DEBUG
4116 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4117 #endif
4119 x_free_frame_resources (f);
4121 /* Check that reference counts are indeed correct. */
4122 xassert (dpyinfo->reference_count == dpyinfo_refcount);
4123 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
4125 return Qt;
4128 return Qnil;
4132 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4133 1, 1, 0,
4134 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4135 Return an Emacs frame object.
4136 PARAMETERS is an alist of frame parameters.
4137 If the parameters specify that the frame should not have a minibuffer,
4138 and do not specify a specific minibuffer window to use,
4139 then `default-minibuffer-frame' must be a frame whose minibuffer can
4140 be shared by the new frame.
4142 This function is an internal primitive--use `make-frame' instead. */)
4143 (parameters)
4144 Lisp_Object parameters;
4146 struct frame *f;
4147 Lisp_Object frame, tem;
4148 Lisp_Object name;
4149 int minibuffer_only = 0;
4150 long window_prompting = 0;
4151 int width, height;
4152 int count = SPECPDL_INDEX ();
4153 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4154 Lisp_Object display;
4155 struct w32_display_info *dpyinfo = NULL;
4156 Lisp_Object parent;
4157 struct kboard *kb;
4159 check_w32 ();
4161 /* Use this general default value to start with
4162 until we know if this frame has a specified name. */
4163 Vx_resource_name = Vinvocation_name;
4165 display = w32_get_arg (parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4166 if (EQ (display, Qunbound))
4167 display = Qnil;
4168 dpyinfo = check_x_display_info (display);
4169 #ifdef MULTI_KBOARD
4170 kb = dpyinfo->kboard;
4171 #else
4172 kb = &the_only_kboard;
4173 #endif
4175 name = w32_get_arg (parameters, Qname, "name", "Name", RES_TYPE_STRING);
4176 if (!STRINGP (name)
4177 && ! EQ (name, Qunbound)
4178 && ! NILP (name))
4179 error ("Invalid frame name--not a string or nil");
4181 if (STRINGP (name))
4182 Vx_resource_name = name;
4184 /* See if parent window is specified. */
4185 parent = w32_get_arg (parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4186 if (EQ (parent, Qunbound))
4187 parent = Qnil;
4188 if (! NILP (parent))
4189 CHECK_NUMBER (parent);
4191 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4192 /* No need to protect DISPLAY because that's not used after passing
4193 it to make_frame_without_minibuffer. */
4194 frame = Qnil;
4195 GCPRO4 (parameters, parent, name, frame);
4196 tem = w32_get_arg (parameters, Qminibuffer, "minibuffer", "Minibuffer",
4197 RES_TYPE_SYMBOL);
4198 if (EQ (tem, Qnone) || NILP (tem))
4199 f = make_frame_without_minibuffer (Qnil, kb, display);
4200 else if (EQ (tem, Qonly))
4202 f = make_minibuffer_frame ();
4203 minibuffer_only = 1;
4205 else if (WINDOWP (tem))
4206 f = make_frame_without_minibuffer (tem, kb, display);
4207 else
4208 f = make_frame (1);
4210 XSETFRAME (frame, f);
4212 /* Note that Windows does support scroll bars. */
4213 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
4215 /* By default, make scrollbars the system standard width. */
4216 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4218 f->output_method = output_w32;
4219 f->output_data.w32 =
4220 (struct w32_output *) xmalloc (sizeof (struct w32_output));
4221 bzero (f->output_data.w32, sizeof (struct w32_output));
4222 FRAME_FONTSET (f) = -1;
4223 record_unwind_protect (unwind_create_frame, frame);
4225 f->icon_name
4226 = w32_get_arg (parameters, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
4227 if (! STRINGP (f->icon_name))
4228 f->icon_name = Qnil;
4230 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
4231 #ifdef MULTI_KBOARD
4232 FRAME_KBOARD (f) = kb;
4233 #endif
4235 /* Specify the parent under which to make this window. */
4237 if (!NILP (parent))
4239 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4240 f->output_data.w32->explicit_parent = 1;
4242 else
4244 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4245 f->output_data.w32->explicit_parent = 0;
4248 /* Set the name; the functions to which we pass f expect the name to
4249 be set. */
4250 if (EQ (name, Qunbound) || NILP (name))
4252 f->name = build_string (dpyinfo->w32_id_name);
4253 f->explicit_name = 0;
4255 else
4257 f->name = name;
4258 f->explicit_name = 1;
4259 /* use the frame's title when getting resources for this frame. */
4260 specbind (Qx_resource_name, name);
4263 /* Extract the window parameters from the supplied values
4264 that are needed to determine window geometry. */
4266 Lisp_Object font;
4268 font = w32_get_arg (parameters, Qfont, "font", "Font", RES_TYPE_STRING);
4270 BLOCK_INPUT;
4271 /* First, try whatever font the caller has specified. */
4272 if (STRINGP (font))
4274 tem = Fquery_fontset (font, Qnil);
4275 if (STRINGP (tem))
4276 font = x_new_fontset (f, SDATA (tem));
4277 else
4278 font = x_new_font (f, SDATA (font));
4280 /* Try out a font which we hope has bold and italic variations. */
4281 if (!STRINGP (font))
4282 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
4283 if (! STRINGP (font))
4284 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
4285 /* If those didn't work, look for something which will at least work. */
4286 if (! STRINGP (font))
4287 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
4288 UNBLOCK_INPUT;
4289 if (! STRINGP (font))
4290 font = build_string ("Fixedsys");
4292 x_default_parameter (f, parameters, Qfont, font,
4293 "font", "Font", RES_TYPE_STRING);
4296 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4297 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4298 /* This defaults to 2 in order to match xterm. We recognize either
4299 internalBorderWidth or internalBorder (which is what xterm calls
4300 it). */
4301 if (NILP (Fassq (Qinternal_border_width, parameters)))
4303 Lisp_Object value;
4305 value = w32_get_arg (parameters, Qinternal_border_width,
4306 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4307 if (! EQ (value, Qunbound))
4308 parameters = Fcons (Fcons (Qinternal_border_width, value),
4309 parameters);
4311 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4312 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4313 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4314 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4315 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4317 /* Also do the stuff which must be set before the window exists. */
4318 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4319 "foreground", "Foreground", RES_TYPE_STRING);
4320 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4321 "background", "Background", RES_TYPE_STRING);
4322 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4323 "pointerColor", "Foreground", RES_TYPE_STRING);
4324 x_default_parameter (f, parameters, Qcursor_color, build_string ("black"),
4325 "cursorColor", "Foreground", RES_TYPE_STRING);
4326 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4327 "borderColor", "BorderColor", RES_TYPE_STRING);
4328 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4329 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4330 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4331 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4332 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4333 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4334 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4335 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4338 /* Init faces before x_default_parameter is called for scroll-bar
4339 parameters because that function calls x_set_scroll_bar_width,
4340 which calls change_frame_size, which calls Fset_window_buffer,
4341 which runs hooks, which call Fvertical_motion. At the end, we
4342 end up in init_iterator with a null face cache, which should not
4343 happen. */
4344 init_frame_faces (f);
4346 x_default_parameter (f, parameters, Qmenu_bar_lines, make_number (1),
4347 "menuBar", "MenuBar", RES_TYPE_NUMBER);
4348 x_default_parameter (f, parameters, Qtool_bar_lines, make_number (1),
4349 "toolBar", "ToolBar", RES_TYPE_NUMBER);
4351 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4352 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4353 x_default_parameter (f, parameters, Qtitle, Qnil,
4354 "title", "Title", RES_TYPE_STRING);
4355 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4356 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4358 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4359 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4361 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4362 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4363 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4364 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4365 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4366 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4368 window_prompting = x_figure_window_size (f, parameters, 1);
4370 tem = w32_get_arg (parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4371 f->no_split = minibuffer_only || EQ (tem, Qt);
4373 w32_window (f, window_prompting, minibuffer_only);
4374 x_icon (f, parameters);
4376 x_make_gc (f);
4378 /* Now consider the frame official. */
4379 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
4380 Vframe_list = Fcons (frame, Vframe_list);
4382 /* We need to do this after creating the window, so that the
4383 icon-creation functions can say whose icon they're describing. */
4384 x_default_parameter (f, parameters, Qicon_type, Qnil,
4385 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4387 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4388 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4389 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4390 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4391 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4392 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4393 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4394 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4396 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4397 Change will not be effected unless different from the current
4398 FRAME_LINES (f). */
4399 width = FRAME_COLS (f);
4400 height = FRAME_LINES (f);
4402 FRAME_LINES (f) = 0;
4403 SET_FRAME_COLS (f, 0);
4404 change_frame_size (f, height, width, 1, 0, 0);
4406 /* Tell the server what size and position, etc, we want, and how
4407 badly we want them. This should be done after we have the menu
4408 bar so that its size can be taken into account. */
4409 BLOCK_INPUT;
4410 x_wm_set_size_hint (f, window_prompting, 0);
4411 UNBLOCK_INPUT;
4413 /* Make the window appear on the frame and enable display, unless
4414 the caller says not to. However, with explicit parent, Emacs
4415 cannot control visibility, so don't try. */
4416 if (! f->output_data.w32->explicit_parent)
4418 Lisp_Object visibility;
4420 visibility = w32_get_arg (parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4421 if (EQ (visibility, Qunbound))
4422 visibility = Qt;
4424 if (EQ (visibility, Qicon))
4425 x_iconify_frame (f);
4426 else if (! NILP (visibility))
4427 x_make_frame_visible (f);
4428 else
4429 /* Must have been Qnil. */
4432 UNGCPRO;
4434 /* Make sure windows on this frame appear in calls to next-window
4435 and similar functions. */
4436 Vwindow_list = Qnil;
4438 return unbind_to (count, frame);
4441 /* FRAME is used only to get a handle on the X display. We don't pass the
4442 display info directly because we're called from frame.c, which doesn't
4443 know about that structure. */
4444 Lisp_Object
4445 x_get_focus_frame (frame)
4446 struct frame *frame;
4448 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
4449 Lisp_Object xfocus;
4450 if (! dpyinfo->w32_focus_frame)
4451 return Qnil;
4453 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4454 return xfocus;
4457 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
4458 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
4459 (frame)
4460 Lisp_Object frame;
4462 x_focus_on_frame (check_x_frame (frame));
4463 return Qnil;
4467 /* Return the charset portion of a font name. */
4468 char *
4469 xlfd_charset_of_font (char * fontname)
4471 char *charset, *encoding;
4473 encoding = strrchr (fontname, '-');
4474 if (!encoding || encoding == fontname)
4475 return NULL;
4477 for (charset = encoding - 1; charset >= fontname; charset--)
4478 if (*charset == '-')
4479 break;
4481 if (charset == fontname || strcmp (charset, "-*-*") == 0)
4482 return NULL;
4484 return charset + 1;
4487 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
4488 int size, char* filename);
4489 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
4490 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
4491 char * charset);
4492 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
4494 static struct font_info *
4495 w32_load_system_font (f, fontname, size)
4496 struct frame *f;
4497 char * fontname;
4498 int size;
4500 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4501 Lisp_Object font_names;
4503 /* Get a list of all the fonts that match this name. Once we
4504 have a list of matching fonts, we compare them against the fonts
4505 we already have loaded by comparing names. */
4506 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
4508 if (!NILP (font_names))
4510 Lisp_Object tail;
4511 int i;
4513 /* First check if any are already loaded, as that is cheaper
4514 than loading another one. */
4515 for (i = 0; i < dpyinfo->n_fonts; i++)
4516 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
4517 if (dpyinfo->font_table[i].name
4518 && (!strcmp (dpyinfo->font_table[i].name,
4519 SDATA (XCAR (tail)))
4520 || !strcmp (dpyinfo->font_table[i].full_name,
4521 SDATA (XCAR (tail)))))
4522 return (dpyinfo->font_table + i);
4524 fontname = (char *) SDATA (XCAR (font_names));
4526 else if (w32_strict_fontnames)
4528 /* If EnumFontFamiliesEx was available, we got a full list of
4529 fonts back so stop now to avoid the possibility of loading a
4530 random font. If we had to fall back to EnumFontFamilies, the
4531 list is incomplete, so continue whether the font we want was
4532 listed or not. */
4533 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
4534 FARPROC enum_font_families_ex
4535 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
4536 if (enum_font_families_ex)
4537 return NULL;
4540 /* Load the font and add it to the table. */
4542 char *full_name, *encoding, *charset;
4543 XFontStruct *font;
4544 struct font_info *fontp;
4545 LOGFONT lf;
4546 BOOL ok;
4547 int codepage;
4548 int i;
4550 if (!fontname || !x_to_w32_font (fontname, &lf))
4551 return (NULL);
4553 if (!*lf.lfFaceName)
4554 /* If no name was specified for the font, we get a random font
4555 from CreateFontIndirect - this is not particularly
4556 desirable, especially since CreateFontIndirect does not
4557 fill out the missing name in lf, so we never know what we
4558 ended up with. */
4559 return NULL;
4561 lf.lfQuality = DEFAULT_QUALITY;
4563 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
4564 bzero (font, sizeof (*font));
4566 /* Set bdf to NULL to indicate that this is a Windows font. */
4567 font->bdf = NULL;
4569 BLOCK_INPUT;
4571 font->hfont = CreateFontIndirect (&lf);
4573 if (font->hfont == NULL)
4575 ok = FALSE;
4577 else
4579 HDC hdc;
4580 HANDLE oldobj;
4582 codepage = w32_codepage_for_font (fontname);
4584 hdc = GetDC (dpyinfo->root_window);
4585 oldobj = SelectObject (hdc, font->hfont);
4587 ok = GetTextMetrics (hdc, &font->tm);
4588 if (codepage == CP_UNICODE)
4589 font->double_byte_p = 1;
4590 else
4592 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
4593 don't report themselves as double byte fonts, when
4594 patently they are. So instead of trusting
4595 GetFontLanguageInfo, we check the properties of the
4596 codepage directly, since that is ultimately what we are
4597 working from anyway. */
4598 /* font->double_byte_p = GetFontLanguageInfo (hdc) & GCP_DBCS; */
4599 CPINFO cpi = {0};
4600 GetCPInfo (codepage, &cpi);
4601 font->double_byte_p = cpi.MaxCharSize > 1;
4604 SelectObject (hdc, oldobj);
4605 ReleaseDC (dpyinfo->root_window, hdc);
4606 /* Fill out details in lf according to the font that was
4607 actually loaded. */
4608 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
4609 lf.lfWidth = font->tm.tmMaxCharWidth;
4610 lf.lfWeight = font->tm.tmWeight;
4611 lf.lfItalic = font->tm.tmItalic;
4612 lf.lfCharSet = font->tm.tmCharSet;
4613 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
4614 ? VARIABLE_PITCH : FIXED_PITCH);
4615 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
4616 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
4618 w32_cache_char_metrics (font);
4621 UNBLOCK_INPUT;
4623 if (!ok)
4625 w32_unload_font (dpyinfo, font);
4626 return (NULL);
4629 /* Find a free slot in the font table. */
4630 for (i = 0; i < dpyinfo->n_fonts; ++i)
4631 if (dpyinfo->font_table[i].name == NULL)
4632 break;
4634 /* If no free slot found, maybe enlarge the font table. */
4635 if (i == dpyinfo->n_fonts
4636 && dpyinfo->n_fonts == dpyinfo->font_table_size)
4638 int sz;
4639 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
4640 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
4641 dpyinfo->font_table
4642 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
4645 fontp = dpyinfo->font_table + i;
4646 if (i == dpyinfo->n_fonts)
4647 ++dpyinfo->n_fonts;
4649 /* Now fill in the slots of *FONTP. */
4650 BLOCK_INPUT;
4651 bzero (fontp, sizeof (*fontp));
4652 fontp->font = font;
4653 fontp->font_idx = i;
4654 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
4655 bcopy (fontname, fontp->name, strlen (fontname) + 1);
4657 if (lf.lfPitchAndFamily == FIXED_PITCH)
4659 /* Fixed width font. */
4660 fontp->average_width = fontp->space_width = FONT_WIDTH (font);
4662 else
4664 wchar_t space = 32;
4665 XCharStruct* pcm;
4666 pcm = w32_per_char_metric (font, &space, ANSI_FONT);
4667 if (pcm)
4668 fontp->space_width = pcm->width;
4669 else
4670 fontp->space_width = FONT_WIDTH (font);
4672 fontp->average_width = font->tm.tmAveCharWidth;
4675 charset = xlfd_charset_of_font (fontname);
4677 /* Cache the W32 codepage for a font. This makes w32_encode_char
4678 (called for every glyph during redisplay) much faster. */
4679 fontp->codepage = codepage;
4681 /* Work out the font's full name. */
4682 full_name = (char *)xmalloc (100);
4683 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
4684 fontp->full_name = full_name;
4685 else
4687 /* If all else fails - just use the name we used to load it. */
4688 xfree (full_name);
4689 fontp->full_name = fontp->name;
4692 fontp->size = FONT_WIDTH (font);
4693 fontp->height = FONT_HEIGHT (font);
4695 /* The slot `encoding' specifies how to map a character
4696 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
4697 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
4698 (0:0x20..0x7F, 1:0xA0..0xFF,
4699 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
4700 2:0xA020..0xFF7F). For the moment, we don't know which charset
4701 uses this font. So, we set information in fontp->encoding[1]
4702 which is never used by any charset. If mapping can't be
4703 decided, set FONT_ENCODING_NOT_DECIDED. */
4705 /* SJIS fonts need to be set to type 4, all others seem to work as
4706 type FONT_ENCODING_NOT_DECIDED. */
4707 encoding = strrchr (fontp->name, '-');
4708 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
4709 fontp->encoding[1] = 4;
4710 else
4711 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
4713 /* The following three values are set to 0 under W32, which is
4714 what they get set to if XGetFontProperty fails under X. */
4715 fontp->baseline_offset = 0;
4716 fontp->relative_compose = 0;
4717 fontp->default_ascent = 0;
4719 /* Set global flag fonts_changed_p to non-zero if the font loaded
4720 has a character with a smaller width than any other character
4721 before, or if the font loaded has a smaller height than any
4722 other font loaded before. If this happens, it will make a
4723 glyph matrix reallocation necessary. */
4724 fonts_changed_p |= x_compute_min_glyph_bounds (f);
4725 UNBLOCK_INPUT;
4726 return fontp;
4730 /* Load font named FONTNAME of size SIZE for frame F, and return a
4731 pointer to the structure font_info while allocating it dynamically.
4732 If loading fails, return NULL. */
4733 struct font_info *
4734 w32_load_font (f, fontname, size)
4735 struct frame *f;
4736 char * fontname;
4737 int size;
4739 Lisp_Object bdf_fonts;
4740 struct font_info *retval = NULL;
4741 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4743 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
4745 while (!retval && CONSP (bdf_fonts))
4747 char *bdf_name, *bdf_file;
4748 Lisp_Object bdf_pair;
4749 int i;
4751 bdf_name = SDATA (XCAR (bdf_fonts));
4752 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
4753 bdf_file = SDATA (XCDR (bdf_pair));
4755 // If the font is already loaded, do not load it again.
4756 for (i = 0; i < dpyinfo->n_fonts; i++)
4758 if ((dpyinfo->font_table[i].name
4759 && !strcmp (dpyinfo->font_table[i].name, bdf_name))
4760 || (dpyinfo->font_table[i].full_name
4761 && !strcmp (dpyinfo->font_table[i].full_name, bdf_name)))
4762 return dpyinfo->font_table + i;
4765 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
4767 bdf_fonts = XCDR (bdf_fonts);
4770 if (retval)
4771 return retval;
4773 return w32_load_system_font (f, fontname, size);
4777 void
4778 w32_unload_font (dpyinfo, font)
4779 struct w32_display_info *dpyinfo;
4780 XFontStruct * font;
4782 if (font)
4784 if (font->per_char) xfree (font->per_char);
4785 if (font->bdf) w32_free_bdf_font (font->bdf);
4787 if (font->hfont) DeleteObject (font->hfont);
4788 xfree (font);
4792 /* The font conversion stuff between x and w32 */
4794 /* X font string is as follows (from faces.el)
4795 * (let ((- "[-?]")
4796 * (foundry "[^-]+")
4797 * (family "[^-]+")
4798 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
4799 * (weight\? "\\([^-]*\\)") ; 1
4800 * (slant "\\([ior]\\)") ; 2
4801 * (slant\? "\\([^-]?\\)") ; 2
4802 * (swidth "\\([^-]*\\)") ; 3
4803 * (adstyle "[^-]*") ; 4
4804 * (pixelsize "[0-9]+")
4805 * (pointsize "[0-9][0-9]+")
4806 * (resx "[0-9][0-9]+")
4807 * (resy "[0-9][0-9]+")
4808 * (spacing "[cmp?*]")
4809 * (avgwidth "[0-9]+")
4810 * (registry "[^-]+")
4811 * (encoding "[^-]+")
4815 static LONG
4816 x_to_w32_weight (lpw)
4817 char * lpw;
4819 if (!lpw) return (FW_DONTCARE);
4821 if (stricmp (lpw, "heavy") == 0) return FW_HEAVY;
4822 else if (stricmp (lpw, "extrabold") == 0) return FW_EXTRABOLD;
4823 else if (stricmp (lpw, "bold") == 0) return FW_BOLD;
4824 else if (stricmp (lpw, "demibold") == 0) return FW_SEMIBOLD;
4825 else if (stricmp (lpw, "semibold") == 0) return FW_SEMIBOLD;
4826 else if (stricmp (lpw, "medium") == 0) return FW_MEDIUM;
4827 else if (stricmp (lpw, "normal") == 0) return FW_NORMAL;
4828 else if (stricmp (lpw, "light") == 0) return FW_LIGHT;
4829 else if (stricmp (lpw, "extralight") == 0) return FW_EXTRALIGHT;
4830 else if (stricmp (lpw, "thin") == 0) return FW_THIN;
4831 else
4832 return FW_DONTCARE;
4836 static char *
4837 w32_to_x_weight (fnweight)
4838 int fnweight;
4840 if (fnweight >= FW_HEAVY) return "heavy";
4841 if (fnweight >= FW_EXTRABOLD) return "extrabold";
4842 if (fnweight >= FW_BOLD) return "bold";
4843 if (fnweight >= FW_SEMIBOLD) return "demibold";
4844 if (fnweight >= FW_MEDIUM) return "medium";
4845 if (fnweight >= FW_NORMAL) return "normal";
4846 if (fnweight >= FW_LIGHT) return "light";
4847 if (fnweight >= FW_EXTRALIGHT) return "extralight";
4848 if (fnweight >= FW_THIN) return "thin";
4849 else
4850 return "*";
4853 static LONG
4854 x_to_w32_charset (lpcs)
4855 char * lpcs;
4857 Lisp_Object this_entry, w32_charset;
4858 char *charset;
4859 int len = strlen (lpcs);
4861 /* Support "*-#nnn" format for unknown charsets. */
4862 if (strncmp (lpcs, "*-#", 3) == 0)
4863 return atoi (lpcs + 3);
4865 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
4866 charset = alloca (len + 1);
4867 strcpy (charset, lpcs);
4868 lpcs = strchr (charset, '*');
4869 if (lpcs)
4870 *lpcs = 0;
4872 /* Look through w32-charset-info-alist for the character set.
4873 Format of each entry is
4874 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
4876 this_entry = Fassoc (build_string (charset), Vw32_charset_info_alist);
4878 if (NILP (this_entry))
4880 /* At startup, we want iso8859-1 fonts to come up properly. */
4881 if (stricmp (charset, "iso8859-1") == 0)
4882 return ANSI_CHARSET;
4883 else
4884 return DEFAULT_CHARSET;
4887 w32_charset = Fcar (Fcdr (this_entry));
4889 /* Translate Lisp symbol to number. */
4890 if (EQ (w32_charset, Qw32_charset_ansi))
4891 return ANSI_CHARSET;
4892 if (EQ (w32_charset, Qw32_charset_symbol))
4893 return SYMBOL_CHARSET;
4894 if (EQ (w32_charset, Qw32_charset_shiftjis))
4895 return SHIFTJIS_CHARSET;
4896 if (EQ (w32_charset, Qw32_charset_hangeul))
4897 return HANGEUL_CHARSET;
4898 if (EQ (w32_charset, Qw32_charset_chinesebig5))
4899 return CHINESEBIG5_CHARSET;
4900 if (EQ (w32_charset, Qw32_charset_gb2312))
4901 return GB2312_CHARSET;
4902 if (EQ (w32_charset, Qw32_charset_oem))
4903 return OEM_CHARSET;
4904 #ifdef JOHAB_CHARSET
4905 if (EQ (w32_charset, Qw32_charset_johab))
4906 return JOHAB_CHARSET;
4907 if (EQ (w32_charset, Qw32_charset_easteurope))
4908 return EASTEUROPE_CHARSET;
4909 if (EQ (w32_charset, Qw32_charset_turkish))
4910 return TURKISH_CHARSET;
4911 if (EQ (w32_charset, Qw32_charset_baltic))
4912 return BALTIC_CHARSET;
4913 if (EQ (w32_charset, Qw32_charset_russian))
4914 return RUSSIAN_CHARSET;
4915 if (EQ (w32_charset, Qw32_charset_arabic))
4916 return ARABIC_CHARSET;
4917 if (EQ (w32_charset, Qw32_charset_greek))
4918 return GREEK_CHARSET;
4919 if (EQ (w32_charset, Qw32_charset_hebrew))
4920 return HEBREW_CHARSET;
4921 if (EQ (w32_charset, Qw32_charset_vietnamese))
4922 return VIETNAMESE_CHARSET;
4923 if (EQ (w32_charset, Qw32_charset_thai))
4924 return THAI_CHARSET;
4925 if (EQ (w32_charset, Qw32_charset_mac))
4926 return MAC_CHARSET;
4927 #endif /* JOHAB_CHARSET */
4928 #ifdef UNICODE_CHARSET
4929 if (EQ (w32_charset, Qw32_charset_unicode))
4930 return UNICODE_CHARSET;
4931 #endif
4933 return DEFAULT_CHARSET;
4937 static char *
4938 w32_to_x_charset (fncharset)
4939 int fncharset;
4941 static char buf[32];
4942 Lisp_Object charset_type;
4944 switch (fncharset)
4946 case ANSI_CHARSET:
4947 /* Handle startup case of w32-charset-info-alist not
4948 being set up yet. */
4949 if (NILP (Vw32_charset_info_alist))
4950 return "iso8859-1";
4951 charset_type = Qw32_charset_ansi;
4952 break;
4953 case DEFAULT_CHARSET:
4954 charset_type = Qw32_charset_default;
4955 break;
4956 case SYMBOL_CHARSET:
4957 charset_type = Qw32_charset_symbol;
4958 break;
4959 case SHIFTJIS_CHARSET:
4960 charset_type = Qw32_charset_shiftjis;
4961 break;
4962 case HANGEUL_CHARSET:
4963 charset_type = Qw32_charset_hangeul;
4964 break;
4965 case GB2312_CHARSET:
4966 charset_type = Qw32_charset_gb2312;
4967 break;
4968 case CHINESEBIG5_CHARSET:
4969 charset_type = Qw32_charset_chinesebig5;
4970 break;
4971 case OEM_CHARSET:
4972 charset_type = Qw32_charset_oem;
4973 break;
4975 /* More recent versions of Windows (95 and NT4.0) define more
4976 character sets. */
4977 #ifdef EASTEUROPE_CHARSET
4978 case EASTEUROPE_CHARSET:
4979 charset_type = Qw32_charset_easteurope;
4980 break;
4981 case TURKISH_CHARSET:
4982 charset_type = Qw32_charset_turkish;
4983 break;
4984 case BALTIC_CHARSET:
4985 charset_type = Qw32_charset_baltic;
4986 break;
4987 case RUSSIAN_CHARSET:
4988 charset_type = Qw32_charset_russian;
4989 break;
4990 case ARABIC_CHARSET:
4991 charset_type = Qw32_charset_arabic;
4992 break;
4993 case GREEK_CHARSET:
4994 charset_type = Qw32_charset_greek;
4995 break;
4996 case HEBREW_CHARSET:
4997 charset_type = Qw32_charset_hebrew;
4998 break;
4999 case VIETNAMESE_CHARSET:
5000 charset_type = Qw32_charset_vietnamese;
5001 break;
5002 case THAI_CHARSET:
5003 charset_type = Qw32_charset_thai;
5004 break;
5005 case MAC_CHARSET:
5006 charset_type = Qw32_charset_mac;
5007 break;
5008 case JOHAB_CHARSET:
5009 charset_type = Qw32_charset_johab;
5010 break;
5011 #endif
5013 #ifdef UNICODE_CHARSET
5014 case UNICODE_CHARSET:
5015 charset_type = Qw32_charset_unicode;
5016 break;
5017 #endif
5018 default:
5019 /* Encode numerical value of unknown charset. */
5020 sprintf (buf, "*-#%u", fncharset);
5021 return buf;
5025 Lisp_Object rest;
5026 char * best_match = NULL;
5028 /* Look through w32-charset-info-alist for the character set.
5029 Prefer ISO codepages, and prefer lower numbers in the ISO
5030 range. Only return charsets for codepages which are installed.
5032 Format of each entry is
5033 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5035 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5037 char * x_charset;
5038 Lisp_Object w32_charset;
5039 Lisp_Object codepage;
5041 Lisp_Object this_entry = XCAR (rest);
5043 /* Skip invalid entries in alist. */
5044 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5045 || !CONSP (XCDR (this_entry))
5046 || !SYMBOLP (XCAR (XCDR (this_entry))))
5047 continue;
5049 x_charset = SDATA (XCAR (this_entry));
5050 w32_charset = XCAR (XCDR (this_entry));
5051 codepage = XCDR (XCDR (this_entry));
5053 /* Look for Same charset and a valid codepage (or non-int
5054 which means ignore). */
5055 if (EQ (w32_charset, charset_type)
5056 && (!INTEGERP (codepage) || XINT (codepage) == CP_DEFAULT
5057 || IsValidCodePage (XINT (codepage))))
5059 /* If we don't have a match already, then this is the
5060 best. */
5061 if (!best_match)
5062 best_match = x_charset;
5063 /* If this is an ISO codepage, and the best so far isn't,
5064 then this is better. */
5065 else if (strnicmp (best_match, "iso", 3) != 0
5066 && strnicmp (x_charset, "iso", 3) == 0)
5067 best_match = x_charset;
5068 /* If both are ISO8859 codepages, choose the one with the
5069 lowest number in the encoding field. */
5070 else if (strnicmp (best_match, "iso8859-", 8) == 0
5071 && strnicmp (x_charset, "iso8859-", 8) == 0)
5073 int best_enc = atoi (best_match + 8);
5074 int this_enc = atoi (x_charset + 8);
5075 if (this_enc > 0 && this_enc < best_enc)
5076 best_match = x_charset;
5081 /* If no match, encode the numeric value. */
5082 if (!best_match)
5084 sprintf (buf, "*-#%u", fncharset);
5085 return buf;
5088 strncpy (buf, best_match, 31);
5089 buf[31] = '\0';
5090 return buf;
5095 /* Return all the X charsets that map to a font. */
5096 static Lisp_Object
5097 w32_to_all_x_charsets (fncharset)
5098 int fncharset;
5100 static char buf[32];
5101 Lisp_Object charset_type;
5102 Lisp_Object retval = Qnil;
5104 switch (fncharset)
5106 case ANSI_CHARSET:
5107 /* Handle startup case of w32-charset-info-alist not
5108 being set up yet. */
5109 if (NILP (Vw32_charset_info_alist))
5110 return Fcons (build_string ("iso8859-1"), Qnil);
5112 charset_type = Qw32_charset_ansi;
5113 break;
5114 case DEFAULT_CHARSET:
5115 charset_type = Qw32_charset_default;
5116 break;
5117 case SYMBOL_CHARSET:
5118 charset_type = Qw32_charset_symbol;
5119 break;
5120 case SHIFTJIS_CHARSET:
5121 charset_type = Qw32_charset_shiftjis;
5122 break;
5123 case HANGEUL_CHARSET:
5124 charset_type = Qw32_charset_hangeul;
5125 break;
5126 case GB2312_CHARSET:
5127 charset_type = Qw32_charset_gb2312;
5128 break;
5129 case CHINESEBIG5_CHARSET:
5130 charset_type = Qw32_charset_chinesebig5;
5131 break;
5132 case OEM_CHARSET:
5133 charset_type = Qw32_charset_oem;
5134 break;
5136 /* More recent versions of Windows (95 and NT4.0) define more
5137 character sets. */
5138 #ifdef EASTEUROPE_CHARSET
5139 case EASTEUROPE_CHARSET:
5140 charset_type = Qw32_charset_easteurope;
5141 break;
5142 case TURKISH_CHARSET:
5143 charset_type = Qw32_charset_turkish;
5144 break;
5145 case BALTIC_CHARSET:
5146 charset_type = Qw32_charset_baltic;
5147 break;
5148 case RUSSIAN_CHARSET:
5149 charset_type = Qw32_charset_russian;
5150 break;
5151 case ARABIC_CHARSET:
5152 charset_type = Qw32_charset_arabic;
5153 break;
5154 case GREEK_CHARSET:
5155 charset_type = Qw32_charset_greek;
5156 break;
5157 case HEBREW_CHARSET:
5158 charset_type = Qw32_charset_hebrew;
5159 break;
5160 case VIETNAMESE_CHARSET:
5161 charset_type = Qw32_charset_vietnamese;
5162 break;
5163 case THAI_CHARSET:
5164 charset_type = Qw32_charset_thai;
5165 break;
5166 case MAC_CHARSET:
5167 charset_type = Qw32_charset_mac;
5168 break;
5169 case JOHAB_CHARSET:
5170 charset_type = Qw32_charset_johab;
5171 break;
5172 #endif
5174 #ifdef UNICODE_CHARSET
5175 case UNICODE_CHARSET:
5176 charset_type = Qw32_charset_unicode;
5177 break;
5178 #endif
5179 default:
5180 /* Encode numerical value of unknown charset. */
5181 sprintf (buf, "*-#%u", fncharset);
5182 return Fcons (build_string (buf), Qnil);
5186 Lisp_Object rest;
5187 /* Look through w32-charset-info-alist for the character set.
5188 Only return charsets for codepages which are installed.
5190 Format of each entry in Vw32_charset_info_alist is
5191 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5193 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5195 Lisp_Object x_charset;
5196 Lisp_Object w32_charset;
5197 Lisp_Object codepage;
5199 Lisp_Object this_entry = XCAR (rest);
5201 /* Skip invalid entries in alist. */
5202 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5203 || !CONSP (XCDR (this_entry))
5204 || !SYMBOLP (XCAR (XCDR (this_entry))))
5205 continue;
5207 x_charset = XCAR (this_entry);
5208 w32_charset = XCAR (XCDR (this_entry));
5209 codepage = XCDR (XCDR (this_entry));
5211 /* Look for Same charset and a valid codepage (or non-int
5212 which means ignore). */
5213 if (EQ (w32_charset, charset_type)
5214 && (!INTEGERP (codepage) || XINT (codepage) == CP_DEFAULT
5215 || IsValidCodePage (XINT (codepage))))
5217 retval = Fcons (x_charset, retval);
5221 /* If no match, encode the numeric value. */
5222 if (NILP (retval))
5224 sprintf (buf, "*-#%u", fncharset);
5225 return Fcons (build_string (buf), Qnil);
5228 return retval;
5232 /* Get the Windows codepage corresponding to the specified font. The
5233 charset info in the font name is used to look up
5234 w32-charset-to-codepage-alist. */
5236 w32_codepage_for_font (char *fontname)
5238 Lisp_Object codepage, entry;
5239 char *charset_str, *charset, *end;
5241 if (NILP (Vw32_charset_info_alist))
5242 return CP_DEFAULT;
5244 /* Extract charset part of font string. */
5245 charset = xlfd_charset_of_font (fontname);
5247 if (!charset)
5248 return CP_UNKNOWN;
5250 charset_str = (char *) alloca (strlen (charset) + 1);
5251 strcpy (charset_str, charset);
5253 #if 0
5254 /* Remove leading "*-". */
5255 if (strncmp ("*-", charset_str, 2) == 0)
5256 charset = charset_str + 2;
5257 else
5258 #endif
5259 charset = charset_str;
5261 /* Stop match at wildcard (including preceding '-'). */
5262 if (end = strchr (charset, '*'))
5264 if (end > charset && *(end-1) == '-')
5265 end--;
5266 *end = '\0';
5269 entry = Fassoc (build_string (charset), Vw32_charset_info_alist);
5270 if (NILP (entry))
5271 return CP_UNKNOWN;
5273 codepage = Fcdr (Fcdr (entry));
5275 if (NILP (codepage))
5276 return CP_8BIT;
5277 else if (XFASTINT (codepage) == XFASTINT (Qt))
5278 return CP_UNICODE;
5279 else if (INTEGERP (codepage))
5280 return XINT (codepage);
5281 else
5282 return CP_UNKNOWN;
5286 static BOOL
5287 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
5288 LOGFONT * lplogfont;
5289 char * lpxstr;
5290 int len;
5291 char * specific_charset;
5293 char* fonttype;
5294 char *fontname;
5295 char height_pixels[8];
5296 char height_dpi[8];
5297 char width_pixels[8];
5298 char *fontname_dash;
5299 int display_resy = (int) one_w32_display_info.resy;
5300 int display_resx = (int) one_w32_display_info.resx;
5301 int bufsz;
5302 struct coding_system coding;
5304 if (!lpxstr) abort ();
5306 if (!lplogfont)
5307 return FALSE;
5309 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5310 fonttype = "raster";
5311 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5312 fonttype = "outline";
5313 else
5314 fonttype = "unknown";
5316 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
5317 &coding);
5318 coding.src_multibyte = 0;
5319 coding.dst_multibyte = 1;
5320 coding.mode |= CODING_MODE_LAST_BLOCK;
5321 /* We explicitely disable composition handling because selection
5322 data should not contain any composition sequence. */
5323 coding.composing = COMPOSITION_DISABLED;
5324 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
5326 fontname = alloca (sizeof (*fontname) * bufsz);
5327 decode_coding (&coding, lplogfont->lfFaceName, fontname,
5328 strlen (lplogfont->lfFaceName), bufsz - 1);
5329 *(fontname + coding.produced) = '\0';
5331 /* Replace dashes with underscores so the dashes are not
5332 misinterpreted. */
5333 fontname_dash = fontname;
5334 while (fontname_dash = strchr (fontname_dash, '-'))
5335 *fontname_dash = '_';
5337 if (lplogfont->lfHeight)
5339 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
5340 sprintf (height_dpi, "%u",
5341 abs (lplogfont->lfHeight) * 720 / display_resy);
5343 else
5345 strcpy (height_pixels, "*");
5346 strcpy (height_dpi, "*");
5349 #if 0 /* Never put the width in the xfld. It fails on fonts with
5350 double-width characters. */
5351 if (lplogfont->lfWidth)
5352 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5353 else
5354 #endif
5355 strcpy (width_pixels, "*");
5357 _snprintf (lpxstr, len - 1,
5358 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5359 fonttype, /* foundry */
5360 fontname, /* family */
5361 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5362 lplogfont->lfItalic?'i':'r', /* slant */
5363 /* setwidth name */
5364 /* add style name */
5365 height_pixels, /* pixel size */
5366 height_dpi, /* point size */
5367 display_resx, /* resx */
5368 display_resy, /* resy */
5369 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5370 ? 'p' : 'c', /* spacing */
5371 width_pixels, /* avg width */
5372 specific_charset ? specific_charset
5373 : w32_to_x_charset (lplogfont->lfCharSet)
5374 /* charset registry and encoding */
5377 lpxstr[len - 1] = 0; /* just to be sure */
5378 return (TRUE);
5381 static BOOL
5382 x_to_w32_font (lpxstr, lplogfont)
5383 char * lpxstr;
5384 LOGFONT * lplogfont;
5386 struct coding_system coding;
5388 if (!lplogfont) return (FALSE);
5390 memset (lplogfont, 0, sizeof (*lplogfont));
5392 /* Set default value for each field. */
5393 #if 1
5394 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5395 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5396 lplogfont->lfQuality = DEFAULT_QUALITY;
5397 #else
5398 /* go for maximum quality */
5399 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5400 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5401 lplogfont->lfQuality = PROOF_QUALITY;
5402 #endif
5404 lplogfont->lfCharSet = DEFAULT_CHARSET;
5405 lplogfont->lfWeight = FW_DONTCARE;
5406 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5408 if (!lpxstr)
5409 return FALSE;
5411 /* Provide a simple escape mechanism for specifying Windows font names
5412 * directly -- if font spec does not beginning with '-', assume this
5413 * format:
5414 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5417 if (*lpxstr == '-')
5419 int fields, tem;
5420 char name[50], weight[20], slant, pitch, pixels[10], height[10],
5421 width[10], resy[10], remainder[50];
5422 char * encoding;
5423 int dpi = (int) one_w32_display_info.resy;
5425 fields = sscanf (lpxstr,
5426 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
5427 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
5428 if (fields == EOF)
5429 return (FALSE);
5431 /* In the general case when wildcards cover more than one field,
5432 we don't know which field is which, so don't fill any in.
5433 However, we need to cope with this particular form, which is
5434 generated by font_list_1 (invoked by try_font_list):
5435 "-raster-6x10-*-gb2312*-*"
5436 and make sure to correctly parse the charset field. */
5437 if (fields == 3)
5439 fields = sscanf (lpxstr,
5440 "-%*[^-]-%49[^-]-*-%49s",
5441 name, remainder);
5443 else if (fields < 9)
5445 fields = 0;
5446 remainder[0] = 0;
5449 if (fields > 0 && name[0] != '*')
5451 int bufsize;
5452 unsigned char *buf;
5454 setup_coding_system
5455 (Fcheck_coding_system (Vlocale_coding_system), &coding);
5456 coding.src_multibyte = 1;
5457 coding.dst_multibyte = 0;
5458 /* Need to set COMPOSITION_DISABLED, otherwise Emacs crashes in
5459 encode_coding_iso2022 trying to dereference a null pointer. */
5460 coding.composing = COMPOSITION_DISABLED;
5461 if (coding.type == coding_type_iso2022)
5462 coding.flags |= CODING_FLAG_ISO_SAFE;
5463 bufsize = encoding_buffer_size (&coding, strlen (name));
5464 buf = (unsigned char *) alloca (bufsize);
5465 coding.mode |= CODING_MODE_LAST_BLOCK;
5466 encode_coding (&coding, name, buf, strlen (name), bufsize);
5467 if (coding.produced >= LF_FACESIZE)
5468 coding.produced = LF_FACESIZE - 1;
5469 buf[coding.produced] = 0;
5470 strcpy (lplogfont->lfFaceName, buf);
5472 else
5474 lplogfont->lfFaceName[0] = '\0';
5477 fields--;
5479 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5481 fields--;
5483 lplogfont->lfItalic = (fields > 0 && slant == 'i');
5485 fields--;
5487 if (fields > 0 && pixels[0] != '*')
5488 lplogfont->lfHeight = atoi (pixels);
5490 fields--;
5491 fields--;
5492 if (fields > 0 && resy[0] != '*')
5494 tem = atoi (resy);
5495 if (tem > 0) dpi = tem;
5498 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
5499 lplogfont->lfHeight = atoi (height) * dpi / 720;
5501 if (fields > 0)
5502 lplogfont->lfPitchAndFamily =
5503 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
5505 fields--;
5507 if (fields > 0 && width[0] != '*')
5508 lplogfont->lfWidth = atoi (width) / 10;
5510 fields--;
5512 /* Strip the trailing '-' if present. (it shouldn't be, as it
5513 fails the test against xlfd-tight-regexp in fontset.el). */
5515 int len = strlen (remainder);
5516 if (len > 0 && remainder[len-1] == '-')
5517 remainder[len-1] = 0;
5519 encoding = remainder;
5520 #if 0
5521 if (strncmp (encoding, "*-", 2) == 0)
5522 encoding += 2;
5523 #endif
5524 lplogfont->lfCharSet = x_to_w32_charset (encoding);
5526 else
5528 int fields;
5529 char name[100], height[10], width[10], weight[20];
5531 fields = sscanf (lpxstr,
5532 "%99[^:]:%9[^:]:%9[^:]:%19s",
5533 name, height, width, weight);
5535 if (fields == EOF) return (FALSE);
5537 if (fields > 0)
5539 strncpy (lplogfont->lfFaceName, name, LF_FACESIZE);
5540 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
5542 else
5544 lplogfont->lfFaceName[0] = 0;
5547 fields--;
5549 if (fields > 0)
5550 lplogfont->lfHeight = atoi (height);
5552 fields--;
5554 if (fields > 0)
5555 lplogfont->lfWidth = atoi (width);
5557 fields--;
5559 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5562 /* This makes TrueType fonts work better. */
5563 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
5565 return (TRUE);
5568 /* Strip the pixel height and point height from the given xlfd, and
5569 return the pixel height. If no pixel height is specified, calculate
5570 one from the point height, or if that isn't defined either, return
5571 0 (which usually signifies a scalable font).
5573 static int
5574 xlfd_strip_height (char *fontname)
5576 int pixel_height, field_number;
5577 char *read_from, *write_to;
5579 xassert (fontname);
5581 pixel_height = field_number = 0;
5582 write_to = NULL;
5584 /* Look for height fields. */
5585 for (read_from = fontname; *read_from; read_from++)
5587 if (*read_from == '-')
5589 field_number++;
5590 if (field_number == 7) /* Pixel height. */
5592 read_from++;
5593 write_to = read_from;
5595 /* Find end of field. */
5596 for (;*read_from && *read_from != '-'; read_from++)
5599 /* Split the fontname at end of field. */
5600 if (*read_from)
5602 *read_from = '\0';
5603 read_from++;
5605 pixel_height = atoi (write_to);
5606 /* Blank out field. */
5607 if (read_from > write_to)
5609 *write_to = '-';
5610 write_to++;
5612 /* If the pixel height field is at the end (partial xlfd),
5613 return now. */
5614 else
5615 return pixel_height;
5617 /* If we got a pixel height, the point height can be
5618 ignored. Just blank it out and break now. */
5619 if (pixel_height)
5621 /* Find end of point size field. */
5622 for (; *read_from && *read_from != '-'; read_from++)
5625 if (*read_from)
5626 read_from++;
5628 /* Blank out the point size field. */
5629 if (read_from > write_to)
5631 *write_to = '-';
5632 write_to++;
5634 else
5635 return pixel_height;
5637 break;
5639 /* If the point height is already blank, break now. */
5640 if (*read_from == '-')
5642 read_from++;
5643 break;
5646 else if (field_number == 8)
5648 /* If we didn't get a pixel height, try to get the point
5649 height and convert that. */
5650 int point_size;
5651 char *point_size_start = read_from++;
5653 /* Find end of field. */
5654 for (; *read_from && *read_from != '-'; read_from++)
5657 if (*read_from)
5659 *read_from = '\0';
5660 read_from++;
5663 point_size = atoi (point_size_start);
5665 /* Convert to pixel height. */
5666 pixel_height = point_size
5667 * one_w32_display_info.height_in / 720;
5669 /* Blank out this field and break. */
5670 *write_to = '-';
5671 write_to++;
5672 break;
5677 /* Shift the rest of the font spec into place. */
5678 if (write_to && read_from > write_to)
5680 for (; *read_from; read_from++, write_to++)
5681 *write_to = *read_from;
5682 *write_to = '\0';
5685 return pixel_height;
5688 /* Assume parameter 1 is fully qualified, no wildcards. */
5689 static BOOL
5690 w32_font_match (fontname, pattern)
5691 char * fontname;
5692 char * pattern;
5694 char *ptr;
5695 char *font_name_copy;
5696 char *regex = alloca (strlen (pattern) * 2 + 3);
5698 font_name_copy = alloca (strlen (fontname) + 1);
5699 strcpy (font_name_copy, fontname);
5701 ptr = regex;
5702 *ptr++ = '^';
5704 /* Turn pattern into a regexp and do a regexp match. */
5705 for (; *pattern; pattern++)
5707 if (*pattern == '?')
5708 *ptr++ = '.';
5709 else if (*pattern == '*')
5711 *ptr++ = '.';
5712 *ptr++ = '*';
5714 else
5715 *ptr++ = *pattern;
5717 *ptr = '$';
5718 *(ptr + 1) = '\0';
5720 /* Strip out font heights and compare them seperately, since
5721 rounding error can cause mismatches. This also allows a
5722 comparison between a font that declares only a pixel height and a
5723 pattern that declares the point height.
5726 int font_height, pattern_height;
5728 font_height = xlfd_strip_height (font_name_copy);
5729 pattern_height = xlfd_strip_height (regex);
5731 /* Compare now, and don't bother doing expensive regexp matching
5732 if the heights differ. */
5733 if (font_height && pattern_height && (font_height != pattern_height))
5734 return FALSE;
5737 return (fast_string_match_ignore_case (build_string (regex),
5738 build_string (font_name_copy)) >= 0);
5741 /* Callback functions, and a structure holding info they need, for
5742 listing system fonts on W32. We need one set of functions to do the
5743 job properly, but these don't work on NT 3.51 and earlier, so we
5744 have a second set which don't handle character sets properly to
5745 fall back on.
5747 In both cases, there are two passes made. The first pass gets one
5748 font from each family, the second pass lists all the fonts from
5749 each family. */
5751 typedef struct enumfont_t
5753 HDC hdc;
5754 int numFonts;
5755 LOGFONT logfont;
5756 XFontStruct *size_ref;
5757 Lisp_Object pattern;
5758 Lisp_Object list;
5759 } enumfont_t;
5762 static void
5763 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
5766 static int CALLBACK
5767 enum_font_cb2 (lplf, lptm, FontType, lpef)
5768 ENUMLOGFONT * lplf;
5769 NEWTEXTMETRIC * lptm;
5770 int FontType;
5771 enumfont_t * lpef;
5773 /* Ignore struck out and underlined versions of fonts. */
5774 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
5775 return 1;
5777 /* Only return fonts with names starting with @ if they were
5778 explicitly specified, since Microsoft uses an initial @ to
5779 denote fonts for vertical writing, without providing a more
5780 convenient way of identifying them. */
5781 if (lplf->elfLogFont.lfFaceName[0] == '@'
5782 && lpef->logfont.lfFaceName[0] != '@')
5783 return 1;
5785 /* Check that the character set matches if it was specified */
5786 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
5787 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
5788 return 1;
5790 if (FontType == RASTER_FONTTYPE)
5792 /* DBCS raster fonts have problems displaying, so skip them. */
5793 int charset = lplf->elfLogFont.lfCharSet;
5794 if (charset == SHIFTJIS_CHARSET
5795 || charset == HANGEUL_CHARSET
5796 || charset == CHINESEBIG5_CHARSET
5797 || charset == GB2312_CHARSET
5798 #ifdef JOHAB_CHARSET
5799 || charset == JOHAB_CHARSET
5800 #endif
5802 return 1;
5806 char buf[100];
5807 Lisp_Object width = Qnil;
5808 Lisp_Object charset_list = Qnil;
5809 char *charset = NULL;
5811 /* Truetype fonts do not report their true metrics until loaded */
5812 if (FontType != RASTER_FONTTYPE)
5814 if (!NILP (lpef->pattern))
5816 /* Scalable fonts are as big as you want them to be. */
5817 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
5818 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
5819 width = make_number (lpef->logfont.lfWidth);
5821 else
5823 lplf->elfLogFont.lfHeight = 0;
5824 lplf->elfLogFont.lfWidth = 0;
5828 /* Make sure the height used here is the same as everywhere
5829 else (ie character height, not cell height). */
5830 if (lplf->elfLogFont.lfHeight > 0)
5832 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
5833 if (FontType == RASTER_FONTTYPE)
5834 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
5835 else
5836 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
5839 if (!NILP (lpef->pattern))
5841 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
5843 /* We already checked charsets above, but DEFAULT_CHARSET
5844 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
5845 if (charset
5846 && strncmp (charset, "*-*", 3) != 0
5847 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
5848 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
5849 return 1;
5851 /* Reject raster fonts if we are looking for a unicode font. */
5852 if (charset
5853 && FontType == RASTER_FONTTYPE
5854 && strncmp (charset, "iso10646", 8) == 0)
5855 return 1;
5858 if (charset)
5859 charset_list = Fcons (build_string (charset), Qnil);
5860 else
5861 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
5863 /* Loop through the charsets. */
5864 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
5866 Lisp_Object this_charset = Fcar (charset_list);
5867 charset = SDATA (this_charset);
5869 /* Don't list raster fonts as unicode. */
5870 if (charset
5871 && FontType == RASTER_FONTTYPE
5872 && strncmp (charset, "iso10646", 8) == 0)
5873 continue;
5875 /* List bold and italic variations if w32-enable-synthesized-fonts
5876 is non-nil and this is a plain font. */
5877 if (w32_enable_synthesized_fonts
5878 && lplf->elfLogFont.lfWeight == FW_NORMAL
5879 && lplf->elfLogFont.lfItalic == FALSE)
5881 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5882 charset, width);
5883 /* bold. */
5884 lplf->elfLogFont.lfWeight = FW_BOLD;
5885 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5886 charset, width);
5887 /* bold italic. */
5888 lplf->elfLogFont.lfItalic = TRUE;
5889 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5890 charset, width);
5891 /* italic. */
5892 lplf->elfLogFont.lfWeight = FW_NORMAL;
5893 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5894 charset, width);
5896 else
5897 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5898 charset, width);
5902 return 1;
5905 static void
5906 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
5907 enumfont_t * lpef;
5908 LOGFONT * logfont;
5909 char * match_charset;
5910 Lisp_Object width;
5912 char buf[100];
5914 if (!w32_to_x_font (logfont, buf, 100, match_charset))
5915 return;
5917 if (NILP (lpef->pattern)
5918 || w32_font_match (buf, SDATA (lpef->pattern)))
5920 /* Check if we already listed this font. This may happen if
5921 w32_enable_synthesized_fonts is non-nil, and there are real
5922 bold and italic versions of the font. */
5923 Lisp_Object font_name = build_string (buf);
5924 if (NILP (Fmember (font_name, lpef->list)))
5926 Lisp_Object entry = Fcons (font_name, width);
5927 lpef->list = Fcons (entry, lpef->list);
5928 lpef->numFonts++;
5934 static int CALLBACK
5935 enum_font_cb1 (lplf, lptm, FontType, lpef)
5936 ENUMLOGFONT * lplf;
5937 NEWTEXTMETRIC * lptm;
5938 int FontType;
5939 enumfont_t * lpef;
5941 return EnumFontFamilies (lpef->hdc,
5942 lplf->elfLogFont.lfFaceName,
5943 (FONTENUMPROC) enum_font_cb2,
5944 (LPARAM) lpef);
5948 static int CALLBACK
5949 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
5950 ENUMLOGFONTEX * lplf;
5951 NEWTEXTMETRICEX * lptm;
5952 int font_type;
5953 enumfont_t * lpef;
5955 /* We are not interested in the extra info we get back from the 'Ex
5956 version - only the fact that we get character set variations
5957 enumerated seperately. */
5958 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
5959 font_type, lpef);
5962 static int CALLBACK
5963 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
5964 ENUMLOGFONTEX * lplf;
5965 NEWTEXTMETRICEX * lptm;
5966 int font_type;
5967 enumfont_t * lpef;
5969 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5970 FARPROC enum_font_families_ex
5971 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
5972 /* We don't really expect EnumFontFamiliesEx to disappear once we
5973 get here, so don't bother handling it gracefully. */
5974 if (enum_font_families_ex == NULL)
5975 error ("gdi32.dll has disappeared!");
5976 return enum_font_families_ex (lpef->hdc,
5977 &lplf->elfLogFont,
5978 (FONTENUMPROC) enum_fontex_cb2,
5979 (LPARAM) lpef, 0);
5982 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
5983 and xterm.c in Emacs 20.3) */
5985 static Lisp_Object
5986 w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
5988 char *fontname, *ptnstr;
5989 Lisp_Object list, tem, newlist = Qnil;
5990 int n_fonts = 0;
5992 list = Vw32_bdf_filename_alist;
5993 ptnstr = SDATA (pattern);
5995 for ( ; CONSP (list); list = XCDR (list))
5997 tem = XCAR (list);
5998 if (CONSP (tem))
5999 fontname = SDATA (XCAR (tem));
6000 else if (STRINGP (tem))
6001 fontname = SDATA (tem);
6002 else
6003 continue;
6005 if (w32_font_match (fontname, ptnstr))
6007 newlist = Fcons (XCAR (tem), newlist);
6008 n_fonts++;
6009 if (max_names >= 0 && n_fonts >= max_names)
6010 break;
6014 return newlist;
6018 /* Return a list of names of available fonts matching PATTERN on frame
6019 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6020 to be listed. Frame F NULL means we have not yet created any
6021 frame, which means we can't get proper size info, as we don't have
6022 a device context to use for GetTextMetrics.
6023 MAXNAMES sets a limit on how many fonts to match. If MAXNAMES is
6024 negative, then all matching fonts are returned. */
6026 Lisp_Object
6027 w32_list_fonts (f, pattern, size, maxnames)
6028 struct frame *f;
6029 Lisp_Object pattern;
6030 int size;
6031 int maxnames;
6033 Lisp_Object patterns, key = Qnil, tem, tpat;
6034 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6035 struct w32_display_info *dpyinfo = &one_w32_display_info;
6036 int n_fonts = 0;
6038 patterns = Fassoc (pattern, Valternate_fontname_alist);
6039 if (NILP (patterns))
6040 patterns = Fcons (pattern, Qnil);
6042 for (; CONSP (patterns); patterns = XCDR (patterns))
6044 enumfont_t ef;
6045 int codepage;
6047 tpat = XCAR (patterns);
6049 if (!STRINGP (tpat))
6050 continue;
6052 /* Avoid expensive EnumFontFamilies functions if we are not
6053 going to be able to output one of these anyway. */
6054 codepage = w32_codepage_for_font (SDATA (tpat));
6055 if (codepage != CP_8BIT && codepage != CP_UNICODE
6056 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6057 && !IsValidCodePage (codepage))
6058 continue;
6060 /* See if we cached the result for this particular query.
6061 The cache is an alist of the form:
6062 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6064 if (tem = XCDR (dpyinfo->name_list_element),
6065 !NILP (list = Fassoc (tpat, tem)))
6067 list = Fcdr_safe (list);
6068 /* We have a cached list. Don't have to get the list again. */
6069 goto label_cached;
6072 BLOCK_INPUT;
6073 /* At first, put PATTERN in the cache. */
6074 ef.pattern = tpat;
6075 ef.list = Qnil;
6076 ef.numFonts = 0;
6078 /* Use EnumFontFamiliesEx where it is available, as it knows
6079 about character sets. Fall back to EnumFontFamilies for
6080 older versions of NT that don't support the 'Ex function. */
6081 x_to_w32_font (SDATA (tpat), &ef.logfont);
6083 LOGFONT font_match_pattern;
6084 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6085 FARPROC enum_font_families_ex
6086 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6088 /* We do our own pattern matching so we can handle wildcards. */
6089 font_match_pattern.lfFaceName[0] = 0;
6090 font_match_pattern.lfPitchAndFamily = 0;
6091 /* We can use the charset, because if it is a wildcard it will
6092 be DEFAULT_CHARSET anyway. */
6093 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6095 ef.hdc = GetDC (dpyinfo->root_window);
6097 if (enum_font_families_ex)
6098 enum_font_families_ex (ef.hdc,
6099 &font_match_pattern,
6100 (FONTENUMPROC) enum_fontex_cb1,
6101 (LPARAM) &ef, 0);
6102 else
6103 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6104 (LPARAM)&ef);
6106 ReleaseDC (dpyinfo->root_window, ef.hdc);
6109 UNBLOCK_INPUT;
6110 list = ef.list;
6112 /* Make a list of the fonts we got back.
6113 Store that in the font cache for the display. */
6114 XSETCDR (dpyinfo->name_list_element,
6115 Fcons (Fcons (tpat, list),
6116 XCDR (dpyinfo->name_list_element)));
6118 label_cached:
6119 if (NILP (list)) continue; /* Try the remaining alternatives. */
6121 newlist = second_best = Qnil;
6123 /* Make a list of the fonts that have the right width. */
6124 for (; CONSP (list); list = XCDR (list))
6126 int found_size;
6127 tem = XCAR (list);
6129 if (!CONSP (tem))
6130 continue;
6131 if (NILP (XCAR (tem)))
6132 continue;
6133 if (!size)
6135 newlist = Fcons (XCAR (tem), newlist);
6136 n_fonts++;
6137 if (maxnames >= 0 && n_fonts >= maxnames)
6138 break;
6139 else
6140 continue;
6142 if (!INTEGERP (XCDR (tem)))
6144 /* Since we don't yet know the size of the font, we must
6145 load it and try GetTextMetrics. */
6146 W32FontStruct thisinfo;
6147 LOGFONT lf;
6148 HDC hdc;
6149 HANDLE oldobj;
6151 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
6152 continue;
6154 BLOCK_INPUT;
6155 thisinfo.bdf = NULL;
6156 thisinfo.hfont = CreateFontIndirect (&lf);
6157 if (thisinfo.hfont == NULL)
6158 continue;
6160 hdc = GetDC (dpyinfo->root_window);
6161 oldobj = SelectObject (hdc, thisinfo.hfont);
6162 if (GetTextMetrics (hdc, &thisinfo.tm))
6163 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
6164 else
6165 XSETCDR (tem, make_number (0));
6166 SelectObject (hdc, oldobj);
6167 ReleaseDC (dpyinfo->root_window, hdc);
6168 DeleteObject (thisinfo.hfont);
6169 UNBLOCK_INPUT;
6171 found_size = XINT (XCDR (tem));
6172 if (found_size == size)
6174 newlist = Fcons (XCAR (tem), newlist);
6175 n_fonts++;
6176 if (maxnames >= 0 && n_fonts >= maxnames)
6177 break;
6179 /* keep track of the closest matching size in case
6180 no exact match is found. */
6181 else if (found_size > 0)
6183 if (NILP (second_best))
6184 second_best = tem;
6186 else if (found_size < size)
6188 if (XINT (XCDR (second_best)) > size
6189 || XINT (XCDR (second_best)) < found_size)
6190 second_best = tem;
6192 else
6194 if (XINT (XCDR (second_best)) > size
6195 && XINT (XCDR (second_best)) >
6196 found_size)
6197 second_best = tem;
6202 if (!NILP (newlist))
6203 break;
6204 else if (!NILP (second_best))
6206 newlist = Fcons (XCAR (second_best), Qnil);
6207 break;
6211 /* Include any bdf fonts. */
6212 if (n_fonts < maxnames || maxnames < 0)
6214 Lisp_Object combined[2];
6215 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6216 combined[1] = newlist;
6217 newlist = Fnconc (2, combined);
6220 return newlist;
6224 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6225 struct font_info *
6226 w32_get_font_info (f, font_idx)
6227 FRAME_PTR f;
6228 int font_idx;
6230 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6234 struct font_info*
6235 w32_query_font (struct frame *f, char *fontname)
6237 int i;
6238 struct font_info *pfi;
6240 pfi = FRAME_W32_FONT_TABLE (f);
6242 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6244 if (stricmp (pfi->name, fontname) == 0) return pfi;
6247 return NULL;
6250 /* Find a CCL program for a font specified by FONTP, and set the member
6251 `encoder' of the structure. */
6253 void
6254 w32_find_ccl_program (fontp)
6255 struct font_info *fontp;
6257 Lisp_Object list, elt;
6259 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6261 elt = XCAR (list);
6262 if (CONSP (elt)
6263 && STRINGP (XCAR (elt))
6264 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6265 >= 0))
6266 break;
6268 if (! NILP (list))
6270 struct ccl_program *ccl
6271 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6273 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6274 xfree (ccl);
6275 else
6276 fontp->font_encoder = ccl;
6280 /* directory-files from dired.c. */
6281 Lisp_Object Fdirectory_files P_ ((Lisp_Object, Lisp_Object, Lisp_Object, Lisp_Object));
6284 /* Find BDF files in a specified directory. (use GCPRO when calling,
6285 as this calls lisp to get a directory listing). */
6286 static Lisp_Object
6287 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
6289 Lisp_Object filelist, list = Qnil;
6290 char fontname[100];
6292 if (!STRINGP (directory))
6293 return Qnil;
6295 filelist = Fdirectory_files (directory, Qt,
6296 build_string (".*\\.[bB][dD][fF]"), Qt);
6298 for ( ; CONSP (filelist); filelist = XCDR (filelist))
6300 Lisp_Object filename = XCAR (filelist);
6301 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
6302 store_in_alist (&list, build_string (fontname), filename);
6304 return list;
6307 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6308 1, 1, 0,
6309 doc: /* Return a list of BDF fonts in DIRECTORY.
6310 The list is suitable for appending to `w32-bdf-filename-alist'.
6311 Fonts which do not contain an xlfd description will not be included
6312 in the list. DIRECTORY may be a list of directories. */)
6313 (directory)
6314 Lisp_Object directory;
6316 Lisp_Object list = Qnil;
6317 struct gcpro gcpro1, gcpro2;
6319 if (!CONSP (directory))
6320 return w32_find_bdf_fonts_in_dir (directory);
6322 for ( ; CONSP (directory); directory = XCDR (directory))
6324 Lisp_Object pair[2];
6325 pair[0] = list;
6326 pair[1] = Qnil;
6327 GCPRO2 (directory, list);
6328 pair[1] = w32_find_bdf_fonts_in_dir ( XCAR (directory) );
6329 list = Fnconc ( 2, pair );
6330 UNGCPRO;
6332 return list;
6336 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6337 doc: /* Internal function called by `color-defined-p', which see. */)
6338 (color, frame)
6339 Lisp_Object color, frame;
6341 XColor foo;
6342 FRAME_PTR f = check_x_frame (frame);
6344 CHECK_STRING (color);
6346 if (w32_defined_color (f, SDATA (color), &foo, 0))
6347 return Qt;
6348 else
6349 return Qnil;
6352 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6353 doc: /* Internal function called by `color-values', which see. */)
6354 (color, frame)
6355 Lisp_Object color, frame;
6357 XColor foo;
6358 FRAME_PTR f = check_x_frame (frame);
6360 CHECK_STRING (color);
6362 if (w32_defined_color (f, SDATA (color), &foo, 0))
6363 return list3 (make_number ((GetRValue (foo.pixel) << 8)
6364 | GetRValue (foo.pixel)),
6365 make_number ((GetGValue (foo.pixel) << 8)
6366 | GetGValue (foo.pixel)),
6367 make_number ((GetBValue (foo.pixel) << 8)
6368 | GetBValue (foo.pixel)));
6369 else
6370 return Qnil;
6373 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6374 doc: /* Internal function called by `display-color-p', which see. */)
6375 (display)
6376 Lisp_Object display;
6378 struct w32_display_info *dpyinfo = check_x_display_info (display);
6380 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6381 return Qnil;
6383 return Qt;
6386 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6387 Sx_display_grayscale_p, 0, 1, 0,
6388 doc: /* Return t if DISPLAY supports shades of gray.
6389 Note that color displays do support shades of gray.
6390 The optional argument DISPLAY specifies which display to ask about.
6391 DISPLAY should be either a frame or a display name (a string).
6392 If omitted or nil, that stands for the selected frame's display. */)
6393 (display)
6394 Lisp_Object display;
6396 struct w32_display_info *dpyinfo = check_x_display_info (display);
6398 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6399 return Qnil;
6401 return Qt;
6404 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6405 Sx_display_pixel_width, 0, 1, 0,
6406 doc: /* Return the width in pixels of DISPLAY.
6407 The optional argument DISPLAY specifies which display to ask about.
6408 DISPLAY should be either a frame or a display name (a string).
6409 If omitted or nil, that stands for the selected frame's display. */)
6410 (display)
6411 Lisp_Object display;
6413 struct w32_display_info *dpyinfo = check_x_display_info (display);
6415 return make_number (dpyinfo->width);
6418 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6419 Sx_display_pixel_height, 0, 1, 0,
6420 doc: /* Return the height in pixels of DISPLAY.
6421 The optional argument DISPLAY specifies which display to ask about.
6422 DISPLAY should be either a frame or a display name (a string).
6423 If omitted or nil, that stands for the selected frame's display. */)
6424 (display)
6425 Lisp_Object display;
6427 struct w32_display_info *dpyinfo = check_x_display_info (display);
6429 return make_number (dpyinfo->height);
6432 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6433 0, 1, 0,
6434 doc: /* Return the number of bitplanes of DISPLAY.
6435 The optional argument DISPLAY specifies which display to ask about.
6436 DISPLAY should be either a frame or a display name (a string).
6437 If omitted or nil, that stands for the selected frame's display. */)
6438 (display)
6439 Lisp_Object display;
6441 struct w32_display_info *dpyinfo = check_x_display_info (display);
6443 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6446 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6447 0, 1, 0,
6448 doc: /* Return the number of color cells of DISPLAY.
6449 The optional argument DISPLAY specifies which display to ask about.
6450 DISPLAY should be either a frame or a display name (a string).
6451 If omitted or nil, that stands for the selected frame's display. */)
6452 (display)
6453 Lisp_Object display;
6455 struct w32_display_info *dpyinfo = check_x_display_info (display);
6456 HDC hdc;
6457 int cap;
6459 hdc = GetDC (dpyinfo->root_window);
6460 if (dpyinfo->has_palette)
6461 cap = GetDeviceCaps (hdc, SIZEPALETTE);
6462 else
6463 cap = GetDeviceCaps (hdc, NUMCOLORS);
6465 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
6466 and because probably is more meaningful on Windows anyway */
6467 if (cap < 0)
6468 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
6470 ReleaseDC (dpyinfo->root_window, hdc);
6472 return make_number (cap);
6475 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6476 Sx_server_max_request_size,
6477 0, 1, 0,
6478 doc: /* Return the maximum request size of the server of DISPLAY.
6479 The optional argument DISPLAY specifies which display to ask about.
6480 DISPLAY should be either a frame or a display name (a string).
6481 If omitted or nil, that stands for the selected frame's display. */)
6482 (display)
6483 Lisp_Object display;
6485 struct w32_display_info *dpyinfo = check_x_display_info (display);
6487 return make_number (1);
6490 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6491 doc: /* Return the "vendor ID" string of the W32 system (Microsoft).
6492 The optional argument DISPLAY specifies which display to ask about.
6493 DISPLAY should be either a frame or a display name (a string).
6494 If omitted or nil, that stands for the selected frame's display. */)
6495 (display)
6496 Lisp_Object display;
6498 return build_string ("Microsoft Corp.");
6501 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6502 doc: /* Return the version numbers of the server of DISPLAY.
6503 The value is a list of three integers: the major and minor
6504 version numbers of the X Protocol in use, and the distributor-specific
6505 release number. See also the function `x-server-vendor'.
6507 The optional argument DISPLAY specifies which display to ask about.
6508 DISPLAY should be either a frame or a display name (a string).
6509 If omitted or nil, that stands for the selected frame's display. */)
6510 (display)
6511 Lisp_Object display;
6513 return Fcons (make_number (w32_major_version),
6514 Fcons (make_number (w32_minor_version),
6515 Fcons (make_number (w32_build_number), Qnil)));
6518 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6519 doc: /* Return the number of screens on the server of DISPLAY.
6520 The optional argument DISPLAY specifies which display to ask about.
6521 DISPLAY should be either a frame or a display name (a string).
6522 If omitted or nil, that stands for the selected frame's display. */)
6523 (display)
6524 Lisp_Object display;
6526 return make_number (1);
6529 DEFUN ("x-display-mm-height", Fx_display_mm_height,
6530 Sx_display_mm_height, 0, 1, 0,
6531 doc: /* Return the height in millimeters of DISPLAY.
6532 The optional argument DISPLAY specifies which display to ask about.
6533 DISPLAY should be either a frame or a display name (a string).
6534 If omitted or nil, that stands for the selected frame's display. */)
6535 (display)
6536 Lisp_Object display;
6538 struct w32_display_info *dpyinfo = check_x_display_info (display);
6539 HDC hdc;
6540 int cap;
6542 hdc = GetDC (dpyinfo->root_window);
6544 cap = GetDeviceCaps (hdc, VERTSIZE);
6546 ReleaseDC (dpyinfo->root_window, hdc);
6548 return make_number (cap);
6551 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6552 doc: /* Return the width in millimeters of DISPLAY.
6553 The optional argument DISPLAY specifies which display to ask about.
6554 DISPLAY should be either a frame or a display name (a string).
6555 If omitted or nil, that stands for the selected frame's display. */)
6556 (display)
6557 Lisp_Object display;
6559 struct w32_display_info *dpyinfo = check_x_display_info (display);
6561 HDC hdc;
6562 int cap;
6564 hdc = GetDC (dpyinfo->root_window);
6566 cap = GetDeviceCaps (hdc, HORZSIZE);
6568 ReleaseDC (dpyinfo->root_window, hdc);
6570 return make_number (cap);
6573 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6574 Sx_display_backing_store, 0, 1, 0,
6575 doc: /* Return an indication of whether DISPLAY does backing store.
6576 The value may be `always', `when-mapped', or `not-useful'.
6577 The optional argument DISPLAY specifies which display to ask about.
6578 DISPLAY should be either a frame or a display name (a string).
6579 If omitted or nil, that stands for the selected frame's display. */)
6580 (display)
6581 Lisp_Object display;
6583 return intern ("not-useful");
6586 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6587 Sx_display_visual_class, 0, 1, 0,
6588 doc: /* Return the visual class of DISPLAY.
6589 The value is one of the symbols `static-gray', `gray-scale',
6590 `static-color', `pseudo-color', `true-color', or `direct-color'.
6592 The optional argument DISPLAY specifies which display to ask about.
6593 DISPLAY should be either a frame or a display name (a string).
6594 If omitted or nil, that stands for the selected frame's display. */)
6595 (display)
6596 Lisp_Object display;
6598 struct w32_display_info *dpyinfo = check_x_display_info (display);
6599 Lisp_Object result = Qnil;
6601 if (dpyinfo->has_palette)
6602 result = intern ("pseudo-color");
6603 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6604 result = intern ("static-grey");
6605 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6606 result = intern ("static-color");
6607 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6608 result = intern ("true-color");
6610 return result;
6613 DEFUN ("x-display-save-under", Fx_display_save_under,
6614 Sx_display_save_under, 0, 1, 0,
6615 doc: /* Return t if DISPLAY supports the save-under feature.
6616 The optional argument DISPLAY specifies which display to ask about.
6617 DISPLAY should be either a frame or a display name (a string).
6618 If omitted or nil, that stands for the selected frame's display. */)
6619 (display)
6620 Lisp_Object display;
6622 return Qnil;
6626 x_pixel_width (f)
6627 register struct frame *f;
6629 return FRAME_PIXEL_WIDTH (f);
6633 x_pixel_height (f)
6634 register struct frame *f;
6636 return FRAME_PIXEL_HEIGHT (f);
6640 x_char_width (f)
6641 register struct frame *f;
6643 return FRAME_COLUMN_WIDTH (f);
6647 x_char_height (f)
6648 register struct frame *f;
6650 return FRAME_LINE_HEIGHT (f);
6654 x_screen_planes (f)
6655 register struct frame *f;
6657 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
6660 /* Return the display structure for the display named NAME.
6661 Open a new connection if necessary. */
6663 struct w32_display_info *
6664 x_display_info_for_name (name)
6665 Lisp_Object name;
6667 Lisp_Object names;
6668 struct w32_display_info *dpyinfo;
6670 CHECK_STRING (name);
6672 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
6673 dpyinfo;
6674 dpyinfo = dpyinfo->next, names = XCDR (names))
6676 Lisp_Object tem;
6677 tem = Fstring_equal (XCAR (XCAR (names)), name);
6678 if (!NILP (tem))
6679 return dpyinfo;
6682 /* Use this general default value to start with. */
6683 Vx_resource_name = Vinvocation_name;
6685 validate_x_resource_name ();
6687 dpyinfo = w32_term_init (name, (unsigned char *)0,
6688 (char *) SDATA (Vx_resource_name));
6690 if (dpyinfo == 0)
6691 error ("Cannot connect to server %s", SDATA (name));
6693 w32_in_use = 1;
6694 XSETFASTINT (Vwindow_system_version, 3);
6696 return dpyinfo;
6699 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6700 1, 3, 0, doc: /* Open a connection to a server.
6701 DISPLAY is the name of the display to connect to.
6702 Optional second arg XRM-STRING is a string of resources in xrdb format.
6703 If the optional third arg MUST-SUCCEED is non-nil,
6704 terminate Emacs if we can't open the connection. */)
6705 (display, xrm_string, must_succeed)
6706 Lisp_Object display, xrm_string, must_succeed;
6708 unsigned char *xrm_option;
6709 struct w32_display_info *dpyinfo;
6711 /* If initialization has already been done, return now to avoid
6712 overwriting critical parts of one_w32_display_info. */
6713 if (w32_in_use)
6714 return Qnil;
6716 CHECK_STRING (display);
6717 if (! NILP (xrm_string))
6718 CHECK_STRING (xrm_string);
6720 if (! EQ (Vwindow_system, intern ("w32")))
6721 error ("Not using Microsoft Windows");
6723 /* Allow color mapping to be defined externally; first look in user's
6724 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6726 Lisp_Object color_file;
6727 struct gcpro gcpro1;
6729 color_file = build_string ("~/rgb.txt");
6731 GCPRO1 (color_file);
6733 if (NILP (Ffile_readable_p (color_file)))
6734 color_file =
6735 Fexpand_file_name (build_string ("rgb.txt"),
6736 Fsymbol_value (intern ("data-directory")));
6738 Vw32_color_map = Fw32_load_color_file (color_file);
6740 UNGCPRO;
6742 if (NILP (Vw32_color_map))
6743 Vw32_color_map = Fw32_default_color_map ();
6745 /* Merge in system logical colors. */
6746 add_system_logical_colors_to_map (&Vw32_color_map);
6748 if (! NILP (xrm_string))
6749 xrm_option = (unsigned char *) SDATA (xrm_string);
6750 else
6751 xrm_option = (unsigned char *) 0;
6753 /* Use this general default value to start with. */
6754 /* First remove .exe suffix from invocation-name - it looks ugly. */
6756 char basename[ MAX_PATH ], *str;
6758 strcpy (basename, SDATA (Vinvocation_name));
6759 str = strrchr (basename, '.');
6760 if (str) *str = 0;
6761 Vinvocation_name = build_string (basename);
6763 Vx_resource_name = Vinvocation_name;
6765 validate_x_resource_name ();
6767 /* This is what opens the connection and sets x_current_display.
6768 This also initializes many symbols, such as those used for input. */
6769 dpyinfo = w32_term_init (display, xrm_option,
6770 (char *) SDATA (Vx_resource_name));
6772 if (dpyinfo == 0)
6774 if (!NILP (must_succeed))
6775 fatal ("Cannot connect to server %s.\n",
6776 SDATA (display));
6777 else
6778 error ("Cannot connect to server %s", SDATA (display));
6781 w32_in_use = 1;
6783 XSETFASTINT (Vwindow_system_version, 3);
6784 return Qnil;
6787 DEFUN ("x-close-connection", Fx_close_connection,
6788 Sx_close_connection, 1, 1, 0,
6789 doc: /* Close the connection to DISPLAY's server.
6790 For DISPLAY, specify either a frame or a display name (a string).
6791 If DISPLAY is nil, that stands for the selected frame's display. */)
6792 (display)
6793 Lisp_Object display;
6795 struct w32_display_info *dpyinfo = check_x_display_info (display);
6796 int i;
6798 if (dpyinfo->reference_count > 0)
6799 error ("Display still has frames on it");
6801 BLOCK_INPUT;
6802 /* Free the fonts in the font table. */
6803 for (i = 0; i < dpyinfo->n_fonts; i++)
6804 if (dpyinfo->font_table[i].name)
6806 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
6807 xfree (dpyinfo->font_table[i].full_name);
6808 xfree (dpyinfo->font_table[i].name);
6809 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
6811 x_destroy_all_bitmaps (dpyinfo);
6813 x_delete_display (dpyinfo);
6814 UNBLOCK_INPUT;
6816 return Qnil;
6819 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6820 doc: /* Return the list of display names that Emacs has connections to. */)
6823 Lisp_Object tail, result;
6825 result = Qnil;
6826 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
6827 result = Fcons (XCAR (XCAR (tail)), result);
6829 return result;
6832 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6833 doc: /* This is a noop on W32 systems. */)
6834 (on, display)
6835 Lisp_Object display, on;
6837 return Qnil;
6842 /***********************************************************************
6843 Window properties
6844 ***********************************************************************/
6846 DEFUN ("x-change-window-property", Fx_change_window_property,
6847 Sx_change_window_property, 2, 6, 0,
6848 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6849 VALUE may be a string or a list of conses, numbers and/or strings.
6850 If an element in the list is a string, it is converted to
6851 an Atom and the value of the Atom is used. If an element is a cons,
6852 it is converted to a 32 bit number where the car is the 16 top bits and the
6853 cdr is the lower 16 bits.
6854 FRAME nil or omitted means use the selected frame.
6855 If TYPE is given and non-nil, it is the name of the type of VALUE.
6856 If TYPE is not given or nil, the type is STRING.
6857 FORMAT gives the size in bits of each element if VALUE is a list.
6858 It must be one of 8, 16 or 32.
6859 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6860 If OUTER_P is non-nil, the property is changed for the outer X window of
6861 FRAME. Default is to change on the edit X window.
6863 Value is VALUE. */)
6864 (prop, value, frame, type, format, outer_p)
6865 Lisp_Object prop, value, frame, type, format, outer_p;
6867 #if 0 /* TODO : port window properties to W32 */
6868 struct frame *f = check_x_frame (frame);
6869 Atom prop_atom;
6871 CHECK_STRING (prop);
6872 CHECK_STRING (value);
6874 BLOCK_INPUT;
6875 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6876 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6877 prop_atom, XA_STRING, 8, PropModeReplace,
6878 SDATA (value), SCHARS (value));
6880 /* Make sure the property is set when we return. */
6881 XFlush (FRAME_W32_DISPLAY (f));
6882 UNBLOCK_INPUT;
6884 #endif /* TODO */
6886 return value;
6890 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6891 Sx_delete_window_property, 1, 2, 0,
6892 doc: /* Remove window property PROP from X window of FRAME.
6893 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6894 (prop, frame)
6895 Lisp_Object prop, frame;
6897 #if 0 /* TODO : port window properties to W32 */
6899 struct frame *f = check_x_frame (frame);
6900 Atom prop_atom;
6902 CHECK_STRING (prop);
6903 BLOCK_INPUT;
6904 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6905 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6907 /* Make sure the property is removed when we return. */
6908 XFlush (FRAME_W32_DISPLAY (f));
6909 UNBLOCK_INPUT;
6910 #endif /* TODO */
6912 return prop;
6916 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6917 1, 2, 0,
6918 doc: /* Value is the value of window property PROP on FRAME.
6919 If FRAME is nil or omitted, use the selected frame. Value is nil
6920 if FRAME hasn't a property with name PROP or if PROP has no string
6921 value. */)
6922 (prop, frame)
6923 Lisp_Object prop, frame;
6925 #if 0 /* TODO : port window properties to W32 */
6927 struct frame *f = check_x_frame (frame);
6928 Atom prop_atom;
6929 int rc;
6930 Lisp_Object prop_value = Qnil;
6931 char *tmp_data = NULL;
6932 Atom actual_type;
6933 int actual_format;
6934 unsigned long actual_size, bytes_remaining;
6936 CHECK_STRING (prop);
6937 BLOCK_INPUT;
6938 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6939 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6940 prop_atom, 0, 0, False, XA_STRING,
6941 &actual_type, &actual_format, &actual_size,
6942 &bytes_remaining, (unsigned char **) &tmp_data);
6943 if (rc == Success)
6945 int size = bytes_remaining;
6947 XFree (tmp_data);
6948 tmp_data = NULL;
6950 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6951 prop_atom, 0, bytes_remaining,
6952 False, XA_STRING,
6953 &actual_type, &actual_format,
6954 &actual_size, &bytes_remaining,
6955 (unsigned char **) &tmp_data);
6956 if (rc == Success)
6957 prop_value = make_string (tmp_data, size);
6959 XFree (tmp_data);
6962 UNBLOCK_INPUT;
6964 return prop_value;
6966 #endif /* TODO */
6967 return Qnil;
6972 /***********************************************************************
6973 Busy cursor
6974 ***********************************************************************/
6976 /* If non-null, an asynchronous timer that, when it expires, displays
6977 an hourglass cursor on all frames. */
6979 static struct atimer *hourglass_atimer;
6981 /* Non-zero means an hourglass cursor is currently shown. */
6983 static int hourglass_shown_p;
6985 /* Number of seconds to wait before displaying an hourglass cursor. */
6987 static Lisp_Object Vhourglass_delay;
6989 /* Default number of seconds to wait before displaying an hourglass
6990 cursor. */
6992 #define DEFAULT_HOURGLASS_DELAY 1
6994 /* Function prototypes. */
6996 static void show_hourglass P_ ((struct atimer *));
6997 static void hide_hourglass P_ ((void));
7000 /* Cancel a currently active hourglass timer, and start a new one. */
7002 void
7003 start_hourglass ()
7005 #if 0 /* TODO: cursor shape changes. */
7006 EMACS_TIME delay;
7007 int secs, usecs = 0;
7009 cancel_hourglass ();
7011 if (INTEGERP (Vhourglass_delay)
7012 && XINT (Vhourglass_delay) > 0)
7013 secs = XFASTINT (Vhourglass_delay);
7014 else if (FLOATP (Vhourglass_delay)
7015 && XFLOAT_DATA (Vhourglass_delay) > 0)
7017 Lisp_Object tem;
7018 tem = Ftruncate (Vhourglass_delay, Qnil);
7019 secs = XFASTINT (tem);
7020 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
7022 else
7023 secs = DEFAULT_HOURGLASS_DELAY;
7025 EMACS_SET_SECS_USECS (delay, secs, usecs);
7026 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
7027 show_hourglass, NULL);
7028 #endif
7032 /* Cancel the hourglass cursor timer if active, hide an hourglass
7033 cursor if shown. */
7035 void
7036 cancel_hourglass ()
7038 if (hourglass_atimer)
7040 cancel_atimer (hourglass_atimer);
7041 hourglass_atimer = NULL;
7044 if (hourglass_shown_p)
7045 hide_hourglass ();
7049 /* Timer function of hourglass_atimer. TIMER is equal to
7050 hourglass_atimer.
7052 Display an hourglass cursor on all frames by mapping the frames'
7053 hourglass_window. Set the hourglass_p flag in the frames'
7054 output_data.x structure to indicate that an hourglass cursor is
7055 shown on the frames. */
7057 static void
7058 show_hourglass (timer)
7059 struct atimer *timer;
7061 #if 0 /* TODO: cursor shape changes. */
7062 /* The timer implementation will cancel this timer automatically
7063 after this function has run. Set hourglass_atimer to null
7064 so that we know the timer doesn't have to be canceled. */
7065 hourglass_atimer = NULL;
7067 if (!hourglass_shown_p)
7069 Lisp_Object rest, frame;
7071 BLOCK_INPUT;
7073 FOR_EACH_FRAME (rest, frame)
7074 if (FRAME_W32_P (XFRAME (frame)))
7076 struct frame *f = XFRAME (frame);
7078 f->output_data.w32->hourglass_p = 1;
7080 if (!f->output_data.w32->hourglass_window)
7082 unsigned long mask = CWCursor;
7083 XSetWindowAttributes attrs;
7085 attrs.cursor = f->output_data.w32->hourglass_cursor;
7087 f->output_data.w32->hourglass_window
7088 = XCreateWindow (FRAME_X_DISPLAY (f),
7089 FRAME_OUTER_WINDOW (f),
7090 0, 0, 32000, 32000, 0, 0,
7091 InputOnly,
7092 CopyFromParent,
7093 mask, &attrs);
7096 XMapRaised (FRAME_X_DISPLAY (f),
7097 f->output_data.w32->hourglass_window);
7098 XFlush (FRAME_X_DISPLAY (f));
7101 hourglass_shown_p = 1;
7102 UNBLOCK_INPUT;
7104 #endif
7108 /* Hide the hourglass cursor on all frames, if it is currently shown. */
7110 static void
7111 hide_hourglass ()
7113 #if 0 /* TODO: cursor shape changes. */
7114 if (hourglass_shown_p)
7116 Lisp_Object rest, frame;
7118 BLOCK_INPUT;
7119 FOR_EACH_FRAME (rest, frame)
7121 struct frame *f = XFRAME (frame);
7123 if (FRAME_W32_P (f)
7124 /* Watch out for newly created frames. */
7125 && f->output_data.x->hourglass_window)
7127 XUnmapWindow (FRAME_X_DISPLAY (f),
7128 f->output_data.x->hourglass_window);
7129 /* Sync here because XTread_socket looks at the
7130 hourglass_p flag that is reset to zero below. */
7131 XSync (FRAME_X_DISPLAY (f), False);
7132 f->output_data.x->hourglass_p = 0;
7136 hourglass_shown_p = 0;
7137 UNBLOCK_INPUT;
7139 #endif
7144 /***********************************************************************
7145 Tool tips
7146 ***********************************************************************/
7148 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
7149 Lisp_Object, Lisp_Object));
7150 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
7151 Lisp_Object, int, int, int *, int *));
7153 /* The frame of a currently visible tooltip. */
7155 Lisp_Object tip_frame;
7157 /* If non-nil, a timer started that hides the last tooltip when it
7158 fires. */
7160 Lisp_Object tip_timer;
7161 Window tip_window;
7163 /* If non-nil, a vector of 3 elements containing the last args
7164 with which x-show-tip was called. See there. */
7166 Lisp_Object last_show_tip_args;
7168 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
7170 Lisp_Object Vx_max_tooltip_size;
7173 static Lisp_Object
7174 unwind_create_tip_frame (frame)
7175 Lisp_Object frame;
7177 Lisp_Object deleted;
7179 deleted = unwind_create_frame (frame);
7180 if (EQ (deleted, Qt))
7182 tip_window = NULL;
7183 tip_frame = Qnil;
7186 return deleted;
7190 /* Create a frame for a tooltip on the display described by DPYINFO.
7191 PARMS is a list of frame parameters. TEXT is the string to
7192 display in the tip frame. Value is the frame.
7194 Note that functions called here, esp. x_default_parameter can
7195 signal errors, for instance when a specified color name is
7196 undefined. We have to make sure that we're in a consistent state
7197 when this happens. */
7199 static Lisp_Object
7200 x_create_tip_frame (dpyinfo, parms, text)
7201 struct w32_display_info *dpyinfo;
7202 Lisp_Object parms, text;
7204 struct frame *f;
7205 Lisp_Object frame, tem;
7206 Lisp_Object name;
7207 long window_prompting = 0;
7208 int width, height;
7209 int count = SPECPDL_INDEX ();
7210 struct gcpro gcpro1, gcpro2, gcpro3;
7211 struct kboard *kb;
7212 int face_change_count_before = face_change_count;
7213 Lisp_Object buffer;
7214 struct buffer *old_buffer;
7216 check_w32 ();
7218 /* Use this general default value to start with until we know if
7219 this frame has a specified name. */
7220 Vx_resource_name = Vinvocation_name;
7222 #ifdef MULTI_KBOARD
7223 kb = dpyinfo->kboard;
7224 #else
7225 kb = &the_only_kboard;
7226 #endif
7228 /* Get the name of the frame to use for resource lookup. */
7229 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
7230 if (!STRINGP (name)
7231 && !EQ (name, Qunbound)
7232 && !NILP (name))
7233 error ("Invalid frame name--not a string or nil");
7234 Vx_resource_name = name;
7236 frame = Qnil;
7237 GCPRO3 (parms, name, frame);
7238 /* Make a frame without minibuffer nor mode-line. */
7239 f = make_frame (0);
7240 f->wants_modeline = 0;
7241 XSETFRAME (frame, f);
7243 buffer = Fget_buffer_create (build_string (" *tip*"));
7244 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer, Qnil);
7245 old_buffer = current_buffer;
7246 set_buffer_internal_1 (XBUFFER (buffer));
7247 current_buffer->truncate_lines = Qnil;
7248 specbind (Qinhibit_read_only, Qt);
7249 specbind (Qinhibit_modification_hooks, Qt);
7250 Ferase_buffer ();
7251 Finsert (1, &text);
7252 set_buffer_internal_1 (old_buffer);
7254 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
7255 record_unwind_protect (unwind_create_tip_frame, frame);
7257 /* By setting the output method, we're essentially saying that
7258 the frame is live, as per FRAME_LIVE_P. If we get a signal
7259 from this point on, x_destroy_window might screw up reference
7260 counts etc. */
7261 f->output_method = output_w32;
7262 f->output_data.w32 =
7263 (struct w32_output *) xmalloc (sizeof (struct w32_output));
7264 bzero (f->output_data.w32, sizeof (struct w32_output));
7266 FRAME_FONTSET (f) = -1;
7267 f->icon_name = Qnil;
7269 #if 0 /* GLYPH_DEBUG TODO: image support. */
7270 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
7271 dpyinfo_refcount = dpyinfo->reference_count;
7272 #endif /* GLYPH_DEBUG */
7273 #ifdef MULTI_KBOARD
7274 FRAME_KBOARD (f) = kb;
7275 #endif
7276 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
7277 f->output_data.w32->explicit_parent = 0;
7279 /* Set the name; the functions to which we pass f expect the name to
7280 be set. */
7281 if (EQ (name, Qunbound) || NILP (name))
7283 f->name = build_string (dpyinfo->w32_id_name);
7284 f->explicit_name = 0;
7286 else
7288 f->name = name;
7289 f->explicit_name = 1;
7290 /* use the frame's title when getting resources for this frame. */
7291 specbind (Qx_resource_name, name);
7294 /* Extract the window parameters from the supplied values
7295 that are needed to determine window geometry. */
7297 Lisp_Object font;
7299 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
7301 BLOCK_INPUT;
7302 /* First, try whatever font the caller has specified. */
7303 if (STRINGP (font))
7305 tem = Fquery_fontset (font, Qnil);
7306 if (STRINGP (tem))
7307 font = x_new_fontset (f, SDATA (tem));
7308 else
7309 font = x_new_font (f, SDATA (font));
7312 /* Try out a font which we hope has bold and italic variations. */
7313 if (!STRINGP (font))
7314 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
7315 if (! STRINGP (font))
7316 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
7317 /* If those didn't work, look for something which will at least work. */
7318 if (! STRINGP (font))
7319 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
7320 UNBLOCK_INPUT;
7321 if (! STRINGP (font))
7322 font = build_string ("Fixedsys");
7324 x_default_parameter (f, parms, Qfont, font,
7325 "font", "Font", RES_TYPE_STRING);
7328 x_default_parameter (f, parms, Qborder_width, make_number (2),
7329 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
7330 /* This defaults to 2 in order to match xterm. We recognize either
7331 internalBorderWidth or internalBorder (which is what xterm calls
7332 it). */
7333 if (NILP (Fassq (Qinternal_border_width, parms)))
7335 Lisp_Object value;
7337 value = w32_get_arg (parms, Qinternal_border_width,
7338 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
7339 if (! EQ (value, Qunbound))
7340 parms = Fcons (Fcons (Qinternal_border_width, value),
7341 parms);
7343 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
7344 "internalBorderWidth", "internalBorderWidth",
7345 RES_TYPE_NUMBER);
7347 /* Also do the stuff which must be set before the window exists. */
7348 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
7349 "foreground", "Foreground", RES_TYPE_STRING);
7350 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
7351 "background", "Background", RES_TYPE_STRING);
7352 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
7353 "pointerColor", "Foreground", RES_TYPE_STRING);
7354 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
7355 "cursorColor", "Foreground", RES_TYPE_STRING);
7356 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
7357 "borderColor", "BorderColor", RES_TYPE_STRING);
7359 /* Init faces before x_default_parameter is called for scroll-bar
7360 parameters because that function calls x_set_scroll_bar_width,
7361 which calls change_frame_size, which calls Fset_window_buffer,
7362 which runs hooks, which call Fvertical_motion. At the end, we
7363 end up in init_iterator with a null face cache, which should not
7364 happen. */
7365 init_frame_faces (f);
7367 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
7368 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
7370 window_prompting = x_figure_window_size (f, parms, 0);
7372 /* No fringes on tip frame. */
7373 f->fringe_cols = 0;
7374 f->left_fringe_width = 0;
7375 f->right_fringe_width = 0;
7377 BLOCK_INPUT;
7378 my_create_tip_window (f);
7379 UNBLOCK_INPUT;
7381 x_make_gc (f);
7383 x_default_parameter (f, parms, Qauto_raise, Qnil,
7384 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7385 x_default_parameter (f, parms, Qauto_lower, Qnil,
7386 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7387 x_default_parameter (f, parms, Qcursor_type, Qbox,
7388 "cursorType", "CursorType", RES_TYPE_SYMBOL);
7390 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
7391 Change will not be effected unless different from the current
7392 FRAME_LINES (f). */
7393 width = FRAME_COLS (f);
7394 height = FRAME_LINES (f);
7395 FRAME_LINES (f) = 0;
7396 SET_FRAME_COLS (f, 0);
7397 change_frame_size (f, height, width, 1, 0, 0);
7399 /* Add `tooltip' frame parameter's default value. */
7400 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
7401 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
7402 Qnil));
7404 /* Set up faces after all frame parameters are known. This call
7405 also merges in face attributes specified for new frames.
7407 Frame parameters may be changed if .Xdefaults contains
7408 specifications for the default font. For example, if there is an
7409 `Emacs.default.attributeBackground: pink', the `background-color'
7410 attribute of the frame get's set, which let's the internal border
7411 of the tooltip frame appear in pink. Prevent this. */
7413 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
7415 /* Set tip_frame here, so that */
7416 tip_frame = frame;
7417 call1 (Qface_set_after_frame_default, frame);
7419 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
7420 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
7421 Qnil));
7424 f->no_split = 1;
7426 UNGCPRO;
7428 /* It is now ok to make the frame official even if we get an error
7429 below. And the frame needs to be on Vframe_list or making it
7430 visible won't work. */
7431 Vframe_list = Fcons (frame, Vframe_list);
7433 /* Now that the frame is official, it counts as a reference to
7434 its display. */
7435 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
7437 /* Setting attributes of faces of the tooltip frame from resources
7438 and similar will increment face_change_count, which leads to the
7439 clearing of all current matrices. Since this isn't necessary
7440 here, avoid it by resetting face_change_count to the value it
7441 had before we created the tip frame. */
7442 face_change_count = face_change_count_before;
7444 /* Discard the unwind_protect. */
7445 return unbind_to (count, frame);
7449 /* Compute where to display tip frame F. PARMS is the list of frame
7450 parameters for F. DX and DY are specified offsets from the current
7451 location of the mouse. WIDTH and HEIGHT are the width and height
7452 of the tooltip. Return coordinates relative to the root window of
7453 the display in *ROOT_X, and *ROOT_Y. */
7455 static void
7456 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
7457 struct frame *f;
7458 Lisp_Object parms, dx, dy;
7459 int width, height;
7460 int *root_x, *root_y;
7462 Lisp_Object left, top;
7464 /* User-specified position? */
7465 left = Fcdr (Fassq (Qleft, parms));
7466 top = Fcdr (Fassq (Qtop, parms));
7468 /* Move the tooltip window where the mouse pointer is. Resize and
7469 show it. */
7470 if (!INTEGERP (left) || !INTEGERP (top))
7472 POINT pt;
7474 BLOCK_INPUT;
7475 GetCursorPos (&pt);
7476 *root_x = pt.x;
7477 *root_y = pt.y;
7478 UNBLOCK_INPUT;
7481 if (INTEGERP (top))
7482 *root_y = XINT (top);
7483 else if (*root_y + XINT (dy) <= 0)
7484 *root_y = 0; /* Can happen for negative dy */
7485 else if (*root_y + XINT (dy) + height <= FRAME_W32_DISPLAY_INFO (f)->height)
7486 /* It fits below the pointer */
7487 *root_y += XINT (dy);
7488 else if (height + XINT (dy) <= *root_y)
7489 /* It fits above the pointer. */
7490 *root_y -= height + XINT (dy);
7491 else
7492 /* Put it on the top. */
7493 *root_y = 0;
7495 if (INTEGERP (left))
7496 *root_x = XINT (left);
7497 else if (*root_x + XINT (dx) <= 0)
7498 *root_x = 0; /* Can happen for negative dx */
7499 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
7500 /* It fits to the right of the pointer. */
7501 *root_x += XINT (dx);
7502 else if (width + XINT (dx) <= *root_x)
7503 /* It fits to the left of the pointer. */
7504 *root_x -= width + XINT (dx);
7505 else
7506 /* Put it left justified on the screen -- it ought to fit that way. */
7507 *root_x = 0;
7511 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
7512 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
7513 A tooltip window is a small window displaying a string.
7515 This is an internal function; Lisp code should call `tooltip-show'.
7517 FRAME nil or omitted means use the selected frame.
7519 PARMS is an optional list of frame parameters which can be
7520 used to change the tooltip's appearance.
7522 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
7523 means use the default timeout of 5 seconds.
7525 If the list of frame parameters PARMS contains a `left' parameter,
7526 the tooltip is displayed at that x-position. Otherwise it is
7527 displayed at the mouse position, with offset DX added (default is 5 if
7528 DX isn't specified). Likewise for the y-position; if a `top' frame
7529 parameter is specified, it determines the y-position of the tooltip
7530 window, otherwise it is displayed at the mouse position, with offset
7531 DY added (default is -10).
7533 A tooltip's maximum size is specified by `x-max-tooltip-size'.
7534 Text larger than the specified size is clipped. */)
7535 (string, frame, parms, timeout, dx, dy)
7536 Lisp_Object string, frame, parms, timeout, dx, dy;
7538 struct frame *f;
7539 struct window *w;
7540 int root_x, root_y;
7541 struct buffer *old_buffer;
7542 struct text_pos pos;
7543 int i, width, height;
7544 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
7545 int old_windows_or_buffers_changed = windows_or_buffers_changed;
7546 int count = SPECPDL_INDEX ();
7548 specbind (Qinhibit_redisplay, Qt);
7550 GCPRO4 (string, parms, frame, timeout);
7552 CHECK_STRING (string);
7553 f = check_x_frame (frame);
7554 if (NILP (timeout))
7555 timeout = make_number (5);
7556 else
7557 CHECK_NATNUM (timeout);
7559 if (NILP (dx))
7560 dx = make_number (5);
7561 else
7562 CHECK_NUMBER (dx);
7564 if (NILP (dy))
7565 dy = make_number (-10);
7566 else
7567 CHECK_NUMBER (dy);
7569 if (NILP (last_show_tip_args))
7570 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
7572 if (!NILP (tip_frame))
7574 Lisp_Object last_string = AREF (last_show_tip_args, 0);
7575 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
7576 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
7578 if (EQ (frame, last_frame)
7579 && !NILP (Fequal (last_string, string))
7580 && !NILP (Fequal (last_parms, parms)))
7582 struct frame *f = XFRAME (tip_frame);
7584 /* Only DX and DY have changed. */
7585 if (!NILP (tip_timer))
7587 Lisp_Object timer = tip_timer;
7588 tip_timer = Qnil;
7589 call1 (Qcancel_timer, timer);
7592 BLOCK_INPUT;
7593 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
7594 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
7596 /* Put tooltip in topmost group and in position. */
7597 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
7598 root_x, root_y, 0, 0,
7599 SWP_NOSIZE | SWP_NOACTIVATE);
7601 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7602 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
7603 0, 0, 0, 0,
7604 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
7606 UNBLOCK_INPUT;
7607 goto start_timer;
7611 /* Hide a previous tip, if any. */
7612 Fx_hide_tip ();
7614 ASET (last_show_tip_args, 0, string);
7615 ASET (last_show_tip_args, 1, frame);
7616 ASET (last_show_tip_args, 2, parms);
7618 /* Add default values to frame parameters. */
7619 if (NILP (Fassq (Qname, parms)))
7620 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7621 if (NILP (Fassq (Qinternal_border_width, parms)))
7622 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7623 if (NILP (Fassq (Qborder_width, parms)))
7624 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7625 if (NILP (Fassq (Qborder_color, parms)))
7626 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7627 if (NILP (Fassq (Qbackground_color, parms)))
7628 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7629 parms);
7631 /* Block input until the tip has been fully drawn, to avoid crashes
7632 when drawing tips in menus. */
7633 BLOCK_INPUT;
7635 /* Create a frame for the tooltip, and record it in the global
7636 variable tip_frame. */
7637 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
7638 f = XFRAME (frame);
7640 /* Set up the frame's root window. */
7641 w = XWINDOW (FRAME_ROOT_WINDOW (f));
7642 w->left_col = w->top_line = make_number (0);
7644 if (CONSP (Vx_max_tooltip_size)
7645 && INTEGERP (XCAR (Vx_max_tooltip_size))
7646 && XINT (XCAR (Vx_max_tooltip_size)) > 0
7647 && INTEGERP (XCDR (Vx_max_tooltip_size))
7648 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
7650 w->total_cols = XCAR (Vx_max_tooltip_size);
7651 w->total_lines = XCDR (Vx_max_tooltip_size);
7653 else
7655 w->total_cols = make_number (80);
7656 w->total_lines = make_number (40);
7659 FRAME_TOTAL_COLS (f) = XINT (w->total_cols);
7660 adjust_glyphs (f);
7661 w->pseudo_window_p = 1;
7663 /* Display the tooltip text in a temporary buffer. */
7664 old_buffer = current_buffer;
7665 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
7666 current_buffer->truncate_lines = Qnil;
7667 clear_glyph_matrix (w->desired_matrix);
7668 clear_glyph_matrix (w->current_matrix);
7669 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7670 try_window (FRAME_ROOT_WINDOW (f), pos, 0);
7672 /* Compute width and height of the tooltip. */
7673 width = height = 0;
7674 for (i = 0; i < w->desired_matrix->nrows; ++i)
7676 struct glyph_row *row = &w->desired_matrix->rows[i];
7677 struct glyph *last;
7678 int row_width;
7680 /* Stop at the first empty row at the end. */
7681 if (!row->enabled_p || !row->displays_text_p)
7682 break;
7684 /* Let the row go over the full width of the frame. */
7685 row->full_width_p = 1;
7687 #ifdef TODO /* Investigate why some fonts need more width than is
7688 calculated for some tooltips. */
7689 /* There's a glyph at the end of rows that is use to place
7690 the cursor there. Don't include the width of this glyph. */
7691 if (row->used[TEXT_AREA])
7693 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
7694 row_width = row->pixel_width - last->pixel_width;
7696 else
7697 #endif
7698 row_width = row->pixel_width;
7700 /* TODO: find why tips do not draw along baseline as instructed. */
7701 height += row->height;
7702 width = max (width, row_width);
7705 /* Add the frame's internal border to the width and height the X
7706 window should have. */
7707 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
7708 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
7710 /* Move the tooltip window where the mouse pointer is. Resize and
7711 show it. */
7712 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
7715 /* Adjust Window size to take border into account. */
7716 RECT rect;
7717 rect.left = rect.top = 0;
7718 rect.right = width;
7719 rect.bottom = height;
7720 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
7721 FRAME_EXTERNAL_MENU_BAR (f));
7723 /* Position and size tooltip, and put it in the topmost group.
7724 The add-on of 3 to the 5th argument is a kludge: without it,
7725 some fonts cause the last character of the tip to be truncated,
7726 for some obscure reason. */
7727 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
7728 root_x, root_y, rect.right - rect.left + 3,
7729 rect.bottom - rect.top, SWP_NOACTIVATE);
7731 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7732 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
7733 0, 0, 0, 0,
7734 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
7736 /* Let redisplay know that we have made the frame visible already. */
7737 f->async_visible = 1;
7739 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
7742 /* Draw into the window. */
7743 w->must_be_updated_p = 1;
7744 update_single_window (w, 1);
7746 UNBLOCK_INPUT;
7748 /* Restore original current buffer. */
7749 set_buffer_internal_1 (old_buffer);
7750 windows_or_buffers_changed = old_windows_or_buffers_changed;
7752 start_timer:
7753 /* Let the tip disappear after timeout seconds. */
7754 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7755 intern ("x-hide-tip"));
7757 UNGCPRO;
7758 return unbind_to (count, Qnil);
7762 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7763 doc: /* Hide the current tooltip window, if there is any.
7764 Value is t if tooltip was open, nil otherwise. */)
7767 int count;
7768 Lisp_Object deleted, frame, timer;
7769 struct gcpro gcpro1, gcpro2;
7771 /* Return quickly if nothing to do. */
7772 if (NILP (tip_timer) && NILP (tip_frame))
7773 return Qnil;
7775 frame = tip_frame;
7776 timer = tip_timer;
7777 GCPRO2 (frame, timer);
7778 tip_frame = tip_timer = deleted = Qnil;
7780 count = SPECPDL_INDEX ();
7781 specbind (Qinhibit_redisplay, Qt);
7782 specbind (Qinhibit_quit, Qt);
7784 if (!NILP (timer))
7785 call1 (Qcancel_timer, timer);
7787 if (FRAMEP (frame))
7789 Fdelete_frame (frame, Qnil);
7790 deleted = Qt;
7793 UNGCPRO;
7794 return unbind_to (count, deleted);
7799 /***********************************************************************
7800 File selection dialog
7801 ***********************************************************************/
7802 extern Lisp_Object Qfile_name_history;
7804 /* Callback for altering the behaviour of the Open File dialog.
7805 Makes the Filename text field contain "Current Directory" and be
7806 read-only when "Directories" is selected in the filter. This
7807 allows us to work around the fact that the standard Open File
7808 dialog does not support directories. */
7809 UINT CALLBACK
7810 file_dialog_callback (hwnd, msg, wParam, lParam)
7811 HWND hwnd;
7812 UINT msg;
7813 WPARAM wParam;
7814 LPARAM lParam;
7816 if (msg == WM_NOTIFY)
7818 OFNOTIFY * notify = (OFNOTIFY *)lParam;
7819 /* Detect when the Filter dropdown is changed. */
7820 if (notify->hdr.code == CDN_TYPECHANGE
7821 || notify->hdr.code == CDN_INITDONE)
7823 HWND dialog = GetParent (hwnd);
7824 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7826 /* Directories is in index 2. */
7827 if (notify->lpOFN->nFilterIndex == 2)
7829 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
7830 "Current Directory");
7831 EnableWindow (edit_control, FALSE);
7833 else
7835 /* Don't override default filename on init done. */
7836 if (notify->hdr.code == CDN_TYPECHANGE)
7837 CommDlg_OpenSave_SetControlText (dialog,
7838 FILE_NAME_TEXT_FIELD, "");
7839 EnableWindow (edit_control, TRUE);
7843 return 0;
7846 /* Since we compile with _WIN32_WINNT set to 0x0400 (for NT4 compatibility)
7847 we end up with the old file dialogs. Define a big enough struct for the
7848 new dialog to trick GetOpenFileName into giving us the new dialogs on
7849 Windows 2000 and XP. */
7850 typedef struct
7852 OPENFILENAME real_details;
7853 void * pReserved;
7854 DWORD dwReserved;
7855 DWORD FlagsEx;
7856 } NEWOPENFILENAME;
7859 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7860 doc: /* Read file name, prompting with PROMPT in directory DIR.
7861 Use a file selection dialog.
7862 Select DEFAULT-FILENAME in the dialog's file selection box, if
7863 specified. Ensure that file exists if MUSTMATCH is non-nil.
7864 If ONLY-DIR-P is non-nil, the user can only select directories. */)
7865 (prompt, dir, default_filename, mustmatch, only_dir_p)
7866 Lisp_Object prompt, dir, default_filename, mustmatch, only_dir_p;
7868 struct frame *f = SELECTED_FRAME ();
7869 Lisp_Object file = Qnil;
7870 int count = SPECPDL_INDEX ();
7871 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
7872 char filename[MAX_PATH + 1];
7873 char init_dir[MAX_PATH + 1];
7874 int default_filter_index = 1; /* 1: All Files, 2: Directories only */
7876 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, file);
7877 CHECK_STRING (prompt);
7878 CHECK_STRING (dir);
7880 /* Create the dialog with PROMPT as title, using DIR as initial
7881 directory and using "*" as pattern. */
7882 dir = Fexpand_file_name (dir, Qnil);
7883 strncpy (init_dir, SDATA (ENCODE_FILE (dir)), MAX_PATH);
7884 init_dir[MAX_PATH] = '\0';
7885 unixtodos_filename (init_dir);
7887 if (STRINGP (default_filename))
7889 char *file_name_only;
7890 char *full_path_name = SDATA (ENCODE_FILE (default_filename));
7892 unixtodos_filename (full_path_name);
7894 file_name_only = strrchr (full_path_name, '\\');
7895 if (!file_name_only)
7896 file_name_only = full_path_name;
7897 else
7898 file_name_only++;
7900 strncpy (filename, file_name_only, MAX_PATH);
7901 filename[MAX_PATH] = '\0';
7903 else
7904 filename[0] = '\0';
7907 NEWOPENFILENAME new_file_details;
7908 BOOL file_opened = FALSE;
7909 OPENFILENAME * file_details = &new_file_details.real_details;
7911 /* Prevent redisplay. */
7912 specbind (Qinhibit_redisplay, Qt);
7913 BLOCK_INPUT;
7915 bzero (&new_file_details, sizeof (new_file_details));
7916 /* Apparently NT4 crashes if you give it an unexpected size.
7917 I'm not sure about Windows 9x, so play it safe. */
7918 if (w32_major_version > 4 && w32_major_version < 95)
7919 file_details->lStructSize = sizeof (NEWOPENFILENAME);
7920 else
7921 file_details->lStructSize = sizeof (OPENFILENAME);
7923 file_details->hwndOwner = FRAME_W32_WINDOW (f);
7924 /* Undocumented Bug in Common File Dialog:
7925 If a filter is not specified, shell links are not resolved. */
7926 file_details->lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
7927 file_details->lpstrFile = filename;
7928 file_details->nMaxFile = sizeof (filename);
7929 file_details->lpstrInitialDir = init_dir;
7930 file_details->lpstrTitle = SDATA (prompt);
7932 if (! NILP (only_dir_p))
7933 default_filter_index = 2;
7935 file_details->nFilterIndex = default_filter_index;
7937 file_details->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7938 | OFN_EXPLORER | OFN_ENABLEHOOK);
7939 if (!NILP (mustmatch))
7941 /* Require that the path to the parent directory exists. */
7942 file_details->Flags |= OFN_PATHMUSTEXIST;
7943 /* If we are looking for a file, require that it exists. */
7944 if (NILP (only_dir_p))
7945 file_details->Flags |= OFN_FILEMUSTEXIST;
7948 file_details->lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
7950 file_opened = GetOpenFileName (file_details);
7952 UNBLOCK_INPUT;
7954 if (file_opened)
7956 dostounix_filename (filename);
7958 if (file_details->nFilterIndex == 2)
7960 /* "Directories" selected - strip dummy file name. */
7961 char * last = strrchr (filename, '/');
7962 *last = '\0';
7965 file = DECODE_FILE (build_string (filename));
7967 /* User cancelled the dialog without making a selection. */
7968 else if (!CommDlgExtendedError ())
7969 file = Qnil;
7970 /* An error occurred, fallback on reading from the mini-buffer. */
7971 else
7972 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
7973 dir, mustmatch, dir, Qfile_name_history,
7974 default_filename, Qnil);
7976 file = unbind_to (count, file);
7979 UNGCPRO;
7981 /* Make "Cancel" equivalent to C-g. */
7982 if (NILP (file))
7983 Fsignal (Qquit, Qnil);
7985 return unbind_to (count, file);
7990 /***********************************************************************
7991 w32 specialized functions
7992 ***********************************************************************/
7994 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
7995 doc: /* Select a font for the named FRAME using the W32 font dialog.
7996 Return an X-style font string corresponding to the selection.
7998 If FRAME is omitted or nil, it defaults to the selected frame.
7999 If INCLUDE-PROPORTIONAL is non-nil, include proportional fonts
8000 in the font selection dialog. */)
8001 (frame, include_proportional)
8002 Lisp_Object frame, include_proportional;
8004 FRAME_PTR f = check_x_frame (frame);
8005 CHOOSEFONT cf;
8006 LOGFONT lf;
8007 TEXTMETRIC tm;
8008 HDC hdc;
8009 HANDLE oldobj;
8010 char buf[100];
8012 bzero (&cf, sizeof (cf));
8013 bzero (&lf, sizeof (lf));
8015 cf.lStructSize = sizeof (cf);
8016 cf.hwndOwner = FRAME_W32_WINDOW (f);
8017 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
8019 /* Unless include_proportional is non-nil, limit the selection to
8020 monospaced fonts. */
8021 if (NILP (include_proportional))
8022 cf.Flags |= CF_FIXEDPITCHONLY;
8024 cf.lpLogFont = &lf;
8026 /* Initialize as much of the font details as we can from the current
8027 default font. */
8028 hdc = GetDC (FRAME_W32_WINDOW (f));
8029 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
8030 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
8031 if (GetTextMetrics (hdc, &tm))
8033 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
8034 lf.lfWeight = tm.tmWeight;
8035 lf.lfItalic = tm.tmItalic;
8036 lf.lfUnderline = tm.tmUnderlined;
8037 lf.lfStrikeOut = tm.tmStruckOut;
8038 lf.lfCharSet = tm.tmCharSet;
8039 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
8041 SelectObject (hdc, oldobj);
8042 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
8044 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
8045 return Qnil;
8047 return build_string (buf);
8050 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
8051 Sw32_send_sys_command, 1, 2, 0,
8052 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
8053 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
8054 to minimize), #xf120 to restore frame to original size, and #xf100
8055 to activate the menubar for keyboard access. #xf140 activates the
8056 screen saver if defined.
8058 If optional parameter FRAME is not specified, use selected frame. */)
8059 (command, frame)
8060 Lisp_Object command, frame;
8062 FRAME_PTR f = check_x_frame (frame);
8064 CHECK_NUMBER (command);
8066 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
8068 return Qnil;
8071 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
8072 doc: /* Get Windows to perform OPERATION on DOCUMENT.
8073 This is a wrapper around the ShellExecute system function, which
8074 invokes the application registered to handle OPERATION for DOCUMENT.
8076 OPERATION is either nil or a string that names a supported operation.
8077 What operations can be used depends on the particular DOCUMENT and its
8078 handler application, but typically it is one of the following common
8079 operations:
8081 \"open\" - open DOCUMENT, which could be a file, a directory, or an
8082 executable program. If it is an application, that
8083 application is launched in the current buffer's default
8084 directory. Otherwise, the application associated with
8085 DOCUMENT is launched in the buffer's default directory.
8086 \"print\" - print DOCUMENT, which must be a file
8087 \"explore\" - start the Windows Explorer on DOCUMENT
8088 \"edit\" - launch an editor and open DOCUMENT for editing; which
8089 editor is launched depends on the association for the
8090 specified DOCUMENT
8091 \"find\" - initiate search starting from DOCUMENT which must specify
8092 a directory
8093 nil - invoke the default OPERATION, or \"open\" if default is
8094 not defined or unavailable
8096 DOCUMENT is typically the name of a document file or a URL, but can
8097 also be a program executable to run, or a directory to open in the
8098 Windows Explorer.
8100 If DOCUMENT is a program executable, the optional third arg PARAMETERS
8101 can be a string containing command line parameters that will be passed
8102 to the program; otherwise, PARAMETERS should be nil or unspecified.
8104 Optional fourth argument SHOW-FLAG can be used to control how the
8105 application will be displayed when it is invoked. If SHOW-FLAG is nil
8106 or unspecified, the application is displayed normally, otherwise it is
8107 an integer representing a ShowWindow flag:
8109 0 - start hidden
8110 1 - start normally
8111 3 - start maximized
8112 6 - start minimized */)
8113 (operation, document, parameters, show_flag)
8114 Lisp_Object operation, document, parameters, show_flag;
8116 Lisp_Object current_dir;
8118 CHECK_STRING (document);
8120 /* Encode filename, current directory and parameters. */
8121 current_dir = ENCODE_FILE (current_buffer->directory);
8122 document = ENCODE_FILE (document);
8123 if (STRINGP (parameters))
8124 parameters = ENCODE_SYSTEM (parameters);
8126 if ((int) ShellExecute (NULL,
8127 (STRINGP (operation) ?
8128 SDATA (operation) : NULL),
8129 SDATA (document),
8130 (STRINGP (parameters) ?
8131 SDATA (parameters) : NULL),
8132 SDATA (current_dir),
8133 (INTEGERP (show_flag) ?
8134 XINT (show_flag) : SW_SHOWDEFAULT))
8135 > 32)
8136 return Qt;
8137 error ("ShellExecute failed: %s", w32_strerror (0));
8140 /* Lookup virtual keycode from string representing the name of a
8141 non-ascii keystroke into the corresponding virtual key, using
8142 lispy_function_keys. */
8143 static int
8144 lookup_vk_code (char *key)
8146 int i;
8148 for (i = 0; i < 256; i++)
8149 if (lispy_function_keys[i]
8150 && strcmp (lispy_function_keys[i], key) == 0)
8151 return i;
8153 return -1;
8156 /* Convert a one-element vector style key sequence to a hot key
8157 definition. */
8158 static Lisp_Object
8159 w32_parse_hot_key (key)
8160 Lisp_Object key;
8162 /* Copied from Fdefine_key and store_in_keymap. */
8163 register Lisp_Object c;
8164 int vk_code;
8165 int lisp_modifiers;
8166 int w32_modifiers;
8167 struct gcpro gcpro1;
8169 CHECK_VECTOR (key);
8171 if (XFASTINT (Flength (key)) != 1)
8172 return Qnil;
8174 GCPRO1 (key);
8176 c = Faref (key, make_number (0));
8178 if (CONSP (c) && lucid_event_type_list_p (c))
8179 c = Fevent_convert_list (c);
8181 UNGCPRO;
8183 if (! INTEGERP (c) && ! SYMBOLP (c))
8184 error ("Key definition is invalid");
8186 /* Work out the base key and the modifiers. */
8187 if (SYMBOLP (c))
8189 c = parse_modifiers (c);
8190 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8191 c = Fcar (c);
8192 if (!SYMBOLP (c))
8193 abort ();
8194 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
8196 else if (INTEGERP (c))
8198 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8199 /* Many ascii characters are their own virtual key code. */
8200 vk_code = XINT (c) & CHARACTERBITS;
8203 if (vk_code < 0 || vk_code > 255)
8204 return Qnil;
8206 if ((lisp_modifiers & meta_modifier) != 0
8207 && !NILP (Vw32_alt_is_meta))
8208 lisp_modifiers |= alt_modifier;
8210 /* Supply defs missing from mingw32. */
8211 #ifndef MOD_ALT
8212 #define MOD_ALT 0x0001
8213 #define MOD_CONTROL 0x0002
8214 #define MOD_SHIFT 0x0004
8215 #define MOD_WIN 0x0008
8216 #endif
8218 /* Convert lisp modifiers to Windows hot-key form. */
8219 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8220 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8221 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8222 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8224 return HOTKEY (vk_code, w32_modifiers);
8227 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8228 Sw32_register_hot_key, 1, 1, 0,
8229 doc: /* Register KEY as a hot-key combination.
8230 Certain key combinations like Alt-Tab are reserved for system use on
8231 Windows, and therefore are normally intercepted by the system. However,
8232 most of these key combinations can be received by registering them as
8233 hot-keys, overriding their special meaning.
8235 KEY must be a one element key definition in vector form that would be
8236 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
8237 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
8238 is always interpreted as the Windows modifier keys.
8240 The return value is the hotkey-id if registered, otherwise nil. */)
8241 (key)
8242 Lisp_Object key;
8244 key = w32_parse_hot_key (key);
8246 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8248 /* Reuse an empty slot if possible. */
8249 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8251 /* Safe to add new key to list, even if we have focus. */
8252 if (NILP (item))
8253 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8254 else
8255 XSETCAR (item, key);
8257 /* Notify input thread about new hot-key definition, so that it
8258 takes effect without needing to switch focus. */
8259 #ifdef USE_LISP_UNION_TYPE
8260 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8261 (WPARAM) key.i, 0);
8262 #else
8263 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8264 (WPARAM) key, 0);
8265 #endif
8268 return key;
8271 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8272 Sw32_unregister_hot_key, 1, 1, 0,
8273 doc: /* Unregister KEY as a hot-key combination. */)
8274 (key)
8275 Lisp_Object key;
8277 Lisp_Object item;
8279 if (!INTEGERP (key))
8280 key = w32_parse_hot_key (key);
8282 item = Fmemq (key, w32_grabbed_keys);
8284 if (!NILP (item))
8286 /* Notify input thread about hot-key definition being removed, so
8287 that it takes effect without needing focus switch. */
8288 #ifdef USE_LISP_UNION_TYPE
8289 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8290 (WPARAM) XINT (XCAR (item)), (LPARAM) item.i))
8291 #else
8292 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8293 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
8294 #endif
8296 MSG msg;
8297 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8299 return Qt;
8301 return Qnil;
8304 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8305 Sw32_registered_hot_keys, 0, 0, 0,
8306 doc: /* Return list of registered hot-key IDs. */)
8309 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8312 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8313 Sw32_reconstruct_hot_key, 1, 1, 0,
8314 doc: /* Convert hot-key ID to a lisp key combination.
8315 usage: (w32-reconstruct-hot-key ID) */)
8316 (hotkeyid)
8317 Lisp_Object hotkeyid;
8319 int vk_code, w32_modifiers;
8320 Lisp_Object key;
8322 CHECK_NUMBER (hotkeyid);
8324 vk_code = HOTKEY_VK_CODE (hotkeyid);
8325 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8327 if (vk_code < 256 && lispy_function_keys[vk_code])
8328 key = intern (lispy_function_keys[vk_code]);
8329 else
8330 key = make_number (vk_code);
8332 key = Fcons (key, Qnil);
8333 if (w32_modifiers & MOD_SHIFT)
8334 key = Fcons (Qshift, key);
8335 if (w32_modifiers & MOD_CONTROL)
8336 key = Fcons (Qctrl, key);
8337 if (w32_modifiers & MOD_ALT)
8338 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8339 if (w32_modifiers & MOD_WIN)
8340 key = Fcons (Qhyper, key);
8342 return key;
8345 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8346 Sw32_toggle_lock_key, 1, 2, 0,
8347 doc: /* Toggle the state of the lock key KEY.
8348 KEY can be `capslock', `kp-numlock', or `scroll'.
8349 If the optional parameter NEW-STATE is a number, then the state of KEY
8350 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
8351 (key, new_state)
8352 Lisp_Object key, new_state;
8354 int vk_code;
8356 if (EQ (key, intern ("capslock")))
8357 vk_code = VK_CAPITAL;
8358 else if (EQ (key, intern ("kp-numlock")))
8359 vk_code = VK_NUMLOCK;
8360 else if (EQ (key, intern ("scroll")))
8361 vk_code = VK_SCROLL;
8362 else
8363 return Qnil;
8365 if (!dwWindowsThreadId)
8366 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8368 #ifdef USE_LISP_UNION_TYPE
8369 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8370 (WPARAM) vk_code, (LPARAM) new_state.i))
8371 #else
8372 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8373 (WPARAM) vk_code, (LPARAM) new_state))
8374 #endif
8376 MSG msg;
8377 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8378 return make_number (msg.wParam);
8380 return Qnil;
8383 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8384 2, 2, 0,
8385 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8387 This is a direct interface to the Windows API FindWindow function. */)
8388 (class, name)
8389 Lisp_Object class, name;
8391 HWND hnd;
8393 if (!NILP (class))
8394 CHECK_STRING (class);
8395 if (!NILP (name))
8396 CHECK_STRING (name);
8398 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8399 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8400 if (!hnd)
8401 return Qnil;
8402 return Qt;
8407 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8408 doc: /* Return storage information about the file system FILENAME is on.
8409 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8410 storage of the file system, FREE is the free storage, and AVAIL is the
8411 storage available to a non-superuser. All 3 numbers are in bytes.
8412 If the underlying system call fails, value is nil. */)
8413 (filename)
8414 Lisp_Object filename;
8416 Lisp_Object encoded, value;
8418 CHECK_STRING (filename);
8419 filename = Fexpand_file_name (filename, Qnil);
8420 encoded = ENCODE_FILE (filename);
8422 value = Qnil;
8424 /* Determining the required information on Windows turns out, sadly,
8425 to be more involved than one would hope. The original Win32 api
8426 call for this will return bogus information on some systems, but we
8427 must dynamically probe for the replacement api, since that was
8428 added rather late on. */
8430 HMODULE hKernel = GetModuleHandle ("kernel32");
8431 BOOL (*pfn_GetDiskFreeSpaceEx)
8432 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
8433 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
8435 /* On Windows, we may need to specify the root directory of the
8436 volume holding FILENAME. */
8437 char rootname[MAX_PATH];
8438 char *name = SDATA (encoded);
8440 /* find the root name of the volume if given */
8441 if (isalpha (name[0]) && name[1] == ':')
8443 rootname[0] = name[0];
8444 rootname[1] = name[1];
8445 rootname[2] = '\\';
8446 rootname[3] = 0;
8448 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8450 char *str = rootname;
8451 int slashes = 4;
8454 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8455 break;
8456 *str++ = *name++;
8458 while ( *name );
8460 *str++ = '\\';
8461 *str = 0;
8464 if (pfn_GetDiskFreeSpaceEx)
8466 /* Unsigned large integers cannot be cast to double, so
8467 use signed ones instead. */
8468 LARGE_INTEGER availbytes;
8469 LARGE_INTEGER freebytes;
8470 LARGE_INTEGER totalbytes;
8472 if (pfn_GetDiskFreeSpaceEx (rootname,
8473 (ULARGE_INTEGER *)&availbytes,
8474 (ULARGE_INTEGER *)&totalbytes,
8475 (ULARGE_INTEGER *)&freebytes))
8476 value = list3 (make_float ((double) totalbytes.QuadPart),
8477 make_float ((double) freebytes.QuadPart),
8478 make_float ((double) availbytes.QuadPart));
8480 else
8482 DWORD sectors_per_cluster;
8483 DWORD bytes_per_sector;
8484 DWORD free_clusters;
8485 DWORD total_clusters;
8487 if (GetDiskFreeSpace (rootname,
8488 &sectors_per_cluster,
8489 &bytes_per_sector,
8490 &free_clusters,
8491 &total_clusters))
8492 value = list3 (make_float ((double) total_clusters
8493 * sectors_per_cluster * bytes_per_sector),
8494 make_float ((double) free_clusters
8495 * sectors_per_cluster * bytes_per_sector),
8496 make_float ((double) free_clusters
8497 * sectors_per_cluster * bytes_per_sector));
8501 return value;
8504 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8505 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8508 static char pname_buf[256];
8509 int err;
8510 HANDLE hPrn;
8511 PRINTER_INFO_2 *ppi2 = NULL;
8512 DWORD dwNeeded = 0, dwReturned = 0;
8514 /* Retrieve the default string from Win.ini (the registry).
8515 * String will be in form "printername,drivername,portname".
8516 * This is the most portable way to get the default printer. */
8517 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8518 return Qnil;
8519 /* printername precedes first "," character */
8520 strtok (pname_buf, ",");
8521 /* We want to know more than the printer name */
8522 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8523 return Qnil;
8524 GetPrinter (hPrn, 2, NULL, 0, &dwNeeded);
8525 if (dwNeeded == 0)
8527 ClosePrinter (hPrn);
8528 return Qnil;
8530 /* Allocate memory for the PRINTER_INFO_2 struct */
8531 ppi2 = (PRINTER_INFO_2 *) xmalloc (dwNeeded);
8532 if (!ppi2)
8534 ClosePrinter (hPrn);
8535 return Qnil;
8537 /* Call GetPrinter again with big enouth memory block */
8538 err = GetPrinter (hPrn, 2, (LPBYTE)ppi2, dwNeeded, &dwReturned);
8539 ClosePrinter (hPrn);
8540 if (!err)
8542 xfree (ppi2);
8543 return Qnil;
8546 if (ppi2)
8548 if (ppi2->Attributes & PRINTER_ATTRIBUTE_SHARED && ppi2->pServerName)
8550 /* a remote printer */
8551 if (*ppi2->pServerName == '\\')
8552 _snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", ppi2->pServerName,
8553 ppi2->pShareName);
8554 else
8555 _snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", ppi2->pServerName,
8556 ppi2->pShareName);
8557 pname_buf[sizeof (pname_buf) - 1] = '\0';
8559 else
8561 /* a local printer */
8562 strncpy (pname_buf, ppi2->pPortName, sizeof (pname_buf));
8563 pname_buf[sizeof (pname_buf) - 1] = '\0';
8564 /* `pPortName' can include several ports, delimited by ','.
8565 * we only use the first one. */
8566 strtok (pname_buf, ",");
8568 xfree (ppi2);
8571 return build_string (pname_buf);
8574 /***********************************************************************
8575 Initialization
8576 ***********************************************************************/
8578 /* Keep this list in the same order as frame_parms in frame.c.
8579 Use 0 for unsupported frame parameters. */
8581 frame_parm_handler w32_frame_parm_handlers[] =
8583 x_set_autoraise,
8584 x_set_autolower,
8585 x_set_background_color,
8586 x_set_border_color,
8587 x_set_border_width,
8588 x_set_cursor_color,
8589 x_set_cursor_type,
8590 x_set_font,
8591 x_set_foreground_color,
8592 x_set_icon_name,
8593 x_set_icon_type,
8594 x_set_internal_border_width,
8595 x_set_menu_bar_lines,
8596 x_set_mouse_color,
8597 x_explicitly_set_name,
8598 x_set_scroll_bar_width,
8599 x_set_title,
8600 x_set_unsplittable,
8601 x_set_vertical_scroll_bars,
8602 x_set_visibility,
8603 x_set_tool_bar_lines,
8604 0, /* x_set_scroll_bar_foreground, */
8605 0, /* x_set_scroll_bar_background, */
8606 x_set_screen_gamma,
8607 x_set_line_spacing,
8608 x_set_fringe_width,
8609 x_set_fringe_width,
8610 0, /* x_set_wait_for_wm, */
8611 x_set_fullscreen,
8614 void
8615 syms_of_w32fns ()
8617 globals_of_w32fns ();
8618 /* This is zero if not using MS-Windows. */
8619 w32_in_use = 0;
8620 track_mouse_window = NULL;
8622 w32_visible_system_caret_hwnd = NULL;
8624 Qnone = intern ("none");
8625 staticpro (&Qnone);
8626 Qsuppress_icon = intern ("suppress-icon");
8627 staticpro (&Qsuppress_icon);
8628 Qundefined_color = intern ("undefined-color");
8629 staticpro (&Qundefined_color);
8630 Qcancel_timer = intern ("cancel-timer");
8631 staticpro (&Qcancel_timer);
8633 Qhyper = intern ("hyper");
8634 staticpro (&Qhyper);
8635 Qsuper = intern ("super");
8636 staticpro (&Qsuper);
8637 Qmeta = intern ("meta");
8638 staticpro (&Qmeta);
8639 Qalt = intern ("alt");
8640 staticpro (&Qalt);
8641 Qctrl = intern ("ctrl");
8642 staticpro (&Qctrl);
8643 Qcontrol = intern ("control");
8644 staticpro (&Qcontrol);
8645 Qshift = intern ("shift");
8646 staticpro (&Qshift);
8647 /* This is the end of symbol initialization. */
8649 /* Text property `display' should be nonsticky by default. */
8650 Vtext_property_default_nonsticky
8651 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
8654 Fput (Qundefined_color, Qerror_conditions,
8655 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
8656 Fput (Qundefined_color, Qerror_message,
8657 build_string ("Undefined color"));
8659 staticpro (&w32_grabbed_keys);
8660 w32_grabbed_keys = Qnil;
8662 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
8663 doc: /* An array of color name mappings for Windows. */);
8664 Vw32_color_map = Qnil;
8666 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
8667 doc: /* Non-nil if Alt key presses are passed on to Windows.
8668 When non-nil, for example, Alt pressed and released and then space will
8669 open the System menu. When nil, Emacs processes the Alt key events, and
8670 then silently swallows them. */);
8671 Vw32_pass_alt_to_system = Qnil;
8673 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
8674 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8675 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8676 Vw32_alt_is_meta = Qt;
8678 DEFVAR_INT ("w32-quit-key", &w32_quit_key,
8679 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8680 w32_quit_key = 0;
8682 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8683 &Vw32_pass_lwindow_to_system,
8684 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8686 When non-nil, the Start menu is opened by tapping the key.
8687 If you set this to nil, the left \"Windows\" key is processed by Emacs
8688 according to the value of `w32-lwindow-modifier', which see.
8690 Note that some combinations of the left \"Windows\" key with other keys are
8691 caught by Windows at low level, and so binding them in Emacs will have no
8692 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8693 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8694 the doc string of `w32-phantom-key-code'. */);
8695 Vw32_pass_lwindow_to_system = Qt;
8697 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8698 &Vw32_pass_rwindow_to_system,
8699 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8701 When non-nil, the Start menu is opened by tapping the key.
8702 If you set this to nil, the right \"Windows\" key is processed by Emacs
8703 according to the value of `w32-rwindow-modifier', which see.
8705 Note that some combinations of the right \"Windows\" key with other keys are
8706 caught by Windows at low level, and so binding them in Emacs will have no
8707 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8708 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8709 the doc string of `w32-phantom-key-code'. */);
8710 Vw32_pass_rwindow_to_system = Qt;
8712 DEFVAR_LISP ("w32-phantom-key-code",
8713 &Vw32_phantom_key_code,
8714 doc: /* Virtual key code used to generate \"phantom\" key presses.
8715 Value is a number between 0 and 255.
8717 Phantom key presses are generated in order to stop the system from
8718 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8719 `w32-pass-rwindow-to-system' is nil. */);
8720 /* Although 255 is technically not a valid key code, it works and
8721 means that this hack won't interfere with any real key code. */
8722 XSETINT (Vw32_phantom_key_code, 255);
8724 DEFVAR_LISP ("w32-enable-num-lock",
8725 &Vw32_enable_num_lock,
8726 doc: /* If non-nil, the Num Lock key acts normally.
8727 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8728 Vw32_enable_num_lock = Qt;
8730 DEFVAR_LISP ("w32-enable-caps-lock",
8731 &Vw32_enable_caps_lock,
8732 doc: /* If non-nil, the Caps Lock key acts normally.
8733 Set to nil to handle Caps Lock as the `capslock' key. */);
8734 Vw32_enable_caps_lock = Qt;
8736 DEFVAR_LISP ("w32-scroll-lock-modifier",
8737 &Vw32_scroll_lock_modifier,
8738 doc: /* Modifier to use for the Scroll Lock ON state.
8739 The value can be hyper, super, meta, alt, control or shift for the
8740 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8741 Any other value will cause the Scroll Lock key to be ignored. */);
8742 Vw32_scroll_lock_modifier = Qt;
8744 DEFVAR_LISP ("w32-lwindow-modifier",
8745 &Vw32_lwindow_modifier,
8746 doc: /* Modifier to use for the left \"Windows\" key.
8747 The value can be hyper, super, meta, alt, control or shift for the
8748 respective modifier, or nil to appear as the `lwindow' key.
8749 Any other value will cause the key to be ignored. */);
8750 Vw32_lwindow_modifier = Qnil;
8752 DEFVAR_LISP ("w32-rwindow-modifier",
8753 &Vw32_rwindow_modifier,
8754 doc: /* Modifier to use for the right \"Windows\" key.
8755 The value can be hyper, super, meta, alt, control or shift for the
8756 respective modifier, or nil to appear as the `rwindow' key.
8757 Any other value will cause the key to be ignored. */);
8758 Vw32_rwindow_modifier = Qnil;
8760 DEFVAR_LISP ("w32-apps-modifier",
8761 &Vw32_apps_modifier,
8762 doc: /* Modifier to use for the \"Apps\" key.
8763 The value can be hyper, super, meta, alt, control or shift for the
8764 respective modifier, or nil to appear as the `apps' key.
8765 Any other value will cause the key to be ignored. */);
8766 Vw32_apps_modifier = Qnil;
8768 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
8769 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8770 w32_enable_synthesized_fonts = 0;
8772 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
8773 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8774 Vw32_enable_palette = Qt;
8776 DEFVAR_INT ("w32-mouse-button-tolerance",
8777 &w32_mouse_button_tolerance,
8778 doc: /* Analogue of double click interval for faking middle mouse events.
8779 The value is the minimum time in milliseconds that must elapse between
8780 left and right button down events before they are considered distinct events.
8781 If both mouse buttons are depressed within this interval, a middle mouse
8782 button down event is generated instead. */);
8783 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8785 DEFVAR_INT ("w32-mouse-move-interval",
8786 &w32_mouse_move_interval,
8787 doc: /* Minimum interval between mouse move events.
8788 The value is the minimum time in milliseconds that must elapse between
8789 successive mouse move (or scroll bar drag) events before they are
8790 reported as lisp events. */);
8791 w32_mouse_move_interval = 0;
8793 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8794 &w32_pass_extra_mouse_buttons_to_system,
8795 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8796 Recent versions of Windows support mice with up to five buttons.
8797 Since most applications don't support these extra buttons, most mouse
8798 drivers will allow you to map them to functions at the system level.
8799 If this variable is non-nil, Emacs will pass them on, allowing the
8800 system to handle them. */);
8801 w32_pass_extra_mouse_buttons_to_system = 0;
8803 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
8804 doc: /* The shape of the pointer when over text.
8805 Changing the value does not affect existing frames
8806 unless you set the mouse color. */);
8807 Vx_pointer_shape = Qnil;
8809 Vx_nontext_pointer_shape = Qnil;
8811 Vx_mode_pointer_shape = Qnil;
8813 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
8814 doc: /* The shape of the pointer when Emacs is busy.
8815 This variable takes effect when you create a new frame
8816 or when you set the mouse color. */);
8817 Vx_hourglass_pointer_shape = Qnil;
8819 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
8820 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
8821 display_hourglass_p = 1;
8823 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
8824 doc: /* *Seconds to wait before displaying an hourglass pointer.
8825 Value must be an integer or float. */);
8826 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
8828 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8829 &Vx_sensitive_text_pointer_shape,
8830 doc: /* The shape of the pointer when over mouse-sensitive text.
8831 This variable takes effect when you create a new frame
8832 or when you set the mouse color. */);
8833 Vx_sensitive_text_pointer_shape = Qnil;
8835 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8836 &Vx_window_horizontal_drag_shape,
8837 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8838 This variable takes effect when you create a new frame
8839 or when you set the mouse color. */);
8840 Vx_window_horizontal_drag_shape = Qnil;
8842 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
8843 doc: /* A string indicating the foreground color of the cursor box. */);
8844 Vx_cursor_fore_pixel = Qnil;
8846 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
8847 doc: /* Maximum size for tooltips.
8848 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8849 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8851 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
8852 doc: /* Non-nil if no window manager is in use.
8853 Emacs doesn't try to figure this out; this is always nil
8854 unless you set it to something else. */);
8855 /* We don't have any way to find this out, so set it to nil
8856 and maybe the user would like to set it to t. */
8857 Vx_no_window_manager = Qnil;
8859 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8860 &Vx_pixel_size_width_font_regexp,
8861 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8863 Since Emacs gets width of a font matching with this regexp from
8864 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8865 such a font. This is especially effective for such large fonts as
8866 Chinese, Japanese, and Korean. */);
8867 Vx_pixel_size_width_font_regexp = Qnil;
8869 DEFVAR_LISP ("w32-bdf-filename-alist",
8870 &Vw32_bdf_filename_alist,
8871 doc: /* List of bdf fonts and their corresponding filenames. */);
8872 Vw32_bdf_filename_alist = Qnil;
8874 DEFVAR_BOOL ("w32-strict-fontnames",
8875 &w32_strict_fontnames,
8876 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8877 Default is nil, which allows old fontnames that are not XLFD compliant,
8878 and allows third-party CJK display to work by specifying false charset
8879 fields to trick Emacs into translating to Big5, SJIS etc.
8880 Setting this to t will prevent wrong fonts being selected when
8881 fontsets are automatically created. */);
8882 w32_strict_fontnames = 0;
8884 DEFVAR_BOOL ("w32-strict-painting",
8885 &w32_strict_painting,
8886 doc: /* Non-nil means use strict rules for repainting frames.
8887 Set this to nil to get the old behavior for repainting; this should
8888 only be necessary if the default setting causes problems. */);
8889 w32_strict_painting = 1;
8891 DEFVAR_LISP ("w32-charset-info-alist",
8892 &Vw32_charset_info_alist,
8893 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
8894 Each entry should be of the form:
8896 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
8898 where CHARSET_NAME is a string used in font names to identify the charset,
8899 WINDOWS_CHARSET is a symbol that can be one of:
8900 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
8901 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
8902 w32-charset-chinesebig5,
8903 w32-charset-johab, w32-charset-hebrew,
8904 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
8905 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
8906 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
8907 w32-charset-unicode,
8908 or w32-charset-oem.
8909 CODEPAGE should be an integer specifying the codepage that should be used
8910 to display the character set, t to do no translation and output as Unicode,
8911 or nil to do no translation and output as 8 bit (or multibyte on far-east
8912 versions of Windows) characters. */);
8913 Vw32_charset_info_alist = Qnil;
8915 staticpro (&Qw32_charset_ansi);
8916 Qw32_charset_ansi = intern ("w32-charset-ansi");
8917 staticpro (&Qw32_charset_symbol);
8918 Qw32_charset_default = intern ("w32-charset-default");
8919 staticpro (&Qw32_charset_default);
8920 Qw32_charset_symbol = intern ("w32-charset-symbol");
8921 staticpro (&Qw32_charset_shiftjis);
8922 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
8923 staticpro (&Qw32_charset_hangeul);
8924 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
8925 staticpro (&Qw32_charset_chinesebig5);
8926 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
8927 staticpro (&Qw32_charset_gb2312);
8928 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
8929 staticpro (&Qw32_charset_oem);
8930 Qw32_charset_oem = intern ("w32-charset-oem");
8932 #ifdef JOHAB_CHARSET
8934 static int w32_extra_charsets_defined = 1;
8935 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
8936 doc: /* Internal variable. */);
8938 staticpro (&Qw32_charset_johab);
8939 Qw32_charset_johab = intern ("w32-charset-johab");
8940 staticpro (&Qw32_charset_easteurope);
8941 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
8942 staticpro (&Qw32_charset_turkish);
8943 Qw32_charset_turkish = intern ("w32-charset-turkish");
8944 staticpro (&Qw32_charset_baltic);
8945 Qw32_charset_baltic = intern ("w32-charset-baltic");
8946 staticpro (&Qw32_charset_russian);
8947 Qw32_charset_russian = intern ("w32-charset-russian");
8948 staticpro (&Qw32_charset_arabic);
8949 Qw32_charset_arabic = intern ("w32-charset-arabic");
8950 staticpro (&Qw32_charset_greek);
8951 Qw32_charset_greek = intern ("w32-charset-greek");
8952 staticpro (&Qw32_charset_hebrew);
8953 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
8954 staticpro (&Qw32_charset_vietnamese);
8955 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
8956 staticpro (&Qw32_charset_thai);
8957 Qw32_charset_thai = intern ("w32-charset-thai");
8958 staticpro (&Qw32_charset_mac);
8959 Qw32_charset_mac = intern ("w32-charset-mac");
8961 #endif
8963 #ifdef UNICODE_CHARSET
8965 static int w32_unicode_charset_defined = 1;
8966 DEFVAR_BOOL ("w32-unicode-charset-defined",
8967 &w32_unicode_charset_defined,
8968 doc: /* Internal variable. */);
8970 staticpro (&Qw32_charset_unicode);
8971 Qw32_charset_unicode = intern ("w32-charset-unicode");
8973 #endif
8975 #if 0 /* TODO: Port to W32 */
8976 defsubr (&Sx_change_window_property);
8977 defsubr (&Sx_delete_window_property);
8978 defsubr (&Sx_window_property);
8979 #endif
8980 defsubr (&Sxw_display_color_p);
8981 defsubr (&Sx_display_grayscale_p);
8982 defsubr (&Sxw_color_defined_p);
8983 defsubr (&Sxw_color_values);
8984 defsubr (&Sx_server_max_request_size);
8985 defsubr (&Sx_server_vendor);
8986 defsubr (&Sx_server_version);
8987 defsubr (&Sx_display_pixel_width);
8988 defsubr (&Sx_display_pixel_height);
8989 defsubr (&Sx_display_mm_width);
8990 defsubr (&Sx_display_mm_height);
8991 defsubr (&Sx_display_screens);
8992 defsubr (&Sx_display_planes);
8993 defsubr (&Sx_display_color_cells);
8994 defsubr (&Sx_display_visual_class);
8995 defsubr (&Sx_display_backing_store);
8996 defsubr (&Sx_display_save_under);
8997 defsubr (&Sx_create_frame);
8998 defsubr (&Sx_open_connection);
8999 defsubr (&Sx_close_connection);
9000 defsubr (&Sx_display_list);
9001 defsubr (&Sx_synchronize);
9003 /* W32 specific functions */
9005 defsubr (&Sw32_focus_frame);
9006 defsubr (&Sw32_select_font);
9007 defsubr (&Sw32_define_rgb_color);
9008 defsubr (&Sw32_default_color_map);
9009 defsubr (&Sw32_load_color_file);
9010 defsubr (&Sw32_send_sys_command);
9011 defsubr (&Sw32_shell_execute);
9012 defsubr (&Sw32_register_hot_key);
9013 defsubr (&Sw32_unregister_hot_key);
9014 defsubr (&Sw32_registered_hot_keys);
9015 defsubr (&Sw32_reconstruct_hot_key);
9016 defsubr (&Sw32_toggle_lock_key);
9017 defsubr (&Sw32_window_exists_p);
9018 defsubr (&Sw32_find_bdf_fonts);
9020 defsubr (&Sfile_system_info);
9021 defsubr (&Sdefault_printer_name);
9023 /* Setting callback functions for fontset handler. */
9024 get_font_info_func = w32_get_font_info;
9026 #if 0 /* This function pointer doesn't seem to be used anywhere.
9027 And the pointer assigned has the wrong type, anyway. */
9028 list_fonts_func = w32_list_fonts;
9029 #endif
9031 load_font_func = w32_load_font;
9032 find_ccl_program_func = w32_find_ccl_program;
9033 query_font_func = w32_query_font;
9034 set_frame_fontset_func = x_set_font;
9035 check_window_system_func = check_w32;
9038 hourglass_atimer = NULL;
9039 hourglass_shown_p = 0;
9040 defsubr (&Sx_show_tip);
9041 defsubr (&Sx_hide_tip);
9042 tip_timer = Qnil;
9043 staticpro (&tip_timer);
9044 tip_frame = Qnil;
9045 staticpro (&tip_frame);
9047 last_show_tip_args = Qnil;
9048 staticpro (&last_show_tip_args);
9050 defsubr (&Sx_file_dialog);
9055 globals_of_w32fns is used to initialize those global variables that
9056 must always be initialized on startup even when the global variable
9057 initialized is non zero (see the function main in emacs.c).
9058 globals_of_w32fns is called from syms_of_w32fns when the global
9059 variable initialized is 0 and directly from main when initialized
9060 is non zero.
9062 void
9063 globals_of_w32fns ()
9065 HMODULE user32_lib = GetModuleHandle ("user32.dll");
9067 TrackMouseEvent not available in all versions of Windows, so must load
9068 it dynamically. Do it once, here, instead of every time it is used.
9070 track_mouse_event_fn = (TrackMouseEvent_Proc)
9071 GetProcAddress (user32_lib, "TrackMouseEvent");
9072 /* ditto for GetClipboardSequenceNumber. */
9073 clipboard_sequence_fn = (ClipboardSequence_Proc)
9074 GetProcAddress (user32_lib, "GetClipboardSequenceNumber");
9076 DEFVAR_INT ("w32-ansi-code-page",
9077 &w32_ansi_code_page,
9078 doc: /* The ANSI code page used by the system. */);
9079 w32_ansi_code_page = GetACP ();
9081 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
9082 InitCommonControls ();
9085 #undef abort
9087 void w32_abort (void) NO_RETURN;
9089 void
9090 w32_abort ()
9092 int button;
9093 button = MessageBox (NULL,
9094 "A fatal error has occurred!\n\n"
9095 "Would you like to attach a debugger?\n\n"
9096 "Select YES to debug, NO to abort Emacs"
9097 #if __GNUC__
9098 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
9099 "\"continue\" inside GDB before clicking YES.)"
9100 #endif
9101 , "Emacs Abort Dialog",
9102 MB_ICONEXCLAMATION | MB_TASKMODAL
9103 | MB_SETFOREGROUND | MB_YESNO);
9104 switch (button)
9106 case IDYES:
9107 DebugBreak ();
9108 exit (2); /* tell the compiler we will never return */
9109 case IDNO:
9110 default:
9111 abort ();
9112 break;
9116 /* For convenience when debugging. */
9118 w32_last_error ()
9120 return GetLastError ();
9123 /* arch-tag: 707589ab-b9be-4638-8cdd-74629cc9b446
9124 (do not change this comment) */