(make_lispy_event): Add string info to the event,
[emacs/old-mirror.git] / src / w32fns.c
blobf3001649f8187f11c21d0307f32039124c345db9
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 92, 93, 94, 95, 1996, 1997, 1998, 1999, 2000, 2001
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* Added by Kevin Gallo */
24 #include <config.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <limits.h>
29 #include <errno.h>
31 #include "lisp.h"
32 #include "charset.h"
33 #include "dispextern.h"
34 #include "w32term.h"
35 #include "frame.h"
36 #include "window.h"
37 #include "buffer.h"
38 #include "fontset.h"
39 #include "intervals.h"
40 #include "keyboard.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "w32heap.h"
44 #include "termhooks.h"
45 #include "coding.h"
46 #include "ccl.h"
47 #include "systime.h"
49 #include "bitmaps/gray.xbm"
51 #include <commdlg.h>
52 #include <shellapi.h>
53 #include <ctype.h>
55 #define max(a, b) ((a) > (b) ? (a) : (b))
57 extern void free_frame_menubar ();
58 extern double atof ();
59 extern int w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state);
60 extern int quit_char;
62 /* A definition of XColor for non-X frames. */
63 #ifndef HAVE_X_WINDOWS
64 typedef struct {
65 unsigned long pixel;
66 unsigned short red, green, blue;
67 char flags;
68 char pad;
69 } XColor;
70 #endif
72 extern char *lispy_function_keys[];
74 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
75 it, and including `bitmaps/gray' more than once is a problem when
76 config.h defines `static' as an empty replacement string. */
78 int gray_bitmap_width = gray_width;
79 int gray_bitmap_height = gray_height;
80 unsigned char *gray_bitmap_bits = gray_bits;
82 /* The colormap for converting color names to RGB values */
83 Lisp_Object Vw32_color_map;
85 /* Non nil if alt key presses are passed on to Windows. */
86 Lisp_Object Vw32_pass_alt_to_system;
88 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
89 to alt_modifier. */
90 Lisp_Object Vw32_alt_is_meta;
92 /* If non-zero, the windows virtual key code for an alternative quit key. */
93 Lisp_Object Vw32_quit_key;
95 /* Non nil if left window key events are passed on to Windows (this only
96 affects whether "tapping" the key opens the Start menu). */
97 Lisp_Object Vw32_pass_lwindow_to_system;
99 /* Non nil if right window key events are passed on to Windows (this
100 only affects whether "tapping" the key opens the Start menu). */
101 Lisp_Object Vw32_pass_rwindow_to_system;
103 /* Virtual key code used to generate "phantom" key presses in order
104 to stop system from acting on Windows key events. */
105 Lisp_Object Vw32_phantom_key_code;
107 /* Modifier associated with the left "Windows" key, or nil to act as a
108 normal key. */
109 Lisp_Object Vw32_lwindow_modifier;
111 /* Modifier associated with the right "Windows" key, or nil to act as a
112 normal key. */
113 Lisp_Object Vw32_rwindow_modifier;
115 /* Modifier associated with the "Apps" key, or nil to act as a normal
116 key. */
117 Lisp_Object Vw32_apps_modifier;
119 /* Value is nil if Num Lock acts as a function key. */
120 Lisp_Object Vw32_enable_num_lock;
122 /* Value is nil if Caps Lock acts as a function key. */
123 Lisp_Object Vw32_enable_caps_lock;
125 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
126 Lisp_Object Vw32_scroll_lock_modifier;
128 /* Switch to control whether we inhibit requests for synthesized bold
129 and italic versions of fonts. */
130 Lisp_Object Vw32_enable_synthesized_fonts;
132 /* Enable palette management. */
133 Lisp_Object Vw32_enable_palette;
135 /* Control how close left/right button down events must be to
136 be converted to a middle button down event. */
137 Lisp_Object Vw32_mouse_button_tolerance;
139 /* Minimum interval between mouse movement (and scroll bar drag)
140 events that are passed on to the event loop. */
141 Lisp_Object Vw32_mouse_move_interval;
143 /* The name we're using in resource queries. */
144 Lisp_Object Vx_resource_name;
146 /* Non nil if no window manager is in use. */
147 Lisp_Object Vx_no_window_manager;
149 /* Non-zero means we're allowed to display a hourglass pointer. */
151 int display_hourglass_p;
153 /* The background and shape of the mouse pointer, and shape when not
154 over text or in the modeline. */
156 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
157 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
159 /* The shape when over mouse-sensitive text. */
161 Lisp_Object Vx_sensitive_text_pointer_shape;
163 /* Color of chars displayed in cursor box. */
165 Lisp_Object Vx_cursor_fore_pixel;
167 /* Nonzero if using Windows. */
169 static int w32_in_use;
171 /* Search path for bitmap files. */
173 Lisp_Object Vx_bitmap_file_path;
175 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
177 Lisp_Object Vx_pixel_size_width_font_regexp;
179 /* Alist of bdf fonts and the files that define them. */
180 Lisp_Object Vw32_bdf_filename_alist;
182 Lisp_Object Vw32_system_coding_system;
184 /* A flag to control whether fonts are matched strictly or not. */
185 int w32_strict_fontnames;
187 /* A flag to control whether we should only repaint if GetUpdateRect
188 indicates there is an update region. */
189 int w32_strict_painting;
191 /* Associative list linking character set strings to Windows codepages. */
192 Lisp_Object Vw32_charset_info_alist;
194 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
195 #ifndef VIETNAMESE_CHARSET
196 #define VIETNAMESE_CHARSET 163
197 #endif
199 Lisp_Object Qauto_raise;
200 Lisp_Object Qauto_lower;
201 Lisp_Object Qbar;
202 Lisp_Object Qborder_color;
203 Lisp_Object Qborder_width;
204 Lisp_Object Qbox;
205 Lisp_Object Qcursor_color;
206 Lisp_Object Qcursor_type;
207 Lisp_Object Qgeometry;
208 Lisp_Object Qicon_left;
209 Lisp_Object Qicon_top;
210 Lisp_Object Qicon_type;
211 Lisp_Object Qicon_name;
212 Lisp_Object Qinternal_border_width;
213 Lisp_Object Qleft;
214 Lisp_Object Qright;
215 Lisp_Object Qmouse_color;
216 Lisp_Object Qnone;
217 Lisp_Object Qparent_id;
218 Lisp_Object Qscroll_bar_width;
219 Lisp_Object Qsuppress_icon;
220 Lisp_Object Qundefined_color;
221 Lisp_Object Qvertical_scroll_bars;
222 Lisp_Object Qvisibility;
223 Lisp_Object Qwindow_id;
224 Lisp_Object Qx_frame_parameter;
225 Lisp_Object Qx_resource_name;
226 Lisp_Object Quser_position;
227 Lisp_Object Quser_size;
228 Lisp_Object Qscreen_gamma;
229 Lisp_Object Qline_spacing;
230 Lisp_Object Qcenter;
231 Lisp_Object Qcancel_timer;
232 Lisp_Object Qhyper;
233 Lisp_Object Qsuper;
234 Lisp_Object Qmeta;
235 Lisp_Object Qalt;
236 Lisp_Object Qctrl;
237 Lisp_Object Qcontrol;
238 Lisp_Object Qshift;
240 Lisp_Object Qw32_charset_ansi;
241 Lisp_Object Qw32_charset_default;
242 Lisp_Object Qw32_charset_symbol;
243 Lisp_Object Qw32_charset_shiftjis;
244 Lisp_Object Qw32_charset_hangeul;
245 Lisp_Object Qw32_charset_gb2312;
246 Lisp_Object Qw32_charset_chinesebig5;
247 Lisp_Object Qw32_charset_oem;
249 #ifndef JOHAB_CHARSET
250 #define JOHAB_CHARSET 130
251 #endif
252 #ifdef JOHAB_CHARSET
253 Lisp_Object Qw32_charset_easteurope;
254 Lisp_Object Qw32_charset_turkish;
255 Lisp_Object Qw32_charset_baltic;
256 Lisp_Object Qw32_charset_russian;
257 Lisp_Object Qw32_charset_arabic;
258 Lisp_Object Qw32_charset_greek;
259 Lisp_Object Qw32_charset_hebrew;
260 Lisp_Object Qw32_charset_vietnamese;
261 Lisp_Object Qw32_charset_thai;
262 Lisp_Object Qw32_charset_johab;
263 Lisp_Object Qw32_charset_mac;
264 #endif
266 #ifdef UNICODE_CHARSET
267 Lisp_Object Qw32_charset_unicode;
268 #endif
270 extern Lisp_Object Qtop;
271 extern Lisp_Object Qdisplay;
272 extern Lisp_Object Qtool_bar_lines;
274 /* State variables for emulating a three button mouse. */
275 #define LMOUSE 1
276 #define MMOUSE 2
277 #define RMOUSE 4
279 static int button_state = 0;
280 static W32Msg saved_mouse_button_msg;
281 static unsigned mouse_button_timer; /* non-zero when timer is active */
282 static W32Msg saved_mouse_move_msg;
283 static unsigned mouse_move_timer;
285 /* W95 mousewheel handler */
286 unsigned int msh_mousewheel = 0;
288 #define MOUSE_BUTTON_ID 1
289 #define MOUSE_MOVE_ID 2
291 /* The below are defined in frame.c. */
293 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
294 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
295 extern Lisp_Object Qtool_bar_lines;
297 extern Lisp_Object Vwindow_system_version;
299 Lisp_Object Qface_set_after_frame_default;
301 #ifdef GLYPH_DEBUG
302 int image_cache_refcount, dpyinfo_refcount;
303 #endif
306 /* From w32term.c. */
307 extern Lisp_Object Vw32_num_mouse_buttons;
308 extern Lisp_Object Vw32_recognize_altgr;
311 /* Error if we are not connected to MS-Windows. */
312 void
313 check_w32 ()
315 if (! w32_in_use)
316 error ("MS-Windows not in use or not initialized");
319 /* Nonzero if we can use mouse menus.
320 You should not call this unless HAVE_MENUS is defined. */
323 have_menus_p ()
325 return w32_in_use;
328 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
329 and checking validity for W32. */
331 FRAME_PTR
332 check_x_frame (frame)
333 Lisp_Object frame;
335 FRAME_PTR f;
337 if (NILP (frame))
338 frame = selected_frame;
339 CHECK_LIVE_FRAME (frame, 0);
340 f = XFRAME (frame);
341 if (! FRAME_W32_P (f))
342 error ("non-w32 frame used");
343 return f;
346 /* Let the user specify an display with a frame.
347 nil stands for the selected frame--or, if that is not a w32 frame,
348 the first display on the list. */
350 static struct w32_display_info *
351 check_x_display_info (frame)
352 Lisp_Object frame;
354 if (NILP (frame))
356 struct frame *sf = XFRAME (selected_frame);
358 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
359 return FRAME_W32_DISPLAY_INFO (sf);
360 else
361 return &one_w32_display_info;
363 else if (STRINGP (frame))
364 return x_display_info_for_name (frame);
365 else
367 FRAME_PTR f;
369 CHECK_LIVE_FRAME (frame, 0);
370 f = XFRAME (frame);
371 if (! FRAME_W32_P (f))
372 error ("non-w32 frame used");
373 return FRAME_W32_DISPLAY_INFO (f);
377 /* Return the Emacs frame-object corresponding to an w32 window.
378 It could be the frame's main window or an icon window. */
380 /* This function can be called during GC, so use GC_xxx type test macros. */
382 struct frame *
383 x_window_to_frame (dpyinfo, wdesc)
384 struct w32_display_info *dpyinfo;
385 HWND wdesc;
387 Lisp_Object tail, frame;
388 struct frame *f;
390 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
392 frame = XCAR (tail);
393 if (!GC_FRAMEP (frame))
394 continue;
395 f = XFRAME (frame);
396 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
397 continue;
398 if (f->output_data.w32->hourglass_window == wdesc)
399 return f;
401 /* TODO: Check tooltips when supported. */
402 if (FRAME_W32_WINDOW (f) == wdesc)
403 return f;
405 return 0;
410 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
411 id, which is just an int that this section returns. Bitmaps are
412 reference counted so they can be shared among frames.
414 Bitmap indices are guaranteed to be > 0, so a negative number can
415 be used to indicate no bitmap.
417 If you use x_create_bitmap_from_data, then you must keep track of
418 the bitmaps yourself. That is, creating a bitmap from the same
419 data more than once will not be caught. */
422 /* Functions to access the contents of a bitmap, given an id. */
425 x_bitmap_height (f, id)
426 FRAME_PTR f;
427 int id;
429 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
433 x_bitmap_width (f, id)
434 FRAME_PTR f;
435 int id;
437 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
441 x_bitmap_pixmap (f, id)
442 FRAME_PTR f;
443 int id;
445 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
449 /* Allocate a new bitmap record. Returns index of new record. */
451 static int
452 x_allocate_bitmap_record (f)
453 FRAME_PTR f;
455 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
456 int i;
458 if (dpyinfo->bitmaps == NULL)
460 dpyinfo->bitmaps_size = 10;
461 dpyinfo->bitmaps
462 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
463 dpyinfo->bitmaps_last = 1;
464 return 1;
467 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
468 return ++dpyinfo->bitmaps_last;
470 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
471 if (dpyinfo->bitmaps[i].refcount == 0)
472 return i + 1;
474 dpyinfo->bitmaps_size *= 2;
475 dpyinfo->bitmaps
476 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
477 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
478 return ++dpyinfo->bitmaps_last;
481 /* Add one reference to the reference count of the bitmap with id ID. */
483 void
484 x_reference_bitmap (f, id)
485 FRAME_PTR f;
486 int id;
488 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
491 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
494 x_create_bitmap_from_data (f, bits, width, height)
495 struct frame *f;
496 char *bits;
497 unsigned int width, height;
499 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
500 Pixmap bitmap;
501 int id;
503 bitmap = CreateBitmap (width, height,
504 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
505 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
506 bits);
508 if (! bitmap)
509 return -1;
511 id = x_allocate_bitmap_record (f);
512 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
513 dpyinfo->bitmaps[id - 1].file = NULL;
514 dpyinfo->bitmaps[id - 1].hinst = NULL;
515 dpyinfo->bitmaps[id - 1].refcount = 1;
516 dpyinfo->bitmaps[id - 1].depth = 1;
517 dpyinfo->bitmaps[id - 1].height = height;
518 dpyinfo->bitmaps[id - 1].width = width;
520 return id;
523 /* Create bitmap from file FILE for frame F. */
526 x_create_bitmap_from_file (f, file)
527 struct frame *f;
528 Lisp_Object file;
530 return -1;
531 #if 0 /* TODO : bitmap support */
532 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
533 unsigned int width, height;
534 HBITMAP bitmap;
535 int xhot, yhot, result, id;
536 Lisp_Object found;
537 int fd;
538 char *filename;
539 HINSTANCE hinst;
541 /* Look for an existing bitmap with the same name. */
542 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
544 if (dpyinfo->bitmaps[id].refcount
545 && dpyinfo->bitmaps[id].file
546 && !strcmp (dpyinfo->bitmaps[id].file, (char *) XSTRING (file)->data))
548 ++dpyinfo->bitmaps[id].refcount;
549 return id + 1;
553 /* Search bitmap-file-path for the file, if appropriate. */
554 fd = openp (Vx_bitmap_file_path, file, "", &found, 0);
555 if (fd < 0)
556 return -1;
557 emacs_close (fd);
559 filename = (char *) XSTRING (found)->data;
561 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
563 if (hinst == NULL)
564 return -1;
567 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
568 filename, &width, &height, &bitmap, &xhot, &yhot);
569 if (result != BitmapSuccess)
570 return -1;
572 id = x_allocate_bitmap_record (f);
573 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
574 dpyinfo->bitmaps[id - 1].refcount = 1;
575 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (XSTRING (file)->size + 1);
576 dpyinfo->bitmaps[id - 1].depth = 1;
577 dpyinfo->bitmaps[id - 1].height = height;
578 dpyinfo->bitmaps[id - 1].width = width;
579 strcpy (dpyinfo->bitmaps[id - 1].file, XSTRING (file)->data);
581 return id;
582 #endif /* TODO */
585 /* Remove reference to bitmap with id number ID. */
587 void
588 x_destroy_bitmap (f, id)
589 FRAME_PTR f;
590 int id;
592 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
594 if (id > 0)
596 --dpyinfo->bitmaps[id - 1].refcount;
597 if (dpyinfo->bitmaps[id - 1].refcount == 0)
599 BLOCK_INPUT;
600 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
601 if (dpyinfo->bitmaps[id - 1].file)
603 xfree (dpyinfo->bitmaps[id - 1].file);
604 dpyinfo->bitmaps[id - 1].file = NULL;
606 UNBLOCK_INPUT;
611 /* Free all the bitmaps for the display specified by DPYINFO. */
613 static void
614 x_destroy_all_bitmaps (dpyinfo)
615 struct w32_display_info *dpyinfo;
617 int i;
618 for (i = 0; i < dpyinfo->bitmaps_last; i++)
619 if (dpyinfo->bitmaps[i].refcount > 0)
621 DeleteObject (dpyinfo->bitmaps[i].pixmap);
622 if (dpyinfo->bitmaps[i].file)
623 xfree (dpyinfo->bitmaps[i].file);
625 dpyinfo->bitmaps_last = 0;
628 /* Connect the frame-parameter names for W32 frames
629 to the ways of passing the parameter values to the window system.
631 The name of a parameter, as a Lisp symbol,
632 has an `x-frame-parameter' property which is an integer in Lisp
633 but can be interpreted as an `enum x_frame_parm' in C. */
635 enum x_frame_parm
637 X_PARM_FOREGROUND_COLOR,
638 X_PARM_BACKGROUND_COLOR,
639 X_PARM_MOUSE_COLOR,
640 X_PARM_CURSOR_COLOR,
641 X_PARM_BORDER_COLOR,
642 X_PARM_ICON_TYPE,
643 X_PARM_FONT,
644 X_PARM_BORDER_WIDTH,
645 X_PARM_INTERNAL_BORDER_WIDTH,
646 X_PARM_NAME,
647 X_PARM_AUTORAISE,
648 X_PARM_AUTOLOWER,
649 X_PARM_VERT_SCROLL_BAR,
650 X_PARM_VISIBILITY,
651 X_PARM_MENU_BAR_LINES
655 struct x_frame_parm_table
657 char *name;
658 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
661 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
662 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
663 static void x_change_window_heights P_ ((Lisp_Object, int));
664 /* TODO: Native Input Method support; see x_create_im. */
665 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
666 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
667 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
668 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
669 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
670 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
671 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
672 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
673 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
674 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
675 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
676 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
677 Lisp_Object));
678 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
679 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
680 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
681 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
682 Lisp_Object));
683 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
684 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
685 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
686 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
687 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
688 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
689 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
691 static struct x_frame_parm_table x_frame_parms[] =
693 "auto-raise", x_set_autoraise,
694 "auto-lower", x_set_autolower,
695 "background-color", x_set_background_color,
696 "border-color", x_set_border_color,
697 "border-width", x_set_border_width,
698 "cursor-color", x_set_cursor_color,
699 "cursor-type", x_set_cursor_type,
700 "font", x_set_font,
701 "foreground-color", x_set_foreground_color,
702 "icon-name", x_set_icon_name,
703 "icon-type", x_set_icon_type,
704 "internal-border-width", x_set_internal_border_width,
705 "menu-bar-lines", x_set_menu_bar_lines,
706 "mouse-color", x_set_mouse_color,
707 "name", x_explicitly_set_name,
708 "scroll-bar-width", x_set_scroll_bar_width,
709 "title", x_set_title,
710 "unsplittable", x_set_unsplittable,
711 "vertical-scroll-bars", x_set_vertical_scroll_bars,
712 "visibility", x_set_visibility,
713 "tool-bar-lines", x_set_tool_bar_lines,
714 "screen-gamma", x_set_screen_gamma,
715 "line-spacing", x_set_line_spacing
718 /* Attach the `x-frame-parameter' properties to
719 the Lisp symbol names of parameters relevant to W32. */
721 void
722 init_x_parm_symbols ()
724 int i;
726 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
727 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
728 make_number (i));
731 /* Change the parameters of frame F as specified by ALIST.
732 If a parameter is not specially recognized, do nothing;
733 otherwise call the `x_set_...' function for that parameter. */
735 void
736 x_set_frame_parameters (f, alist)
737 FRAME_PTR f;
738 Lisp_Object alist;
740 Lisp_Object tail;
742 /* If both of these parameters are present, it's more efficient to
743 set them both at once. So we wait until we've looked at the
744 entire list before we set them. */
745 int width, height;
747 /* Same here. */
748 Lisp_Object left, top;
750 /* Same with these. */
751 Lisp_Object icon_left, icon_top;
753 /* Record in these vectors all the parms specified. */
754 Lisp_Object *parms;
755 Lisp_Object *values;
756 int i, p;
757 int left_no_change = 0, top_no_change = 0;
758 int icon_left_no_change = 0, icon_top_no_change = 0;
760 struct gcpro gcpro1, gcpro2;
762 i = 0;
763 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
764 i++;
766 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
767 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
769 /* Extract parm names and values into those vectors. */
771 i = 0;
772 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
774 Lisp_Object elt;
776 elt = Fcar (tail);
777 parms[i] = Fcar (elt);
778 values[i] = Fcdr (elt);
779 i++;
781 /* TAIL and ALIST are not used again below here. */
782 alist = tail = Qnil;
784 GCPRO2 (*parms, *values);
785 gcpro1.nvars = i;
786 gcpro2.nvars = i;
788 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
789 because their values appear in VALUES and strings are not valid. */
790 top = left = Qunbound;
791 icon_left = icon_top = Qunbound;
793 /* Provide default values for HEIGHT and WIDTH. */
794 if (FRAME_NEW_WIDTH (f))
795 width = FRAME_NEW_WIDTH (f);
796 else
797 width = FRAME_WIDTH (f);
799 if (FRAME_NEW_HEIGHT (f))
800 height = FRAME_NEW_HEIGHT (f);
801 else
802 height = FRAME_HEIGHT (f);
804 /* Process foreground_color and background_color before anything else.
805 They are independent of other properties, but other properties (e.g.,
806 cursor_color) are dependent upon them. */
807 for (p = 0; p < i; p++)
809 Lisp_Object prop, val;
811 prop = parms[p];
812 val = values[p];
813 if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
815 register Lisp_Object param_index, old_value;
817 param_index = Fget (prop, Qx_frame_parameter);
818 old_value = get_frame_param (f, prop);
819 store_frame_param (f, prop, val);
820 if (NATNUMP (param_index)
821 && (XFASTINT (param_index)
822 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
823 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
827 /* Now process them in reverse of specified order. */
828 for (i--; i >= 0; i--)
830 Lisp_Object prop, val;
832 prop = parms[i];
833 val = values[i];
835 if (EQ (prop, Qwidth) && NUMBERP (val))
836 width = XFASTINT (val);
837 else if (EQ (prop, Qheight) && NUMBERP (val))
838 height = XFASTINT (val);
839 else if (EQ (prop, Qtop))
840 top = val;
841 else if (EQ (prop, Qleft))
842 left = val;
843 else if (EQ (prop, Qicon_top))
844 icon_top = val;
845 else if (EQ (prop, Qicon_left))
846 icon_left = val;
847 else if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
848 /* Processed above. */
849 continue;
850 else
852 register Lisp_Object param_index, old_value;
854 param_index = Fget (prop, Qx_frame_parameter);
855 old_value = get_frame_param (f, prop);
856 store_frame_param (f, prop, val);
857 if (NATNUMP (param_index)
858 && (XFASTINT (param_index)
859 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
860 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
864 /* Don't die if just one of these was set. */
865 if (EQ (left, Qunbound))
867 left_no_change = 1;
868 if (f->output_data.w32->left_pos < 0)
869 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
870 else
871 XSETINT (left, f->output_data.w32->left_pos);
873 if (EQ (top, Qunbound))
875 top_no_change = 1;
876 if (f->output_data.w32->top_pos < 0)
877 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
878 else
879 XSETINT (top, f->output_data.w32->top_pos);
882 /* If one of the icon positions was not set, preserve or default it. */
883 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
885 icon_left_no_change = 1;
886 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
887 if (NILP (icon_left))
888 XSETINT (icon_left, 0);
890 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
892 icon_top_no_change = 1;
893 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
894 if (NILP (icon_top))
895 XSETINT (icon_top, 0);
898 /* Don't set these parameters unless they've been explicitly
899 specified. The window might be mapped or resized while we're in
900 this function, and we don't want to override that unless the lisp
901 code has asked for it.
903 Don't set these parameters unless they actually differ from the
904 window's current parameters; the window may not actually exist
905 yet. */
907 Lisp_Object frame;
909 check_frame_size (f, &height, &width);
911 XSETFRAME (frame, f);
913 if (width != FRAME_WIDTH (f)
914 || height != FRAME_HEIGHT (f)
915 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
916 Fset_frame_size (frame, make_number (width), make_number (height));
918 if ((!NILP (left) || !NILP (top))
919 && ! (left_no_change && top_no_change)
920 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
921 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
923 int leftpos = 0;
924 int toppos = 0;
926 /* Record the signs. */
927 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
928 if (EQ (left, Qminus))
929 f->output_data.w32->size_hint_flags |= XNegative;
930 else if (INTEGERP (left))
932 leftpos = XINT (left);
933 if (leftpos < 0)
934 f->output_data.w32->size_hint_flags |= XNegative;
936 else if (CONSP (left) && EQ (XCAR (left), Qminus)
937 && CONSP (XCDR (left))
938 && INTEGERP (XCAR (XCDR (left))))
940 leftpos = - XINT (XCAR (XCDR (left)));
941 f->output_data.w32->size_hint_flags |= XNegative;
943 else if (CONSP (left) && EQ (XCAR (left), Qplus)
944 && CONSP (XCDR (left))
945 && INTEGERP (XCAR (XCDR (left))))
947 leftpos = XINT (XCAR (XCDR (left)));
950 if (EQ (top, Qminus))
951 f->output_data.w32->size_hint_flags |= YNegative;
952 else if (INTEGERP (top))
954 toppos = XINT (top);
955 if (toppos < 0)
956 f->output_data.w32->size_hint_flags |= YNegative;
958 else if (CONSP (top) && EQ (XCAR (top), Qminus)
959 && CONSP (XCDR (top))
960 && INTEGERP (XCAR (XCDR (top))))
962 toppos = - XINT (XCAR (XCDR (top)));
963 f->output_data.w32->size_hint_flags |= YNegative;
965 else if (CONSP (top) && EQ (XCAR (top), Qplus)
966 && CONSP (XCDR (top))
967 && INTEGERP (XCAR (XCDR (top))))
969 toppos = XINT (XCAR (XCDR (top)));
973 /* Store the numeric value of the position. */
974 f->output_data.w32->top_pos = toppos;
975 f->output_data.w32->left_pos = leftpos;
977 f->output_data.w32->win_gravity = NorthWestGravity;
979 /* Actually set that position, and convert to absolute. */
980 x_set_offset (f, leftpos, toppos, -1);
983 if ((!NILP (icon_left) || !NILP (icon_top))
984 && ! (icon_left_no_change && icon_top_no_change))
985 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
988 UNGCPRO;
991 /* Store the screen positions of frame F into XPTR and YPTR.
992 These are the positions of the containing window manager window,
993 not Emacs's own window. */
995 void
996 x_real_positions (f, xptr, yptr)
997 FRAME_PTR f;
998 int *xptr, *yptr;
1000 POINT pt;
1003 RECT rect;
1005 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1006 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1008 pt.x = rect.left;
1009 pt.y = rect.top;
1012 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1014 *xptr = pt.x;
1015 *yptr = pt.y;
1018 /* Insert a description of internally-recorded parameters of frame X
1019 into the parameter alist *ALISTPTR that is to be given to the user.
1020 Only parameters that are specific to W32
1021 and whose values are not correctly recorded in the frame's
1022 param_alist need to be considered here. */
1024 void
1025 x_report_frame_params (f, alistptr)
1026 struct frame *f;
1027 Lisp_Object *alistptr;
1029 char buf[16];
1030 Lisp_Object tem;
1032 /* Represent negative positions (off the top or left screen edge)
1033 in a way that Fmodify_frame_parameters will understand correctly. */
1034 XSETINT (tem, f->output_data.w32->left_pos);
1035 if (f->output_data.w32->left_pos >= 0)
1036 store_in_alist (alistptr, Qleft, tem);
1037 else
1038 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1040 XSETINT (tem, f->output_data.w32->top_pos);
1041 if (f->output_data.w32->top_pos >= 0)
1042 store_in_alist (alistptr, Qtop, tem);
1043 else
1044 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1046 store_in_alist (alistptr, Qborder_width,
1047 make_number (f->output_data.w32->border_width));
1048 store_in_alist (alistptr, Qinternal_border_width,
1049 make_number (f->output_data.w32->internal_border_width));
1050 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1051 store_in_alist (alistptr, Qwindow_id,
1052 build_string (buf));
1053 store_in_alist (alistptr, Qicon_name, f->icon_name);
1054 FRAME_SAMPLE_VISIBILITY (f);
1055 store_in_alist (alistptr, Qvisibility,
1056 (FRAME_VISIBLE_P (f) ? Qt
1057 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1058 store_in_alist (alistptr, Qdisplay,
1059 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1063 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color, Sw32_define_rgb_color, 4, 4, 0,
1064 "Convert RGB numbers to a windows color reference and associate with NAME (a string).\n\
1065 This adds or updates a named color to w32-color-map, making it available for use.\n\
1066 The original entry's RGB ref is returned, or nil if the entry is new.")
1067 (red, green, blue, name)
1068 Lisp_Object red, green, blue, name;
1070 Lisp_Object rgb;
1071 Lisp_Object oldrgb = Qnil;
1072 Lisp_Object entry;
1074 CHECK_NUMBER (red, 0);
1075 CHECK_NUMBER (green, 0);
1076 CHECK_NUMBER (blue, 0);
1077 CHECK_STRING (name, 0);
1079 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1081 BLOCK_INPUT;
1083 /* replace existing entry in w32-color-map or add new entry. */
1084 entry = Fassoc (name, Vw32_color_map);
1085 if (NILP (entry))
1087 entry = Fcons (name, rgb);
1088 Vw32_color_map = Fcons (entry, Vw32_color_map);
1090 else
1092 oldrgb = Fcdr (entry);
1093 Fsetcdr (entry, rgb);
1096 UNBLOCK_INPUT;
1098 return (oldrgb);
1101 DEFUN ("w32-load-color-file", Fw32_load_color_file, Sw32_load_color_file, 1, 1, 0,
1102 "Create an alist of color entries from an external file (ie. rgb.txt).\n\
1103 Assign this value to w32-color-map to replace the existing color map.\n\
1105 The file should define one named RGB color per line like so:\
1106 R G B name\n\
1107 where R,G,B are numbers between 0 and 255 and name is an arbitrary string.")
1108 (filename)
1109 Lisp_Object filename;
1111 FILE *fp;
1112 Lisp_Object cmap = Qnil;
1113 Lisp_Object abspath;
1115 CHECK_STRING (filename, 0);
1116 abspath = Fexpand_file_name (filename, Qnil);
1118 fp = fopen (XSTRING (filename)->data, "rt");
1119 if (fp)
1121 char buf[512];
1122 int red, green, blue;
1123 int num;
1125 BLOCK_INPUT;
1127 while (fgets (buf, sizeof (buf), fp) != NULL) {
1128 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1130 char *name = buf + num;
1131 num = strlen (name) - 1;
1132 if (name[num] == '\n')
1133 name[num] = 0;
1134 cmap = Fcons (Fcons (build_string (name),
1135 make_number (RGB (red, green, blue))),
1136 cmap);
1139 fclose (fp);
1141 UNBLOCK_INPUT;
1144 return cmap;
1147 /* The default colors for the w32 color map */
1148 typedef struct colormap_t
1150 char *name;
1151 COLORREF colorref;
1152 } colormap_t;
1154 colormap_t w32_color_map[] =
1156 {"snow" , PALETTERGB (255,250,250)},
1157 {"ghost white" , PALETTERGB (248,248,255)},
1158 {"GhostWhite" , PALETTERGB (248,248,255)},
1159 {"white smoke" , PALETTERGB (245,245,245)},
1160 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1161 {"gainsboro" , PALETTERGB (220,220,220)},
1162 {"floral white" , PALETTERGB (255,250,240)},
1163 {"FloralWhite" , PALETTERGB (255,250,240)},
1164 {"old lace" , PALETTERGB (253,245,230)},
1165 {"OldLace" , PALETTERGB (253,245,230)},
1166 {"linen" , PALETTERGB (250,240,230)},
1167 {"antique white" , PALETTERGB (250,235,215)},
1168 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1169 {"papaya whip" , PALETTERGB (255,239,213)},
1170 {"PapayaWhip" , PALETTERGB (255,239,213)},
1171 {"blanched almond" , PALETTERGB (255,235,205)},
1172 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1173 {"bisque" , PALETTERGB (255,228,196)},
1174 {"peach puff" , PALETTERGB (255,218,185)},
1175 {"PeachPuff" , PALETTERGB (255,218,185)},
1176 {"navajo white" , PALETTERGB (255,222,173)},
1177 {"NavajoWhite" , PALETTERGB (255,222,173)},
1178 {"moccasin" , PALETTERGB (255,228,181)},
1179 {"cornsilk" , PALETTERGB (255,248,220)},
1180 {"ivory" , PALETTERGB (255,255,240)},
1181 {"lemon chiffon" , PALETTERGB (255,250,205)},
1182 {"LemonChiffon" , PALETTERGB (255,250,205)},
1183 {"seashell" , PALETTERGB (255,245,238)},
1184 {"honeydew" , PALETTERGB (240,255,240)},
1185 {"mint cream" , PALETTERGB (245,255,250)},
1186 {"MintCream" , PALETTERGB (245,255,250)},
1187 {"azure" , PALETTERGB (240,255,255)},
1188 {"alice blue" , PALETTERGB (240,248,255)},
1189 {"AliceBlue" , PALETTERGB (240,248,255)},
1190 {"lavender" , PALETTERGB (230,230,250)},
1191 {"lavender blush" , PALETTERGB (255,240,245)},
1192 {"LavenderBlush" , PALETTERGB (255,240,245)},
1193 {"misty rose" , PALETTERGB (255,228,225)},
1194 {"MistyRose" , PALETTERGB (255,228,225)},
1195 {"white" , PALETTERGB (255,255,255)},
1196 {"black" , PALETTERGB ( 0, 0, 0)},
1197 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1198 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1199 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1200 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1201 {"dim gray" , PALETTERGB (105,105,105)},
1202 {"DimGray" , PALETTERGB (105,105,105)},
1203 {"dim grey" , PALETTERGB (105,105,105)},
1204 {"DimGrey" , PALETTERGB (105,105,105)},
1205 {"slate gray" , PALETTERGB (112,128,144)},
1206 {"SlateGray" , PALETTERGB (112,128,144)},
1207 {"slate grey" , PALETTERGB (112,128,144)},
1208 {"SlateGrey" , PALETTERGB (112,128,144)},
1209 {"light slate gray" , PALETTERGB (119,136,153)},
1210 {"LightSlateGray" , PALETTERGB (119,136,153)},
1211 {"light slate grey" , PALETTERGB (119,136,153)},
1212 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1213 {"gray" , PALETTERGB (190,190,190)},
1214 {"grey" , PALETTERGB (190,190,190)},
1215 {"light grey" , PALETTERGB (211,211,211)},
1216 {"LightGrey" , PALETTERGB (211,211,211)},
1217 {"light gray" , PALETTERGB (211,211,211)},
1218 {"LightGray" , PALETTERGB (211,211,211)},
1219 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1220 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1221 {"navy" , PALETTERGB ( 0, 0,128)},
1222 {"navy blue" , PALETTERGB ( 0, 0,128)},
1223 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1224 {"cornflower blue" , PALETTERGB (100,149,237)},
1225 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1226 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1227 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1228 {"slate blue" , PALETTERGB (106, 90,205)},
1229 {"SlateBlue" , PALETTERGB (106, 90,205)},
1230 {"medium slate blue" , PALETTERGB (123,104,238)},
1231 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1232 {"light slate blue" , PALETTERGB (132,112,255)},
1233 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1234 {"medium blue" , PALETTERGB ( 0, 0,205)},
1235 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1236 {"royal blue" , PALETTERGB ( 65,105,225)},
1237 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1238 {"blue" , PALETTERGB ( 0, 0,255)},
1239 {"dodger blue" , PALETTERGB ( 30,144,255)},
1240 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1241 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1242 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1243 {"sky blue" , PALETTERGB (135,206,235)},
1244 {"SkyBlue" , PALETTERGB (135,206,235)},
1245 {"light sky blue" , PALETTERGB (135,206,250)},
1246 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1247 {"steel blue" , PALETTERGB ( 70,130,180)},
1248 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1249 {"light steel blue" , PALETTERGB (176,196,222)},
1250 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1251 {"light blue" , PALETTERGB (173,216,230)},
1252 {"LightBlue" , PALETTERGB (173,216,230)},
1253 {"powder blue" , PALETTERGB (176,224,230)},
1254 {"PowderBlue" , PALETTERGB (176,224,230)},
1255 {"pale turquoise" , PALETTERGB (175,238,238)},
1256 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1257 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1258 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1259 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1260 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1261 {"turquoise" , PALETTERGB ( 64,224,208)},
1262 {"cyan" , PALETTERGB ( 0,255,255)},
1263 {"light cyan" , PALETTERGB (224,255,255)},
1264 {"LightCyan" , PALETTERGB (224,255,255)},
1265 {"cadet blue" , PALETTERGB ( 95,158,160)},
1266 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1267 {"medium aquamarine" , PALETTERGB (102,205,170)},
1268 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1269 {"aquamarine" , PALETTERGB (127,255,212)},
1270 {"dark green" , PALETTERGB ( 0,100, 0)},
1271 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1272 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1273 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1274 {"dark sea green" , PALETTERGB (143,188,143)},
1275 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1276 {"sea green" , PALETTERGB ( 46,139, 87)},
1277 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1278 {"medium sea green" , PALETTERGB ( 60,179,113)},
1279 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1280 {"light sea green" , PALETTERGB ( 32,178,170)},
1281 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1282 {"pale green" , PALETTERGB (152,251,152)},
1283 {"PaleGreen" , PALETTERGB (152,251,152)},
1284 {"spring green" , PALETTERGB ( 0,255,127)},
1285 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1286 {"lawn green" , PALETTERGB (124,252, 0)},
1287 {"LawnGreen" , PALETTERGB (124,252, 0)},
1288 {"green" , PALETTERGB ( 0,255, 0)},
1289 {"chartreuse" , PALETTERGB (127,255, 0)},
1290 {"medium spring green" , PALETTERGB ( 0,250,154)},
1291 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1292 {"green yellow" , PALETTERGB (173,255, 47)},
1293 {"GreenYellow" , PALETTERGB (173,255, 47)},
1294 {"lime green" , PALETTERGB ( 50,205, 50)},
1295 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1296 {"yellow green" , PALETTERGB (154,205, 50)},
1297 {"YellowGreen" , PALETTERGB (154,205, 50)},
1298 {"forest green" , PALETTERGB ( 34,139, 34)},
1299 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1300 {"olive drab" , PALETTERGB (107,142, 35)},
1301 {"OliveDrab" , PALETTERGB (107,142, 35)},
1302 {"dark khaki" , PALETTERGB (189,183,107)},
1303 {"DarkKhaki" , PALETTERGB (189,183,107)},
1304 {"khaki" , PALETTERGB (240,230,140)},
1305 {"pale goldenrod" , PALETTERGB (238,232,170)},
1306 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1307 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1308 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1309 {"light yellow" , PALETTERGB (255,255,224)},
1310 {"LightYellow" , PALETTERGB (255,255,224)},
1311 {"yellow" , PALETTERGB (255,255, 0)},
1312 {"gold" , PALETTERGB (255,215, 0)},
1313 {"light goldenrod" , PALETTERGB (238,221,130)},
1314 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1315 {"goldenrod" , PALETTERGB (218,165, 32)},
1316 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1317 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1318 {"rosy brown" , PALETTERGB (188,143,143)},
1319 {"RosyBrown" , PALETTERGB (188,143,143)},
1320 {"indian red" , PALETTERGB (205, 92, 92)},
1321 {"IndianRed" , PALETTERGB (205, 92, 92)},
1322 {"saddle brown" , PALETTERGB (139, 69, 19)},
1323 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1324 {"sienna" , PALETTERGB (160, 82, 45)},
1325 {"peru" , PALETTERGB (205,133, 63)},
1326 {"burlywood" , PALETTERGB (222,184,135)},
1327 {"beige" , PALETTERGB (245,245,220)},
1328 {"wheat" , PALETTERGB (245,222,179)},
1329 {"sandy brown" , PALETTERGB (244,164, 96)},
1330 {"SandyBrown" , PALETTERGB (244,164, 96)},
1331 {"tan" , PALETTERGB (210,180,140)},
1332 {"chocolate" , PALETTERGB (210,105, 30)},
1333 {"firebrick" , PALETTERGB (178,34, 34)},
1334 {"brown" , PALETTERGB (165,42, 42)},
1335 {"dark salmon" , PALETTERGB (233,150,122)},
1336 {"DarkSalmon" , PALETTERGB (233,150,122)},
1337 {"salmon" , PALETTERGB (250,128,114)},
1338 {"light salmon" , PALETTERGB (255,160,122)},
1339 {"LightSalmon" , PALETTERGB (255,160,122)},
1340 {"orange" , PALETTERGB (255,165, 0)},
1341 {"dark orange" , PALETTERGB (255,140, 0)},
1342 {"DarkOrange" , PALETTERGB (255,140, 0)},
1343 {"coral" , PALETTERGB (255,127, 80)},
1344 {"light coral" , PALETTERGB (240,128,128)},
1345 {"LightCoral" , PALETTERGB (240,128,128)},
1346 {"tomato" , PALETTERGB (255, 99, 71)},
1347 {"orange red" , PALETTERGB (255, 69, 0)},
1348 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1349 {"red" , PALETTERGB (255, 0, 0)},
1350 {"hot pink" , PALETTERGB (255,105,180)},
1351 {"HotPink" , PALETTERGB (255,105,180)},
1352 {"deep pink" , PALETTERGB (255, 20,147)},
1353 {"DeepPink" , PALETTERGB (255, 20,147)},
1354 {"pink" , PALETTERGB (255,192,203)},
1355 {"light pink" , PALETTERGB (255,182,193)},
1356 {"LightPink" , PALETTERGB (255,182,193)},
1357 {"pale violet red" , PALETTERGB (219,112,147)},
1358 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1359 {"maroon" , PALETTERGB (176, 48, 96)},
1360 {"medium violet red" , PALETTERGB (199, 21,133)},
1361 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1362 {"violet red" , PALETTERGB (208, 32,144)},
1363 {"VioletRed" , PALETTERGB (208, 32,144)},
1364 {"magenta" , PALETTERGB (255, 0,255)},
1365 {"violet" , PALETTERGB (238,130,238)},
1366 {"plum" , PALETTERGB (221,160,221)},
1367 {"orchid" , PALETTERGB (218,112,214)},
1368 {"medium orchid" , PALETTERGB (186, 85,211)},
1369 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1370 {"dark orchid" , PALETTERGB (153, 50,204)},
1371 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1372 {"dark violet" , PALETTERGB (148, 0,211)},
1373 {"DarkViolet" , PALETTERGB (148, 0,211)},
1374 {"blue violet" , PALETTERGB (138, 43,226)},
1375 {"BlueViolet" , PALETTERGB (138, 43,226)},
1376 {"purple" , PALETTERGB (160, 32,240)},
1377 {"medium purple" , PALETTERGB (147,112,219)},
1378 {"MediumPurple" , PALETTERGB (147,112,219)},
1379 {"thistle" , PALETTERGB (216,191,216)},
1380 {"gray0" , PALETTERGB ( 0, 0, 0)},
1381 {"grey0" , PALETTERGB ( 0, 0, 0)},
1382 {"dark grey" , PALETTERGB (169,169,169)},
1383 {"DarkGrey" , PALETTERGB (169,169,169)},
1384 {"dark gray" , PALETTERGB (169,169,169)},
1385 {"DarkGray" , PALETTERGB (169,169,169)},
1386 {"dark blue" , PALETTERGB ( 0, 0,139)},
1387 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1388 {"dark cyan" , PALETTERGB ( 0,139,139)},
1389 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1390 {"dark magenta" , PALETTERGB (139, 0,139)},
1391 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1392 {"dark red" , PALETTERGB (139, 0, 0)},
1393 {"DarkRed" , PALETTERGB (139, 0, 0)},
1394 {"light green" , PALETTERGB (144,238,144)},
1395 {"LightGreen" , PALETTERGB (144,238,144)},
1398 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1399 0, 0, 0, "Return the default color map.")
1402 int i;
1403 colormap_t *pc = w32_color_map;
1404 Lisp_Object cmap;
1406 BLOCK_INPUT;
1408 cmap = Qnil;
1410 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1411 pc++, i++)
1412 cmap = Fcons (Fcons (build_string (pc->name),
1413 make_number (pc->colorref)),
1414 cmap);
1416 UNBLOCK_INPUT;
1418 return (cmap);
1421 Lisp_Object
1422 w32_to_x_color (rgb)
1423 Lisp_Object rgb;
1425 Lisp_Object color;
1427 CHECK_NUMBER (rgb, 0);
1429 BLOCK_INPUT;
1431 color = Frassq (rgb, Vw32_color_map);
1433 UNBLOCK_INPUT;
1435 if (!NILP (color))
1436 return (Fcar (color));
1437 else
1438 return Qnil;
1441 COLORREF
1442 w32_color_map_lookup (colorname)
1443 char *colorname;
1445 Lisp_Object tail, ret = Qnil;
1447 BLOCK_INPUT;
1449 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1451 register Lisp_Object elt, tem;
1453 elt = Fcar (tail);
1454 if (!CONSP (elt)) continue;
1456 tem = Fcar (elt);
1458 if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
1460 ret = XUINT (Fcdr (elt));
1461 break;
1464 QUIT;
1468 UNBLOCK_INPUT;
1470 return ret;
1473 COLORREF
1474 x_to_w32_color (colorname)
1475 char * colorname;
1477 register Lisp_Object ret = Qnil;
1479 BLOCK_INPUT;
1481 if (colorname[0] == '#')
1483 /* Could be an old-style RGB Device specification. */
1484 char *color;
1485 int size;
1486 color = colorname + 1;
1488 size = strlen(color);
1489 if (size == 3 || size == 6 || size == 9 || size == 12)
1491 UINT colorval;
1492 int i, pos;
1493 pos = 0;
1494 size /= 3;
1495 colorval = 0;
1497 for (i = 0; i < 3; i++)
1499 char *end;
1500 char t;
1501 unsigned long value;
1503 /* The check for 'x' in the following conditional takes into
1504 account the fact that strtol allows a "0x" in front of
1505 our numbers, and we don't. */
1506 if (!isxdigit(color[0]) || color[1] == 'x')
1507 break;
1508 t = color[size];
1509 color[size] = '\0';
1510 value = strtoul(color, &end, 16);
1511 color[size] = t;
1512 if (errno == ERANGE || end - color != size)
1513 break;
1514 switch (size)
1516 case 1:
1517 value = value * 0x10;
1518 break;
1519 case 2:
1520 break;
1521 case 3:
1522 value /= 0x10;
1523 break;
1524 case 4:
1525 value /= 0x100;
1526 break;
1528 colorval |= (value << pos);
1529 pos += 0x8;
1530 if (i == 2)
1532 UNBLOCK_INPUT;
1533 return (colorval);
1535 color = end;
1539 else if (strnicmp(colorname, "rgb:", 4) == 0)
1541 char *color;
1542 UINT colorval;
1543 int i, pos;
1544 pos = 0;
1546 colorval = 0;
1547 color = colorname + 4;
1548 for (i = 0; i < 3; i++)
1550 char *end;
1551 unsigned long value;
1553 /* The check for 'x' in the following conditional takes into
1554 account the fact that strtol allows a "0x" in front of
1555 our numbers, and we don't. */
1556 if (!isxdigit(color[0]) || color[1] == 'x')
1557 break;
1558 value = strtoul(color, &end, 16);
1559 if (errno == ERANGE)
1560 break;
1561 switch (end - color)
1563 case 1:
1564 value = value * 0x10 + value;
1565 break;
1566 case 2:
1567 break;
1568 case 3:
1569 value /= 0x10;
1570 break;
1571 case 4:
1572 value /= 0x100;
1573 break;
1574 default:
1575 value = ULONG_MAX;
1577 if (value == ULONG_MAX)
1578 break;
1579 colorval |= (value << pos);
1580 pos += 0x8;
1581 if (i == 2)
1583 if (*end != '\0')
1584 break;
1585 UNBLOCK_INPUT;
1586 return (colorval);
1588 if (*end != '/')
1589 break;
1590 color = end + 1;
1593 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1595 /* This is an RGB Intensity specification. */
1596 char *color;
1597 UINT colorval;
1598 int i, pos;
1599 pos = 0;
1601 colorval = 0;
1602 color = colorname + 5;
1603 for (i = 0; i < 3; i++)
1605 char *end;
1606 double value;
1607 UINT val;
1609 value = strtod(color, &end);
1610 if (errno == ERANGE)
1611 break;
1612 if (value < 0.0 || value > 1.0)
1613 break;
1614 val = (UINT)(0x100 * value);
1615 /* We used 0x100 instead of 0xFF to give an continuous
1616 range between 0.0 and 1.0 inclusive. The next statement
1617 fixes the 1.0 case. */
1618 if (val == 0x100)
1619 val = 0xFF;
1620 colorval |= (val << pos);
1621 pos += 0x8;
1622 if (i == 2)
1624 if (*end != '\0')
1625 break;
1626 UNBLOCK_INPUT;
1627 return (colorval);
1629 if (*end != '/')
1630 break;
1631 color = end + 1;
1634 /* I am not going to attempt to handle any of the CIE color schemes
1635 or TekHVC, since I don't know the algorithms for conversion to
1636 RGB. */
1638 /* If we fail to lookup the color name in w32_color_map, then check the
1639 colorname to see if it can be crudely approximated: If the X color
1640 ends in a number (e.g., "darkseagreen2"), strip the number and
1641 return the result of looking up the base color name. */
1642 ret = w32_color_map_lookup (colorname);
1643 if (NILP (ret))
1645 int len = strlen (colorname);
1647 if (isdigit (colorname[len - 1]))
1649 char *ptr, *approx = alloca (len);
1651 strcpy (approx, colorname);
1652 ptr = &approx[len - 1];
1653 while (ptr > approx && isdigit (*ptr))
1654 *ptr-- = '\0';
1656 ret = w32_color_map_lookup (approx);
1660 UNBLOCK_INPUT;
1661 return ret;
1665 void
1666 w32_regenerate_palette (FRAME_PTR f)
1668 struct w32_palette_entry * list;
1669 LOGPALETTE * log_palette;
1670 HPALETTE new_palette;
1671 int i;
1673 /* don't bother trying to create palette if not supported */
1674 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1675 return;
1677 log_palette = (LOGPALETTE *)
1678 alloca (sizeof (LOGPALETTE) +
1679 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1680 log_palette->palVersion = 0x300;
1681 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1683 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1684 for (i = 0;
1685 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1686 i++, list = list->next)
1687 log_palette->palPalEntry[i] = list->entry;
1689 new_palette = CreatePalette (log_palette);
1691 enter_crit ();
1693 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1694 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1695 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1697 /* Realize display palette and garbage all frames. */
1698 release_frame_dc (f, get_frame_dc (f));
1700 leave_crit ();
1703 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1704 #define SET_W32_COLOR(pe, color) \
1705 do \
1707 pe.peRed = GetRValue (color); \
1708 pe.peGreen = GetGValue (color); \
1709 pe.peBlue = GetBValue (color); \
1710 pe.peFlags = 0; \
1711 } while (0)
1713 #if 0
1714 /* Keep these around in case we ever want to track color usage. */
1715 void
1716 w32_map_color (FRAME_PTR f, COLORREF color)
1718 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1720 if (NILP (Vw32_enable_palette))
1721 return;
1723 /* check if color is already mapped */
1724 while (list)
1726 if (W32_COLOR (list->entry) == color)
1728 ++list->refcount;
1729 return;
1731 list = list->next;
1734 /* not already mapped, so add to list and recreate Windows palette */
1735 list = (struct w32_palette_entry *)
1736 xmalloc (sizeof (struct w32_palette_entry));
1737 SET_W32_COLOR (list->entry, color);
1738 list->refcount = 1;
1739 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1740 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1741 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1743 /* set flag that palette must be regenerated */
1744 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1747 void
1748 w32_unmap_color (FRAME_PTR f, COLORREF color)
1750 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1751 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1753 if (NILP (Vw32_enable_palette))
1754 return;
1756 /* check if color is already mapped */
1757 while (list)
1759 if (W32_COLOR (list->entry) == color)
1761 if (--list->refcount == 0)
1763 *prev = list->next;
1764 xfree (list);
1765 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1766 break;
1768 else
1769 return;
1771 prev = &list->next;
1772 list = list->next;
1775 /* set flag that palette must be regenerated */
1776 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1778 #endif
1781 /* Gamma-correct COLOR on frame F. */
1783 void
1784 gamma_correct (f, color)
1785 struct frame *f;
1786 COLORREF *color;
1788 if (f->gamma)
1790 *color = PALETTERGB (
1791 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1792 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1793 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1798 /* Decide if color named COLOR is valid for the display associated with
1799 the selected frame; if so, return the rgb values in COLOR_DEF.
1800 If ALLOC is nonzero, allocate a new colormap cell. */
1803 w32_defined_color (f, color, color_def, alloc)
1804 FRAME_PTR f;
1805 char *color;
1806 XColor *color_def;
1807 int alloc;
1809 register Lisp_Object tem;
1810 COLORREF w32_color_ref;
1812 tem = x_to_w32_color (color);
1814 if (!NILP (tem))
1816 if (f)
1818 /* Apply gamma correction. */
1819 w32_color_ref = XUINT (tem);
1820 gamma_correct (f, &w32_color_ref);
1821 XSETINT (tem, w32_color_ref);
1824 /* Map this color to the palette if it is enabled. */
1825 if (!NILP (Vw32_enable_palette))
1827 struct w32_palette_entry * entry =
1828 one_w32_display_info.color_list;
1829 struct w32_palette_entry ** prev =
1830 &one_w32_display_info.color_list;
1832 /* check if color is already mapped */
1833 while (entry)
1835 if (W32_COLOR (entry->entry) == XUINT (tem))
1836 break;
1837 prev = &entry->next;
1838 entry = entry->next;
1841 if (entry == NULL && alloc)
1843 /* not already mapped, so add to list */
1844 entry = (struct w32_palette_entry *)
1845 xmalloc (sizeof (struct w32_palette_entry));
1846 SET_W32_COLOR (entry->entry, XUINT (tem));
1847 entry->next = NULL;
1848 *prev = entry;
1849 one_w32_display_info.num_colors++;
1851 /* set flag that palette must be regenerated */
1852 one_w32_display_info.regen_palette = TRUE;
1855 /* Ensure COLORREF value is snapped to nearest color in (default)
1856 palette by simulating the PALETTERGB macro. This works whether
1857 or not the display device has a palette. */
1858 w32_color_ref = XUINT (tem) | 0x2000000;
1860 color_def->pixel = w32_color_ref;
1861 color_def->red = GetRValue (w32_color_ref);
1862 color_def->green = GetGValue (w32_color_ref);
1863 color_def->blue = GetBValue (w32_color_ref);
1865 return 1;
1867 else
1869 return 0;
1873 /* Given a string ARG naming a color, compute a pixel value from it
1874 suitable for screen F.
1875 If F is not a color screen, return DEF (default) regardless of what
1876 ARG says. */
1879 x_decode_color (f, arg, def)
1880 FRAME_PTR f;
1881 Lisp_Object arg;
1882 int def;
1884 XColor cdef;
1886 CHECK_STRING (arg, 0);
1888 if (strcmp (XSTRING (arg)->data, "black") == 0)
1889 return BLACK_PIX_DEFAULT (f);
1890 else if (strcmp (XSTRING (arg)->data, "white") == 0)
1891 return WHITE_PIX_DEFAULT (f);
1893 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1894 return def;
1896 /* w32_defined_color is responsible for coping with failures
1897 by looking for a near-miss. */
1898 if (w32_defined_color (f, XSTRING (arg)->data, &cdef, 1))
1899 return cdef.pixel;
1901 /* defined_color failed; return an ultimate default. */
1902 return def;
1905 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
1906 the previous value of that parameter, NEW_VALUE is the new value. */
1908 static void
1909 x_set_line_spacing (f, new_value, old_value)
1910 struct frame *f;
1911 Lisp_Object new_value, old_value;
1913 if (NILP (new_value))
1914 f->extra_line_spacing = 0;
1915 else if (NATNUMP (new_value))
1916 f->extra_line_spacing = XFASTINT (new_value);
1917 else
1918 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
1919 Fcons (new_value, Qnil)));
1920 if (FRAME_VISIBLE_P (f))
1921 redraw_frame (f);
1925 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
1926 the previous value of that parameter, NEW_VALUE is the new value. */
1928 static void
1929 x_set_screen_gamma (f, new_value, old_value)
1930 struct frame *f;
1931 Lisp_Object new_value, old_value;
1933 if (NILP (new_value))
1934 f->gamma = 0;
1935 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
1936 /* The value 0.4545 is the normal viewing gamma. */
1937 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
1938 else
1939 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
1940 Fcons (new_value, Qnil)));
1942 clear_face_cache (0);
1946 /* Functions called only from `x_set_frame_param'
1947 to set individual parameters.
1949 If FRAME_W32_WINDOW (f) is 0,
1950 the frame is being created and its window does not exist yet.
1951 In that case, just record the parameter's new value
1952 in the standard place; do not attempt to change the window. */
1954 void
1955 x_set_foreground_color (f, arg, oldval)
1956 struct frame *f;
1957 Lisp_Object arg, oldval;
1959 FRAME_FOREGROUND_PIXEL (f)
1960 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1962 if (FRAME_W32_WINDOW (f) != 0)
1964 update_face_from_frame_parameter (f, Qforeground_color, arg);
1965 if (FRAME_VISIBLE_P (f))
1966 redraw_frame (f);
1970 void
1971 x_set_background_color (f, arg, oldval)
1972 struct frame *f;
1973 Lisp_Object arg, oldval;
1975 FRAME_BACKGROUND_PIXEL (f)
1976 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1978 if (FRAME_W32_WINDOW (f) != 0)
1980 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1981 FRAME_BACKGROUND_PIXEL (f));
1983 update_face_from_frame_parameter (f, Qbackground_color, arg);
1985 if (FRAME_VISIBLE_P (f))
1986 redraw_frame (f);
1990 void
1991 x_set_mouse_color (f, arg, oldval)
1992 struct frame *f;
1993 Lisp_Object arg, oldval;
1995 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
1996 int count;
1997 int mask_color;
1999 if (!EQ (Qnil, arg))
2000 f->output_data.w32->mouse_pixel
2001 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2002 mask_color = FRAME_BACKGROUND_PIXEL (f);
2004 /* Don't let pointers be invisible. */
2005 if (mask_color == f->output_data.w32->mouse_pixel
2006 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2007 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2009 #if 0 /* TODO : cursor changes */
2010 BLOCK_INPUT;
2012 /* It's not okay to crash if the user selects a screwy cursor. */
2013 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2015 if (!EQ (Qnil, Vx_pointer_shape))
2017 CHECK_NUMBER (Vx_pointer_shape, 0);
2018 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2020 else
2021 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2022 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2024 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2026 CHECK_NUMBER (Vx_nontext_pointer_shape, 0);
2027 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2028 XINT (Vx_nontext_pointer_shape));
2030 else
2031 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2032 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2034 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
2036 CHECK_NUMBER (Vx_hourglass_pointer_shape, 0);
2037 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2038 XINT (Vx_hourglass_pointer_shape));
2040 else
2041 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2042 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2044 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2045 if (!EQ (Qnil, Vx_mode_pointer_shape))
2047 CHECK_NUMBER (Vx_mode_pointer_shape, 0);
2048 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2049 XINT (Vx_mode_pointer_shape));
2051 else
2052 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2053 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2055 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2057 CHECK_NUMBER (Vx_sensitive_text_pointer_shape, 0);
2058 cross_cursor
2059 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2060 XINT (Vx_sensitive_text_pointer_shape));
2062 else
2063 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2065 if (!NILP (Vx_window_horizontal_drag_shape))
2067 CHECK_NUMBER (Vx_window_horizontal_drag_shape, 0);
2068 horizontal_drag_cursor
2069 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2070 XINT (Vx_window_horizontal_drag_shape));
2072 else
2073 horizontal_drag_cursor
2074 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2076 /* Check and report errors with the above calls. */
2077 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2078 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2081 XColor fore_color, back_color;
2083 fore_color.pixel = f->output_data.w32->mouse_pixel;
2084 back_color.pixel = mask_color;
2085 XQueryColor (FRAME_W32_DISPLAY (f),
2086 DefaultColormap (FRAME_W32_DISPLAY (f),
2087 DefaultScreen (FRAME_W32_DISPLAY (f))),
2088 &fore_color);
2089 XQueryColor (FRAME_W32_DISPLAY (f),
2090 DefaultColormap (FRAME_W32_DISPLAY (f),
2091 DefaultScreen (FRAME_W32_DISPLAY (f))),
2092 &back_color);
2093 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2094 &fore_color, &back_color);
2095 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2096 &fore_color, &back_color);
2097 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2098 &fore_color, &back_color);
2099 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2100 &fore_color, &back_color);
2101 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
2102 &fore_color, &back_color);
2105 if (FRAME_W32_WINDOW (f) != 0)
2106 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2108 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2109 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2110 f->output_data.w32->text_cursor = cursor;
2112 if (nontext_cursor != f->output_data.w32->nontext_cursor
2113 && f->output_data.w32->nontext_cursor != 0)
2114 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2115 f->output_data.w32->nontext_cursor = nontext_cursor;
2117 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
2118 && f->output_data.w32->hourglass_cursor != 0)
2119 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
2120 f->output_data.w32->hourglass_cursor = hourglass_cursor;
2122 if (mode_cursor != f->output_data.w32->modeline_cursor
2123 && f->output_data.w32->modeline_cursor != 0)
2124 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2125 f->output_data.w32->modeline_cursor = mode_cursor;
2127 if (cross_cursor != f->output_data.w32->cross_cursor
2128 && f->output_data.w32->cross_cursor != 0)
2129 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2130 f->output_data.w32->cross_cursor = cross_cursor;
2132 XFlush (FRAME_W32_DISPLAY (f));
2133 UNBLOCK_INPUT;
2135 update_face_from_frame_parameter (f, Qmouse_color, arg);
2136 #endif /* TODO */
2139 /* Defined in w32term.c. */
2140 void x_update_cursor (struct frame *f, int on_p);
2142 void
2143 x_set_cursor_color (f, arg, oldval)
2144 struct frame *f;
2145 Lisp_Object arg, oldval;
2147 unsigned long fore_pixel, pixel;
2149 if (!NILP (Vx_cursor_fore_pixel))
2150 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2151 WHITE_PIX_DEFAULT (f));
2152 else
2153 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2155 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2157 /* Make sure that the cursor color differs from the background color. */
2158 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2160 pixel = f->output_data.w32->mouse_pixel;
2161 if (pixel == fore_pixel)
2162 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2165 FRAME_FOREGROUND_PIXEL (f) = fore_pixel;
2166 f->output_data.w32->cursor_pixel = pixel;
2168 if (FRAME_W32_WINDOW (f) != 0)
2170 if (FRAME_VISIBLE_P (f))
2172 x_update_cursor (f, 0);
2173 x_update_cursor (f, 1);
2177 update_face_from_frame_parameter (f, Qcursor_color, arg);
2180 /* Set the border-color of frame F to pixel value PIX.
2181 Note that this does not fully take effect if done before
2182 F has an window. */
2183 void
2184 x_set_border_pixel (f, pix)
2185 struct frame *f;
2186 int pix;
2188 f->output_data.w32->border_pixel = pix;
2190 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2192 if (FRAME_VISIBLE_P (f))
2193 redraw_frame (f);
2197 /* Set the border-color of frame F to value described by ARG.
2198 ARG can be a string naming a color.
2199 The border-color is used for the border that is drawn by the server.
2200 Note that this does not fully take effect if done before
2201 F has a window; it must be redone when the window is created. */
2203 void
2204 x_set_border_color (f, arg, oldval)
2205 struct frame *f;
2206 Lisp_Object arg, oldval;
2208 int pix;
2210 CHECK_STRING (arg, 0);
2211 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2212 x_set_border_pixel (f, pix);
2213 update_face_from_frame_parameter (f, Qborder_color, arg);
2216 /* Value is the internal representation of the specified cursor type
2217 ARG. If type is BAR_CURSOR, return in *WIDTH the specified width
2218 of the bar cursor. */
2220 enum text_cursor_kinds
2221 x_specified_cursor_type (arg, width)
2222 Lisp_Object arg;
2223 int *width;
2225 enum text_cursor_kinds type;
2227 if (EQ (arg, Qbar))
2229 type = BAR_CURSOR;
2230 *width = 2;
2232 else if (CONSP (arg)
2233 && EQ (XCAR (arg), Qbar)
2234 && INTEGERP (XCDR (arg))
2235 && XINT (XCDR (arg)) >= 0)
2237 type = BAR_CURSOR;
2238 *width = XINT (XCDR (arg));
2240 else if (NILP (arg))
2241 type = NO_CURSOR;
2242 else
2243 /* Treat anything unknown as "box cursor".
2244 It was bad to signal an error; people have trouble fixing
2245 .Xdefaults with Emacs, when it has something bad in it. */
2246 type = FILLED_BOX_CURSOR;
2248 return type;
2251 void
2252 x_set_cursor_type (f, arg, oldval)
2253 FRAME_PTR f;
2254 Lisp_Object arg, oldval;
2256 int width;
2258 FRAME_DESIRED_CURSOR (f) = x_specified_cursor_type (arg, &width);
2259 f->output_data.w32->cursor_width = width;
2261 /* Make sure the cursor gets redrawn. This is overkill, but how
2262 often do people change cursor types? */
2263 update_mode_lines++;
2266 void
2267 x_set_icon_type (f, arg, oldval)
2268 struct frame *f;
2269 Lisp_Object arg, oldval;
2271 int result;
2273 if (NILP (arg) && NILP (oldval))
2274 return;
2276 if (STRINGP (arg) && STRINGP (oldval)
2277 && EQ (Fstring_equal (oldval, arg), Qt))
2278 return;
2280 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2281 return;
2283 BLOCK_INPUT;
2285 result = x_bitmap_icon (f, arg);
2286 if (result)
2288 UNBLOCK_INPUT;
2289 error ("No icon window available");
2292 UNBLOCK_INPUT;
2295 /* Return non-nil if frame F wants a bitmap icon. */
2297 Lisp_Object
2298 x_icon_type (f)
2299 FRAME_PTR f;
2301 Lisp_Object tem;
2303 tem = assq_no_quit (Qicon_type, f->param_alist);
2304 if (CONSP (tem))
2305 return XCDR (tem);
2306 else
2307 return Qnil;
2310 void
2311 x_set_icon_name (f, arg, oldval)
2312 struct frame *f;
2313 Lisp_Object arg, oldval;
2315 if (STRINGP (arg))
2317 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2318 return;
2320 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2321 return;
2323 f->icon_name = arg;
2325 #if 0
2326 if (f->output_data.w32->icon_bitmap != 0)
2327 return;
2329 BLOCK_INPUT;
2331 result = x_text_icon (f,
2332 (char *) XSTRING ((!NILP (f->icon_name)
2333 ? f->icon_name
2334 : !NILP (f->title)
2335 ? f->title
2336 : f->name))->data);
2338 if (result)
2340 UNBLOCK_INPUT;
2341 error ("No icon window available");
2344 /* If the window was unmapped (and its icon was mapped),
2345 the new icon is not mapped, so map the window in its stead. */
2346 if (FRAME_VISIBLE_P (f))
2348 #ifdef USE_X_TOOLKIT
2349 XtPopup (f->output_data.w32->widget, XtGrabNone);
2350 #endif
2351 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2354 XFlush (FRAME_W32_DISPLAY (f));
2355 UNBLOCK_INPUT;
2356 #endif
2359 extern Lisp_Object x_new_font ();
2360 extern Lisp_Object x_new_fontset();
2362 void
2363 x_set_font (f, arg, oldval)
2364 struct frame *f;
2365 Lisp_Object arg, oldval;
2367 Lisp_Object result;
2368 Lisp_Object fontset_name;
2369 Lisp_Object frame;
2371 CHECK_STRING (arg, 1);
2373 fontset_name = Fquery_fontset (arg, Qnil);
2375 BLOCK_INPUT;
2376 result = (STRINGP (fontset_name)
2377 ? x_new_fontset (f, XSTRING (fontset_name)->data)
2378 : x_new_font (f, XSTRING (arg)->data));
2379 UNBLOCK_INPUT;
2381 if (EQ (result, Qnil))
2382 error ("Font `%s' is not defined", XSTRING (arg)->data);
2383 else if (EQ (result, Qt))
2384 error ("The characters of the given font have varying widths");
2385 else if (STRINGP (result))
2387 if (!NILP (Fequal (result, oldval)))
2388 return;
2389 store_frame_param (f, Qfont, result);
2390 recompute_basic_faces (f);
2392 else
2393 abort ();
2395 do_pending_window_change (0);
2397 /* Don't call `face-set-after-frame-default' when faces haven't been
2398 initialized yet. This is the case when called from
2399 Fx_create_frame. In that case, the X widget or window doesn't
2400 exist either, and we can end up in x_report_frame_params with a
2401 null widget which gives a segfault. */
2402 if (FRAME_FACE_CACHE (f))
2404 XSETFRAME (frame, f);
2405 call1 (Qface_set_after_frame_default, frame);
2409 void
2410 x_set_border_width (f, arg, oldval)
2411 struct frame *f;
2412 Lisp_Object arg, oldval;
2414 CHECK_NUMBER (arg, 0);
2416 if (XINT (arg) == f->output_data.w32->border_width)
2417 return;
2419 if (FRAME_W32_WINDOW (f) != 0)
2420 error ("Cannot change the border width of a window");
2422 f->output_data.w32->border_width = XINT (arg);
2425 void
2426 x_set_internal_border_width (f, arg, oldval)
2427 struct frame *f;
2428 Lisp_Object arg, oldval;
2430 int old = f->output_data.w32->internal_border_width;
2432 CHECK_NUMBER (arg, 0);
2433 f->output_data.w32->internal_border_width = XINT (arg);
2434 if (f->output_data.w32->internal_border_width < 0)
2435 f->output_data.w32->internal_border_width = 0;
2437 if (f->output_data.w32->internal_border_width == old)
2438 return;
2440 if (FRAME_W32_WINDOW (f) != 0)
2442 x_set_window_size (f, 0, f->width, f->height);
2443 SET_FRAME_GARBAGED (f);
2444 do_pending_window_change (0);
2448 void
2449 x_set_visibility (f, value, oldval)
2450 struct frame *f;
2451 Lisp_Object value, oldval;
2453 Lisp_Object frame;
2454 XSETFRAME (frame, f);
2456 if (NILP (value))
2457 Fmake_frame_invisible (frame, Qt);
2458 else if (EQ (value, Qicon))
2459 Ficonify_frame (frame);
2460 else
2461 Fmake_frame_visible (frame);
2465 /* Change window heights in windows rooted in WINDOW by N lines. */
2467 static void
2468 x_change_window_heights (window, n)
2469 Lisp_Object window;
2470 int n;
2472 struct window *w = XWINDOW (window);
2474 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2475 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2477 if (INTEGERP (w->orig_top))
2478 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2479 if (INTEGERP (w->orig_height))
2480 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2482 /* Handle just the top child in a vertical split. */
2483 if (!NILP (w->vchild))
2484 x_change_window_heights (w->vchild, n);
2486 /* Adjust all children in a horizontal split. */
2487 for (window = w->hchild; !NILP (window); window = w->next)
2489 w = XWINDOW (window);
2490 x_change_window_heights (window, n);
2494 void
2495 x_set_menu_bar_lines (f, value, oldval)
2496 struct frame *f;
2497 Lisp_Object value, oldval;
2499 int nlines;
2500 int olines = FRAME_MENU_BAR_LINES (f);
2502 /* Right now, menu bars don't work properly in minibuf-only frames;
2503 most of the commands try to apply themselves to the minibuffer
2504 frame itself, and get an error because you can't switch buffers
2505 in or split the minibuffer window. */
2506 if (FRAME_MINIBUF_ONLY_P (f))
2507 return;
2509 if (INTEGERP (value))
2510 nlines = XINT (value);
2511 else
2512 nlines = 0;
2514 FRAME_MENU_BAR_LINES (f) = 0;
2515 if (nlines)
2516 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2517 else
2519 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2520 free_frame_menubar (f);
2521 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2523 /* Adjust the frame size so that the client (text) dimensions
2524 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2525 set correctly. */
2526 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2527 do_pending_window_change (0);
2529 adjust_glyphs (f);
2533 /* Set the number of lines used for the tool bar of frame F to VALUE.
2534 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2535 is the old number of tool bar lines. This function changes the
2536 height of all windows on frame F to match the new tool bar height.
2537 The frame's height doesn't change. */
2539 void
2540 x_set_tool_bar_lines (f, value, oldval)
2541 struct frame *f;
2542 Lisp_Object value, oldval;
2544 int delta, nlines, root_height;
2545 Lisp_Object root_window;
2547 /* Treat tool bars like menu bars. */
2548 if (FRAME_MINIBUF_ONLY_P (f))
2549 return;
2551 /* Use VALUE only if an integer >= 0. */
2552 if (INTEGERP (value) && XINT (value) >= 0)
2553 nlines = XFASTINT (value);
2554 else
2555 nlines = 0;
2557 /* Make sure we redisplay all windows in this frame. */
2558 ++windows_or_buffers_changed;
2560 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2562 /* Don't resize the tool-bar to more than we have room for. */
2563 root_window = FRAME_ROOT_WINDOW (f);
2564 root_height = XINT (XWINDOW (root_window)->height);
2565 if (root_height - delta < 1)
2567 delta = root_height - 1;
2568 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2571 FRAME_TOOL_BAR_LINES (f) = nlines;
2572 x_change_window_heights (root_window, delta);
2573 adjust_glyphs (f);
2575 /* We also have to make sure that the internal border at the top of
2576 the frame, below the menu bar or tool bar, is redrawn when the
2577 tool bar disappears. This is so because the internal border is
2578 below the tool bar if one is displayed, but is below the menu bar
2579 if there isn't a tool bar. The tool bar draws into the area
2580 below the menu bar. */
2581 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2583 updating_frame = f;
2584 clear_frame ();
2585 clear_current_matrices (f);
2586 updating_frame = NULL;
2589 /* If the tool bar gets smaller, the internal border below it
2590 has to be cleared. It was formerly part of the display
2591 of the larger tool bar, and updating windows won't clear it. */
2592 if (delta < 0)
2594 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2595 int width = PIXEL_WIDTH (f);
2596 int y = nlines * CANON_Y_UNIT (f);
2598 BLOCK_INPUT;
2600 HDC hdc = get_frame_dc (f);
2601 w32_clear_area (f, hdc, 0, y, width, height);
2602 release_frame_dc (f, hdc);
2604 UNBLOCK_INPUT;
2609 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2610 w32_id_name.
2612 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2613 name; if NAME is a string, set F's name to NAME and set
2614 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2616 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2617 suggesting a new name, which lisp code should override; if
2618 F->explicit_name is set, ignore the new name; otherwise, set it. */
2620 void
2621 x_set_name (f, name, explicit)
2622 struct frame *f;
2623 Lisp_Object name;
2624 int explicit;
2626 /* Make sure that requests from lisp code override requests from
2627 Emacs redisplay code. */
2628 if (explicit)
2630 /* If we're switching from explicit to implicit, we had better
2631 update the mode lines and thereby update the title. */
2632 if (f->explicit_name && NILP (name))
2633 update_mode_lines = 1;
2635 f->explicit_name = ! NILP (name);
2637 else if (f->explicit_name)
2638 return;
2640 /* If NAME is nil, set the name to the w32_id_name. */
2641 if (NILP (name))
2643 /* Check for no change needed in this very common case
2644 before we do any consing. */
2645 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2646 XSTRING (f->name)->data))
2647 return;
2648 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2650 else
2651 CHECK_STRING (name, 0);
2653 /* Don't change the name if it's already NAME. */
2654 if (! NILP (Fstring_equal (name, f->name)))
2655 return;
2657 f->name = name;
2659 /* For setting the frame title, the title parameter should override
2660 the name parameter. */
2661 if (! NILP (f->title))
2662 name = f->title;
2664 if (FRAME_W32_WINDOW (f))
2666 if (STRING_MULTIBYTE (name))
2667 name = ENCODE_SYSTEM (name);
2669 BLOCK_INPUT;
2670 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2671 UNBLOCK_INPUT;
2675 /* This function should be called when the user's lisp code has
2676 specified a name for the frame; the name will override any set by the
2677 redisplay code. */
2678 void
2679 x_explicitly_set_name (f, arg, oldval)
2680 FRAME_PTR f;
2681 Lisp_Object arg, oldval;
2683 x_set_name (f, arg, 1);
2686 /* This function should be called by Emacs redisplay code to set the
2687 name; names set this way will never override names set by the user's
2688 lisp code. */
2689 void
2690 x_implicitly_set_name (f, arg, oldval)
2691 FRAME_PTR f;
2692 Lisp_Object arg, oldval;
2694 x_set_name (f, arg, 0);
2697 /* Change the title of frame F to NAME.
2698 If NAME is nil, use the frame name as the title.
2700 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2701 name; if NAME is a string, set F's name to NAME and set
2702 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2704 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2705 suggesting a new name, which lisp code should override; if
2706 F->explicit_name is set, ignore the new name; otherwise, set it. */
2708 void
2709 x_set_title (f, name, old_name)
2710 struct frame *f;
2711 Lisp_Object name, old_name;
2713 /* Don't change the title if it's already NAME. */
2714 if (EQ (name, f->title))
2715 return;
2717 update_mode_lines = 1;
2719 f->title = name;
2721 if (NILP (name))
2722 name = f->name;
2724 if (FRAME_W32_WINDOW (f))
2726 if (STRING_MULTIBYTE (name))
2727 name = ENCODE_SYSTEM (name);
2729 BLOCK_INPUT;
2730 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2731 UNBLOCK_INPUT;
2735 void
2736 x_set_autoraise (f, arg, oldval)
2737 struct frame *f;
2738 Lisp_Object arg, oldval;
2740 f->auto_raise = !EQ (Qnil, arg);
2743 void
2744 x_set_autolower (f, arg, oldval)
2745 struct frame *f;
2746 Lisp_Object arg, oldval;
2748 f->auto_lower = !EQ (Qnil, arg);
2751 void
2752 x_set_unsplittable (f, arg, oldval)
2753 struct frame *f;
2754 Lisp_Object arg, oldval;
2756 f->no_split = !NILP (arg);
2759 void
2760 x_set_vertical_scroll_bars (f, arg, oldval)
2761 struct frame *f;
2762 Lisp_Object arg, oldval;
2764 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2765 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2766 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2767 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2769 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2770 vertical_scroll_bar_none :
2771 /* Put scroll bars on the right by default, as is conventional
2772 on MS-Windows. */
2773 EQ (Qleft, arg)
2774 ? vertical_scroll_bar_left
2775 : vertical_scroll_bar_right;
2777 /* We set this parameter before creating the window for the
2778 frame, so we can get the geometry right from the start.
2779 However, if the window hasn't been created yet, we shouldn't
2780 call x_set_window_size. */
2781 if (FRAME_W32_WINDOW (f))
2782 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2783 do_pending_window_change (0);
2787 void
2788 x_set_scroll_bar_width (f, arg, oldval)
2789 struct frame *f;
2790 Lisp_Object arg, oldval;
2792 int wid = FONT_WIDTH (f->output_data.w32->font);
2794 if (NILP (arg))
2796 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2797 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2798 wid - 1) / wid;
2799 if (FRAME_W32_WINDOW (f))
2800 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2801 do_pending_window_change (0);
2803 else if (INTEGERP (arg) && XINT (arg) > 0
2804 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2806 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2807 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2808 + wid-1) / wid;
2809 if (FRAME_W32_WINDOW (f))
2810 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2811 do_pending_window_change (0);
2813 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2814 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2815 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2818 /* Subroutines of creating an frame. */
2820 /* Make sure that Vx_resource_name is set to a reasonable value.
2821 Fix it up, or set it to `emacs' if it is too hopeless. */
2823 static void
2824 validate_x_resource_name ()
2826 int len = 0;
2827 /* Number of valid characters in the resource name. */
2828 int good_count = 0;
2829 /* Number of invalid characters in the resource name. */
2830 int bad_count = 0;
2831 Lisp_Object new;
2832 int i;
2834 if (STRINGP (Vx_resource_name))
2836 unsigned char *p = XSTRING (Vx_resource_name)->data;
2837 int i;
2839 len = STRING_BYTES (XSTRING (Vx_resource_name));
2841 /* Only letters, digits, - and _ are valid in resource names.
2842 Count the valid characters and count the invalid ones. */
2843 for (i = 0; i < len; i++)
2845 int c = p[i];
2846 if (! ((c >= 'a' && c <= 'z')
2847 || (c >= 'A' && c <= 'Z')
2848 || (c >= '0' && c <= '9')
2849 || c == '-' || c == '_'))
2850 bad_count++;
2851 else
2852 good_count++;
2855 else
2856 /* Not a string => completely invalid. */
2857 bad_count = 5, good_count = 0;
2859 /* If name is valid already, return. */
2860 if (bad_count == 0)
2861 return;
2863 /* If name is entirely invalid, or nearly so, use `emacs'. */
2864 if (good_count == 0
2865 || (good_count == 1 && bad_count > 0))
2867 Vx_resource_name = build_string ("emacs");
2868 return;
2871 /* Name is partly valid. Copy it and replace the invalid characters
2872 with underscores. */
2874 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2876 for (i = 0; i < len; i++)
2878 int c = XSTRING (new)->data[i];
2879 if (! ((c >= 'a' && c <= 'z')
2880 || (c >= 'A' && c <= 'Z')
2881 || (c >= '0' && c <= '9')
2882 || c == '-' || c == '_'))
2883 XSTRING (new)->data[i] = '_';
2888 extern char *x_get_string_resource ();
2890 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2891 "Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.\n\
2892 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the\n\
2893 class, where INSTANCE is the name under which Emacs was invoked, or\n\
2894 the name specified by the `-name' or `-rn' command-line arguments.\n\
2896 The optional arguments COMPONENT and SUBCLASS add to the key and the\n\
2897 class, respectively. You must specify both of them or neither.\n\
2898 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'\n\
2899 and the class is `Emacs.CLASS.SUBCLASS'.")
2900 (attribute, class, component, subclass)
2901 Lisp_Object attribute, class, component, subclass;
2903 register char *value;
2904 char *name_key;
2905 char *class_key;
2907 CHECK_STRING (attribute, 0);
2908 CHECK_STRING (class, 0);
2910 if (!NILP (component))
2911 CHECK_STRING (component, 1);
2912 if (!NILP (subclass))
2913 CHECK_STRING (subclass, 2);
2914 if (NILP (component) != NILP (subclass))
2915 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
2917 validate_x_resource_name ();
2919 /* Allocate space for the components, the dots which separate them,
2920 and the final '\0'. Make them big enough for the worst case. */
2921 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vx_resource_name))
2922 + (STRINGP (component)
2923 ? STRING_BYTES (XSTRING (component)) : 0)
2924 + STRING_BYTES (XSTRING (attribute))
2925 + 3);
2927 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2928 + STRING_BYTES (XSTRING (class))
2929 + (STRINGP (subclass)
2930 ? STRING_BYTES (XSTRING (subclass)) : 0)
2931 + 3);
2933 /* Start with emacs.FRAMENAME for the name (the specific one)
2934 and with `Emacs' for the class key (the general one). */
2935 strcpy (name_key, XSTRING (Vx_resource_name)->data);
2936 strcpy (class_key, EMACS_CLASS);
2938 strcat (class_key, ".");
2939 strcat (class_key, XSTRING (class)->data);
2941 if (!NILP (component))
2943 strcat (class_key, ".");
2944 strcat (class_key, XSTRING (subclass)->data);
2946 strcat (name_key, ".");
2947 strcat (name_key, XSTRING (component)->data);
2950 strcat (name_key, ".");
2951 strcat (name_key, XSTRING (attribute)->data);
2953 value = x_get_string_resource (Qnil,
2954 name_key, class_key);
2956 if (value != (char *) 0)
2957 return build_string (value);
2958 else
2959 return Qnil;
2962 /* Used when C code wants a resource value. */
2964 char *
2965 x_get_resource_string (attribute, class)
2966 char *attribute, *class;
2968 char *name_key;
2969 char *class_key;
2970 struct frame *sf = SELECTED_FRAME ();
2972 /* Allocate space for the components, the dots which separate them,
2973 and the final '\0'. */
2974 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vinvocation_name))
2975 + strlen (attribute) + 2);
2976 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2977 + strlen (class) + 2);
2979 sprintf (name_key, "%s.%s",
2980 XSTRING (Vinvocation_name)->data,
2981 attribute);
2982 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
2984 return x_get_string_resource (sf, name_key, class_key);
2987 /* Types we might convert a resource string into. */
2988 enum resource_types
2990 RES_TYPE_NUMBER,
2991 RES_TYPE_FLOAT,
2992 RES_TYPE_BOOLEAN,
2993 RES_TYPE_STRING,
2994 RES_TYPE_SYMBOL
2997 /* Return the value of parameter PARAM.
2999 First search ALIST, then Vdefault_frame_alist, then the X defaults
3000 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3002 Convert the resource to the type specified by desired_type.
3004 If no default is specified, return Qunbound. If you call
3005 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3006 and don't let it get stored in any Lisp-visible variables! */
3008 static Lisp_Object
3009 w32_get_arg (alist, param, attribute, class, type)
3010 Lisp_Object alist, param;
3011 char *attribute;
3012 char *class;
3013 enum resource_types type;
3015 register Lisp_Object tem;
3017 tem = Fassq (param, alist);
3018 if (EQ (tem, Qnil))
3019 tem = Fassq (param, Vdefault_frame_alist);
3020 if (EQ (tem, Qnil))
3023 if (attribute)
3025 tem = Fx_get_resource (build_string (attribute),
3026 build_string (class),
3027 Qnil, Qnil);
3029 if (NILP (tem))
3030 return Qunbound;
3032 switch (type)
3034 case RES_TYPE_NUMBER:
3035 return make_number (atoi (XSTRING (tem)->data));
3037 case RES_TYPE_FLOAT:
3038 return make_float (atof (XSTRING (tem)->data));
3040 case RES_TYPE_BOOLEAN:
3041 tem = Fdowncase (tem);
3042 if (!strcmp (XSTRING (tem)->data, "on")
3043 || !strcmp (XSTRING (tem)->data, "true"))
3044 return Qt;
3045 else
3046 return Qnil;
3048 case RES_TYPE_STRING:
3049 return tem;
3051 case RES_TYPE_SYMBOL:
3052 /* As a special case, we map the values `true' and `on'
3053 to Qt, and `false' and `off' to Qnil. */
3055 Lisp_Object lower;
3056 lower = Fdowncase (tem);
3057 if (!strcmp (XSTRING (lower)->data, "on")
3058 || !strcmp (XSTRING (lower)->data, "true"))
3059 return Qt;
3060 else if (!strcmp (XSTRING (lower)->data, "off")
3061 || !strcmp (XSTRING (lower)->data, "false"))
3062 return Qnil;
3063 else
3064 return Fintern (tem, Qnil);
3067 default:
3068 abort ();
3071 else
3072 return Qunbound;
3074 return Fcdr (tem);
3077 /* Record in frame F the specified or default value according to ALIST
3078 of the parameter named PROP (a Lisp symbol).
3079 If no value is specified for PROP, look for an X default for XPROP
3080 on the frame named NAME.
3081 If that is not found either, use the value DEFLT. */
3083 static Lisp_Object
3084 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3085 struct frame *f;
3086 Lisp_Object alist;
3087 Lisp_Object prop;
3088 Lisp_Object deflt;
3089 char *xprop;
3090 char *xclass;
3091 enum resource_types type;
3093 Lisp_Object tem;
3095 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3096 if (EQ (tem, Qunbound))
3097 tem = deflt;
3098 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3099 return tem;
3102 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3103 "Parse an X-style geometry string STRING.\n\
3104 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).\n\
3105 The properties returned may include `top', `left', `height', and `width'.\n\
3106 The value of `left' or `top' may be an integer,\n\
3107 or a list (+ N) meaning N pixels relative to top/left corner,\n\
3108 or a list (- N) meaning -N pixels relative to bottom/right corner.")
3109 (string)
3110 Lisp_Object string;
3112 int geometry, x, y;
3113 unsigned int width, height;
3114 Lisp_Object result;
3116 CHECK_STRING (string, 0);
3118 geometry = XParseGeometry ((char *) XSTRING (string)->data,
3119 &x, &y, &width, &height);
3121 result = Qnil;
3122 if (geometry & XValue)
3124 Lisp_Object element;
3126 if (x >= 0 && (geometry & XNegative))
3127 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3128 else if (x < 0 && ! (geometry & XNegative))
3129 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3130 else
3131 element = Fcons (Qleft, make_number (x));
3132 result = Fcons (element, result);
3135 if (geometry & YValue)
3137 Lisp_Object element;
3139 if (y >= 0 && (geometry & YNegative))
3140 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3141 else if (y < 0 && ! (geometry & YNegative))
3142 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3143 else
3144 element = Fcons (Qtop, make_number (y));
3145 result = Fcons (element, result);
3148 if (geometry & WidthValue)
3149 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3150 if (geometry & HeightValue)
3151 result = Fcons (Fcons (Qheight, make_number (height)), result);
3153 return result;
3156 /* Calculate the desired size and position of this window,
3157 and return the flags saying which aspects were specified.
3159 This function does not make the coordinates positive. */
3161 #define DEFAULT_ROWS 40
3162 #define DEFAULT_COLS 80
3164 static int
3165 x_figure_window_size (f, parms)
3166 struct frame *f;
3167 Lisp_Object parms;
3169 register Lisp_Object tem0, tem1, tem2;
3170 long window_prompting = 0;
3172 /* Default values if we fall through.
3173 Actually, if that happens we should get
3174 window manager prompting. */
3175 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3176 f->height = DEFAULT_ROWS;
3177 /* Window managers expect that if program-specified
3178 positions are not (0,0), they're intentional, not defaults. */
3179 f->output_data.w32->top_pos = 0;
3180 f->output_data.w32->left_pos = 0;
3182 /* Ensure that old new_width and new_height will not override the
3183 values set here. */
3184 FRAME_NEW_WIDTH (f) = 0;
3185 FRAME_NEW_HEIGHT (f) = 0;
3187 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3188 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3189 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3190 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3192 if (!EQ (tem0, Qunbound))
3194 CHECK_NUMBER (tem0, 0);
3195 f->height = XINT (tem0);
3197 if (!EQ (tem1, Qunbound))
3199 CHECK_NUMBER (tem1, 0);
3200 SET_FRAME_WIDTH (f, XINT (tem1));
3202 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3203 window_prompting |= USSize;
3204 else
3205 window_prompting |= PSize;
3208 f->output_data.w32->vertical_scroll_bar_extra
3209 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3211 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3212 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3213 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3214 f->output_data.w32->flags_areas_extra
3215 = FRAME_FLAGS_AREA_WIDTH (f);
3216 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3217 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3219 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3220 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3221 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3222 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3224 if (EQ (tem0, Qminus))
3226 f->output_data.w32->top_pos = 0;
3227 window_prompting |= YNegative;
3229 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3230 && CONSP (XCDR (tem0))
3231 && INTEGERP (XCAR (XCDR (tem0))))
3233 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3234 window_prompting |= YNegative;
3236 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3237 && CONSP (XCDR (tem0))
3238 && INTEGERP (XCAR (XCDR (tem0))))
3240 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3242 else if (EQ (tem0, Qunbound))
3243 f->output_data.w32->top_pos = 0;
3244 else
3246 CHECK_NUMBER (tem0, 0);
3247 f->output_data.w32->top_pos = XINT (tem0);
3248 if (f->output_data.w32->top_pos < 0)
3249 window_prompting |= YNegative;
3252 if (EQ (tem1, Qminus))
3254 f->output_data.w32->left_pos = 0;
3255 window_prompting |= XNegative;
3257 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3258 && CONSP (XCDR (tem1))
3259 && INTEGERP (XCAR (XCDR (tem1))))
3261 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3262 window_prompting |= XNegative;
3264 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3265 && CONSP (XCDR (tem1))
3266 && INTEGERP (XCAR (XCDR (tem1))))
3268 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3270 else if (EQ (tem1, Qunbound))
3271 f->output_data.w32->left_pos = 0;
3272 else
3274 CHECK_NUMBER (tem1, 0);
3275 f->output_data.w32->left_pos = XINT (tem1);
3276 if (f->output_data.w32->left_pos < 0)
3277 window_prompting |= XNegative;
3280 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3281 window_prompting |= USPosition;
3282 else
3283 window_prompting |= PPosition;
3286 return window_prompting;
3291 extern LRESULT CALLBACK w32_wnd_proc ();
3293 BOOL
3294 w32_init_class (hinst)
3295 HINSTANCE hinst;
3297 WNDCLASS wc;
3299 wc.style = CS_HREDRAW | CS_VREDRAW;
3300 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3301 wc.cbClsExtra = 0;
3302 wc.cbWndExtra = WND_EXTRA_BYTES;
3303 wc.hInstance = hinst;
3304 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3305 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3306 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3307 wc.lpszMenuName = NULL;
3308 wc.lpszClassName = EMACS_CLASS;
3310 return (RegisterClass (&wc));
3313 HWND
3314 w32_createscrollbar (f, bar)
3315 struct frame *f;
3316 struct scroll_bar * bar;
3318 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3319 /* Position and size of scroll bar. */
3320 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3321 XINT(bar->top),
3322 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3323 XINT(bar->height),
3324 FRAME_W32_WINDOW (f),
3325 NULL,
3326 hinst,
3327 NULL));
3330 void
3331 w32_createwindow (f)
3332 struct frame *f;
3334 HWND hwnd;
3335 RECT rect;
3337 rect.left = rect.top = 0;
3338 rect.right = PIXEL_WIDTH (f);
3339 rect.bottom = PIXEL_HEIGHT (f);
3341 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3342 FRAME_EXTERNAL_MENU_BAR (f));
3344 /* Do first time app init */
3346 if (!hprevinst)
3348 w32_init_class (hinst);
3351 FRAME_W32_WINDOW (f) = hwnd
3352 = CreateWindow (EMACS_CLASS,
3353 f->namebuf,
3354 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3355 f->output_data.w32->left_pos,
3356 f->output_data.w32->top_pos,
3357 rect.right - rect.left,
3358 rect.bottom - rect.top,
3359 NULL,
3360 NULL,
3361 hinst,
3362 NULL);
3364 if (hwnd)
3366 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3367 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3368 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3369 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3370 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3372 /* Enable drag-n-drop. */
3373 DragAcceptFiles (hwnd, TRUE);
3375 /* Do this to discard the default setting specified by our parent. */
3376 ShowWindow (hwnd, SW_HIDE);
3380 void
3381 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3382 W32Msg * wmsg;
3383 HWND hwnd;
3384 UINT msg;
3385 WPARAM wParam;
3386 LPARAM lParam;
3388 wmsg->msg.hwnd = hwnd;
3389 wmsg->msg.message = msg;
3390 wmsg->msg.wParam = wParam;
3391 wmsg->msg.lParam = lParam;
3392 wmsg->msg.time = GetMessageTime ();
3394 post_msg (wmsg);
3397 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3398 between left and right keys as advertised. We test for this
3399 support dynamically, and set a flag when the support is absent. If
3400 absent, we keep track of the left and right control and alt keys
3401 ourselves. This is particularly necessary on keyboards that rely
3402 upon the AltGr key, which is represented as having the left control
3403 and right alt keys pressed. For these keyboards, we need to know
3404 when the left alt key has been pressed in addition to the AltGr key
3405 so that we can properly support M-AltGr-key sequences (such as M-@
3406 on Swedish keyboards). */
3408 #define EMACS_LCONTROL 0
3409 #define EMACS_RCONTROL 1
3410 #define EMACS_LMENU 2
3411 #define EMACS_RMENU 3
3413 static int modifiers[4];
3414 static int modifiers_recorded;
3415 static int modifier_key_support_tested;
3417 static void
3418 test_modifier_support (unsigned int wparam)
3420 unsigned int l, r;
3422 if (wparam != VK_CONTROL && wparam != VK_MENU)
3423 return;
3424 if (wparam == VK_CONTROL)
3426 l = VK_LCONTROL;
3427 r = VK_RCONTROL;
3429 else
3431 l = VK_LMENU;
3432 r = VK_RMENU;
3434 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3435 modifiers_recorded = 1;
3436 else
3437 modifiers_recorded = 0;
3438 modifier_key_support_tested = 1;
3441 static void
3442 record_keydown (unsigned int wparam, unsigned int lparam)
3444 int i;
3446 if (!modifier_key_support_tested)
3447 test_modifier_support (wparam);
3449 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3450 return;
3452 if (wparam == VK_CONTROL)
3453 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3454 else
3455 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3457 modifiers[i] = 1;
3460 static void
3461 record_keyup (unsigned int wparam, unsigned int lparam)
3463 int i;
3465 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3466 return;
3468 if (wparam == VK_CONTROL)
3469 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3470 else
3471 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3473 modifiers[i] = 0;
3476 /* Emacs can lose focus while a modifier key has been pressed. When
3477 it regains focus, be conservative and clear all modifiers since
3478 we cannot reconstruct the left and right modifier state. */
3479 static void
3480 reset_modifiers ()
3482 SHORT ctrl, alt;
3484 if (GetFocus () == NULL)
3485 /* Emacs doesn't have keyboard focus. Do nothing. */
3486 return;
3488 ctrl = GetAsyncKeyState (VK_CONTROL);
3489 alt = GetAsyncKeyState (VK_MENU);
3491 if (!(ctrl & 0x08000))
3492 /* Clear any recorded control modifier state. */
3493 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3495 if (!(alt & 0x08000))
3496 /* Clear any recorded alt modifier state. */
3497 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3499 /* Update the state of all modifier keys, because modifiers used in
3500 hot-key combinations can get stuck on if Emacs loses focus as a
3501 result of a hot-key being pressed. */
3503 BYTE keystate[256];
3505 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3507 GetKeyboardState (keystate);
3508 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3509 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3510 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3511 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3512 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3513 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3514 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3515 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3516 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3517 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3518 SetKeyboardState (keystate);
3522 /* Synchronize modifier state with what is reported with the current
3523 keystroke. Even if we cannot distinguish between left and right
3524 modifier keys, we know that, if no modifiers are set, then neither
3525 the left or right modifier should be set. */
3526 static void
3527 sync_modifiers ()
3529 if (!modifiers_recorded)
3530 return;
3532 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3533 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3535 if (!(GetKeyState (VK_MENU) & 0x8000))
3536 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3539 static int
3540 modifier_set (int vkey)
3542 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3543 return (GetKeyState (vkey) & 0x1);
3544 if (!modifiers_recorded)
3545 return (GetKeyState (vkey) & 0x8000);
3547 switch (vkey)
3549 case VK_LCONTROL:
3550 return modifiers[EMACS_LCONTROL];
3551 case VK_RCONTROL:
3552 return modifiers[EMACS_RCONTROL];
3553 case VK_LMENU:
3554 return modifiers[EMACS_LMENU];
3555 case VK_RMENU:
3556 return modifiers[EMACS_RMENU];
3558 return (GetKeyState (vkey) & 0x8000);
3561 /* Convert between the modifier bits W32 uses and the modifier bits
3562 Emacs uses. */
3564 unsigned int
3565 w32_key_to_modifier (int key)
3567 Lisp_Object key_mapping;
3569 switch (key)
3571 case VK_LWIN:
3572 key_mapping = Vw32_lwindow_modifier;
3573 break;
3574 case VK_RWIN:
3575 key_mapping = Vw32_rwindow_modifier;
3576 break;
3577 case VK_APPS:
3578 key_mapping = Vw32_apps_modifier;
3579 break;
3580 case VK_SCROLL:
3581 key_mapping = Vw32_scroll_lock_modifier;
3582 break;
3583 default:
3584 key_mapping = Qnil;
3587 /* NB. This code runs in the input thread, asychronously to the lisp
3588 thread, so we must be careful to ensure access to lisp data is
3589 thread-safe. The following code is safe because the modifier
3590 variable values are updated atomically from lisp and symbols are
3591 not relocated by GC. Also, we don't have to worry about seeing GC
3592 markbits here. */
3593 if (EQ (key_mapping, Qhyper))
3594 return hyper_modifier;
3595 if (EQ (key_mapping, Qsuper))
3596 return super_modifier;
3597 if (EQ (key_mapping, Qmeta))
3598 return meta_modifier;
3599 if (EQ (key_mapping, Qalt))
3600 return alt_modifier;
3601 if (EQ (key_mapping, Qctrl))
3602 return ctrl_modifier;
3603 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3604 return ctrl_modifier;
3605 if (EQ (key_mapping, Qshift))
3606 return shift_modifier;
3608 /* Don't generate any modifier if not explicitly requested. */
3609 return 0;
3612 unsigned int
3613 w32_get_modifiers ()
3615 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3616 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3617 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3618 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3619 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3620 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3621 (modifier_set (VK_MENU) ?
3622 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3625 /* We map the VK_* modifiers into console modifier constants
3626 so that we can use the same routines to handle both console
3627 and window input. */
3629 static int
3630 construct_console_modifiers ()
3632 int mods;
3634 mods = 0;
3635 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3636 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3637 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3638 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3639 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3640 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3641 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3642 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3643 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3644 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3645 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3647 return mods;
3650 static int
3651 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3653 int mods;
3655 /* Convert to emacs modifiers. */
3656 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3658 return mods;
3661 unsigned int
3662 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3664 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3665 return virt_key;
3667 if (virt_key == VK_RETURN)
3668 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3670 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3671 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3673 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3674 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3676 if (virt_key == VK_CLEAR)
3677 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3679 return virt_key;
3682 /* List of special key combinations which w32 would normally capture,
3683 but emacs should grab instead. Not directly visible to lisp, to
3684 simplify synchronization. Each item is an integer encoding a virtual
3685 key code and modifier combination to capture. */
3686 Lisp_Object w32_grabbed_keys;
3688 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3689 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3690 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3691 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3693 /* Register hot-keys for reserved key combinations when Emacs has
3694 keyboard focus, since this is the only way Emacs can receive key
3695 combinations like Alt-Tab which are used by the system. */
3697 static void
3698 register_hot_keys (hwnd)
3699 HWND hwnd;
3701 Lisp_Object keylist;
3703 /* Use GC_CONSP, since we are called asynchronously. */
3704 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3706 Lisp_Object key = XCAR (keylist);
3708 /* Deleted entries get set to nil. */
3709 if (!INTEGERP (key))
3710 continue;
3712 RegisterHotKey (hwnd, HOTKEY_ID (key),
3713 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3717 static void
3718 unregister_hot_keys (hwnd)
3719 HWND hwnd;
3721 Lisp_Object keylist;
3723 /* Use GC_CONSP, since we are called asynchronously. */
3724 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3726 Lisp_Object key = XCAR (keylist);
3728 if (!INTEGERP (key))
3729 continue;
3731 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3735 /* Main message dispatch loop. */
3737 static void
3738 w32_msg_pump (deferred_msg * msg_buf)
3740 MSG msg;
3741 int result;
3742 HWND focus_window;
3744 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3746 while (GetMessage (&msg, NULL, 0, 0))
3748 if (msg.hwnd == NULL)
3750 switch (msg.message)
3752 case WM_NULL:
3753 /* Produced by complete_deferred_msg; just ignore. */
3754 break;
3755 case WM_EMACS_CREATEWINDOW:
3756 w32_createwindow ((struct frame *) msg.wParam);
3757 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3758 abort ();
3759 break;
3760 case WM_EMACS_SETLOCALE:
3761 SetThreadLocale (msg.wParam);
3762 /* Reply is not expected. */
3763 break;
3764 case WM_EMACS_SETKEYBOARDLAYOUT:
3765 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3766 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3767 result, 0))
3768 abort ();
3769 break;
3770 case WM_EMACS_REGISTER_HOT_KEY:
3771 focus_window = GetFocus ();
3772 if (focus_window != NULL)
3773 RegisterHotKey (focus_window,
3774 HOTKEY_ID (msg.wParam),
3775 HOTKEY_MODIFIERS (msg.wParam),
3776 HOTKEY_VK_CODE (msg.wParam));
3777 /* Reply is not expected. */
3778 break;
3779 case WM_EMACS_UNREGISTER_HOT_KEY:
3780 focus_window = GetFocus ();
3781 if (focus_window != NULL)
3782 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3783 /* Mark item as erased. NB: this code must be
3784 thread-safe. The next line is okay because the cons
3785 cell is never made into garbage and is not relocated by
3786 GC. */
3787 XCAR ((Lisp_Object) msg.lParam) = Qnil;
3788 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3789 abort ();
3790 break;
3791 case WM_EMACS_TOGGLE_LOCK_KEY:
3793 int vk_code = (int) msg.wParam;
3794 int cur_state = (GetKeyState (vk_code) & 1);
3795 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3797 /* NB: This code must be thread-safe. It is safe to
3798 call NILP because symbols are not relocated by GC,
3799 and pointer here is not touched by GC (so the markbit
3800 can't be set). Numbers are safe because they are
3801 immediate values. */
3802 if (NILP (new_state)
3803 || (NUMBERP (new_state)
3804 && ((XUINT (new_state)) & 1) != cur_state))
3806 one_w32_display_info.faked_key = vk_code;
3808 keybd_event ((BYTE) vk_code,
3809 (BYTE) MapVirtualKey (vk_code, 0),
3810 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3811 keybd_event ((BYTE) vk_code,
3812 (BYTE) MapVirtualKey (vk_code, 0),
3813 KEYEVENTF_EXTENDEDKEY | 0, 0);
3814 keybd_event ((BYTE) vk_code,
3815 (BYTE) MapVirtualKey (vk_code, 0),
3816 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3817 cur_state = !cur_state;
3819 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3820 cur_state, 0))
3821 abort ();
3823 break;
3824 default:
3825 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3828 else
3830 DispatchMessage (&msg);
3833 /* Exit nested loop when our deferred message has completed. */
3834 if (msg_buf->completed)
3835 break;
3839 deferred_msg * deferred_msg_head;
3841 static deferred_msg *
3842 find_deferred_msg (HWND hwnd, UINT msg)
3844 deferred_msg * item;
3846 /* Don't actually need synchronization for read access, since
3847 modification of single pointer is always atomic. */
3848 /* enter_crit (); */
3850 for (item = deferred_msg_head; item != NULL; item = item->next)
3851 if (item->w32msg.msg.hwnd == hwnd
3852 && item->w32msg.msg.message == msg)
3853 break;
3855 /* leave_crit (); */
3857 return item;
3860 static LRESULT
3861 send_deferred_msg (deferred_msg * msg_buf,
3862 HWND hwnd,
3863 UINT msg,
3864 WPARAM wParam,
3865 LPARAM lParam)
3867 /* Only input thread can send deferred messages. */
3868 if (GetCurrentThreadId () != dwWindowsThreadId)
3869 abort ();
3871 /* It is an error to send a message that is already deferred. */
3872 if (find_deferred_msg (hwnd, msg) != NULL)
3873 abort ();
3875 /* Enforced synchronization is not needed because this is the only
3876 function that alters deferred_msg_head, and the following critical
3877 section is guaranteed to only be serially reentered (since only the
3878 input thread can call us). */
3880 /* enter_crit (); */
3882 msg_buf->completed = 0;
3883 msg_buf->next = deferred_msg_head;
3884 deferred_msg_head = msg_buf;
3885 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3887 /* leave_crit (); */
3889 /* Start a new nested message loop to process other messages until
3890 this one is completed. */
3891 w32_msg_pump (msg_buf);
3893 deferred_msg_head = msg_buf->next;
3895 return msg_buf->result;
3898 void
3899 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3901 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3903 if (msg_buf == NULL)
3904 /* Message may have been cancelled, so don't abort(). */
3905 return;
3907 msg_buf->result = result;
3908 msg_buf->completed = 1;
3910 /* Ensure input thread is woken so it notices the completion. */
3911 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3914 void
3915 cancel_all_deferred_msgs ()
3917 deferred_msg * item;
3919 /* Don't actually need synchronization for read access, since
3920 modification of single pointer is always atomic. */
3921 /* enter_crit (); */
3923 for (item = deferred_msg_head; item != NULL; item = item->next)
3925 item->result = 0;
3926 item->completed = 1;
3929 /* leave_crit (); */
3931 /* Ensure input thread is woken so it notices the completion. */
3932 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3935 DWORD
3936 w32_msg_worker (dw)
3937 DWORD dw;
3939 MSG msg;
3940 deferred_msg dummy_buf;
3942 /* Ensure our message queue is created */
3944 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3946 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3947 abort ();
3949 memset (&dummy_buf, 0, sizeof (dummy_buf));
3950 dummy_buf.w32msg.msg.hwnd = NULL;
3951 dummy_buf.w32msg.msg.message = WM_NULL;
3953 /* This is the inital message loop which should only exit when the
3954 application quits. */
3955 w32_msg_pump (&dummy_buf);
3957 return 0;
3960 static void
3961 post_character_message (hwnd, msg, wParam, lParam, modifiers)
3962 HWND hwnd;
3963 UINT msg;
3964 WPARAM wParam;
3965 LPARAM lParam;
3966 DWORD modifiers;
3969 W32Msg wmsg;
3971 wmsg.dwModifiers = modifiers;
3973 /* Detect quit_char and set quit-flag directly. Note that we
3974 still need to post a message to ensure the main thread will be
3975 woken up if blocked in sys_select(), but we do NOT want to post
3976 the quit_char message itself (because it will usually be as if
3977 the user had typed quit_char twice). Instead, we post a dummy
3978 message that has no particular effect. */
3980 int c = wParam;
3981 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
3982 c = make_ctrl_char (c) & 0377;
3983 if (c == quit_char
3984 || (wmsg.dwModifiers == 0 &&
3985 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
3987 Vquit_flag = Qt;
3989 /* The choice of message is somewhat arbitrary, as long as
3990 the main thread handler just ignores it. */
3991 msg = WM_NULL;
3993 /* Interrupt any blocking system calls. */
3994 signal_quit ();
3996 /* As a safety precaution, forcibly complete any deferred
3997 messages. This is a kludge, but I don't see any particularly
3998 clean way to handle the situation where a deferred message is
3999 "dropped" in the lisp thread, and will thus never be
4000 completed, eg. by the user trying to activate the menubar
4001 when the lisp thread is busy, and then typing C-g when the
4002 menubar doesn't open promptly (with the result that the
4003 menubar never responds at all because the deferred
4004 WM_INITMENU message is never completed). Another problem
4005 situation is when the lisp thread calls SendMessage (to send
4006 a window manager command) when a message has been deferred;
4007 the lisp thread gets blocked indefinitely waiting for the
4008 deferred message to be completed, which itself is waiting for
4009 the lisp thread to respond.
4011 Note that we don't want to block the input thread waiting for
4012 a reponse from the lisp thread (although that would at least
4013 solve the deadlock problem above), because we want to be able
4014 to receive C-g to interrupt the lisp thread. */
4015 cancel_all_deferred_msgs ();
4019 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4022 /* Main window procedure */
4024 LRESULT CALLBACK
4025 w32_wnd_proc (hwnd, msg, wParam, lParam)
4026 HWND hwnd;
4027 UINT msg;
4028 WPARAM wParam;
4029 LPARAM lParam;
4031 struct frame *f;
4032 struct w32_display_info *dpyinfo = &one_w32_display_info;
4033 W32Msg wmsg;
4034 int windows_translate;
4035 int key;
4037 /* Note that it is okay to call x_window_to_frame, even though we are
4038 not running in the main lisp thread, because frame deletion
4039 requires the lisp thread to synchronize with this thread. Thus, if
4040 a frame struct is returned, it can be used without concern that the
4041 lisp thread might make it disappear while we are using it.
4043 NB. Walking the frame list in this thread is safe (as long as
4044 writes of Lisp_Object slots are atomic, which they are on Windows).
4045 Although delete-frame can destructively modify the frame list while
4046 we are walking it, a garbage collection cannot occur until after
4047 delete-frame has synchronized with this thread.
4049 It is also safe to use functions that make GDI calls, such as
4050 w32_clear_rect, because these functions must obtain a DC handle
4051 from the frame struct using get_frame_dc which is thread-aware. */
4053 switch (msg)
4055 case WM_ERASEBKGND:
4056 f = x_window_to_frame (dpyinfo, hwnd);
4057 if (f)
4059 HDC hdc = get_frame_dc (f);
4060 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4061 w32_clear_rect (f, hdc, &wmsg.rect);
4062 release_frame_dc (f, hdc);
4064 #if defined (W32_DEBUG_DISPLAY)
4065 DebPrint (("WM_ERASEBKGND: erasing %d,%d-%d,%d\n",
4066 wmsg.rect.left, wmsg.rect.top, wmsg.rect.right,
4067 wmsg.rect.bottom));
4068 #endif /* W32_DEBUG_DISPLAY */
4070 return 1;
4071 case WM_PALETTECHANGED:
4072 /* ignore our own changes */
4073 if ((HWND)wParam != hwnd)
4075 f = x_window_to_frame (dpyinfo, hwnd);
4076 if (f)
4077 /* get_frame_dc will realize our palette and force all
4078 frames to be redrawn if needed. */
4079 release_frame_dc (f, get_frame_dc (f));
4081 return 0;
4082 case WM_PAINT:
4084 PAINTSTRUCT paintStruct;
4085 RECT update_rect;
4087 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4088 fails. Apparently this can happen under some
4089 circumstances. */
4090 if (!w32_strict_painting || GetUpdateRect (hwnd, &update_rect, FALSE))
4092 enter_crit ();
4093 BeginPaint (hwnd, &paintStruct);
4095 if (w32_strict_painting)
4096 /* The rectangles returned by GetUpdateRect and BeginPaint
4097 do not always match. GetUpdateRect seems to be the
4098 more reliable of the two. */
4099 wmsg.rect = update_rect;
4100 else
4101 wmsg.rect = paintStruct.rcPaint;
4103 #if defined (W32_DEBUG_DISPLAY)
4104 DebPrint (("WM_PAINT: painting %d,%d-%d,%d\n", wmsg.rect.left,
4105 wmsg.rect.top, wmsg.rect.right, wmsg.rect.bottom));
4106 DebPrint (("WM_PAINT: update region is %d,%d-%d,%d\n",
4107 update_rect.left, update_rect.top,
4108 update_rect.right, update_rect.bottom));
4109 #endif
4110 EndPaint (hwnd, &paintStruct);
4111 leave_crit ();
4113 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4115 return 0;
4118 /* If GetUpdateRect returns 0 (meaning there is no update
4119 region), assume the whole window needs to be repainted. */
4120 GetClientRect(hwnd, &wmsg.rect);
4121 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4122 return 0;
4125 case WM_INPUTLANGCHANGE:
4126 /* Inform lisp thread of keyboard layout changes. */
4127 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4129 /* Clear dead keys in the keyboard state; for simplicity only
4130 preserve modifier key states. */
4132 int i;
4133 BYTE keystate[256];
4135 GetKeyboardState (keystate);
4136 for (i = 0; i < 256; i++)
4137 if (1
4138 && i != VK_SHIFT
4139 && i != VK_LSHIFT
4140 && i != VK_RSHIFT
4141 && i != VK_CAPITAL
4142 && i != VK_NUMLOCK
4143 && i != VK_SCROLL
4144 && i != VK_CONTROL
4145 && i != VK_LCONTROL
4146 && i != VK_RCONTROL
4147 && i != VK_MENU
4148 && i != VK_LMENU
4149 && i != VK_RMENU
4150 && i != VK_LWIN
4151 && i != VK_RWIN)
4152 keystate[i] = 0;
4153 SetKeyboardState (keystate);
4155 goto dflt;
4157 case WM_HOTKEY:
4158 /* Synchronize hot keys with normal input. */
4159 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4160 return (0);
4162 case WM_KEYUP:
4163 case WM_SYSKEYUP:
4164 record_keyup (wParam, lParam);
4165 goto dflt;
4167 case WM_KEYDOWN:
4168 case WM_SYSKEYDOWN:
4169 /* Ignore keystrokes we fake ourself; see below. */
4170 if (dpyinfo->faked_key == wParam)
4172 dpyinfo->faked_key = 0;
4173 /* Make sure TranslateMessage sees them though (as long as
4174 they don't produce WM_CHAR messages). This ensures that
4175 indicator lights are toggled promptly on Windows 9x, for
4176 example. */
4177 if (lispy_function_keys[wParam] != 0)
4179 windows_translate = 1;
4180 goto translate;
4182 return 0;
4185 /* Synchronize modifiers with current keystroke. */
4186 sync_modifiers ();
4187 record_keydown (wParam, lParam);
4188 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4190 windows_translate = 0;
4192 switch (wParam)
4194 case VK_LWIN:
4195 if (NILP (Vw32_pass_lwindow_to_system))
4197 /* Prevent system from acting on keyup (which opens the
4198 Start menu if no other key was pressed) by simulating a
4199 press of Space which we will ignore. */
4200 if (GetAsyncKeyState (wParam) & 1)
4202 if (NUMBERP (Vw32_phantom_key_code))
4203 key = XUINT (Vw32_phantom_key_code) & 255;
4204 else
4205 key = VK_SPACE;
4206 dpyinfo->faked_key = key;
4207 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4210 if (!NILP (Vw32_lwindow_modifier))
4211 return 0;
4212 break;
4213 case VK_RWIN:
4214 if (NILP (Vw32_pass_rwindow_to_system))
4216 if (GetAsyncKeyState (wParam) & 1)
4218 if (NUMBERP (Vw32_phantom_key_code))
4219 key = XUINT (Vw32_phantom_key_code) & 255;
4220 else
4221 key = VK_SPACE;
4222 dpyinfo->faked_key = key;
4223 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4226 if (!NILP (Vw32_rwindow_modifier))
4227 return 0;
4228 break;
4229 case VK_APPS:
4230 if (!NILP (Vw32_apps_modifier))
4231 return 0;
4232 break;
4233 case VK_MENU:
4234 if (NILP (Vw32_pass_alt_to_system))
4235 /* Prevent DefWindowProc from activating the menu bar if an
4236 Alt key is pressed and released by itself. */
4237 return 0;
4238 windows_translate = 1;
4239 break;
4240 case VK_CAPITAL:
4241 /* Decide whether to treat as modifier or function key. */
4242 if (NILP (Vw32_enable_caps_lock))
4243 goto disable_lock_key;
4244 windows_translate = 1;
4245 break;
4246 case VK_NUMLOCK:
4247 /* Decide whether to treat as modifier or function key. */
4248 if (NILP (Vw32_enable_num_lock))
4249 goto disable_lock_key;
4250 windows_translate = 1;
4251 break;
4252 case VK_SCROLL:
4253 /* Decide whether to treat as modifier or function key. */
4254 if (NILP (Vw32_scroll_lock_modifier))
4255 goto disable_lock_key;
4256 windows_translate = 1;
4257 break;
4258 disable_lock_key:
4259 /* Ensure the appropriate lock key state (and indicator light)
4260 remains in the same state. We do this by faking another
4261 press of the relevant key. Apparently, this really is the
4262 only way to toggle the state of the indicator lights. */
4263 dpyinfo->faked_key = wParam;
4264 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4265 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4266 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4267 KEYEVENTF_EXTENDEDKEY | 0, 0);
4268 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4269 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4270 /* Ensure indicator lights are updated promptly on Windows 9x
4271 (TranslateMessage apparently does this), after forwarding
4272 input event. */
4273 post_character_message (hwnd, msg, wParam, lParam,
4274 w32_get_key_modifiers (wParam, lParam));
4275 windows_translate = 1;
4276 break;
4277 case VK_CONTROL:
4278 case VK_SHIFT:
4279 case VK_PROCESSKEY: /* Generated by IME. */
4280 windows_translate = 1;
4281 break;
4282 case VK_CANCEL:
4283 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4284 which is confusing for purposes of key binding; convert
4285 VK_CANCEL events into VK_PAUSE events. */
4286 wParam = VK_PAUSE;
4287 break;
4288 case VK_PAUSE:
4289 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4290 for purposes of key binding; convert these back into
4291 VK_NUMLOCK events, at least when we want to see NumLock key
4292 presses. (Note that there is never any possibility that
4293 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4294 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4295 wParam = VK_NUMLOCK;
4296 break;
4297 default:
4298 /* If not defined as a function key, change it to a WM_CHAR message. */
4299 if (lispy_function_keys[wParam] == 0)
4301 DWORD modifiers = construct_console_modifiers ();
4303 if (!NILP (Vw32_recognize_altgr)
4304 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4306 /* Always let TranslateMessage handle AltGr key chords;
4307 for some reason, ToAscii doesn't always process AltGr
4308 chords correctly. */
4309 windows_translate = 1;
4311 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4313 /* Handle key chords including any modifiers other
4314 than shift directly, in order to preserve as much
4315 modifier information as possible. */
4316 if ('A' <= wParam && wParam <= 'Z')
4318 /* Don't translate modified alphabetic keystrokes,
4319 so the user doesn't need to constantly switch
4320 layout to type control or meta keystrokes when
4321 the normal layout translates alphabetic
4322 characters to non-ascii characters. */
4323 if (!modifier_set (VK_SHIFT))
4324 wParam += ('a' - 'A');
4325 msg = WM_CHAR;
4327 else
4329 /* Try to handle other keystrokes by determining the
4330 base character (ie. translating the base key plus
4331 shift modifier). */
4332 int add;
4333 int isdead = 0;
4334 KEY_EVENT_RECORD key;
4336 key.bKeyDown = TRUE;
4337 key.wRepeatCount = 1;
4338 key.wVirtualKeyCode = wParam;
4339 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4340 key.uChar.AsciiChar = 0;
4341 key.dwControlKeyState = modifiers;
4343 add = w32_kbd_patch_key (&key);
4344 /* 0 means an unrecognised keycode, negative means
4345 dead key. Ignore both. */
4346 while (--add >= 0)
4348 /* Forward asciified character sequence. */
4349 post_character_message
4350 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4351 w32_get_key_modifiers (wParam, lParam));
4352 w32_kbd_patch_key (&key);
4354 return 0;
4357 else
4359 /* Let TranslateMessage handle everything else. */
4360 windows_translate = 1;
4365 translate:
4366 if (windows_translate)
4368 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4370 windows_msg.time = GetMessageTime ();
4371 TranslateMessage (&windows_msg);
4372 goto dflt;
4375 /* Fall through */
4377 case WM_SYSCHAR:
4378 case WM_CHAR:
4379 post_character_message (hwnd, msg, wParam, lParam,
4380 w32_get_key_modifiers (wParam, lParam));
4381 break;
4383 /* Simulate middle mouse button events when left and right buttons
4384 are used together, but only if user has two button mouse. */
4385 case WM_LBUTTONDOWN:
4386 case WM_RBUTTONDOWN:
4387 if (XINT (Vw32_num_mouse_buttons) > 2)
4388 goto handle_plain_button;
4391 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4392 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4394 if (button_state & this)
4395 return 0;
4397 if (button_state == 0)
4398 SetCapture (hwnd);
4400 button_state |= this;
4402 if (button_state & other)
4404 if (mouse_button_timer)
4406 KillTimer (hwnd, mouse_button_timer);
4407 mouse_button_timer = 0;
4409 /* Generate middle mouse event instead. */
4410 msg = WM_MBUTTONDOWN;
4411 button_state |= MMOUSE;
4413 else if (button_state & MMOUSE)
4415 /* Ignore button event if we've already generated a
4416 middle mouse down event. This happens if the
4417 user releases and press one of the two buttons
4418 after we've faked a middle mouse event. */
4419 return 0;
4421 else
4423 /* Flush out saved message. */
4424 post_msg (&saved_mouse_button_msg);
4426 wmsg.dwModifiers = w32_get_modifiers ();
4427 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4429 /* Clear message buffer. */
4430 saved_mouse_button_msg.msg.hwnd = 0;
4432 else
4434 /* Hold onto message for now. */
4435 mouse_button_timer =
4436 SetTimer (hwnd, MOUSE_BUTTON_ID,
4437 XINT (Vw32_mouse_button_tolerance), NULL);
4438 saved_mouse_button_msg.msg.hwnd = hwnd;
4439 saved_mouse_button_msg.msg.message = msg;
4440 saved_mouse_button_msg.msg.wParam = wParam;
4441 saved_mouse_button_msg.msg.lParam = lParam;
4442 saved_mouse_button_msg.msg.time = GetMessageTime ();
4443 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4446 return 0;
4448 case WM_LBUTTONUP:
4449 case WM_RBUTTONUP:
4450 if (XINT (Vw32_num_mouse_buttons) > 2)
4451 goto handle_plain_button;
4454 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4455 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4457 if ((button_state & this) == 0)
4458 return 0;
4460 button_state &= ~this;
4462 if (button_state & MMOUSE)
4464 /* Only generate event when second button is released. */
4465 if ((button_state & other) == 0)
4467 msg = WM_MBUTTONUP;
4468 button_state &= ~MMOUSE;
4470 if (button_state) abort ();
4472 else
4473 return 0;
4475 else
4477 /* Flush out saved message if necessary. */
4478 if (saved_mouse_button_msg.msg.hwnd)
4480 post_msg (&saved_mouse_button_msg);
4483 wmsg.dwModifiers = w32_get_modifiers ();
4484 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4486 /* Always clear message buffer and cancel timer. */
4487 saved_mouse_button_msg.msg.hwnd = 0;
4488 KillTimer (hwnd, mouse_button_timer);
4489 mouse_button_timer = 0;
4491 if (button_state == 0)
4492 ReleaseCapture ();
4494 return 0;
4496 case WM_MBUTTONDOWN:
4497 case WM_MBUTTONUP:
4498 handle_plain_button:
4500 BOOL up;
4501 int button;
4503 if (parse_button (msg, &button, &up))
4505 if (up) ReleaseCapture ();
4506 else SetCapture (hwnd);
4507 button = (button == 0) ? LMOUSE :
4508 ((button == 1) ? MMOUSE : RMOUSE);
4509 if (up)
4510 button_state &= ~button;
4511 else
4512 button_state |= button;
4516 wmsg.dwModifiers = w32_get_modifiers ();
4517 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4518 return 0;
4520 case WM_VSCROLL:
4521 case WM_MOUSEMOVE:
4522 if (XINT (Vw32_mouse_move_interval) <= 0
4523 || (msg == WM_MOUSEMOVE && button_state == 0))
4525 wmsg.dwModifiers = w32_get_modifiers ();
4526 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4527 return 0;
4530 /* Hang onto mouse move and scroll messages for a bit, to avoid
4531 sending such events to Emacs faster than it can process them.
4532 If we get more events before the timer from the first message
4533 expires, we just replace the first message. */
4535 if (saved_mouse_move_msg.msg.hwnd == 0)
4536 mouse_move_timer =
4537 SetTimer (hwnd, MOUSE_MOVE_ID,
4538 XINT (Vw32_mouse_move_interval), NULL);
4540 /* Hold onto message for now. */
4541 saved_mouse_move_msg.msg.hwnd = hwnd;
4542 saved_mouse_move_msg.msg.message = msg;
4543 saved_mouse_move_msg.msg.wParam = wParam;
4544 saved_mouse_move_msg.msg.lParam = lParam;
4545 saved_mouse_move_msg.msg.time = GetMessageTime ();
4546 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4548 return 0;
4550 case WM_MOUSEWHEEL:
4551 wmsg.dwModifiers = w32_get_modifiers ();
4552 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4553 return 0;
4555 case WM_DROPFILES:
4556 wmsg.dwModifiers = w32_get_modifiers ();
4557 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4558 return 0;
4560 case WM_TIMER:
4561 /* Flush out saved messages if necessary. */
4562 if (wParam == mouse_button_timer)
4564 if (saved_mouse_button_msg.msg.hwnd)
4566 post_msg (&saved_mouse_button_msg);
4567 saved_mouse_button_msg.msg.hwnd = 0;
4569 KillTimer (hwnd, mouse_button_timer);
4570 mouse_button_timer = 0;
4572 else if (wParam == mouse_move_timer)
4574 if (saved_mouse_move_msg.msg.hwnd)
4576 post_msg (&saved_mouse_move_msg);
4577 saved_mouse_move_msg.msg.hwnd = 0;
4579 KillTimer (hwnd, mouse_move_timer);
4580 mouse_move_timer = 0;
4582 return 0;
4584 case WM_NCACTIVATE:
4585 /* Windows doesn't send us focus messages when putting up and
4586 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4587 The only indication we get that something happened is receiving
4588 this message afterwards. So this is a good time to reset our
4589 keyboard modifiers' state. */
4590 reset_modifiers ();
4591 goto dflt;
4593 case WM_INITMENU:
4594 button_state = 0;
4595 ReleaseCapture ();
4596 /* We must ensure menu bar is fully constructed and up to date
4597 before allowing user interaction with it. To achieve this
4598 we send this message to the lisp thread and wait for a
4599 reply (whose value is not actually needed) to indicate that
4600 the menu bar is now ready for use, so we can now return.
4602 To remain responsive in the meantime, we enter a nested message
4603 loop that can process all other messages.
4605 However, we skip all this if the message results from calling
4606 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4607 thread a message because it is blocked on us at this point. We
4608 set menubar_active before calling TrackPopupMenu to indicate
4609 this (there is no possibility of confusion with real menubar
4610 being active). */
4612 f = x_window_to_frame (dpyinfo, hwnd);
4613 if (f
4614 && (f->output_data.w32->menubar_active
4615 /* We can receive this message even in the absence of a
4616 menubar (ie. when the system menu is activated) - in this
4617 case we do NOT want to forward the message, otherwise it
4618 will cause the menubar to suddenly appear when the user
4619 had requested it to be turned off! */
4620 || f->output_data.w32->menubar_widget == NULL))
4621 return 0;
4624 deferred_msg msg_buf;
4626 /* Detect if message has already been deferred; in this case
4627 we cannot return any sensible value to ignore this. */
4628 if (find_deferred_msg (hwnd, msg) != NULL)
4629 abort ();
4631 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4634 case WM_EXITMENULOOP:
4635 f = x_window_to_frame (dpyinfo, hwnd);
4637 /* Indicate that menubar can be modified again. */
4638 if (f)
4639 f->output_data.w32->menubar_active = 0;
4640 goto dflt;
4642 case WM_MENUSELECT:
4643 wmsg.dwModifiers = w32_get_modifiers ();
4644 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4645 return 0;
4647 case WM_MEASUREITEM:
4648 f = x_window_to_frame (dpyinfo, hwnd);
4649 if (f)
4651 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4653 if (pMis->CtlType == ODT_MENU)
4655 /* Work out dimensions for popup menu titles. */
4656 char * title = (char *) pMis->itemData;
4657 HDC hdc = GetDC (hwnd);
4658 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4659 LOGFONT menu_logfont;
4660 HFONT old_font;
4661 SIZE size;
4663 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4664 menu_logfont.lfWeight = FW_BOLD;
4665 menu_font = CreateFontIndirect (&menu_logfont);
4666 old_font = SelectObject (hdc, menu_font);
4668 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4669 if (title)
4671 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4672 pMis->itemWidth = size.cx;
4673 if (pMis->itemHeight < size.cy)
4674 pMis->itemHeight = size.cy;
4676 else
4677 pMis->itemWidth = 0;
4679 SelectObject (hdc, old_font);
4680 DeleteObject (menu_font);
4681 ReleaseDC (hwnd, hdc);
4682 return TRUE;
4685 return 0;
4687 case WM_DRAWITEM:
4688 f = x_window_to_frame (dpyinfo, hwnd);
4689 if (f)
4691 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4693 if (pDis->CtlType == ODT_MENU)
4695 /* Draw popup menu title. */
4696 char * title = (char *) pDis->itemData;
4697 if (title)
4699 HDC hdc = pDis->hDC;
4700 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4701 LOGFONT menu_logfont;
4702 HFONT old_font;
4704 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4705 menu_logfont.lfWeight = FW_BOLD;
4706 menu_font = CreateFontIndirect (&menu_logfont);
4707 old_font = SelectObject (hdc, menu_font);
4709 /* Always draw title as if not selected. */
4710 ExtTextOut (hdc,
4711 pDis->rcItem.left
4712 + GetSystemMetrics (SM_CXMENUCHECK),
4713 pDis->rcItem.top,
4714 ETO_OPAQUE, &pDis->rcItem,
4715 title, strlen (title), NULL);
4717 SelectObject (hdc, old_font);
4718 DeleteObject (menu_font);
4720 return TRUE;
4723 return 0;
4725 #if 0
4726 /* Still not right - can't distinguish between clicks in the
4727 client area of the frame from clicks forwarded from the scroll
4728 bars - may have to hook WM_NCHITTEST to remember the mouse
4729 position and then check if it is in the client area ourselves. */
4730 case WM_MOUSEACTIVATE:
4731 /* Discard the mouse click that activates a frame, allowing the
4732 user to click anywhere without changing point (or worse!).
4733 Don't eat mouse clicks on scrollbars though!! */
4734 if (LOWORD (lParam) == HTCLIENT )
4735 return MA_ACTIVATEANDEAT;
4736 goto dflt;
4737 #endif
4739 case WM_ACTIVATEAPP:
4740 case WM_ACTIVATE:
4741 case WM_WINDOWPOSCHANGED:
4742 case WM_SHOWWINDOW:
4743 /* Inform lisp thread that a frame might have just been obscured
4744 or exposed, so should recheck visibility of all frames. */
4745 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4746 goto dflt;
4748 case WM_SETFOCUS:
4749 dpyinfo->faked_key = 0;
4750 reset_modifiers ();
4751 register_hot_keys (hwnd);
4752 goto command;
4753 case WM_KILLFOCUS:
4754 unregister_hot_keys (hwnd);
4755 button_state = 0;
4756 ReleaseCapture ();
4757 case WM_MOVE:
4758 case WM_SIZE:
4759 case WM_COMMAND:
4760 command:
4761 wmsg.dwModifiers = w32_get_modifiers ();
4762 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4763 goto dflt;
4765 case WM_CLOSE:
4766 wmsg.dwModifiers = w32_get_modifiers ();
4767 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4768 return 0;
4770 case WM_WINDOWPOSCHANGING:
4772 WINDOWPLACEMENT wp;
4773 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4775 wp.length = sizeof (WINDOWPLACEMENT);
4776 GetWindowPlacement (hwnd, &wp);
4778 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4780 RECT rect;
4781 int wdiff;
4782 int hdiff;
4783 DWORD font_width;
4784 DWORD line_height;
4785 DWORD internal_border;
4786 DWORD scrollbar_extra;
4787 RECT wr;
4789 wp.length = sizeof(wp);
4790 GetWindowRect (hwnd, &wr);
4792 enter_crit ();
4794 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4795 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4796 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4797 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
4799 leave_crit ();
4801 memset (&rect, 0, sizeof (rect));
4802 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4803 GetMenu (hwnd) != NULL);
4805 /* Force width and height of client area to be exact
4806 multiples of the character cell dimensions. */
4807 wdiff = (lppos->cx - (rect.right - rect.left)
4808 - 2 * internal_border - scrollbar_extra)
4809 % font_width;
4810 hdiff = (lppos->cy - (rect.bottom - rect.top)
4811 - 2 * internal_border)
4812 % line_height;
4814 if (wdiff || hdiff)
4816 /* For right/bottom sizing we can just fix the sizes.
4817 However for top/left sizing we will need to fix the X
4818 and Y positions as well. */
4820 lppos->cx -= wdiff;
4821 lppos->cy -= hdiff;
4823 if (wp.showCmd != SW_SHOWMAXIMIZED
4824 && (lppos->flags & SWP_NOMOVE) == 0)
4826 if (lppos->x != wr.left || lppos->y != wr.top)
4828 lppos->x += wdiff;
4829 lppos->y += hdiff;
4831 else
4833 lppos->flags |= SWP_NOMOVE;
4837 return 0;
4842 goto dflt;
4844 case WM_GETMINMAXINFO:
4845 /* Hack to correct bug that allows Emacs frames to be resized
4846 below the Minimum Tracking Size. */
4847 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
4848 /* Hack to allow resizing the Emacs frame above the screen size.
4849 Note that Windows 9x limits coordinates to 16-bits. */
4850 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
4851 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
4852 return 0;
4854 case WM_EMACS_CREATESCROLLBAR:
4855 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
4856 (struct scroll_bar *) lParam);
4858 case WM_EMACS_SHOWWINDOW:
4859 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4861 case WM_EMACS_SETFOREGROUND:
4863 HWND foreground_window;
4864 DWORD foreground_thread, retval;
4866 /* On NT 5.0, and apparently Windows 98, it is necessary to
4867 attach to the thread that currently has focus in order to
4868 pull the focus away from it. */
4869 foreground_window = GetForegroundWindow ();
4870 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4871 if (!foreground_window
4872 || foreground_thread == GetCurrentThreadId ()
4873 || !AttachThreadInput (GetCurrentThreadId (),
4874 foreground_thread, TRUE))
4875 foreground_thread = 0;
4877 retval = SetForegroundWindow ((HWND) wParam);
4879 /* Detach from the previous foreground thread. */
4880 if (foreground_thread)
4881 AttachThreadInput (GetCurrentThreadId (),
4882 foreground_thread, FALSE);
4884 return retval;
4887 case WM_EMACS_SETWINDOWPOS:
4889 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4890 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4891 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4894 case WM_EMACS_DESTROYWINDOW:
4895 DragAcceptFiles ((HWND) wParam, FALSE);
4896 return DestroyWindow ((HWND) wParam);
4898 case WM_EMACS_TRACKPOPUPMENU:
4900 UINT flags;
4901 POINT *pos;
4902 int retval;
4903 pos = (POINT *)lParam;
4904 flags = TPM_CENTERALIGN;
4905 if (button_state & LMOUSE)
4906 flags |= TPM_LEFTBUTTON;
4907 else if (button_state & RMOUSE)
4908 flags |= TPM_RIGHTBUTTON;
4910 /* Remember we did a SetCapture on the initial mouse down event,
4911 so for safety, we make sure the capture is cancelled now. */
4912 ReleaseCapture ();
4913 button_state = 0;
4915 /* Use menubar_active to indicate that WM_INITMENU is from
4916 TrackPopupMenu below, and should be ignored. */
4917 f = x_window_to_frame (dpyinfo, hwnd);
4918 if (f)
4919 f->output_data.w32->menubar_active = 1;
4921 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4922 0, hwnd, NULL))
4924 MSG amsg;
4925 /* Eat any mouse messages during popupmenu */
4926 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4927 PM_REMOVE));
4928 /* Get the menu selection, if any */
4929 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4931 retval = LOWORD (amsg.wParam);
4933 else
4935 retval = 0;
4938 else
4940 retval = -1;
4943 return retval;
4946 default:
4947 /* Check for messages registered at runtime. */
4948 if (msg == msh_mousewheel)
4950 wmsg.dwModifiers = w32_get_modifiers ();
4951 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4952 return 0;
4955 dflt:
4956 return DefWindowProc (hwnd, msg, wParam, lParam);
4960 /* The most common default return code for handled messages is 0. */
4961 return 0;
4964 void
4965 my_create_window (f)
4966 struct frame * f;
4968 MSG msg;
4970 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4971 abort ();
4972 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4975 /* Create and set up the w32 window for frame F. */
4977 static void
4978 w32_window (f, window_prompting, minibuffer_only)
4979 struct frame *f;
4980 long window_prompting;
4981 int minibuffer_only;
4983 BLOCK_INPUT;
4985 /* Use the resource name as the top-level window name
4986 for looking up resources. Make a non-Lisp copy
4987 for the window manager, so GC relocation won't bother it.
4989 Elsewhere we specify the window name for the window manager. */
4992 char *str = (char *) XSTRING (Vx_resource_name)->data;
4993 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4994 strcpy (f->namebuf, str);
4997 my_create_window (f);
4999 validate_x_resource_name ();
5001 /* x_set_name normally ignores requests to set the name if the
5002 requested name is the same as the current name. This is the one
5003 place where that assumption isn't correct; f->name is set, but
5004 the server hasn't been told. */
5006 Lisp_Object name;
5007 int explicit = f->explicit_name;
5009 f->explicit_name = 0;
5010 name = f->name;
5011 f->name = Qnil;
5012 x_set_name (f, name, explicit);
5015 UNBLOCK_INPUT;
5017 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5018 initialize_frame_menubar (f);
5020 if (FRAME_W32_WINDOW (f) == 0)
5021 error ("Unable to create window");
5024 /* Handle the icon stuff for this window. Perhaps later we might
5025 want an x_set_icon_position which can be called interactively as
5026 well. */
5028 static void
5029 x_icon (f, parms)
5030 struct frame *f;
5031 Lisp_Object parms;
5033 Lisp_Object icon_x, icon_y;
5035 /* Set the position of the icon. Note that Windows 95 groups all
5036 icons in the tray. */
5037 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5038 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5039 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5041 CHECK_NUMBER (icon_x, 0);
5042 CHECK_NUMBER (icon_y, 0);
5044 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5045 error ("Both left and top icon corners of icon must be specified");
5047 BLOCK_INPUT;
5049 if (! EQ (icon_x, Qunbound))
5050 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5052 #if 0 /* TODO */
5053 /* Start up iconic or window? */
5054 x_wm_set_window_state
5055 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5056 ? IconicState
5057 : NormalState));
5059 x_text_icon (f, (char *) XSTRING ((!NILP (f->icon_name)
5060 ? f->icon_name
5061 : f->name))->data);
5062 #endif
5064 UNBLOCK_INPUT;
5068 static void
5069 x_make_gc (f)
5070 struct frame *f;
5072 XGCValues gc_values;
5074 BLOCK_INPUT;
5076 /* Create the GC's of this frame.
5077 Note that many default values are used. */
5079 /* Normal video */
5080 gc_values.font = f->output_data.w32->font;
5082 /* Cursor has cursor-color background, background-color foreground. */
5083 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5084 gc_values.background = f->output_data.w32->cursor_pixel;
5085 f->output_data.w32->cursor_gc
5086 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5087 (GCFont | GCForeground | GCBackground),
5088 &gc_values);
5090 /* Reliefs. */
5091 f->output_data.w32->white_relief.gc = 0;
5092 f->output_data.w32->black_relief.gc = 0;
5094 UNBLOCK_INPUT;
5098 /* Handler for signals raised during x_create_frame and
5099 x_create_top_frame. FRAME is the frame which is partially
5100 constructed. */
5102 static Lisp_Object
5103 unwind_create_frame (frame)
5104 Lisp_Object frame;
5106 struct frame *f = XFRAME (frame);
5108 /* If frame is ``official'', nothing to do. */
5109 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
5111 #ifdef GLYPH_DEBUG
5112 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5113 #endif
5115 x_free_frame_resources (f);
5117 /* Check that reference counts are indeed correct. */
5118 xassert (dpyinfo->reference_count == dpyinfo_refcount);
5119 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
5121 return Qt;
5124 return Qnil;
5128 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5129 1, 1, 0,
5130 "Make a new window, which is called a \"frame\" in Emacs terms.\n\
5131 Returns an Emacs frame object.\n\
5132 ALIST is an alist of frame parameters.\n\
5133 If the parameters specify that the frame should not have a minibuffer,\n\
5134 and do not specify a specific minibuffer window to use,\n\
5135 then `default-minibuffer-frame' must be a frame whose minibuffer can\n\
5136 be shared by the new frame.\n\
5138 This function is an internal primitive--use `make-frame' instead.")
5139 (parms)
5140 Lisp_Object parms;
5142 struct frame *f;
5143 Lisp_Object frame, tem;
5144 Lisp_Object name;
5145 int minibuffer_only = 0;
5146 long window_prompting = 0;
5147 int width, height;
5148 int count = BINDING_STACK_SIZE ();
5149 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5150 Lisp_Object display;
5151 struct w32_display_info *dpyinfo = NULL;
5152 Lisp_Object parent;
5153 struct kboard *kb;
5155 check_w32 ();
5157 /* Use this general default value to start with
5158 until we know if this frame has a specified name. */
5159 Vx_resource_name = Vinvocation_name;
5161 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5162 if (EQ (display, Qunbound))
5163 display = Qnil;
5164 dpyinfo = check_x_display_info (display);
5165 #ifdef MULTI_KBOARD
5166 kb = dpyinfo->kboard;
5167 #else
5168 kb = &the_only_kboard;
5169 #endif
5171 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5172 if (!STRINGP (name)
5173 && ! EQ (name, Qunbound)
5174 && ! NILP (name))
5175 error ("Invalid frame name--not a string or nil");
5177 if (STRINGP (name))
5178 Vx_resource_name = name;
5180 /* See if parent window is specified. */
5181 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5182 if (EQ (parent, Qunbound))
5183 parent = Qnil;
5184 if (! NILP (parent))
5185 CHECK_NUMBER (parent, 0);
5187 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5188 /* No need to protect DISPLAY because that's not used after passing
5189 it to make_frame_without_minibuffer. */
5190 frame = Qnil;
5191 GCPRO4 (parms, parent, name, frame);
5192 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5193 RES_TYPE_SYMBOL);
5194 if (EQ (tem, Qnone) || NILP (tem))
5195 f = make_frame_without_minibuffer (Qnil, kb, display);
5196 else if (EQ (tem, Qonly))
5198 f = make_minibuffer_frame ();
5199 minibuffer_only = 1;
5201 else if (WINDOWP (tem))
5202 f = make_frame_without_minibuffer (tem, kb, display);
5203 else
5204 f = make_frame (1);
5206 XSETFRAME (frame, f);
5208 /* Note that Windows does support scroll bars. */
5209 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5210 /* By default, make scrollbars the system standard width. */
5211 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5213 f->output_method = output_w32;
5214 f->output_data.w32 =
5215 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5216 bzero (f->output_data.w32, sizeof (struct w32_output));
5217 FRAME_FONTSET (f) = -1;
5218 record_unwind_protect (unwind_create_frame, frame);
5220 f->icon_name
5221 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5222 if (! STRINGP (f->icon_name))
5223 f->icon_name = Qnil;
5225 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5226 #ifdef MULTI_KBOARD
5227 FRAME_KBOARD (f) = kb;
5228 #endif
5230 /* Specify the parent under which to make this window. */
5232 if (!NILP (parent))
5234 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5235 f->output_data.w32->explicit_parent = 1;
5237 else
5239 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5240 f->output_data.w32->explicit_parent = 0;
5243 /* Set the name; the functions to which we pass f expect the name to
5244 be set. */
5245 if (EQ (name, Qunbound) || NILP (name))
5247 f->name = build_string (dpyinfo->w32_id_name);
5248 f->explicit_name = 0;
5250 else
5252 f->name = name;
5253 f->explicit_name = 1;
5254 /* use the frame's title when getting resources for this frame. */
5255 specbind (Qx_resource_name, name);
5258 /* Extract the window parameters from the supplied values
5259 that are needed to determine window geometry. */
5261 Lisp_Object font;
5263 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5265 BLOCK_INPUT;
5266 /* First, try whatever font the caller has specified. */
5267 if (STRINGP (font))
5269 tem = Fquery_fontset (font, Qnil);
5270 if (STRINGP (tem))
5271 font = x_new_fontset (f, XSTRING (tem)->data);
5272 else
5273 font = x_new_font (f, XSTRING (font)->data);
5275 /* Try out a font which we hope has bold and italic variations. */
5276 if (!STRINGP (font))
5277 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5278 if (! STRINGP (font))
5279 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5280 /* If those didn't work, look for something which will at least work. */
5281 if (! STRINGP (font))
5282 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5283 UNBLOCK_INPUT;
5284 if (! STRINGP (font))
5285 font = build_string ("Fixedsys");
5287 x_default_parameter (f, parms, Qfont, font,
5288 "font", "Font", RES_TYPE_STRING);
5291 x_default_parameter (f, parms, Qborder_width, make_number (2),
5292 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5293 /* This defaults to 2 in order to match xterm. We recognize either
5294 internalBorderWidth or internalBorder (which is what xterm calls
5295 it). */
5296 if (NILP (Fassq (Qinternal_border_width, parms)))
5298 Lisp_Object value;
5300 value = w32_get_arg (parms, Qinternal_border_width,
5301 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5302 if (! EQ (value, Qunbound))
5303 parms = Fcons (Fcons (Qinternal_border_width, value),
5304 parms);
5306 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5307 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5308 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5309 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5310 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5312 /* Also do the stuff which must be set before the window exists. */
5313 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5314 "foreground", "Foreground", RES_TYPE_STRING);
5315 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5316 "background", "Background", RES_TYPE_STRING);
5317 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5318 "pointerColor", "Foreground", RES_TYPE_STRING);
5319 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5320 "cursorColor", "Foreground", RES_TYPE_STRING);
5321 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5322 "borderColor", "BorderColor", RES_TYPE_STRING);
5323 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5324 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5325 x_default_parameter (f, parms, Qline_spacing, Qnil,
5326 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5329 /* Init faces before x_default_parameter is called for scroll-bar
5330 parameters because that function calls x_set_scroll_bar_width,
5331 which calls change_frame_size, which calls Fset_window_buffer,
5332 which runs hooks, which call Fvertical_motion. At the end, we
5333 end up in init_iterator with a null face cache, which should not
5334 happen. */
5335 init_frame_faces (f);
5337 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5338 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5339 x_default_parameter (f, parms, Qtool_bar_lines, make_number (0),
5340 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5341 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5342 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5343 x_default_parameter (f, parms, Qtitle, Qnil,
5344 "title", "Title", RES_TYPE_STRING);
5346 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5347 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5348 window_prompting = x_figure_window_size (f, parms);
5350 if (window_prompting & XNegative)
5352 if (window_prompting & YNegative)
5353 f->output_data.w32->win_gravity = SouthEastGravity;
5354 else
5355 f->output_data.w32->win_gravity = NorthEastGravity;
5357 else
5359 if (window_prompting & YNegative)
5360 f->output_data.w32->win_gravity = SouthWestGravity;
5361 else
5362 f->output_data.w32->win_gravity = NorthWestGravity;
5365 f->output_data.w32->size_hint_flags = window_prompting;
5367 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5368 f->no_split = minibuffer_only || EQ (tem, Qt);
5370 w32_window (f, window_prompting, minibuffer_only);
5371 x_icon (f, parms);
5373 x_make_gc (f);
5375 /* Now consider the frame official. */
5376 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5377 Vframe_list = Fcons (frame, Vframe_list);
5379 /* We need to do this after creating the window, so that the
5380 icon-creation functions can say whose icon they're describing. */
5381 x_default_parameter (f, parms, Qicon_type, Qnil,
5382 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5384 x_default_parameter (f, parms, Qauto_raise, Qnil,
5385 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5386 x_default_parameter (f, parms, Qauto_lower, Qnil,
5387 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5388 x_default_parameter (f, parms, Qcursor_type, Qbox,
5389 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5390 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5391 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5393 /* Dimensions, especially f->height, must be done via change_frame_size.
5394 Change will not be effected unless different from the current
5395 f->height. */
5396 width = f->width;
5397 height = f->height;
5399 /* Add the tool-bar height to the initial frame height so that the
5400 user gets a text display area of the size he specified with -g or
5401 via .Xdefaults. Later changes of the tool-bar height don't
5402 change the frame size. This is done so that users can create
5403 tall Emacs frames without having to guess how tall the tool-bar
5404 will get. */
5405 if (FRAME_TOOL_BAR_LINES (f))
5407 int margin, relief, bar_height;
5409 relief = (tool_bar_button_relief > 0
5410 ? tool_bar_button_relief
5411 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
5413 if (INTEGERP (Vtool_bar_button_margin)
5414 && XINT (Vtool_bar_button_margin) > 0)
5415 margin = XFASTINT (Vtool_bar_button_margin);
5416 else if (CONSP (Vtool_bar_button_margin)
5417 && INTEGERP (XCDR (Vtool_bar_button_margin))
5418 && XINT (XCDR (Vtool_bar_button_margin)) > 0)
5419 margin = XFASTINT (XCDR (Vtool_bar_button_margin));
5420 else
5421 margin = 0;
5423 bar_height = DEFAULT_TOOL_BAR_IMAGE_HEIGHT + 2 * margin + 2 * relief;
5424 height += (bar_height + CANON_Y_UNIT (f) - 1) / CANON_Y_UNIT (f);
5427 f->height = 0;
5428 SET_FRAME_WIDTH (f, 0);
5429 change_frame_size (f, height, width, 1, 0, 0);
5431 /* Tell the server what size and position, etc, we want, and how
5432 badly we want them. This should be done after we have the menu
5433 bar so that its size can be taken into account. */
5434 BLOCK_INPUT;
5435 x_wm_set_size_hint (f, window_prompting, 0);
5436 UNBLOCK_INPUT;
5438 /* Set up faces after all frame parameters are known. This call
5439 also merges in face attributes specified for new frames. If we
5440 don't do this, the `menu' face for instance won't have the right
5441 colors, and the menu bar won't appear in the specified colors for
5442 new frames. */
5443 call1 (Qface_set_after_frame_default, frame);
5445 /* Make the window appear on the frame and enable display, unless
5446 the caller says not to. However, with explicit parent, Emacs
5447 cannot control visibility, so don't try. */
5448 if (! f->output_data.w32->explicit_parent)
5450 Lisp_Object visibility;
5452 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5453 if (EQ (visibility, Qunbound))
5454 visibility = Qt;
5456 if (EQ (visibility, Qicon))
5457 x_iconify_frame (f);
5458 else if (! NILP (visibility))
5459 x_make_frame_visible (f);
5460 else
5461 /* Must have been Qnil. */
5464 UNGCPRO;
5466 /* Make sure windows on this frame appear in calls to next-window
5467 and similar functions. */
5468 Vwindow_list = Qnil;
5470 return unbind_to (count, frame);
5473 /* FRAME is used only to get a handle on the X display. We don't pass the
5474 display info directly because we're called from frame.c, which doesn't
5475 know about that structure. */
5476 Lisp_Object
5477 x_get_focus_frame (frame)
5478 struct frame *frame;
5480 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5481 Lisp_Object xfocus;
5482 if (! dpyinfo->w32_focus_frame)
5483 return Qnil;
5485 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5486 return xfocus;
5489 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5490 "Give FRAME input focus, raising to foreground if necessary.")
5491 (frame)
5492 Lisp_Object frame;
5494 x_focus_on_frame (check_x_frame (frame));
5495 return Qnil;
5499 /* Return the charset portion of a font name. */
5500 char * xlfd_charset_of_font (char * fontname)
5502 char *charset, *encoding;
5504 encoding = strrchr(fontname, '-');
5505 if (!encoding || encoding == fontname)
5506 return NULL;
5508 for (charset = encoding - 1; charset >= fontname; charset--)
5509 if (*charset == '-')
5510 break;
5512 if (charset == fontname || strcmp(charset, "-*-*") == 0)
5513 return NULL;
5515 return charset + 1;
5518 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5519 int size, char* filename);
5520 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
5521 BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len, char * charset);
5523 static struct font_info *
5524 w32_load_system_font (f,fontname,size)
5525 struct frame *f;
5526 char * fontname;
5527 int size;
5529 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5530 Lisp_Object font_names;
5532 /* Get a list of all the fonts that match this name. Once we
5533 have a list of matching fonts, we compare them against the fonts
5534 we already have loaded by comparing names. */
5535 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5537 if (!NILP (font_names))
5539 Lisp_Object tail;
5540 int i;
5542 /* First check if any are already loaded, as that is cheaper
5543 than loading another one. */
5544 for (i = 0; i < dpyinfo->n_fonts; i++)
5545 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5546 if (dpyinfo->font_table[i].name
5547 && (!strcmp (dpyinfo->font_table[i].name,
5548 XSTRING (XCAR (tail))->data)
5549 || !strcmp (dpyinfo->font_table[i].full_name,
5550 XSTRING (XCAR (tail))->data)))
5551 return (dpyinfo->font_table + i);
5553 fontname = (char *) XSTRING (XCAR (font_names))->data;
5555 else if (w32_strict_fontnames)
5557 /* If EnumFontFamiliesEx was available, we got a full list of
5558 fonts back so stop now to avoid the possibility of loading a
5559 random font. If we had to fall back to EnumFontFamilies, the
5560 list is incomplete, so continue whether the font we want was
5561 listed or not. */
5562 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5563 FARPROC enum_font_families_ex
5564 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5565 if (enum_font_families_ex)
5566 return NULL;
5569 /* Load the font and add it to the table. */
5571 char *full_name, *encoding, *charset;
5572 XFontStruct *font;
5573 struct font_info *fontp;
5574 LOGFONT lf;
5575 BOOL ok;
5576 int i;
5578 if (!fontname || !x_to_w32_font (fontname, &lf))
5579 return (NULL);
5581 if (!*lf.lfFaceName)
5582 /* If no name was specified for the font, we get a random font
5583 from CreateFontIndirect - this is not particularly
5584 desirable, especially since CreateFontIndirect does not
5585 fill out the missing name in lf, so we never know what we
5586 ended up with. */
5587 return NULL;
5589 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5590 bzero (font, sizeof (*font));
5592 /* Set bdf to NULL to indicate that this is a Windows font. */
5593 font->bdf = NULL;
5595 BLOCK_INPUT;
5597 font->hfont = CreateFontIndirect (&lf);
5599 if (font->hfont == NULL)
5601 ok = FALSE;
5603 else
5605 HDC hdc;
5606 HANDLE oldobj;
5607 int codepage = w32_codepage_for_font (fontname);
5609 hdc = GetDC (dpyinfo->root_window);
5610 oldobj = SelectObject (hdc, font->hfont);
5612 ok = GetTextMetrics (hdc, &font->tm);
5613 if (codepage == CP_UNICODE)
5614 font->double_byte_p = 1;
5615 else
5616 font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS;
5618 SelectObject (hdc, oldobj);
5619 ReleaseDC (dpyinfo->root_window, hdc);
5620 /* Fill out details in lf according to the font that was
5621 actually loaded. */
5622 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5623 lf.lfWidth = font->tm.tmAveCharWidth;
5624 lf.lfWeight = font->tm.tmWeight;
5625 lf.lfItalic = font->tm.tmItalic;
5626 lf.lfCharSet = font->tm.tmCharSet;
5627 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5628 ? VARIABLE_PITCH : FIXED_PITCH);
5629 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5630 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5632 w32_cache_char_metrics (font);
5635 UNBLOCK_INPUT;
5637 if (!ok)
5639 w32_unload_font (dpyinfo, font);
5640 return (NULL);
5643 /* Find a free slot in the font table. */
5644 for (i = 0; i < dpyinfo->n_fonts; ++i)
5645 if (dpyinfo->font_table[i].name == NULL)
5646 break;
5648 /* If no free slot found, maybe enlarge the font table. */
5649 if (i == dpyinfo->n_fonts
5650 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5652 int sz;
5653 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5654 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5655 dpyinfo->font_table
5656 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5659 fontp = dpyinfo->font_table + i;
5660 if (i == dpyinfo->n_fonts)
5661 ++dpyinfo->n_fonts;
5663 /* Now fill in the slots of *FONTP. */
5664 BLOCK_INPUT;
5665 fontp->font = font;
5666 fontp->font_idx = i;
5667 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5668 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5670 charset = xlfd_charset_of_font (fontname);
5672 /* Work out the font's full name. */
5673 full_name = (char *)xmalloc (100);
5674 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
5675 fontp->full_name = full_name;
5676 else
5678 /* If all else fails - just use the name we used to load it. */
5679 xfree (full_name);
5680 fontp->full_name = fontp->name;
5683 fontp->size = FONT_WIDTH (font);
5684 fontp->height = FONT_HEIGHT (font);
5686 /* The slot `encoding' specifies how to map a character
5687 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
5688 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
5689 (0:0x20..0x7F, 1:0xA0..0xFF,
5690 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
5691 2:0xA020..0xFF7F). For the moment, we don't know which charset
5692 uses this font. So, we set information in fontp->encoding[1]
5693 which is never used by any charset. If mapping can't be
5694 decided, set FONT_ENCODING_NOT_DECIDED. */
5696 /* SJIS fonts need to be set to type 4, all others seem to work as
5697 type FONT_ENCODING_NOT_DECIDED. */
5698 encoding = strrchr (fontp->name, '-');
5699 if (encoding && stricmp (encoding+1, "sjis") == 0)
5700 fontp->encoding[1] = 4;
5701 else
5702 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
5704 /* The following three values are set to 0 under W32, which is
5705 what they get set to if XGetFontProperty fails under X. */
5706 fontp->baseline_offset = 0;
5707 fontp->relative_compose = 0;
5708 fontp->default_ascent = 0;
5710 /* Set global flag fonts_changed_p to non-zero if the font loaded
5711 has a character with a smaller width than any other character
5712 before, or if the font loaded has a smalle>r height than any
5713 other font loaded before. If this happens, it will make a
5714 glyph matrix reallocation necessary. */
5715 fonts_changed_p = x_compute_min_glyph_bounds (f);
5716 UNBLOCK_INPUT;
5717 return fontp;
5721 /* Load font named FONTNAME of size SIZE for frame F, and return a
5722 pointer to the structure font_info while allocating it dynamically.
5723 If loading fails, return NULL. */
5724 struct font_info *
5725 w32_load_font (f,fontname,size)
5726 struct frame *f;
5727 char * fontname;
5728 int size;
5730 Lisp_Object bdf_fonts;
5731 struct font_info *retval = NULL;
5733 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
5735 while (!retval && CONSP (bdf_fonts))
5737 char *bdf_name, *bdf_file;
5738 Lisp_Object bdf_pair;
5740 bdf_name = XSTRING (XCAR (bdf_fonts))->data;
5741 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
5742 bdf_file = XSTRING (XCDR (bdf_pair))->data;
5744 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
5746 bdf_fonts = XCDR (bdf_fonts);
5749 if (retval)
5750 return retval;
5752 return w32_load_system_font(f, fontname, size);
5756 void
5757 w32_unload_font (dpyinfo, font)
5758 struct w32_display_info *dpyinfo;
5759 XFontStruct * font;
5761 if (font)
5763 if (font->per_char) xfree (font->per_char);
5764 if (font->bdf) w32_free_bdf_font (font->bdf);
5766 if (font->hfont) DeleteObject(font->hfont);
5767 xfree (font);
5771 /* The font conversion stuff between x and w32 */
5773 /* X font string is as follows (from faces.el)
5774 * (let ((- "[-?]")
5775 * (foundry "[^-]+")
5776 * (family "[^-]+")
5777 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
5778 * (weight\? "\\([^-]*\\)") ; 1
5779 * (slant "\\([ior]\\)") ; 2
5780 * (slant\? "\\([^-]?\\)") ; 2
5781 * (swidth "\\([^-]*\\)") ; 3
5782 * (adstyle "[^-]*") ; 4
5783 * (pixelsize "[0-9]+")
5784 * (pointsize "[0-9][0-9]+")
5785 * (resx "[0-9][0-9]+")
5786 * (resy "[0-9][0-9]+")
5787 * (spacing "[cmp?*]")
5788 * (avgwidth "[0-9]+")
5789 * (registry "[^-]+")
5790 * (encoding "[^-]+")
5794 static LONG
5795 x_to_w32_weight (lpw)
5796 char * lpw;
5798 if (!lpw) return (FW_DONTCARE);
5800 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
5801 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
5802 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
5803 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
5804 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5805 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
5806 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
5807 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
5808 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
5809 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
5810 else
5811 return FW_DONTCARE;
5815 static char *
5816 w32_to_x_weight (fnweight)
5817 int fnweight;
5819 if (fnweight >= FW_HEAVY) return "heavy";
5820 if (fnweight >= FW_EXTRABOLD) return "extrabold";
5821 if (fnweight >= FW_BOLD) return "bold";
5822 if (fnweight >= FW_SEMIBOLD) return "demibold";
5823 if (fnweight >= FW_MEDIUM) return "medium";
5824 if (fnweight >= FW_NORMAL) return "normal";
5825 if (fnweight >= FW_LIGHT) return "light";
5826 if (fnweight >= FW_EXTRALIGHT) return "extralight";
5827 if (fnweight >= FW_THIN) return "thin";
5828 else
5829 return "*";
5832 static LONG
5833 x_to_w32_charset (lpcs)
5834 char * lpcs;
5836 Lisp_Object this_entry, w32_charset;
5838 /* Look through w32-charset-info-alist for the character set.
5839 Format of each entry is
5840 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5842 this_entry = Fassoc (build_string(lpcs), Vw32_charset_info_alist);
5844 if (NILP(this_entry))
5846 /* At startup, we want iso8859-1 fonts to come up properly. */
5847 if (stricmp(lpcs, "iso8859-1") == 0)
5848 return ANSI_CHARSET;
5849 else
5850 return DEFAULT_CHARSET;
5853 w32_charset = Fcar (Fcdr (this_entry));
5855 // Translate Lisp symbol to number.
5856 if (w32_charset == Qw32_charset_ansi)
5857 return ANSI_CHARSET;
5858 if (w32_charset == Qw32_charset_symbol)
5859 return SYMBOL_CHARSET;
5860 if (w32_charset == Qw32_charset_shiftjis)
5861 return SHIFTJIS_CHARSET;
5862 if (w32_charset == Qw32_charset_hangeul)
5863 return HANGEUL_CHARSET;
5864 if (w32_charset == Qw32_charset_chinesebig5)
5865 return CHINESEBIG5_CHARSET;
5866 if (w32_charset == Qw32_charset_gb2312)
5867 return GB2312_CHARSET;
5868 if (w32_charset == Qw32_charset_oem)
5869 return OEM_CHARSET;
5870 #ifdef JOHAB_CHARSET
5871 if (w32_charset == Qw32_charset_johab)
5872 return JOHAB_CHARSET;
5873 if (w32_charset == Qw32_charset_easteurope)
5874 return EASTEUROPE_CHARSET;
5875 if (w32_charset == Qw32_charset_turkish)
5876 return TURKISH_CHARSET;
5877 if (w32_charset == Qw32_charset_baltic)
5878 return BALTIC_CHARSET;
5879 if (w32_charset == Qw32_charset_russian)
5880 return RUSSIAN_CHARSET;
5881 if (w32_charset == Qw32_charset_arabic)
5882 return ARABIC_CHARSET;
5883 if (w32_charset == Qw32_charset_greek)
5884 return GREEK_CHARSET;
5885 if (w32_charset == Qw32_charset_hebrew)
5886 return HEBREW_CHARSET;
5887 if (w32_charset == Qw32_charset_vietnamese)
5888 return VIETNAMESE_CHARSET;
5889 if (w32_charset == Qw32_charset_thai)
5890 return THAI_CHARSET;
5891 if (w32_charset == Qw32_charset_mac)
5892 return MAC_CHARSET;
5893 #endif /* JOHAB_CHARSET */
5894 #ifdef UNICODE_CHARSET
5895 if (w32_charset == Qw32_charset_unicode)
5896 return UNICODE_CHARSET;
5897 #endif
5899 return DEFAULT_CHARSET;
5903 static char *
5904 w32_to_x_charset (fncharset)
5905 int fncharset;
5907 static char buf[16];
5908 Lisp_Object charset_type;
5910 switch (fncharset)
5912 case ANSI_CHARSET:
5913 /* Handle startup case of w32-charset-info-alist not
5914 being set up yet. */
5915 if (NILP(Vw32_charset_info_alist))
5916 return "iso8859-1";
5917 charset_type = Qw32_charset_ansi;
5918 break;
5919 case DEFAULT_CHARSET:
5920 charset_type = Qw32_charset_default;
5921 break;
5922 case SYMBOL_CHARSET:
5923 charset_type = Qw32_charset_symbol;
5924 break;
5925 case SHIFTJIS_CHARSET:
5926 charset_type = Qw32_charset_shiftjis;
5927 break;
5928 case HANGEUL_CHARSET:
5929 charset_type = Qw32_charset_hangeul;
5930 break;
5931 case GB2312_CHARSET:
5932 charset_type = Qw32_charset_gb2312;
5933 break;
5934 case CHINESEBIG5_CHARSET:
5935 charset_type = Qw32_charset_chinesebig5;
5936 break;
5937 case OEM_CHARSET:
5938 charset_type = Qw32_charset_oem;
5939 break;
5941 /* More recent versions of Windows (95 and NT4.0) define more
5942 character sets. */
5943 #ifdef EASTEUROPE_CHARSET
5944 case EASTEUROPE_CHARSET:
5945 charset_type = Qw32_charset_easteurope;
5946 break;
5947 case TURKISH_CHARSET:
5948 charset_type = Qw32_charset_turkish;
5949 break;
5950 case BALTIC_CHARSET:
5951 charset_type = Qw32_charset_baltic;
5952 break;
5953 case RUSSIAN_CHARSET:
5954 charset_type = Qw32_charset_russian;
5955 break;
5956 case ARABIC_CHARSET:
5957 charset_type = Qw32_charset_arabic;
5958 break;
5959 case GREEK_CHARSET:
5960 charset_type = Qw32_charset_greek;
5961 break;
5962 case HEBREW_CHARSET:
5963 charset_type = Qw32_charset_hebrew;
5964 break;
5965 case VIETNAMESE_CHARSET:
5966 charset_type = Qw32_charset_vietnamese;
5967 break;
5968 case THAI_CHARSET:
5969 charset_type = Qw32_charset_thai;
5970 break;
5971 case MAC_CHARSET:
5972 charset_type = Qw32_charset_mac;
5973 break;
5974 case JOHAB_CHARSET:
5975 charset_type = Qw32_charset_johab;
5976 break;
5977 #endif
5979 #ifdef UNICODE_CHARSET
5980 case UNICODE_CHARSET:
5981 charset_type = Qw32_charset_unicode;
5982 break;
5983 #endif
5984 default:
5985 /* Encode numerical value of unknown charset. */
5986 sprintf (buf, "*-#%u", fncharset);
5987 return buf;
5991 Lisp_Object rest;
5992 char * best_match = NULL;
5994 /* Look through w32-charset-info-alist for the character set.
5995 Prefer ISO codepages, and prefer lower numbers in the ISO
5996 range. Only return charsets for codepages which are installed.
5998 Format of each entry is
5999 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6001 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6003 char * x_charset;
6004 Lisp_Object w32_charset;
6005 Lisp_Object codepage;
6007 Lisp_Object this_entry = XCAR (rest);
6009 /* Skip invalid entries in alist. */
6010 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6011 || !CONSP (XCDR (this_entry))
6012 || !SYMBOLP (XCAR (XCDR (this_entry))))
6013 continue;
6015 x_charset = XSTRING (XCAR (this_entry))->data;
6016 w32_charset = XCAR (XCDR (this_entry));
6017 codepage = XCDR (XCDR (this_entry));
6019 /* Look for Same charset and a valid codepage (or non-int
6020 which means ignore). */
6021 if (w32_charset == charset_type
6022 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6023 || IsValidCodePage (XINT (codepage))))
6025 /* If we don't have a match already, then this is the
6026 best. */
6027 if (!best_match)
6028 best_match = x_charset;
6029 /* If this is an ISO codepage, and the best so far isn't,
6030 then this is better. */
6031 else if (stricmp (best_match, "iso") != 0
6032 && stricmp (x_charset, "iso") == 0)
6033 best_match = x_charset;
6034 /* If both are ISO8859 codepages, choose the one with the
6035 lowest number in the encoding field. */
6036 else if (stricmp (best_match, "iso8859-") == 0
6037 && stricmp (x_charset, "iso8859-") == 0)
6039 int best_enc = atoi (best_match + 8);
6040 int this_enc = atoi (x_charset + 8);
6041 if (this_enc > 0 && this_enc < best_enc)
6042 best_match = x_charset;
6047 /* If no match, encode the numeric value. */
6048 if (!best_match)
6050 sprintf (buf, "*-#%u", fncharset);
6051 return buf;
6054 strncpy(buf, best_match, 15);
6055 buf[15] = '\0';
6056 return buf;
6061 /* Get the Windows codepage corresponding to the specified font. The
6062 charset info in the font name is used to look up
6063 w32-charset-to-codepage-alist. */
6064 int
6065 w32_codepage_for_font (char *fontname)
6067 Lisp_Object codepage, entry;
6068 char *charset_str, *charset, *end;
6070 if (NILP (Vw32_charset_info_alist))
6071 return CP_DEFAULT;
6073 /* Extract charset part of font string. */
6074 charset = xlfd_charset_of_font (fontname);
6076 if (!charset)
6077 return CP_UNKNOWN;
6079 charset_str = (char *) alloca (strlen (charset));
6080 strcpy (charset_str, charset);
6082 /* Remove leading "*-". */
6083 if (strncmp ("*-", charset_str, 2) == 0)
6084 charset = charset_str + 2;
6085 else
6086 charset = charset_str;
6088 /* Stop match at wildcard (including preceding '-'). */
6089 if (end = strchr (charset, '*'))
6091 if (end > charset && *(end-1) == '-')
6092 end--;
6093 *end = '\0';
6096 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6097 if (NILP (entry))
6098 return CP_UNKNOWN;
6100 codepage = Fcdr (Fcdr (entry));
6102 if (NILP (codepage))
6103 return CP_8BIT;
6104 else if (XFASTINT (codepage) == XFASTINT (Qt))
6105 return CP_UNICODE;
6106 else if (INTEGERP (codepage))
6107 return XINT (codepage);
6108 else
6109 return CP_UNKNOWN;
6113 static BOOL
6114 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6115 LOGFONT * lplogfont;
6116 char * lpxstr;
6117 int len;
6118 char * specific_charset;
6120 char* fonttype;
6121 char *fontname;
6122 char height_pixels[8];
6123 char height_dpi[8];
6124 char width_pixels[8];
6125 char *fontname_dash;
6126 int display_resy = one_w32_display_info.resy;
6127 int display_resx = one_w32_display_info.resx;
6128 int bufsz;
6129 struct coding_system coding;
6131 if (!lpxstr) abort ();
6133 if (!lplogfont)
6134 return FALSE;
6136 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6137 fonttype = "raster";
6138 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6139 fonttype = "outline";
6140 else
6141 fonttype = "unknown";
6143 setup_coding_system (Fcheck_coding_system (Vw32_system_coding_system),
6144 &coding);
6145 coding.src_multibyte = 0;
6146 coding.dst_multibyte = 1;
6147 coding.mode |= CODING_MODE_LAST_BLOCK;
6148 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6150 fontname = alloca(sizeof(*fontname) * bufsz);
6151 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6152 strlen(lplogfont->lfFaceName), bufsz - 1);
6153 *(fontname + coding.produced) = '\0';
6155 /* Replace dashes with underscores so the dashes are not
6156 misinterpreted. */
6157 fontname_dash = fontname;
6158 while (fontname_dash = strchr (fontname_dash, '-'))
6159 *fontname_dash = '_';
6161 if (lplogfont->lfHeight)
6163 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6164 sprintf (height_dpi, "%u",
6165 abs (lplogfont->lfHeight) * 720 / display_resy);
6167 else
6169 strcpy (height_pixels, "*");
6170 strcpy (height_dpi, "*");
6172 if (lplogfont->lfWidth)
6173 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6174 else
6175 strcpy (width_pixels, "*");
6177 _snprintf (lpxstr, len - 1,
6178 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6179 fonttype, /* foundry */
6180 fontname, /* family */
6181 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6182 lplogfont->lfItalic?'i':'r', /* slant */
6183 /* setwidth name */
6184 /* add style name */
6185 height_pixels, /* pixel size */
6186 height_dpi, /* point size */
6187 display_resx, /* resx */
6188 display_resy, /* resy */
6189 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6190 ? 'p' : 'c', /* spacing */
6191 width_pixels, /* avg width */
6192 specific_charset ? specific_charset
6193 : w32_to_x_charset (lplogfont->lfCharSet)
6194 /* charset registry and encoding */
6197 lpxstr[len - 1] = 0; /* just to be sure */
6198 return (TRUE);
6201 static BOOL
6202 x_to_w32_font (lpxstr, lplogfont)
6203 char * lpxstr;
6204 LOGFONT * lplogfont;
6206 struct coding_system coding;
6208 if (!lplogfont) return (FALSE);
6210 memset (lplogfont, 0, sizeof (*lplogfont));
6212 /* Set default value for each field. */
6213 #if 1
6214 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6215 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6216 lplogfont->lfQuality = DEFAULT_QUALITY;
6217 #else
6218 /* go for maximum quality */
6219 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6220 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6221 lplogfont->lfQuality = PROOF_QUALITY;
6222 #endif
6224 lplogfont->lfCharSet = DEFAULT_CHARSET;
6225 lplogfont->lfWeight = FW_DONTCARE;
6226 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6228 if (!lpxstr)
6229 return FALSE;
6231 /* Provide a simple escape mechanism for specifying Windows font names
6232 * directly -- if font spec does not beginning with '-', assume this
6233 * format:
6234 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6237 if (*lpxstr == '-')
6239 int fields, tem;
6240 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6241 width[10], resy[10], remainder[20];
6242 char * encoding;
6243 int dpi = one_w32_display_info.resy;
6245 fields = sscanf (lpxstr,
6246 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%19s",
6247 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6248 if (fields == EOF) return (FALSE);
6250 /* If wildcards cover more than one field, we don't know which
6251 field is which, so don't fill any in. */
6253 if (fields < 9)
6254 fields = 0;
6256 if (fields > 0 && name[0] != '*')
6258 int bufsize;
6259 unsigned char *buf;
6261 setup_coding_system
6262 (Fcheck_coding_system (Vw32_system_coding_system), &coding);
6263 coding.src_multibyte = 1;
6264 coding.dst_multibyte = 1;
6265 bufsize = encoding_buffer_size (&coding, strlen (name));
6266 buf = (unsigned char *) alloca (bufsize);
6267 coding.mode |= CODING_MODE_LAST_BLOCK;
6268 encode_coding (&coding, name, buf, strlen (name), bufsize);
6269 if (coding.produced >= LF_FACESIZE)
6270 coding.produced = LF_FACESIZE - 1;
6271 buf[coding.produced] = 0;
6272 strcpy (lplogfont->lfFaceName, buf);
6274 else
6276 lplogfont->lfFaceName[0] = '\0';
6279 fields--;
6281 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6283 fields--;
6285 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6287 fields--;
6289 if (fields > 0 && pixels[0] != '*')
6290 lplogfont->lfHeight = atoi (pixels);
6292 fields--;
6293 fields--;
6294 if (fields > 0 && resy[0] != '*')
6296 tem = atoi (resy);
6297 if (tem > 0) dpi = tem;
6300 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6301 lplogfont->lfHeight = atoi (height) * dpi / 720;
6303 if (fields > 0)
6304 lplogfont->lfPitchAndFamily =
6305 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6307 fields--;
6309 if (fields > 0 && width[0] != '*')
6310 lplogfont->lfWidth = atoi (width) / 10;
6312 fields--;
6314 /* Strip the trailing '-' if present. (it shouldn't be, as it
6315 fails the test against xlfd-tight-regexp in fontset.el). */
6317 int len = strlen (remainder);
6318 if (len > 0 && remainder[len-1] == '-')
6319 remainder[len-1] = 0;
6321 encoding = remainder;
6322 if (strncmp (encoding, "*-", 2) == 0)
6323 encoding += 2;
6324 lplogfont->lfCharSet = x_to_w32_charset (fields > 0 ? encoding : "");
6326 else
6328 int fields;
6329 char name[100], height[10], width[10], weight[20];
6331 fields = sscanf (lpxstr,
6332 "%99[^:]:%9[^:]:%9[^:]:%19s",
6333 name, height, width, weight);
6335 if (fields == EOF) return (FALSE);
6337 if (fields > 0)
6339 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6340 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6342 else
6344 lplogfont->lfFaceName[0] = 0;
6347 fields--;
6349 if (fields > 0)
6350 lplogfont->lfHeight = atoi (height);
6352 fields--;
6354 if (fields > 0)
6355 lplogfont->lfWidth = atoi (width);
6357 fields--;
6359 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6362 /* This makes TrueType fonts work better. */
6363 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6365 return (TRUE);
6368 /* Strip the pixel height and point height from the given xlfd, and
6369 return the pixel height. If no pixel height is specified, calculate
6370 one from the point height, or if that isn't defined either, return
6371 0 (which usually signifies a scalable font).
6373 static int
6374 xlfd_strip_height (char *fontname)
6376 int pixel_height, field_number;
6377 char *read_from, *write_to;
6379 xassert (fontname);
6381 pixel_height = field_number = 0;
6382 write_to = NULL;
6384 /* Look for height fields. */
6385 for (read_from = fontname; *read_from; read_from++)
6387 if (*read_from == '-')
6389 field_number++;
6390 if (field_number == 7) /* Pixel height. */
6392 read_from++;
6393 write_to = read_from;
6395 /* Find end of field. */
6396 for (;*read_from && *read_from != '-'; read_from++)
6399 /* Split the fontname at end of field. */
6400 if (*read_from)
6402 *read_from = '\0';
6403 read_from++;
6405 pixel_height = atoi (write_to);
6406 /* Blank out field. */
6407 if (read_from > write_to)
6409 *write_to = '-';
6410 write_to++;
6412 /* If the pixel height field is at the end (partial xlfd),
6413 return now. */
6414 else
6415 return pixel_height;
6417 /* If we got a pixel height, the point height can be
6418 ignored. Just blank it out and break now. */
6419 if (pixel_height)
6421 /* Find end of point size field. */
6422 for (; *read_from && *read_from != '-'; read_from++)
6425 if (*read_from)
6426 read_from++;
6428 /* Blank out the point size field. */
6429 if (read_from > write_to)
6431 *write_to = '-';
6432 write_to++;
6434 else
6435 return pixel_height;
6437 break;
6439 /* If the point height is already blank, break now. */
6440 if (*read_from == '-')
6442 read_from++;
6443 break;
6446 else if (field_number == 8)
6448 /* If we didn't get a pixel height, try to get the point
6449 height and convert that. */
6450 int point_size;
6451 char *point_size_start = read_from++;
6453 /* Find end of field. */
6454 for (; *read_from && *read_from != '-'; read_from++)
6457 if (*read_from)
6459 *read_from = '\0';
6460 read_from++;
6463 point_size = atoi (point_size_start);
6465 /* Convert to pixel height. */
6466 pixel_height = point_size
6467 * one_w32_display_info.height_in / 720;
6469 /* Blank out this field and break. */
6470 *write_to = '-';
6471 write_to++;
6472 break;
6477 /* Shift the rest of the font spec into place. */
6478 if (write_to && read_from > write_to)
6480 for (; *read_from; read_from++, write_to++)
6481 *write_to = *read_from;
6482 *write_to = '\0';
6485 return pixel_height;
6488 /* Assume parameter 1 is fully qualified, no wildcards. */
6489 static BOOL
6490 w32_font_match (fontname, pattern)
6491 char * fontname;
6492 char * pattern;
6494 char *regex = alloca (strlen (pattern) * 2 + 3);
6495 char *font_name_copy = alloca (strlen (fontname) + 1);
6496 char *ptr;
6498 /* Copy fontname so we can modify it during comparison. */
6499 strcpy (font_name_copy, fontname);
6501 ptr = regex;
6502 *ptr++ = '^';
6504 /* Turn pattern into a regexp and do a regexp match. */
6505 for (; *pattern; pattern++)
6507 if (*pattern == '?')
6508 *ptr++ = '.';
6509 else if (*pattern == '*')
6511 *ptr++ = '.';
6512 *ptr++ = '*';
6514 else
6515 *ptr++ = *pattern;
6517 *ptr = '$';
6518 *(ptr + 1) = '\0';
6520 /* Strip out font heights and compare them seperately, since
6521 rounding error can cause mismatches. This also allows a
6522 comparison between a font that declares only a pixel height and a
6523 pattern that declares the point height.
6526 int font_height, pattern_height;
6528 font_height = xlfd_strip_height (font_name_copy);
6529 pattern_height = xlfd_strip_height (regex);
6531 /* Compare now, and don't bother doing expensive regexp matching
6532 if the heights differ. */
6533 if (font_height && pattern_height && (font_height != pattern_height))
6534 return FALSE;
6537 return (fast_c_string_match_ignore_case (build_string (regex),
6538 font_name_copy) >= 0);
6541 /* Callback functions, and a structure holding info they need, for
6542 listing system fonts on W32. We need one set of functions to do the
6543 job properly, but these don't work on NT 3.51 and earlier, so we
6544 have a second set which don't handle character sets properly to
6545 fall back on.
6547 In both cases, there are two passes made. The first pass gets one
6548 font from each family, the second pass lists all the fonts from
6549 each family. */
6551 typedef struct enumfont_t
6553 HDC hdc;
6554 int numFonts;
6555 LOGFONT logfont;
6556 XFontStruct *size_ref;
6557 Lisp_Object *pattern;
6558 Lisp_Object *tail;
6559 } enumfont_t;
6561 static int CALLBACK
6562 enum_font_cb2 (lplf, lptm, FontType, lpef)
6563 ENUMLOGFONT * lplf;
6564 NEWTEXTMETRIC * lptm;
6565 int FontType;
6566 enumfont_t * lpef;
6568 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
6569 return (1);
6571 /* Check that the character set matches if it was specified */
6572 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
6573 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
6574 return (1);
6577 char buf[100];
6578 Lisp_Object width = Qnil;
6579 char *charset = NULL;
6581 /* Truetype fonts do not report their true metrics until loaded */
6582 if (FontType != RASTER_FONTTYPE)
6584 if (!NILP (*(lpef->pattern)))
6586 /* Scalable fonts are as big as you want them to be. */
6587 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
6588 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
6589 width = make_number (lpef->logfont.lfWidth);
6591 else
6593 lplf->elfLogFont.lfHeight = 0;
6594 lplf->elfLogFont.lfWidth = 0;
6598 /* Make sure the height used here is the same as everywhere
6599 else (ie character height, not cell height). */
6600 if (lplf->elfLogFont.lfHeight > 0)
6602 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
6603 if (FontType == RASTER_FONTTYPE)
6604 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
6605 else
6606 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
6609 if (!NILP (*(lpef->pattern)))
6611 charset = xlfd_charset_of_font (XSTRING(*(lpef->pattern))->data);
6613 /* Ensure that charset is valid for this font. */
6614 if (charset
6615 && (x_to_w32_charset (charset) != lplf->elfLogFont.lfCharSet))
6616 charset = NULL;
6619 /* TODO: List all relevant charsets if charset not specified. */
6620 if (!w32_to_x_font (&(lplf->elfLogFont), buf, 100, charset))
6621 return (0);
6623 if (NILP (*(lpef->pattern))
6624 || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
6626 *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
6627 lpef->tail = &(XCDR (*lpef->tail));
6628 lpef->numFonts++;
6632 return (1);
6635 static int CALLBACK
6636 enum_font_cb1 (lplf, lptm, FontType, lpef)
6637 ENUMLOGFONT * lplf;
6638 NEWTEXTMETRIC * lptm;
6639 int FontType;
6640 enumfont_t * lpef;
6642 return EnumFontFamilies (lpef->hdc,
6643 lplf->elfLogFont.lfFaceName,
6644 (FONTENUMPROC) enum_font_cb2,
6645 (LPARAM) lpef);
6649 static int CALLBACK
6650 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6651 ENUMLOGFONTEX * lplf;
6652 NEWTEXTMETRICEX * lptm;
6653 int font_type;
6654 enumfont_t * lpef;
6656 /* We are not interested in the extra info we get back from the 'Ex
6657 version - only the fact that we get character set variations
6658 enumerated seperately. */
6659 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6660 font_type, lpef);
6663 static int CALLBACK
6664 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6665 ENUMLOGFONTEX * lplf;
6666 NEWTEXTMETRICEX * lptm;
6667 int font_type;
6668 enumfont_t * lpef;
6670 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6671 FARPROC enum_font_families_ex
6672 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6673 /* We don't really expect EnumFontFamiliesEx to disappear once we
6674 get here, so don't bother handling it gracefully. */
6675 if (enum_font_families_ex == NULL)
6676 error ("gdi32.dll has disappeared!");
6677 return enum_font_families_ex (lpef->hdc,
6678 &lplf->elfLogFont,
6679 (FONTENUMPROC) enum_fontex_cb2,
6680 (LPARAM) lpef, 0);
6683 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6684 and xterm.c in Emacs 20.3) */
6686 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6688 char *fontname, *ptnstr;
6689 Lisp_Object list, tem, newlist = Qnil;
6690 int n_fonts = 0;
6692 list = Vw32_bdf_filename_alist;
6693 ptnstr = XSTRING (pattern)->data;
6695 for ( ; CONSP (list); list = XCDR (list))
6697 tem = XCAR (list);
6698 if (CONSP (tem))
6699 fontname = XSTRING (XCAR (tem))->data;
6700 else if (STRINGP (tem))
6701 fontname = XSTRING (tem)->data;
6702 else
6703 continue;
6705 if (w32_font_match (fontname, ptnstr))
6707 newlist = Fcons (XCAR (tem), newlist);
6708 n_fonts++;
6709 if (n_fonts >= max_names)
6710 break;
6714 return newlist;
6717 static Lisp_Object w32_list_synthesized_fonts (FRAME_PTR f,
6718 Lisp_Object pattern,
6719 int size, int max_names);
6721 /* Return a list of names of available fonts matching PATTERN on frame
6722 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6723 to be listed. Frame F NULL means we have not yet created any
6724 frame, which means we can't get proper size info, as we don't have
6725 a device context to use for GetTextMetrics.
6726 MAXNAMES sets a limit on how many fonts to match. */
6728 Lisp_Object
6729 w32_list_fonts (f, pattern, size, maxnames)
6730 struct frame *f;
6731 Lisp_Object pattern;
6732 int size;
6733 int maxnames;
6735 Lisp_Object patterns, key = Qnil, tem, tpat;
6736 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6737 struct w32_display_info *dpyinfo = &one_w32_display_info;
6738 int n_fonts = 0;
6740 patterns = Fassoc (pattern, Valternate_fontname_alist);
6741 if (NILP (patterns))
6742 patterns = Fcons (pattern, Qnil);
6744 for (; CONSP (patterns); patterns = XCDR (patterns))
6746 enumfont_t ef;
6747 int codepage;
6749 tpat = XCAR (patterns);
6751 if (!STRINGP (tpat))
6752 continue;
6754 /* Avoid expensive EnumFontFamilies functions if we are not
6755 going to be able to output one of these anyway. */
6756 codepage = w32_codepage_for_font (XSTRING (tpat)->data);
6757 if (codepage != CP_8BIT && codepage != CP_UNICODE
6758 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6759 && !IsValidCodePage(codepage))
6760 continue;
6762 /* See if we cached the result for this particular query.
6763 The cache is an alist of the form:
6764 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6766 if (tem = XCDR (dpyinfo->name_list_element),
6767 !NILP (list = Fassoc (tpat, tem)))
6769 list = Fcdr_safe (list);
6770 /* We have a cached list. Don't have to get the list again. */
6771 goto label_cached;
6774 BLOCK_INPUT;
6775 /* At first, put PATTERN in the cache. */
6776 list = Qnil;
6777 ef.pattern = &tpat;
6778 ef.tail = &list;
6779 ef.numFonts = 0;
6781 /* Use EnumFontFamiliesEx where it is available, as it knows
6782 about character sets. Fall back to EnumFontFamilies for
6783 older versions of NT that don't support the 'Ex function. */
6784 x_to_w32_font (XSTRING (tpat)->data, &ef.logfont);
6786 LOGFONT font_match_pattern;
6787 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6788 FARPROC enum_font_families_ex
6789 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6791 /* We do our own pattern matching so we can handle wildcards. */
6792 font_match_pattern.lfFaceName[0] = 0;
6793 font_match_pattern.lfPitchAndFamily = 0;
6794 /* We can use the charset, because if it is a wildcard it will
6795 be DEFAULT_CHARSET anyway. */
6796 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6798 ef.hdc = GetDC (dpyinfo->root_window);
6800 if (enum_font_families_ex)
6801 enum_font_families_ex (ef.hdc,
6802 &font_match_pattern,
6803 (FONTENUMPROC) enum_fontex_cb1,
6804 (LPARAM) &ef, 0);
6805 else
6806 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6807 (LPARAM)&ef);
6809 ReleaseDC (dpyinfo->root_window, ef.hdc);
6812 UNBLOCK_INPUT;
6814 /* Make a list of the fonts we got back.
6815 Store that in the font cache for the display. */
6816 XCDR (dpyinfo->name_list_element)
6817 = Fcons (Fcons (tpat, list),
6818 XCDR (dpyinfo->name_list_element));
6820 label_cached:
6821 if (NILP (list)) continue; /* Try the remaining alternatives. */
6823 newlist = second_best = Qnil;
6825 /* Make a list of the fonts that have the right width. */
6826 for (; CONSP (list); list = XCDR (list))
6828 int found_size;
6829 tem = XCAR (list);
6831 if (!CONSP (tem))
6832 continue;
6833 if (NILP (XCAR (tem)))
6834 continue;
6835 if (!size)
6837 newlist = Fcons (XCAR (tem), newlist);
6838 n_fonts++;
6839 if (n_fonts >= maxnames)
6840 break;
6841 else
6842 continue;
6844 if (!INTEGERP (XCDR (tem)))
6846 /* Since we don't yet know the size of the font, we must
6847 load it and try GetTextMetrics. */
6848 W32FontStruct thisinfo;
6849 LOGFONT lf;
6850 HDC hdc;
6851 HANDLE oldobj;
6853 if (!x_to_w32_font (XSTRING (XCAR (tem))->data, &lf))
6854 continue;
6856 BLOCK_INPUT;
6857 thisinfo.bdf = NULL;
6858 thisinfo.hfont = CreateFontIndirect (&lf);
6859 if (thisinfo.hfont == NULL)
6860 continue;
6862 hdc = GetDC (dpyinfo->root_window);
6863 oldobj = SelectObject (hdc, thisinfo.hfont);
6864 if (GetTextMetrics (hdc, &thisinfo.tm))
6865 XCDR (tem) = make_number (FONT_WIDTH (&thisinfo));
6866 else
6867 XCDR (tem) = make_number (0);
6868 SelectObject (hdc, oldobj);
6869 ReleaseDC (dpyinfo->root_window, hdc);
6870 DeleteObject(thisinfo.hfont);
6871 UNBLOCK_INPUT;
6873 found_size = XINT (XCDR (tem));
6874 if (found_size == size)
6876 newlist = Fcons (XCAR (tem), newlist);
6877 n_fonts++;
6878 if (n_fonts >= maxnames)
6879 break;
6881 /* keep track of the closest matching size in case
6882 no exact match is found. */
6883 else if (found_size > 0)
6885 if (NILP (second_best))
6886 second_best = tem;
6888 else if (found_size < size)
6890 if (XINT (XCDR (second_best)) > size
6891 || XINT (XCDR (second_best)) < found_size)
6892 second_best = tem;
6894 else
6896 if (XINT (XCDR (second_best)) > size
6897 && XINT (XCDR (second_best)) >
6898 found_size)
6899 second_best = tem;
6904 if (!NILP (newlist))
6905 break;
6906 else if (!NILP (second_best))
6908 newlist = Fcons (XCAR (second_best), Qnil);
6909 break;
6913 /* Include any bdf fonts. */
6914 if (n_fonts < maxnames)
6916 Lisp_Object combined[2];
6917 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6918 combined[1] = newlist;
6919 newlist = Fnconc(2, combined);
6922 /* If we can't find a font that matches, check if Windows would be
6923 able to synthesize it from a different style. */
6924 if (NILP (newlist) && !NILP (Vw32_enable_synthesized_fonts))
6925 newlist = w32_list_synthesized_fonts (f, pattern, size, maxnames);
6927 return newlist;
6930 static Lisp_Object
6931 w32_list_synthesized_fonts (f, pattern, size, max_names)
6932 FRAME_PTR f;
6933 Lisp_Object pattern;
6934 int size;
6935 int max_names;
6937 int fields;
6938 char *full_pattn, *new_pattn, foundary[50], family[50], *pattn_part2;
6939 char style[20], slant;
6940 Lisp_Object matches, tem, synthed_matches = Qnil;
6942 full_pattn = XSTRING (pattern)->data;
6944 pattn_part2 = alloca (XSTRING (pattern)->size);
6945 /* Allow some space for wildcard expansion. */
6946 new_pattn = alloca (XSTRING (pattern)->size + 100);
6948 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%19[^-]-%c-%s",
6949 foundary, family, style, &slant, pattn_part2);
6950 if (fields == EOF || fields < 5)
6951 return Qnil;
6953 /* If the style and slant are wildcards already there is no point
6954 checking again (and we don't want to keep recursing). */
6955 if (*style == '*' && slant == '*')
6956 return Qnil;
6958 sprintf (new_pattn, "-%s-%s-*-*-%s", foundary, family, pattn_part2);
6960 matches = w32_list_fonts (f, build_string (new_pattn), size, max_names);
6962 for ( ; CONSP (matches); matches = XCDR (matches))
6964 tem = XCAR (matches);
6965 if (!STRINGP (tem))
6966 continue;
6968 full_pattn = XSTRING (tem)->data;
6969 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%*[^-]-%*c-%s",
6970 foundary, family, pattn_part2);
6971 if (fields == EOF || fields < 3)
6972 continue;
6974 sprintf (new_pattn, "-%s-%s-%s-%c-%s", foundary, family, style,
6975 slant, pattn_part2);
6977 synthed_matches = Fcons (build_string (new_pattn),
6978 synthed_matches);
6981 return synthed_matches;
6985 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6986 struct font_info *
6987 w32_get_font_info (f, font_idx)
6988 FRAME_PTR f;
6989 int font_idx;
6991 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6995 struct font_info*
6996 w32_query_font (struct frame *f, char *fontname)
6998 int i;
6999 struct font_info *pfi;
7001 pfi = FRAME_W32_FONT_TABLE (f);
7003 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
7005 if (strcmp(pfi->name, fontname) == 0) return pfi;
7008 return NULL;
7011 /* Find a CCL program for a font specified by FONTP, and set the member
7012 `encoder' of the structure. */
7014 void
7015 w32_find_ccl_program (fontp)
7016 struct font_info *fontp;
7018 Lisp_Object list, elt;
7020 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7022 elt = XCAR (list);
7023 if (CONSP (elt)
7024 && STRINGP (XCAR (elt))
7025 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7026 >= 0))
7027 break;
7029 if (! NILP (list))
7031 struct ccl_program *ccl
7032 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7034 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7035 xfree (ccl);
7036 else
7037 fontp->font_encoder = ccl;
7042 /* Find BDF files in a specified directory. (use GCPRO when calling,
7043 as this calls lisp to get a directory listing). */
7044 static Lisp_Object
7045 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
7047 Lisp_Object filelist, list = Qnil;
7048 char fontname[100];
7050 if (!STRINGP(directory))
7051 return Qnil;
7053 filelist = Fdirectory_files (directory, Qt,
7054 build_string (".*\\.[bB][dD][fF]"), Qt);
7056 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7058 Lisp_Object filename = XCAR (filelist);
7059 if (w32_BDF_to_x_font (XSTRING (filename)->data, fontname, 100))
7060 store_in_alist (&list, build_string (fontname), filename);
7062 return list;
7065 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
7066 1, 1, 0,
7067 "Return a list of BDF fonts in DIR, suitable for appending to\n\
7068 w32-bdf-filename-alist. Fonts which do not contain an xlfd description\n\
7069 will not be included in the list. DIR may be a list of directories.")
7070 (directory)
7071 Lisp_Object directory;
7073 Lisp_Object list = Qnil;
7074 struct gcpro gcpro1, gcpro2;
7076 if (!CONSP (directory))
7077 return w32_find_bdf_fonts_in_dir (directory);
7079 for ( ; CONSP (directory); directory = XCDR (directory))
7081 Lisp_Object pair[2];
7082 pair[0] = list;
7083 pair[1] = Qnil;
7084 GCPRO2 (directory, list);
7085 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7086 list = Fnconc( 2, pair );
7087 UNGCPRO;
7089 return list;
7093 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7094 "Internal function called by `color-defined-p', which see.")
7095 (color, frame)
7096 Lisp_Object color, frame;
7098 XColor foo;
7099 FRAME_PTR f = check_x_frame (frame);
7101 CHECK_STRING (color, 1);
7103 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7104 return Qt;
7105 else
7106 return Qnil;
7109 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7110 "Internal function called by `color-values', which see.")
7111 (color, frame)
7112 Lisp_Object color, frame;
7114 XColor foo;
7115 FRAME_PTR f = check_x_frame (frame);
7117 CHECK_STRING (color, 1);
7119 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7121 Lisp_Object rgb[3];
7123 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7124 | GetRValue (foo.pixel));
7125 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7126 | GetGValue (foo.pixel));
7127 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7128 | GetBValue (foo.pixel));
7129 return Flist (3, rgb);
7131 else
7132 return Qnil;
7135 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7136 "Internal function called by `display-color-p', which see.")
7137 (display)
7138 Lisp_Object display;
7140 struct w32_display_info *dpyinfo = check_x_display_info (display);
7142 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7143 return Qnil;
7145 return Qt;
7148 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
7149 0, 1, 0,
7150 "Return t if the X display supports shades of gray.\n\
7151 Note that color displays do support shades of gray.\n\
7152 The optional argument DISPLAY specifies which display to ask about.\n\
7153 DISPLAY should be either a frame or a display name (a string).\n\
7154 If omitted or nil, that stands for the selected frame's display.")
7155 (display)
7156 Lisp_Object display;
7158 struct w32_display_info *dpyinfo = check_x_display_info (display);
7160 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7161 return Qnil;
7163 return Qt;
7166 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
7167 0, 1, 0,
7168 "Returns the width in pixels of the X display DISPLAY.\n\
7169 The optional argument DISPLAY specifies which display to ask about.\n\
7170 DISPLAY should be either a frame or a display name (a string).\n\
7171 If omitted or nil, that stands for the selected frame's display.")
7172 (display)
7173 Lisp_Object display;
7175 struct w32_display_info *dpyinfo = check_x_display_info (display);
7177 return make_number (dpyinfo->width);
7180 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7181 Sx_display_pixel_height, 0, 1, 0,
7182 "Returns the height in pixels of the X display DISPLAY.\n\
7183 The optional argument DISPLAY specifies which display to ask about.\n\
7184 DISPLAY should be either a frame or a display name (a string).\n\
7185 If omitted or nil, that stands for the selected frame's display.")
7186 (display)
7187 Lisp_Object display;
7189 struct w32_display_info *dpyinfo = check_x_display_info (display);
7191 return make_number (dpyinfo->height);
7194 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7195 0, 1, 0,
7196 "Returns the number of bitplanes of the display DISPLAY.\n\
7197 The optional argument DISPLAY specifies which display to ask about.\n\
7198 DISPLAY should be either a frame or a display name (a string).\n\
7199 If omitted or nil, that stands for the selected frame's display.")
7200 (display)
7201 Lisp_Object display;
7203 struct w32_display_info *dpyinfo = check_x_display_info (display);
7205 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7208 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7209 0, 1, 0,
7210 "Returns the number of color cells of the display DISPLAY.\n\
7211 The optional argument DISPLAY specifies which display to ask about.\n\
7212 DISPLAY should be either a frame or a display name (a string).\n\
7213 If omitted or nil, that stands for the selected frame's display.")
7214 (display)
7215 Lisp_Object display;
7217 struct w32_display_info *dpyinfo = check_x_display_info (display);
7218 HDC hdc;
7219 int cap;
7221 hdc = GetDC (dpyinfo->root_window);
7222 if (dpyinfo->has_palette)
7223 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7224 else
7225 cap = GetDeviceCaps (hdc,NUMCOLORS);
7227 if (cap < 0)
7228 cap = 1 << (dpyinfo->n_planes * dpyinfo->n_cbits);
7230 ReleaseDC (dpyinfo->root_window, hdc);
7232 return make_number (cap);
7235 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7236 Sx_server_max_request_size,
7237 0, 1, 0,
7238 "Returns the maximum request size of the server of display DISPLAY.\n\
7239 The optional argument DISPLAY specifies which display to ask about.\n\
7240 DISPLAY should be either a frame or a display name (a string).\n\
7241 If omitted or nil, that stands for the selected frame's display.")
7242 (display)
7243 Lisp_Object display;
7245 struct w32_display_info *dpyinfo = check_x_display_info (display);
7247 return make_number (1);
7250 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7251 "Returns the vendor ID string of the W32 system (Microsoft).\n\
7252 The optional argument DISPLAY specifies which display to ask about.\n\
7253 DISPLAY should be either a frame or a display name (a string).\n\
7254 If omitted or nil, that stands for the selected frame's display.")
7255 (display)
7256 Lisp_Object display;
7258 return build_string ("Microsoft Corp.");
7261 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7262 "Returns the version numbers of the server of display DISPLAY.\n\
7263 The value is a list of three integers: the major and minor\n\
7264 version numbers, and the vendor-specific release\n\
7265 number. See also the function `x-server-vendor'.\n\n\
7266 The optional argument DISPLAY specifies which display to ask about.\n\
7267 DISPLAY should be either a frame or a display name (a string).\n\
7268 If omitted or nil, that stands for the selected frame's display.")
7269 (display)
7270 Lisp_Object display;
7272 return Fcons (make_number (w32_major_version),
7273 Fcons (make_number (w32_minor_version),
7274 Fcons (make_number (w32_build_number), Qnil)));
7277 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7278 "Returns the number of screens on the server of display DISPLAY.\n\
7279 The optional argument DISPLAY specifies which display to ask about.\n\
7280 DISPLAY should be either a frame or a display name (a string).\n\
7281 If omitted or nil, that stands for the selected frame's display.")
7282 (display)
7283 Lisp_Object display;
7285 return make_number (1);
7288 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
7289 "Returns the height in millimeters of the X display DISPLAY.\n\
7290 The optional argument DISPLAY specifies which display to ask about.\n\
7291 DISPLAY should be either a frame or a display name (a string).\n\
7292 If omitted or nil, that stands for the selected frame's display.")
7293 (display)
7294 Lisp_Object display;
7296 struct w32_display_info *dpyinfo = check_x_display_info (display);
7297 HDC hdc;
7298 int cap;
7300 hdc = GetDC (dpyinfo->root_window);
7302 cap = GetDeviceCaps (hdc, VERTSIZE);
7304 ReleaseDC (dpyinfo->root_window, hdc);
7306 return make_number (cap);
7309 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7310 "Returns the width in millimeters of the X display DISPLAY.\n\
7311 The optional argument DISPLAY specifies which display to ask about.\n\
7312 DISPLAY should be either a frame or a display name (a string).\n\
7313 If omitted or nil, that stands for the selected frame's display.")
7314 (display)
7315 Lisp_Object display;
7317 struct w32_display_info *dpyinfo = check_x_display_info (display);
7319 HDC hdc;
7320 int cap;
7322 hdc = GetDC (dpyinfo->root_window);
7324 cap = GetDeviceCaps (hdc, HORZSIZE);
7326 ReleaseDC (dpyinfo->root_window, hdc);
7328 return make_number (cap);
7331 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7332 Sx_display_backing_store, 0, 1, 0,
7333 "Returns an indication of whether display DISPLAY does backing store.\n\
7334 The value may be `always', `when-mapped', or `not-useful'.\n\
7335 The optional argument DISPLAY specifies which display to ask about.\n\
7336 DISPLAY should be either a frame or a display name (a string).\n\
7337 If omitted or nil, that stands for the selected frame's display.")
7338 (display)
7339 Lisp_Object display;
7341 return intern ("not-useful");
7344 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7345 Sx_display_visual_class, 0, 1, 0,
7346 "Returns the visual class of the display DISPLAY.\n\
7347 The value is one of the symbols `static-gray', `gray-scale',\n\
7348 `static-color', `pseudo-color', `true-color', or `direct-color'.\n\n\
7349 The optional argument DISPLAY specifies which display to ask about.\n\
7350 DISPLAY should be either a frame or a display name (a string).\n\
7351 If omitted or nil, that stands for the selected frame's display.")
7352 (display)
7353 Lisp_Object display;
7355 struct w32_display_info *dpyinfo = check_x_display_info (display);
7356 Lisp_Object result = Qnil;
7358 if (dpyinfo->has_palette)
7359 result = intern ("pseudo-color");
7360 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
7361 result = intern ("static-grey");
7362 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
7363 result = intern ("static-color");
7364 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
7365 result = intern ("true-color");
7367 return result;
7370 DEFUN ("x-display-save-under", Fx_display_save_under,
7371 Sx_display_save_under, 0, 1, 0,
7372 "Returns t if the display DISPLAY supports the save-under feature.\n\
7373 The optional argument DISPLAY specifies which display to ask about.\n\
7374 DISPLAY should be either a frame or a display name (a string).\n\
7375 If omitted or nil, that stands for the selected frame's display.")
7376 (display)
7377 Lisp_Object display;
7379 return Qnil;
7383 x_pixel_width (f)
7384 register struct frame *f;
7386 return PIXEL_WIDTH (f);
7390 x_pixel_height (f)
7391 register struct frame *f;
7393 return PIXEL_HEIGHT (f);
7397 x_char_width (f)
7398 register struct frame *f;
7400 return FONT_WIDTH (f->output_data.w32->font);
7404 x_char_height (f)
7405 register struct frame *f;
7407 return f->output_data.w32->line_height;
7411 x_screen_planes (f)
7412 register struct frame *f;
7414 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7417 /* Return the display structure for the display named NAME.
7418 Open a new connection if necessary. */
7420 struct w32_display_info *
7421 x_display_info_for_name (name)
7422 Lisp_Object name;
7424 Lisp_Object names;
7425 struct w32_display_info *dpyinfo;
7427 CHECK_STRING (name, 0);
7429 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7430 dpyinfo;
7431 dpyinfo = dpyinfo->next, names = XCDR (names))
7433 Lisp_Object tem;
7434 tem = Fstring_equal (XCAR (XCAR (names)), name);
7435 if (!NILP (tem))
7436 return dpyinfo;
7439 /* Use this general default value to start with. */
7440 Vx_resource_name = Vinvocation_name;
7442 validate_x_resource_name ();
7444 dpyinfo = w32_term_init (name, (unsigned char *)0,
7445 (char *) XSTRING (Vx_resource_name)->data);
7447 if (dpyinfo == 0)
7448 error ("Cannot connect to server %s", XSTRING (name)->data);
7450 w32_in_use = 1;
7451 XSETFASTINT (Vwindow_system_version, 3);
7453 return dpyinfo;
7456 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7457 1, 3, 0, "Open a connection to a server.\n\
7458 DISPLAY is the name of the display to connect to.\n\
7459 Optional second arg XRM-STRING is a string of resources in xrdb format.\n\
7460 If the optional third arg MUST-SUCCEED is non-nil,\n\
7461 terminate Emacs if we can't open the connection.")
7462 (display, xrm_string, must_succeed)
7463 Lisp_Object display, xrm_string, must_succeed;
7465 unsigned char *xrm_option;
7466 struct w32_display_info *dpyinfo;
7468 CHECK_STRING (display, 0);
7469 if (! NILP (xrm_string))
7470 CHECK_STRING (xrm_string, 1);
7472 if (! EQ (Vwindow_system, intern ("w32")))
7473 error ("Not using Microsoft Windows");
7475 /* Allow color mapping to be defined externally; first look in user's
7476 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
7478 Lisp_Object color_file;
7479 struct gcpro gcpro1;
7481 color_file = build_string("~/rgb.txt");
7483 GCPRO1 (color_file);
7485 if (NILP (Ffile_readable_p (color_file)))
7486 color_file =
7487 Fexpand_file_name (build_string ("rgb.txt"),
7488 Fsymbol_value (intern ("data-directory")));
7490 Vw32_color_map = Fw32_load_color_file (color_file);
7492 UNGCPRO;
7494 if (NILP (Vw32_color_map))
7495 Vw32_color_map = Fw32_default_color_map ();
7497 if (! NILP (xrm_string))
7498 xrm_option = (unsigned char *) XSTRING (xrm_string)->data;
7499 else
7500 xrm_option = (unsigned char *) 0;
7502 /* Use this general default value to start with. */
7503 /* First remove .exe suffix from invocation-name - it looks ugly. */
7505 char basename[ MAX_PATH ], *str;
7507 strcpy (basename, XSTRING (Vinvocation_name)->data);
7508 str = strrchr (basename, '.');
7509 if (str) *str = 0;
7510 Vinvocation_name = build_string (basename);
7512 Vx_resource_name = Vinvocation_name;
7514 validate_x_resource_name ();
7516 /* This is what opens the connection and sets x_current_display.
7517 This also initializes many symbols, such as those used for input. */
7518 dpyinfo = w32_term_init (display, xrm_option,
7519 (char *) XSTRING (Vx_resource_name)->data);
7521 if (dpyinfo == 0)
7523 if (!NILP (must_succeed))
7524 fatal ("Cannot connect to server %s.\n",
7525 XSTRING (display)->data);
7526 else
7527 error ("Cannot connect to server %s", XSTRING (display)->data);
7530 w32_in_use = 1;
7532 XSETFASTINT (Vwindow_system_version, 3);
7533 return Qnil;
7536 DEFUN ("x-close-connection", Fx_close_connection,
7537 Sx_close_connection, 1, 1, 0,
7538 "Close the connection to DISPLAY's server.\n\
7539 For DISPLAY, specify either a frame or a display name (a string).\n\
7540 If DISPLAY is nil, that stands for the selected frame's display.")
7541 (display)
7542 Lisp_Object display;
7544 struct w32_display_info *dpyinfo = check_x_display_info (display);
7545 int i;
7547 if (dpyinfo->reference_count > 0)
7548 error ("Display still has frames on it");
7550 BLOCK_INPUT;
7551 /* Free the fonts in the font table. */
7552 for (i = 0; i < dpyinfo->n_fonts; i++)
7553 if (dpyinfo->font_table[i].name)
7555 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
7556 xfree (dpyinfo->font_table[i].full_name);
7557 xfree (dpyinfo->font_table[i].name);
7558 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
7560 x_destroy_all_bitmaps (dpyinfo);
7562 x_delete_display (dpyinfo);
7563 UNBLOCK_INPUT;
7565 return Qnil;
7568 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
7569 "Return the list of display names that Emacs has connections to.")
7572 Lisp_Object tail, result;
7574 result = Qnil;
7575 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
7576 result = Fcons (XCAR (XCAR (tail)), result);
7578 return result;
7581 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7582 "If ON is non-nil, report errors as soon as the erring request is made.\n\
7583 If ON is nil, allow buffering of requests.\n\
7584 This is a noop on W32 systems.\n\
7585 The optional second argument DISPLAY specifies which display to act on.\n\
7586 DISPLAY should be either a frame or a display name (a string).\n\
7587 If DISPLAY is omitted or nil, that stands for the selected frame's display.")
7588 (on, display)
7589 Lisp_Object display, on;
7591 return Qnil;
7596 /***********************************************************************
7597 Image types
7598 ***********************************************************************/
7600 /* Value is the number of elements of vector VECTOR. */
7602 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
7604 /* List of supported image types. Use define_image_type to add new
7605 types. Use lookup_image_type to find a type for a given symbol. */
7607 static struct image_type *image_types;
7609 /* The symbol `image' which is the car of the lists used to represent
7610 images in Lisp. */
7612 extern Lisp_Object Qimage;
7614 /* The symbol `xbm' which is used as the type symbol for XBM images. */
7616 Lisp_Object Qxbm;
7618 /* Keywords. */
7620 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
7621 extern Lisp_Object QCdata;
7622 Lisp_Object QCtype, QCascent, QCmargin, QCrelief;
7623 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
7624 Lisp_Object QCindex;
7626 /* Other symbols. */
7628 Lisp_Object Qlaplace;
7630 /* Time in seconds after which images should be removed from the cache
7631 if not displayed. */
7633 Lisp_Object Vimage_cache_eviction_delay;
7635 /* Function prototypes. */
7637 static void define_image_type P_ ((struct image_type *type));
7638 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
7639 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
7640 static void x_laplace P_ ((struct frame *, struct image *));
7641 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
7642 Lisp_Object));
7645 /* Define a new image type from TYPE. This adds a copy of TYPE to
7646 image_types and adds the symbol *TYPE->type to Vimage_types. */
7648 static void
7649 define_image_type (type)
7650 struct image_type *type;
7652 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
7653 The initialized data segment is read-only. */
7654 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
7655 bcopy (type, p, sizeof *p);
7656 p->next = image_types;
7657 image_types = p;
7658 Vimage_types = Fcons (*p->type, Vimage_types);
7662 /* Look up image type SYMBOL, and return a pointer to its image_type
7663 structure. Value is null if SYMBOL is not a known image type. */
7665 static INLINE struct image_type *
7666 lookup_image_type (symbol)
7667 Lisp_Object symbol;
7669 struct image_type *type;
7671 for (type = image_types; type; type = type->next)
7672 if (EQ (symbol, *type->type))
7673 break;
7675 return type;
7679 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
7680 valid image specification is a list whose car is the symbol
7681 `image', and whose rest is a property list. The property list must
7682 contain a value for key `:type'. That value must be the name of a
7683 supported image type. The rest of the property list depends on the
7684 image type. */
7687 valid_image_p (object)
7688 Lisp_Object object;
7690 int valid_p = 0;
7692 if (CONSP (object) && EQ (XCAR (object), Qimage))
7694 Lisp_Object symbol = Fplist_get (XCDR (object), QCtype);
7695 struct image_type *type = lookup_image_type (symbol);
7697 if (type)
7698 valid_p = type->valid_p (object);
7701 return valid_p;
7705 /* Log error message with format string FORMAT and argument ARG.
7706 Signaling an error, e.g. when an image cannot be loaded, is not a
7707 good idea because this would interrupt redisplay, and the error
7708 message display would lead to another redisplay. This function
7709 therefore simply displays a message. */
7711 static void
7712 image_error (format, arg1, arg2)
7713 char *format;
7714 Lisp_Object arg1, arg2;
7716 add_to_log (format, arg1, arg2);
7721 /***********************************************************************
7722 Image specifications
7723 ***********************************************************************/
7725 enum image_value_type
7727 IMAGE_DONT_CHECK_VALUE_TYPE,
7728 IMAGE_STRING_VALUE,
7729 IMAGE_SYMBOL_VALUE,
7730 IMAGE_POSITIVE_INTEGER_VALUE,
7731 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
7732 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
7733 IMAGE_ASCENT_VALUE,
7734 IMAGE_INTEGER_VALUE,
7735 IMAGE_FUNCTION_VALUE,
7736 IMAGE_NUMBER_VALUE,
7737 IMAGE_BOOL_VALUE
7740 /* Structure used when parsing image specifications. */
7742 struct image_keyword
7744 /* Name of keyword. */
7745 char *name;
7747 /* The type of value allowed. */
7748 enum image_value_type type;
7750 /* Non-zero means key must be present. */
7751 int mandatory_p;
7753 /* Used to recognize duplicate keywords in a property list. */
7754 int count;
7756 /* The value that was found. */
7757 Lisp_Object value;
7761 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7762 int, Lisp_Object));
7763 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7766 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
7767 has the format (image KEYWORD VALUE ...). One of the keyword/
7768 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7769 image_keywords structures of size NKEYWORDS describing other
7770 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7772 static int
7773 parse_image_spec (spec, keywords, nkeywords, type)
7774 Lisp_Object spec;
7775 struct image_keyword *keywords;
7776 int nkeywords;
7777 Lisp_Object type;
7779 int i;
7780 Lisp_Object plist;
7782 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7783 return 0;
7785 plist = XCDR (spec);
7786 while (CONSP (plist))
7788 Lisp_Object key, value;
7790 /* First element of a pair must be a symbol. */
7791 key = XCAR (plist);
7792 plist = XCDR (plist);
7793 if (!SYMBOLP (key))
7794 return 0;
7796 /* There must follow a value. */
7797 if (!CONSP (plist))
7798 return 0;
7799 value = XCAR (plist);
7800 plist = XCDR (plist);
7802 /* Find key in KEYWORDS. Error if not found. */
7803 for (i = 0; i < nkeywords; ++i)
7804 if (strcmp (keywords[i].name, XSYMBOL (key)->name->data) == 0)
7805 break;
7807 if (i == nkeywords)
7808 continue;
7810 /* Record that we recognized the keyword. If a keywords
7811 was found more than once, it's an error. */
7812 keywords[i].value = value;
7813 ++keywords[i].count;
7815 if (keywords[i].count > 1)
7816 return 0;
7818 /* Check type of value against allowed type. */
7819 switch (keywords[i].type)
7821 case IMAGE_STRING_VALUE:
7822 if (!STRINGP (value))
7823 return 0;
7824 break;
7826 case IMAGE_SYMBOL_VALUE:
7827 if (!SYMBOLP (value))
7828 return 0;
7829 break;
7831 case IMAGE_POSITIVE_INTEGER_VALUE:
7832 if (!INTEGERP (value) || XINT (value) <= 0)
7833 return 0;
7834 break;
7836 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
7837 if (INTEGERP (value) && XINT (value) >= 0)
7838 break;
7839 if (CONSP (value)
7840 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
7841 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
7842 break;
7843 return 0;
7845 case IMAGE_ASCENT_VALUE:
7846 if (SYMBOLP (value) && EQ (value, Qcenter))
7847 break;
7848 else if (INTEGERP (value)
7849 && XINT (value) >= 0
7850 && XINT (value) <= 100)
7851 break;
7852 return 0;
7854 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7855 if (!INTEGERP (value) || XINT (value) < 0)
7856 return 0;
7857 break;
7859 case IMAGE_DONT_CHECK_VALUE_TYPE:
7860 break;
7862 case IMAGE_FUNCTION_VALUE:
7863 value = indirect_function (value);
7864 if (SUBRP (value)
7865 || COMPILEDP (value)
7866 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7867 break;
7868 return 0;
7870 case IMAGE_NUMBER_VALUE:
7871 if (!INTEGERP (value) && !FLOATP (value))
7872 return 0;
7873 break;
7875 case IMAGE_INTEGER_VALUE:
7876 if (!INTEGERP (value))
7877 return 0;
7878 break;
7880 case IMAGE_BOOL_VALUE:
7881 if (!NILP (value) && !EQ (value, Qt))
7882 return 0;
7883 break;
7885 default:
7886 abort ();
7887 break;
7890 if (EQ (key, QCtype) && !EQ (type, value))
7891 return 0;
7894 /* Check that all mandatory fields are present. */
7895 for (i = 0; i < nkeywords; ++i)
7896 if (keywords[i].mandatory_p && keywords[i].count == 0)
7897 return 0;
7899 return NILP (plist);
7903 /* Return the value of KEY in image specification SPEC. Value is nil
7904 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7905 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7907 static Lisp_Object
7908 image_spec_value (spec, key, found)
7909 Lisp_Object spec, key;
7910 int *found;
7912 Lisp_Object tail;
7914 xassert (valid_image_p (spec));
7916 for (tail = XCDR (spec);
7917 CONSP (tail) && CONSP (XCDR (tail));
7918 tail = XCDR (XCDR (tail)))
7920 if (EQ (XCAR (tail), key))
7922 if (found)
7923 *found = 1;
7924 return XCAR (XCDR (tail));
7928 if (found)
7929 *found = 0;
7930 return Qnil;
7936 /***********************************************************************
7937 Image type independent image structures
7938 ***********************************************************************/
7940 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7941 static void free_image P_ ((struct frame *f, struct image *img));
7944 /* Allocate and return a new image structure for image specification
7945 SPEC. SPEC has a hash value of HASH. */
7947 static struct image *
7948 make_image (spec, hash)
7949 Lisp_Object spec;
7950 unsigned hash;
7952 struct image *img = (struct image *) xmalloc (sizeof *img);
7954 xassert (valid_image_p (spec));
7955 bzero (img, sizeof *img);
7956 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7957 xassert (img->type != NULL);
7958 img->spec = spec;
7959 img->data.lisp_val = Qnil;
7960 img->ascent = DEFAULT_IMAGE_ASCENT;
7961 img->hash = hash;
7962 return img;
7966 /* Free image IMG which was used on frame F, including its resources. */
7968 static void
7969 free_image (f, img)
7970 struct frame *f;
7971 struct image *img;
7973 if (img)
7975 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7977 /* Remove IMG from the hash table of its cache. */
7978 if (img->prev)
7979 img->prev->next = img->next;
7980 else
7981 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7983 if (img->next)
7984 img->next->prev = img->prev;
7986 c->images[img->id] = NULL;
7988 /* Free resources, then free IMG. */
7989 img->type->free (f, img);
7990 xfree (img);
7995 /* Prepare image IMG for display on frame F. Must be called before
7996 drawing an image. */
7998 void
7999 prepare_image_for_display (f, img)
8000 struct frame *f;
8001 struct image *img;
8003 EMACS_TIME t;
8005 /* We're about to display IMG, so set its timestamp to `now'. */
8006 EMACS_GET_TIME (t);
8007 img->timestamp = EMACS_SECS (t);
8009 /* If IMG doesn't have a pixmap yet, load it now, using the image
8010 type dependent loader function. */
8011 if (img->pixmap == 0 && !img->load_failed_p)
8012 img->load_failed_p = img->type->load (f, img) == 0;
8016 /* Value is the number of pixels for the ascent of image IMG when
8017 drawn in face FACE. */
8020 image_ascent (img, face)
8021 struct image *img;
8022 struct face *face;
8024 int height = img->height + img->vmargin;
8025 int ascent;
8027 if (img->ascent == CENTERED_IMAGE_ASCENT)
8029 if (face->font)
8030 ascent = height / 2 - (FONT_DESCENT(face->font)
8031 - FONT_BASE(face->font)) / 2;
8032 else
8033 ascent = height / 2;
8035 else
8036 ascent = height * img->ascent / 100.0;
8038 return ascent;
8043 /***********************************************************************
8044 Helper functions for X image types
8045 ***********************************************************************/
8047 static void x_clear_image P_ ((struct frame *f, struct image *img));
8048 static unsigned long x_alloc_image_color P_ ((struct frame *f,
8049 struct image *img,
8050 Lisp_Object color_name,
8051 unsigned long dflt));
8053 /* Free X resources of image IMG which is used on frame F. */
8055 static void
8056 x_clear_image (f, img)
8057 struct frame *f;
8058 struct image *img;
8060 #if 0 /* TODO: W32 image support */
8062 if (img->pixmap)
8064 BLOCK_INPUT;
8065 XFreePixmap (NULL, img->pixmap);
8066 img->pixmap = 0;
8067 UNBLOCK_INPUT;
8070 if (img->ncolors)
8072 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8074 /* If display has an immutable color map, freeing colors is not
8075 necessary and some servers don't allow it. So don't do it. */
8076 if (class != StaticColor
8077 && class != StaticGray
8078 && class != TrueColor)
8080 Colormap cmap;
8081 BLOCK_INPUT;
8082 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8083 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8084 img->ncolors, 0);
8085 UNBLOCK_INPUT;
8088 xfree (img->colors);
8089 img->colors = NULL;
8090 img->ncolors = 0;
8092 #endif
8096 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8097 cannot be allocated, use DFLT. Add a newly allocated color to
8098 IMG->colors, so that it can be freed again. Value is the pixel
8099 color. */
8101 static unsigned long
8102 x_alloc_image_color (f, img, color_name, dflt)
8103 struct frame *f;
8104 struct image *img;
8105 Lisp_Object color_name;
8106 unsigned long dflt;
8108 #if 0 /* TODO: allocing colors. */
8109 XColor color;
8110 unsigned long result;
8112 xassert (STRINGP (color_name));
8114 if (w32_defined_color (f, XSTRING (color_name)->data, &color, 1))
8116 /* This isn't called frequently so we get away with simply
8117 reallocating the color vector to the needed size, here. */
8118 ++img->ncolors;
8119 img->colors =
8120 (unsigned long *) xrealloc (img->colors,
8121 img->ncolors * sizeof *img->colors);
8122 img->colors[img->ncolors - 1] = color.pixel;
8123 result = color.pixel;
8125 else
8126 result = dflt;
8127 return result;
8128 #endif
8129 return 0;
8134 /***********************************************************************
8135 Image Cache
8136 ***********************************************************************/
8138 static void cache_image P_ ((struct frame *f, struct image *img));
8141 /* Return a new, initialized image cache that is allocated from the
8142 heap. Call free_image_cache to free an image cache. */
8144 struct image_cache *
8145 make_image_cache ()
8147 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8148 int size;
8150 bzero (c, sizeof *c);
8151 c->size = 50;
8152 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8153 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8154 c->buckets = (struct image **) xmalloc (size);
8155 bzero (c->buckets, size);
8156 return c;
8160 /* Free image cache of frame F. Be aware that X frames share images
8161 caches. */
8163 void
8164 free_image_cache (f)
8165 struct frame *f;
8167 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8168 if (c)
8170 int i;
8172 /* Cache should not be referenced by any frame when freed. */
8173 xassert (c->refcount == 0);
8175 for (i = 0; i < c->used; ++i)
8176 free_image (f, c->images[i]);
8177 xfree (c->images);
8178 xfree (c);
8179 xfree (c->buckets);
8180 FRAME_X_IMAGE_CACHE (f) = NULL;
8185 /* Clear image cache of frame F. FORCE_P non-zero means free all
8186 images. FORCE_P zero means clear only images that haven't been
8187 displayed for some time. Should be called from time to time to
8188 reduce the number of loaded images. If image-eviction-seconds is
8189 non-nil, this frees images in the cache which weren't displayed for
8190 at least that many seconds. */
8192 void
8193 clear_image_cache (f, force_p)
8194 struct frame *f;
8195 int force_p;
8197 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8199 if (c && INTEGERP (Vimage_cache_eviction_delay))
8201 EMACS_TIME t;
8202 unsigned long old;
8203 int i, any_freed_p = 0;
8205 EMACS_GET_TIME (t);
8206 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8208 for (i = 0; i < c->used; ++i)
8210 struct image *img = c->images[i];
8211 if (img != NULL
8212 && (force_p
8213 || (img->timestamp > old)))
8215 free_image (f, img);
8216 any_freed_p = 1;
8220 /* We may be clearing the image cache because, for example,
8221 Emacs was iconified for a longer period of time. In that
8222 case, current matrices may still contain references to
8223 images freed above. So, clear these matrices. */
8224 if (any_freed_p)
8226 clear_current_matrices (f);
8227 ++windows_or_buffers_changed;
8233 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
8234 0, 1, 0,
8235 "Clear the image cache of FRAME.\n\
8236 FRAME nil or omitted means use the selected frame.\n\
8237 FRAME t means clear the image caches of all frames.")
8238 (frame)
8239 Lisp_Object frame;
8241 if (EQ (frame, Qt))
8243 Lisp_Object tail;
8245 FOR_EACH_FRAME (tail, frame)
8246 if (FRAME_W32_P (XFRAME (frame)))
8247 clear_image_cache (XFRAME (frame), 1);
8249 else
8250 clear_image_cache (check_x_frame (frame), 1);
8252 return Qnil;
8256 /* Return the id of image with Lisp specification SPEC on frame F.
8257 SPEC must be a valid Lisp image specification (see valid_image_p). */
8260 lookup_image (f, spec)
8261 struct frame *f;
8262 Lisp_Object spec;
8264 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8265 struct image *img;
8266 int i;
8267 unsigned hash;
8268 struct gcpro gcpro1;
8269 EMACS_TIME now;
8271 /* F must be a window-system frame, and SPEC must be a valid image
8272 specification. */
8273 xassert (FRAME_WINDOW_P (f));
8274 xassert (valid_image_p (spec));
8276 GCPRO1 (spec);
8278 /* Look up SPEC in the hash table of the image cache. */
8279 hash = sxhash (spec, 0);
8280 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
8282 for (img = c->buckets[i]; img; img = img->next)
8283 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
8284 break;
8286 /* If not found, create a new image and cache it. */
8287 if (img == NULL)
8289 BLOCK_INPUT;
8290 img = make_image (spec, hash);
8291 cache_image (f, img);
8292 img->load_failed_p = img->type->load (f, img) == 0;
8294 /* If we can't load the image, and we don't have a width and
8295 height, use some arbitrary width and height so that we can
8296 draw a rectangle for it. */
8297 if (img->load_failed_p)
8299 Lisp_Object value;
8301 value = image_spec_value (spec, QCwidth, NULL);
8302 img->width = (INTEGERP (value)
8303 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
8304 value = image_spec_value (spec, QCheight, NULL);
8305 img->height = (INTEGERP (value)
8306 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
8308 else
8310 /* Handle image type independent image attributes
8311 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF'. */
8312 Lisp_Object ascent, margin, relief;
8314 ascent = image_spec_value (spec, QCascent, NULL);
8315 if (INTEGERP (ascent))
8316 img->ascent = XFASTINT (ascent);
8317 else if (EQ (ascent, Qcenter))
8318 img->ascent = CENTERED_IMAGE_ASCENT;
8320 margin = image_spec_value (spec, QCmargin, NULL);
8321 if (INTEGERP (margin) && XINT (margin) >= 0)
8322 img->vmargin = img->hmargin = XFASTINT (margin);
8323 else if (CONSP (margin) && INTEGERP (XCAR (margin))
8324 && INTEGERP (XCDR (margin)))
8326 if (XINT (XCAR (margin)) > 0)
8327 img->hmargin = XFASTINT (XCAR (margin));
8328 if (XINT (XCDR (margin)) > 0)
8329 img->vmargin = XFASTINT (XCDR (margin));
8332 relief = image_spec_value (spec, QCrelief, NULL);
8333 if (INTEGERP (relief))
8335 img->relief = XINT (relief);
8336 img->hmargin += abs (img->relief);
8337 img->vmargin += abs (img->relief);
8340 #if 0 /* TODO: image mask and algorithm. */
8341 /* Manipulation of the image's mask. */
8342 if (img->pixmap)
8344 /* `:heuristic-mask t'
8345 `:mask heuristic'
8346 means build a mask heuristically.
8347 `:heuristic-mask (R G B)'
8348 `:mask (heuristic (R G B))'
8349 means build a mask from color (R G B) in the
8350 image.
8351 `:mask nil'
8352 means remove a mask, if any. */
8354 Lisp_Object mask;
8356 mask = image_spec_value (spec, QCheuristic_mask, NULL);
8357 if (!NILP (mask))
8358 x_build_heuristic_mask (f, img, mask);
8359 else
8361 int found_p;
8363 mask = image_spec_value (spec, QCmask, &found_p);
8365 if (EQ (mask, Qheuristic))
8366 x_build_heuristic_mask (f, img, Qt);
8367 else if (CONSP (mask)
8368 && EQ (XCAR (mask), Qheuristic))
8370 if (CONSP (XCDR (mask)))
8371 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
8372 else
8373 x_build_heuristic_mask (f, img, XCDR (mask));
8375 else if (NILP (mask) && found_p && img->mask)
8377 XFreePixmap (FRAME_X_DISPLAY (f), img->mask);
8378 img->mask = None;
8383 /* Should we apply an image transformation algorithm? */
8384 if (img->pixmap)
8386 Lisp_Object conversion;
8388 algorithm = image_spec_value (spec, QCconversion, NULL);
8389 if (EQ (conversion, Qdisabled))
8390 x_disable_image (f, img);
8391 else if (EQ (conversion, Qlaplace))
8392 x_laplace (f, img);
8393 else if (EQ (conversion, Qemboss))
8394 x_emboss (f, img);
8395 else if (CONSP (conversion)
8396 && EQ (XCAR (conversion), Qedge_detection))
8398 Lisp_Object tem;
8399 tem = XCDR (conversion);
8400 if (CONSP (tem))
8401 x_edge_detection (f, img,
8402 Fplist_get (tem, QCmatrix),
8403 Fplist_get (tem, QCcolor_adjustment));
8406 #endif /* TODO. */
8408 UNBLOCK_INPUT;
8409 xassert (!interrupt_input_blocked);
8412 /* We're using IMG, so set its timestamp to `now'. */
8413 EMACS_GET_TIME (now);
8414 img->timestamp = EMACS_SECS (now);
8416 UNGCPRO;
8418 /* Value is the image id. */
8419 return img->id;
8423 /* Cache image IMG in the image cache of frame F. */
8425 static void
8426 cache_image (f, img)
8427 struct frame *f;
8428 struct image *img;
8430 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8431 int i;
8433 /* Find a free slot in c->images. */
8434 for (i = 0; i < c->used; ++i)
8435 if (c->images[i] == NULL)
8436 break;
8438 /* If no free slot found, maybe enlarge c->images. */
8439 if (i == c->used && c->used == c->size)
8441 c->size *= 2;
8442 c->images = (struct image **) xrealloc (c->images,
8443 c->size * sizeof *c->images);
8446 /* Add IMG to c->images, and assign IMG an id. */
8447 c->images[i] = img;
8448 img->id = i;
8449 if (i == c->used)
8450 ++c->used;
8452 /* Add IMG to the cache's hash table. */
8453 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8454 img->next = c->buckets[i];
8455 if (img->next)
8456 img->next->prev = img;
8457 img->prev = NULL;
8458 c->buckets[i] = img;
8462 /* Call FN on every image in the image cache of frame F. Used to mark
8463 Lisp Objects in the image cache. */
8465 void
8466 forall_images_in_image_cache (f, fn)
8467 struct frame *f;
8468 void (*fn) P_ ((struct image *img));
8470 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8472 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8473 if (c)
8475 int i;
8476 for (i = 0; i < c->used; ++i)
8477 if (c->images[i])
8478 fn (c->images[i]);
8485 /***********************************************************************
8486 W32 support code
8487 ***********************************************************************/
8489 #if 0 /* TODO: W32 specific image code. */
8491 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8492 XImage **, Pixmap *));
8493 static void x_destroy_x_image P_ ((XImage *));
8494 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8497 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8498 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8499 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
8500 via xmalloc. Print error messages via image_error if an error
8501 occurs. Value is non-zero if successful. */
8503 static int
8504 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8505 struct frame *f;
8506 int width, height, depth;
8507 XImage **ximg;
8508 Pixmap *pixmap;
8510 #if 0 /* TODO: Image support for W32 */
8511 Display *display = FRAME_W32_DISPLAY (f);
8512 Screen *screen = FRAME_X_SCREEN (f);
8513 Window window = FRAME_W32_WINDOW (f);
8515 xassert (interrupt_input_blocked);
8517 if (depth <= 0)
8518 depth = DefaultDepthOfScreen (screen);
8519 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
8520 depth, ZPixmap, 0, NULL, width, height,
8521 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
8522 if (*ximg == NULL)
8524 image_error ("Unable to allocate X image", Qnil, Qnil);
8525 return 0;
8528 /* Allocate image raster. */
8529 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
8531 /* Allocate a pixmap of the same size. */
8532 *pixmap = XCreatePixmap (display, window, width, height, depth);
8533 if (*pixmap == 0)
8535 x_destroy_x_image (*ximg);
8536 *ximg = NULL;
8537 image_error ("Unable to create X pixmap", Qnil, Qnil);
8538 return 0;
8540 #endif
8541 return 1;
8545 /* Destroy XImage XIMG. Free XIMG->data. */
8547 static void
8548 x_destroy_x_image (ximg)
8549 XImage *ximg;
8551 xassert (interrupt_input_blocked);
8552 if (ximg)
8554 xfree (ximg->data);
8555 ximg->data = NULL;
8556 XDestroyImage (ximg);
8561 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8562 are width and height of both the image and pixmap. */
8564 static void
8565 x_put_x_image (f, ximg, pixmap, width, height)
8566 struct frame *f;
8567 XImage *ximg;
8568 Pixmap pixmap;
8570 GC gc;
8572 xassert (interrupt_input_blocked);
8573 gc = XCreateGC (NULL, pixmap, 0, NULL);
8574 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
8575 XFreeGC (NULL, gc);
8578 #endif
8581 /***********************************************************************
8582 Searching files
8583 ***********************************************************************/
8585 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
8587 /* Find image file FILE. Look in data-directory, then
8588 x-bitmap-file-path. Value is the full name of the file found, or
8589 nil if not found. */
8591 static Lisp_Object
8592 x_find_image_file (file)
8593 Lisp_Object file;
8595 Lisp_Object file_found, search_path;
8596 struct gcpro gcpro1, gcpro2;
8597 int fd;
8599 file_found = Qnil;
8600 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8601 GCPRO2 (file_found, search_path);
8603 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
8604 fd = openp (search_path, file, "", &file_found, 0);
8606 if (fd == -1)
8607 file_found = Qnil;
8608 else
8609 close (fd);
8611 UNGCPRO;
8612 return file_found;
8617 /***********************************************************************
8618 XBM images
8619 ***********************************************************************/
8621 static int xbm_load P_ ((struct frame *f, struct image *img));
8622 static int xbm_load_image_from_file P_ ((struct frame *f, struct image *img,
8623 Lisp_Object file));
8624 static int xbm_image_p P_ ((Lisp_Object object));
8625 static int xbm_read_bitmap_file_data P_ ((char *, int *, int *,
8626 unsigned char **));
8629 /* Indices of image specification fields in xbm_format, below. */
8631 enum xbm_keyword_index
8633 XBM_TYPE,
8634 XBM_FILE,
8635 XBM_WIDTH,
8636 XBM_HEIGHT,
8637 XBM_DATA,
8638 XBM_FOREGROUND,
8639 XBM_BACKGROUND,
8640 XBM_ASCENT,
8641 XBM_MARGIN,
8642 XBM_RELIEF,
8643 XBM_ALGORITHM,
8644 XBM_HEURISTIC_MASK,
8645 XBM_LAST
8648 /* Vector of image_keyword structures describing the format
8649 of valid XBM image specifications. */
8651 static struct image_keyword xbm_format[XBM_LAST] =
8653 {":type", IMAGE_SYMBOL_VALUE, 1},
8654 {":file", IMAGE_STRING_VALUE, 0},
8655 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8656 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8657 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8658 {":foreground", IMAGE_STRING_VALUE, 0},
8659 {":background", IMAGE_STRING_VALUE, 0},
8660 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8661 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8662 {":relief", IMAGE_INTEGER_VALUE, 0},
8663 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8664 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8667 /* Structure describing the image type XBM. */
8669 static struct image_type xbm_type =
8671 &Qxbm,
8672 xbm_image_p,
8673 xbm_load,
8674 x_clear_image,
8675 NULL
8678 /* Tokens returned from xbm_scan. */
8680 enum xbm_token
8682 XBM_TK_IDENT = 256,
8683 XBM_TK_NUMBER
8687 /* Return non-zero if OBJECT is a valid XBM-type image specification.
8688 A valid specification is a list starting with the symbol `image'
8689 The rest of the list is a property list which must contain an
8690 entry `:type xbm..
8692 If the specification specifies a file to load, it must contain
8693 an entry `:file FILENAME' where FILENAME is a string.
8695 If the specification is for a bitmap loaded from memory it must
8696 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8697 WIDTH and HEIGHT are integers > 0. DATA may be:
8699 1. a string large enough to hold the bitmap data, i.e. it must
8700 have a size >= (WIDTH + 7) / 8 * HEIGHT
8702 2. a bool-vector of size >= WIDTH * HEIGHT
8704 3. a vector of strings or bool-vectors, one for each line of the
8705 bitmap.
8707 Both the file and data forms may contain the additional entries
8708 `:background COLOR' and `:foreground COLOR'. If not present,
8709 foreground and background of the frame on which the image is
8710 displayed, is used. */
8712 static int
8713 xbm_image_p (object)
8714 Lisp_Object object;
8716 struct image_keyword kw[XBM_LAST];
8718 bcopy (xbm_format, kw, sizeof kw);
8719 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8720 return 0;
8722 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8724 if (kw[XBM_FILE].count)
8726 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8727 return 0;
8729 else
8731 Lisp_Object data;
8732 int width, height;
8734 /* Entries for `:width', `:height' and `:data' must be present. */
8735 if (!kw[XBM_WIDTH].count
8736 || !kw[XBM_HEIGHT].count
8737 || !kw[XBM_DATA].count)
8738 return 0;
8740 data = kw[XBM_DATA].value;
8741 width = XFASTINT (kw[XBM_WIDTH].value);
8742 height = XFASTINT (kw[XBM_HEIGHT].value);
8744 /* Check type of data, and width and height against contents of
8745 data. */
8746 if (VECTORP (data))
8748 int i;
8750 /* Number of elements of the vector must be >= height. */
8751 if (XVECTOR (data)->size < height)
8752 return 0;
8754 /* Each string or bool-vector in data must be large enough
8755 for one line of the image. */
8756 for (i = 0; i < height; ++i)
8758 Lisp_Object elt = XVECTOR (data)->contents[i];
8760 if (STRINGP (elt))
8762 if (XSTRING (elt)->size
8763 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8764 return 0;
8766 else if (BOOL_VECTOR_P (elt))
8768 if (XBOOL_VECTOR (elt)->size < width)
8769 return 0;
8771 else
8772 return 0;
8775 else if (STRINGP (data))
8777 if (XSTRING (data)->size
8778 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8779 return 0;
8781 else if (BOOL_VECTOR_P (data))
8783 if (XBOOL_VECTOR (data)->size < width * height)
8784 return 0;
8786 else
8787 return 0;
8790 /* Baseline must be a value between 0 and 100 (a percentage). */
8791 if (kw[XBM_ASCENT].count
8792 && XFASTINT (kw[XBM_ASCENT].value) > 100)
8793 return 0;
8795 return 1;
8799 /* Scan a bitmap file. FP is the stream to read from. Value is
8800 either an enumerator from enum xbm_token, or a character for a
8801 single-character token, or 0 at end of file. If scanning an
8802 identifier, store the lexeme of the identifier in SVAL. If
8803 scanning a number, store its value in *IVAL. */
8805 static int
8806 xbm_scan (fp, sval, ival)
8807 FILE *fp;
8808 char *sval;
8809 int *ival;
8811 int c;
8813 /* Skip white space. */
8814 while ((c = fgetc (fp)) != EOF && isspace (c))
8817 if (c == EOF)
8818 c = 0;
8819 else if (isdigit (c))
8821 int value = 0, digit;
8823 if (c == '0')
8825 c = fgetc (fp);
8826 if (c == 'x' || c == 'X')
8828 while ((c = fgetc (fp)) != EOF)
8830 if (isdigit (c))
8831 digit = c - '0';
8832 else if (c >= 'a' && c <= 'f')
8833 digit = c - 'a' + 10;
8834 else if (c >= 'A' && c <= 'F')
8835 digit = c - 'A' + 10;
8836 else
8837 break;
8838 value = 16 * value + digit;
8841 else if (isdigit (c))
8843 value = c - '0';
8844 while ((c = fgetc (fp)) != EOF
8845 && isdigit (c))
8846 value = 8 * value + c - '0';
8849 else
8851 value = c - '0';
8852 while ((c = fgetc (fp)) != EOF
8853 && isdigit (c))
8854 value = 10 * value + c - '0';
8857 if (c != EOF)
8858 ungetc (c, fp);
8859 *ival = value;
8860 c = XBM_TK_NUMBER;
8862 else if (isalpha (c) || c == '_')
8864 *sval++ = c;
8865 while ((c = fgetc (fp)) != EOF
8866 && (isalnum (c) || c == '_'))
8867 *sval++ = c;
8868 *sval = 0;
8869 if (c != EOF)
8870 ungetc (c, fp);
8871 c = XBM_TK_IDENT;
8874 return c;
8878 /* Replacement for XReadBitmapFileData which isn't available under old
8879 X versions. FILE is the name of the bitmap file to read. Set
8880 *WIDTH and *HEIGHT to the width and height of the image. Return in
8881 *DATA the bitmap data allocated with xmalloc. Value is non-zero if
8882 successful. */
8884 static int
8885 xbm_read_bitmap_file_data (file, width, height, data)
8886 char *file;
8887 int *width, *height;
8888 unsigned char **data;
8890 FILE *fp;
8891 char buffer[BUFSIZ];
8892 int padding_p = 0;
8893 int v10 = 0;
8894 int bytes_per_line, i, nbytes;
8895 unsigned char *p;
8896 int value;
8897 int LA1;
8899 #define match() \
8900 LA1 = xbm_scan (fp, buffer, &value)
8902 #define expect(TOKEN) \
8903 if (LA1 != (TOKEN)) \
8904 goto failure; \
8905 else \
8906 match ()
8908 #define expect_ident(IDENT) \
8909 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8910 match (); \
8911 else \
8912 goto failure
8914 fp = fopen (file, "r");
8915 if (fp == NULL)
8916 return 0;
8918 *width = *height = -1;
8919 *data = NULL;
8920 LA1 = xbm_scan (fp, buffer, &value);
8922 /* Parse defines for width, height and hot-spots. */
8923 while (LA1 == '#')
8925 match ();
8926 expect_ident ("define");
8927 expect (XBM_TK_IDENT);
8929 if (LA1 == XBM_TK_NUMBER);
8931 char *p = strrchr (buffer, '_');
8932 p = p ? p + 1 : buffer;
8933 if (strcmp (p, "width") == 0)
8934 *width = value;
8935 else if (strcmp (p, "height") == 0)
8936 *height = value;
8938 expect (XBM_TK_NUMBER);
8941 if (*width < 0 || *height < 0)
8942 goto failure;
8944 /* Parse bits. Must start with `static'. */
8945 expect_ident ("static");
8946 if (LA1 == XBM_TK_IDENT)
8948 if (strcmp (buffer, "unsigned") == 0)
8950 match ();
8951 expect_ident ("char");
8953 else if (strcmp (buffer, "short") == 0)
8955 match ();
8956 v10 = 1;
8957 if (*width % 16 && *width % 16 < 9)
8958 padding_p = 1;
8960 else if (strcmp (buffer, "char") == 0)
8961 match ();
8962 else
8963 goto failure;
8965 else
8966 goto failure;
8968 expect (XBM_TK_IDENT);
8969 expect ('[');
8970 expect (']');
8971 expect ('=');
8972 expect ('{');
8974 bytes_per_line = (*width + 7) / 8 + padding_p;
8975 nbytes = bytes_per_line * *height;
8976 p = *data = (char *) xmalloc (nbytes);
8978 if (v10)
8981 for (i = 0; i < nbytes; i += 2)
8983 int val = value;
8984 expect (XBM_TK_NUMBER);
8986 *p++ = val;
8987 if (!padding_p || ((i + 2) % bytes_per_line))
8988 *p++ = value >> 8;
8990 if (LA1 == ',' || LA1 == '}')
8991 match ();
8992 else
8993 goto failure;
8996 else
8998 for (i = 0; i < nbytes; ++i)
9000 int val = value;
9001 expect (XBM_TK_NUMBER);
9003 *p++ = val;
9005 if (LA1 == ',' || LA1 == '}')
9006 match ();
9007 else
9008 goto failure;
9012 fclose (fp);
9013 return 1;
9015 failure:
9017 fclose (fp);
9018 if (*data)
9020 xfree (*data);
9021 *data = NULL;
9023 return 0;
9025 #undef match
9026 #undef expect
9027 #undef expect_ident
9031 /* Load XBM image IMG which will be displayed on frame F from file
9032 SPECIFIED_FILE. Value is non-zero if successful. */
9034 static int
9035 xbm_load_image_from_file (f, img, specified_file)
9036 struct frame *f;
9037 struct image *img;
9038 Lisp_Object specified_file;
9040 int rc;
9041 unsigned char *data;
9042 int success_p = 0;
9043 Lisp_Object file;
9044 struct gcpro gcpro1;
9046 xassert (STRINGP (specified_file));
9047 file = Qnil;
9048 GCPRO1 (file);
9050 file = x_find_image_file (specified_file);
9051 if (!STRINGP (file))
9053 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9054 UNGCPRO;
9055 return 0;
9058 rc = xbm_read_bitmap_file_data (XSTRING (file)->data, &img->width,
9059 &img->height, &data);
9060 if (rc)
9062 int depth = one_w32_display_info.n_cbits;
9063 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9064 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9065 Lisp_Object value;
9067 xassert (img->width > 0 && img->height > 0);
9069 /* Get foreground and background colors, maybe allocate colors. */
9070 value = image_spec_value (img->spec, QCforeground, NULL);
9071 if (!NILP (value))
9072 foreground = x_alloc_image_color (f, img, value, foreground);
9074 value = image_spec_value (img->spec, QCbackground, NULL);
9075 if (!NILP (value))
9076 background = x_alloc_image_color (f, img, value, background);
9078 #if 0 /* TODO : Port image display to W32 */
9079 BLOCK_INPUT;
9080 img->pixmap
9081 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
9082 FRAME_W32_WINDOW (f),
9083 data,
9084 img->width, img->height,
9085 foreground, background,
9086 depth);
9087 xfree (data);
9089 if (img->pixmap == 0)
9091 x_clear_image (f, img);
9092 image_error ("Unable to create X pixmap for `%s'", file, Qnil);
9094 else
9095 success_p = 1;
9097 UNBLOCK_INPUT;
9098 #endif
9100 else
9101 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
9103 UNGCPRO;
9104 return success_p;
9108 /* Fill image IMG which is used on frame F with pixmap data. Value is
9109 non-zero if successful. */
9111 static int
9112 xbm_load (f, img)
9113 struct frame *f;
9114 struct image *img;
9116 int success_p = 0;
9117 Lisp_Object file_name;
9119 xassert (xbm_image_p (img->spec));
9121 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9122 file_name = image_spec_value (img->spec, QCfile, NULL);
9123 if (STRINGP (file_name))
9124 success_p = xbm_load_image_from_file (f, img, file_name);
9125 else
9127 struct image_keyword fmt[XBM_LAST];
9128 Lisp_Object data;
9129 int depth;
9130 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9131 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9132 char *bits;
9133 int parsed_p;
9135 /* Parse the list specification. */
9136 bcopy (xbm_format, fmt, sizeof fmt);
9137 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
9138 xassert (parsed_p);
9140 /* Get specified width, and height. */
9141 img->width = XFASTINT (fmt[XBM_WIDTH].value);
9142 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
9143 xassert (img->width > 0 && img->height > 0);
9145 BLOCK_INPUT;
9147 if (fmt[XBM_ASCENT].count)
9148 img->ascent = XFASTINT (fmt[XBM_ASCENT].value);
9150 /* Get foreground and background colors, maybe allocate colors. */
9151 if (fmt[XBM_FOREGROUND].count)
9152 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
9153 foreground);
9154 if (fmt[XBM_BACKGROUND].count)
9155 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
9156 background);
9158 /* Set bits to the bitmap image data. */
9159 data = fmt[XBM_DATA].value;
9160 if (VECTORP (data))
9162 int i;
9163 char *p;
9164 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
9166 p = bits = (char *) alloca (nbytes * img->height);
9167 for (i = 0; i < img->height; ++i, p += nbytes)
9169 Lisp_Object line = XVECTOR (data)->contents[i];
9170 if (STRINGP (line))
9171 bcopy (XSTRING (line)->data, p, nbytes);
9172 else
9173 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
9176 else if (STRINGP (data))
9177 bits = XSTRING (data)->data;
9178 else
9179 bits = XBOOL_VECTOR (data)->data;
9181 #if 0 /* TODO : W32 XPM code */
9182 /* Create the pixmap. */
9183 depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
9184 img->pixmap
9185 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
9186 FRAME_W32_WINDOW (f),
9187 bits,
9188 img->width, img->height,
9189 foreground, background,
9190 depth);
9191 #endif /* TODO */
9193 if (img->pixmap)
9194 success_p = 1;
9195 else
9197 image_error ("Unable to create pixmap for XBM image `%s'",
9198 img->spec, Qnil);
9199 x_clear_image (f, img);
9202 UNBLOCK_INPUT;
9205 return success_p;
9210 /***********************************************************************
9211 XPM images
9212 ***********************************************************************/
9214 #if HAVE_XPM
9216 static int xpm_image_p P_ ((Lisp_Object object));
9217 static int xpm_load P_ ((struct frame *f, struct image *img));
9218 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
9220 #include "X11/xpm.h"
9222 /* The symbol `xpm' identifying XPM-format images. */
9224 Lisp_Object Qxpm;
9226 /* Indices of image specification fields in xpm_format, below. */
9228 enum xpm_keyword_index
9230 XPM_TYPE,
9231 XPM_FILE,
9232 XPM_DATA,
9233 XPM_ASCENT,
9234 XPM_MARGIN,
9235 XPM_RELIEF,
9236 XPM_ALGORITHM,
9237 XPM_HEURISTIC_MASK,
9238 XPM_COLOR_SYMBOLS,
9239 XPM_LAST
9242 /* Vector of image_keyword structures describing the format
9243 of valid XPM image specifications. */
9245 static struct image_keyword xpm_format[XPM_LAST] =
9247 {":type", IMAGE_SYMBOL_VALUE, 1},
9248 {":file", IMAGE_STRING_VALUE, 0},
9249 {":data", IMAGE_STRING_VALUE, 0},
9250 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9251 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9252 {":relief", IMAGE_INTEGER_VALUE, 0},
9253 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9254 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9255 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9258 /* Structure describing the image type XBM. */
9260 static struct image_type xpm_type =
9262 &Qxpm,
9263 xpm_image_p,
9264 xpm_load,
9265 x_clear_image,
9266 NULL
9270 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9271 for XPM images. Such a list must consist of conses whose car and
9272 cdr are strings. */
9274 static int
9275 xpm_valid_color_symbols_p (color_symbols)
9276 Lisp_Object color_symbols;
9278 while (CONSP (color_symbols))
9280 Lisp_Object sym = XCAR (color_symbols);
9281 if (!CONSP (sym)
9282 || !STRINGP (XCAR (sym))
9283 || !STRINGP (XCDR (sym)))
9284 break;
9285 color_symbols = XCDR (color_symbols);
9288 return NILP (color_symbols);
9292 /* Value is non-zero if OBJECT is a valid XPM image specification. */
9294 static int
9295 xpm_image_p (object)
9296 Lisp_Object object;
9298 struct image_keyword fmt[XPM_LAST];
9299 bcopy (xpm_format, fmt, sizeof fmt);
9300 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9301 /* Either `:file' or `:data' must be present. */
9302 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9303 /* Either no `:color-symbols' or it's a list of conses
9304 whose car and cdr are strings. */
9305 && (fmt[XPM_COLOR_SYMBOLS].count == 0
9306 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
9307 && (fmt[XPM_ASCENT].count == 0
9308 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
9312 /* Load image IMG which will be displayed on frame F. Value is
9313 non-zero if successful. */
9315 static int
9316 xpm_load (f, img)
9317 struct frame *f;
9318 struct image *img;
9320 int rc, i;
9321 XpmAttributes attrs;
9322 Lisp_Object specified_file, color_symbols;
9324 /* Configure the XPM lib. Use the visual of frame F. Allocate
9325 close colors. Return colors allocated. */
9326 bzero (&attrs, sizeof attrs);
9327 attrs.visual = FRAME_X_VISUAL (f);
9328 attrs.colormap = FRAME_X_COLORMAP (f);
9329 attrs.valuemask |= XpmVisual;
9330 attrs.valuemask |= XpmColormap;
9331 attrs.valuemask |= XpmReturnAllocPixels;
9332 #ifdef XpmAllocCloseColors
9333 attrs.alloc_close_colors = 1;
9334 attrs.valuemask |= XpmAllocCloseColors;
9335 #else
9336 attrs.closeness = 600;
9337 attrs.valuemask |= XpmCloseness;
9338 #endif
9340 /* If image specification contains symbolic color definitions, add
9341 these to `attrs'. */
9342 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
9343 if (CONSP (color_symbols))
9345 Lisp_Object tail;
9346 XpmColorSymbol *xpm_syms;
9347 int i, size;
9349 attrs.valuemask |= XpmColorSymbols;
9351 /* Count number of symbols. */
9352 attrs.numsymbols = 0;
9353 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
9354 ++attrs.numsymbols;
9356 /* Allocate an XpmColorSymbol array. */
9357 size = attrs.numsymbols * sizeof *xpm_syms;
9358 xpm_syms = (XpmColorSymbol *) alloca (size);
9359 bzero (xpm_syms, size);
9360 attrs.colorsymbols = xpm_syms;
9362 /* Fill the color symbol array. */
9363 for (tail = color_symbols, i = 0;
9364 CONSP (tail);
9365 ++i, tail = XCDR (tail))
9367 Lisp_Object name = XCAR (XCAR (tail));
9368 Lisp_Object color = XCDR (XCAR (tail));
9369 xpm_syms[i].name = (char *) alloca (XSTRING (name)->size + 1);
9370 strcpy (xpm_syms[i].name, XSTRING (name)->data);
9371 xpm_syms[i].value = (char *) alloca (XSTRING (color)->size + 1);
9372 strcpy (xpm_syms[i].value, XSTRING (color)->data);
9376 /* Create a pixmap for the image, either from a file, or from a
9377 string buffer containing data in the same format as an XPM file. */
9378 BLOCK_INPUT;
9379 specified_file = image_spec_value (img->spec, QCfile, NULL);
9380 if (STRINGP (specified_file))
9382 Lisp_Object file = x_find_image_file (specified_file);
9383 if (!STRINGP (file))
9385 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9386 UNBLOCK_INPUT;
9387 return 0;
9390 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
9391 XSTRING (file)->data, &img->pixmap, &img->mask,
9392 &attrs);
9394 else
9396 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
9397 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
9398 XSTRING (buffer)->data,
9399 &img->pixmap, &img->mask,
9400 &attrs);
9402 UNBLOCK_INPUT;
9404 if (rc == XpmSuccess)
9406 /* Remember allocated colors. */
9407 img->ncolors = attrs.nalloc_pixels;
9408 img->colors = (unsigned long *) xmalloc (img->ncolors
9409 * sizeof *img->colors);
9410 for (i = 0; i < attrs.nalloc_pixels; ++i)
9411 img->colors[i] = attrs.alloc_pixels[i];
9413 img->width = attrs.width;
9414 img->height = attrs.height;
9415 xassert (img->width > 0 && img->height > 0);
9417 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
9418 BLOCK_INPUT;
9419 XpmFreeAttributes (&attrs);
9420 UNBLOCK_INPUT;
9422 else
9424 switch (rc)
9426 case XpmOpenFailed:
9427 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9428 break;
9430 case XpmFileInvalid:
9431 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9432 break;
9434 case XpmNoMemory:
9435 image_error ("Out of memory (%s)", img->spec, Qnil);
9436 break;
9438 case XpmColorFailed:
9439 image_error ("Color allocation error (%s)", img->spec, Qnil);
9440 break;
9442 default:
9443 image_error ("Unknown error (%s)", img->spec, Qnil);
9444 break;
9448 return rc == XpmSuccess;
9451 #endif /* HAVE_XPM != 0 */
9454 #if 0 /* TODO : Color tables on W32. */
9455 /***********************************************************************
9456 Color table
9457 ***********************************************************************/
9459 /* An entry in the color table mapping an RGB color to a pixel color. */
9461 struct ct_color
9463 int r, g, b;
9464 unsigned long pixel;
9466 /* Next in color table collision list. */
9467 struct ct_color *next;
9470 /* The bucket vector size to use. Must be prime. */
9472 #define CT_SIZE 101
9474 /* Value is a hash of the RGB color given by R, G, and B. */
9476 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9478 /* The color hash table. */
9480 struct ct_color **ct_table;
9482 /* Number of entries in the color table. */
9484 int ct_colors_allocated;
9486 /* Function prototypes. */
9488 static void init_color_table P_ ((void));
9489 static void free_color_table P_ ((void));
9490 static unsigned long *colors_in_color_table P_ ((int *n));
9491 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9492 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9495 /* Initialize the color table. */
9497 static void
9498 init_color_table ()
9500 int size = CT_SIZE * sizeof (*ct_table);
9501 ct_table = (struct ct_color **) xmalloc (size);
9502 bzero (ct_table, size);
9503 ct_colors_allocated = 0;
9507 /* Free memory associated with the color table. */
9509 static void
9510 free_color_table ()
9512 int i;
9513 struct ct_color *p, *next;
9515 for (i = 0; i < CT_SIZE; ++i)
9516 for (p = ct_table[i]; p; p = next)
9518 next = p->next;
9519 xfree (p);
9522 xfree (ct_table);
9523 ct_table = NULL;
9527 /* Value is a pixel color for RGB color R, G, B on frame F. If an
9528 entry for that color already is in the color table, return the
9529 pixel color of that entry. Otherwise, allocate a new color for R,
9530 G, B, and make an entry in the color table. */
9532 static unsigned long
9533 lookup_rgb_color (f, r, g, b)
9534 struct frame *f;
9535 int r, g, b;
9537 unsigned hash = CT_HASH_RGB (r, g, b);
9538 int i = hash % CT_SIZE;
9539 struct ct_color *p;
9541 for (p = ct_table[i]; p; p = p->next)
9542 if (p->r == r && p->g == g && p->b == b)
9543 break;
9545 if (p == NULL)
9547 COLORREF color;
9548 Colormap cmap;
9549 int rc;
9551 color = PALETTERGB (r, g, b);
9553 ++ct_colors_allocated;
9555 p = (struct ct_color *) xmalloc (sizeof *p);
9556 p->r = r;
9557 p->g = g;
9558 p->b = b;
9559 p->pixel = color;
9560 p->next = ct_table[i];
9561 ct_table[i] = p;
9564 return p->pixel;
9568 /* Look up pixel color PIXEL which is used on frame F in the color
9569 table. If not already present, allocate it. Value is PIXEL. */
9571 static unsigned long
9572 lookup_pixel_color (f, pixel)
9573 struct frame *f;
9574 unsigned long pixel;
9576 int i = pixel % CT_SIZE;
9577 struct ct_color *p;
9579 for (p = ct_table[i]; p; p = p->next)
9580 if (p->pixel == pixel)
9581 break;
9583 if (p == NULL)
9585 XColor color;
9586 Colormap cmap;
9587 int rc;
9589 BLOCK_INPUT;
9591 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9592 color.pixel = pixel;
9593 XQueryColor (NULL, cmap, &color);
9594 rc = x_alloc_nearest_color (f, cmap, &color);
9595 UNBLOCK_INPUT;
9597 if (rc)
9599 ++ct_colors_allocated;
9601 p = (struct ct_color *) xmalloc (sizeof *p);
9602 p->r = color.red;
9603 p->g = color.green;
9604 p->b = color.blue;
9605 p->pixel = pixel;
9606 p->next = ct_table[i];
9607 ct_table[i] = p;
9609 else
9610 return FRAME_FOREGROUND_PIXEL (f);
9612 return p->pixel;
9616 /* Value is a vector of all pixel colors contained in the color table,
9617 allocated via xmalloc. Set *N to the number of colors. */
9619 static unsigned long *
9620 colors_in_color_table (n)
9621 int *n;
9623 int i, j;
9624 struct ct_color *p;
9625 unsigned long *colors;
9627 if (ct_colors_allocated == 0)
9629 *n = 0;
9630 colors = NULL;
9632 else
9634 colors = (unsigned long *) xmalloc (ct_colors_allocated
9635 * sizeof *colors);
9636 *n = ct_colors_allocated;
9638 for (i = j = 0; i < CT_SIZE; ++i)
9639 for (p = ct_table[i]; p; p = p->next)
9640 colors[j++] = p->pixel;
9643 return colors;
9646 #endif /* TODO */
9649 /***********************************************************************
9650 Algorithms
9651 ***********************************************************************/
9653 #if 0 /* TODO : W32 versions of low level algorithms */
9654 static void x_laplace_write_row P_ ((struct frame *, long *,
9655 int, XImage *, int));
9656 static void x_laplace_read_row P_ ((struct frame *, Colormap,
9657 XColor *, int, XImage *, int));
9660 /* Fill COLORS with RGB colors from row Y of image XIMG. F is the
9661 frame we operate on, CMAP is the color-map in effect, and WIDTH is
9662 the width of one row in the image. */
9664 static void
9665 x_laplace_read_row (f, cmap, colors, width, ximg, y)
9666 struct frame *f;
9667 Colormap cmap;
9668 XColor *colors;
9669 int width;
9670 XImage *ximg;
9671 int y;
9673 int x;
9675 for (x = 0; x < width; ++x)
9676 colors[x].pixel = XGetPixel (ximg, x, y);
9678 XQueryColors (NULL, cmap, colors, width);
9682 /* Write row Y of image XIMG. PIXELS is an array of WIDTH longs
9683 containing the pixel colors to write. F is the frame we are
9684 working on. */
9686 static void
9687 x_laplace_write_row (f, pixels, width, ximg, y)
9688 struct frame *f;
9689 long *pixels;
9690 int width;
9691 XImage *ximg;
9692 int y;
9694 int x;
9696 for (x = 0; x < width; ++x)
9697 XPutPixel (ximg, x, y, pixels[x]);
9699 #endif
9701 /* Transform image IMG which is used on frame F with a Laplace
9702 edge-detection algorithm. The result is an image that can be used
9703 to draw disabled buttons, for example. */
9705 static void
9706 x_laplace (f, img)
9707 struct frame *f;
9708 struct image *img;
9710 #if 0 /* TODO : W32 version */
9711 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9712 XImage *ximg, *oimg;
9713 XColor *in[3];
9714 long *out;
9715 Pixmap pixmap;
9716 int x, y, i;
9717 long pixel;
9718 int in_y, out_y, rc;
9719 int mv2 = 45000;
9721 BLOCK_INPUT;
9723 /* Get the X image IMG->pixmap. */
9724 ximg = XGetImage (NULL, img->pixmap,
9725 0, 0, img->width, img->height, ~0, ZPixmap);
9727 /* Allocate 3 input rows, and one output row of colors. */
9728 for (i = 0; i < 3; ++i)
9729 in[i] = (XColor *) alloca (img->width * sizeof (XColor));
9730 out = (long *) alloca (img->width * sizeof (long));
9732 /* Create an X image for output. */
9733 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9734 &oimg, &pixmap);
9736 /* Fill first two rows. */
9737 x_laplace_read_row (f, cmap, in[0], img->width, ximg, 0);
9738 x_laplace_read_row (f, cmap, in[1], img->width, ximg, 1);
9739 in_y = 2;
9741 /* Write first row, all zeros. */
9742 init_color_table ();
9743 pixel = lookup_rgb_color (f, 0, 0, 0);
9744 for (x = 0; x < img->width; ++x)
9745 out[x] = pixel;
9746 x_laplace_write_row (f, out, img->width, oimg, 0);
9747 out_y = 1;
9749 for (y = 2; y < img->height; ++y)
9751 int rowa = y % 3;
9752 int rowb = (y + 2) % 3;
9754 x_laplace_read_row (f, cmap, in[rowa], img->width, ximg, in_y++);
9756 for (x = 0; x < img->width - 2; ++x)
9758 int r = in[rowa][x].red + mv2 - in[rowb][x + 2].red;
9759 int g = in[rowa][x].green + mv2 - in[rowb][x + 2].green;
9760 int b = in[rowa][x].blue + mv2 - in[rowb][x + 2].blue;
9762 out[x + 1] = lookup_rgb_color (f, r & 0xffff, g & 0xffff,
9763 b & 0xffff);
9766 x_laplace_write_row (f, out, img->width, oimg, out_y++);
9769 /* Write last line, all zeros. */
9770 for (x = 0; x < img->width; ++x)
9771 out[x] = pixel;
9772 x_laplace_write_row (f, out, img->width, oimg, out_y);
9774 /* Free the input image, and free resources of IMG. */
9775 XDestroyImage (ximg);
9776 x_clear_image (f, img);
9778 /* Put the output image into pixmap, and destroy it. */
9779 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9780 x_destroy_x_image (oimg);
9782 /* Remember new pixmap and colors in IMG. */
9783 img->pixmap = pixmap;
9784 img->colors = colors_in_color_table (&img->ncolors);
9785 free_color_table ();
9787 UNBLOCK_INPUT;
9788 #endif /* TODO */
9792 /* Build a mask for image IMG which is used on frame F. FILE is the
9793 name of an image file, for error messages. HOW determines how to
9794 determine the background color of IMG. If it is a list '(R G B)',
9795 with R, G, and B being integers >= 0, take that as the color of the
9796 background. Otherwise, determine the background color of IMG
9797 heuristically. Value is non-zero if successful. */
9799 static int
9800 x_build_heuristic_mask (f, img, how)
9801 struct frame *f;
9802 struct image *img;
9803 Lisp_Object how;
9805 #if 0 /* TODO : W32 version */
9806 Display *dpy = FRAME_W32_DISPLAY (f);
9807 XImage *ximg, *mask_img;
9808 int x, y, rc, look_at_corners_p;
9809 unsigned long bg;
9811 BLOCK_INPUT;
9813 /* Create an image and pixmap serving as mask. */
9814 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
9815 &mask_img, &img->mask);
9816 if (!rc)
9818 UNBLOCK_INPUT;
9819 return 0;
9822 /* Get the X image of IMG->pixmap. */
9823 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
9824 ~0, ZPixmap);
9826 /* Determine the background color of ximg. If HOW is `(R G B)'
9827 take that as color. Otherwise, try to determine the color
9828 heuristically. */
9829 look_at_corners_p = 1;
9831 if (CONSP (how))
9833 int rgb[3], i = 0;
9835 while (i < 3
9836 && CONSP (how)
9837 && NATNUMP (XCAR (how)))
9839 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9840 how = XCDR (how);
9843 if (i == 3 && NILP (how))
9845 char color_name[30];
9846 XColor exact, color;
9847 Colormap cmap;
9849 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
9851 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9852 if (XLookupColor (dpy, cmap, color_name, &exact, &color))
9854 bg = color.pixel;
9855 look_at_corners_p = 0;
9860 if (look_at_corners_p)
9862 unsigned long corners[4];
9863 int i, best_count;
9865 /* Get the colors at the corners of ximg. */
9866 corners[0] = XGetPixel (ximg, 0, 0);
9867 corners[1] = XGetPixel (ximg, img->width - 1, 0);
9868 corners[2] = XGetPixel (ximg, img->width - 1, img->height - 1);
9869 corners[3] = XGetPixel (ximg, 0, img->height - 1);
9871 /* Choose the most frequently found color as background. */
9872 for (i = best_count = 0; i < 4; ++i)
9874 int j, n;
9876 for (j = n = 0; j < 4; ++j)
9877 if (corners[i] == corners[j])
9878 ++n;
9880 if (n > best_count)
9881 bg = corners[i], best_count = n;
9885 /* Set all bits in mask_img to 1 whose color in ximg is different
9886 from the background color bg. */
9887 for (y = 0; y < img->height; ++y)
9888 for (x = 0; x < img->width; ++x)
9889 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
9891 /* Put mask_img into img->mask. */
9892 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
9893 x_destroy_x_image (mask_img);
9894 XDestroyImage (ximg);
9896 UNBLOCK_INPUT;
9897 #endif /* TODO */
9899 return 1;
9904 /***********************************************************************
9905 PBM (mono, gray, color)
9906 ***********************************************************************/
9907 #ifdef HAVE_PBM
9909 static int pbm_image_p P_ ((Lisp_Object object));
9910 static int pbm_load P_ ((struct frame *f, struct image *img));
9911 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
9913 /* The symbol `pbm' identifying images of this type. */
9915 Lisp_Object Qpbm;
9917 /* Indices of image specification fields in gs_format, below. */
9919 enum pbm_keyword_index
9921 PBM_TYPE,
9922 PBM_FILE,
9923 PBM_DATA,
9924 PBM_ASCENT,
9925 PBM_MARGIN,
9926 PBM_RELIEF,
9927 PBM_ALGORITHM,
9928 PBM_HEURISTIC_MASK,
9929 PBM_LAST
9932 /* Vector of image_keyword structures describing the format
9933 of valid user-defined image specifications. */
9935 static struct image_keyword pbm_format[PBM_LAST] =
9937 {":type", IMAGE_SYMBOL_VALUE, 1},
9938 {":file", IMAGE_STRING_VALUE, 0},
9939 {":data", IMAGE_STRING_VALUE, 0},
9940 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9941 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9942 {":relief", IMAGE_INTEGER_VALUE, 0},
9943 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9944 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9947 /* Structure describing the image type `pbm'. */
9949 static struct image_type pbm_type =
9951 &Qpbm,
9952 pbm_image_p,
9953 pbm_load,
9954 x_clear_image,
9955 NULL
9959 /* Return non-zero if OBJECT is a valid PBM image specification. */
9961 static int
9962 pbm_image_p (object)
9963 Lisp_Object object;
9965 struct image_keyword fmt[PBM_LAST];
9967 bcopy (pbm_format, fmt, sizeof fmt);
9969 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
9970 || (fmt[PBM_ASCENT].count
9971 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
9972 return 0;
9974 /* Must specify either :data or :file. */
9975 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
9979 /* Scan a decimal number from *S and return it. Advance *S while
9980 reading the number. END is the end of the string. Value is -1 at
9981 end of input. */
9983 static int
9984 pbm_scan_number (s, end)
9985 unsigned char **s, *end;
9987 int c, val = -1;
9989 while (*s < end)
9991 /* Skip white-space. */
9992 while (*s < end && (c = *(*s)++, isspace (c)))
9995 if (c == '#')
9997 /* Skip comment to end of line. */
9998 while (*s < end && (c = *(*s)++, c != '\n'))
10001 else if (isdigit (c))
10003 /* Read decimal number. */
10004 val = c - '0';
10005 while (*s < end && (c = *(*s)++, isdigit (c)))
10006 val = 10 * val + c - '0';
10007 break;
10009 else
10010 break;
10013 return val;
10017 /* Read FILE into memory. Value is a pointer to a buffer allocated
10018 with xmalloc holding FILE's contents. Value is null if an error
10019 occured. *SIZE is set to the size of the file. */
10021 static char *
10022 pbm_read_file (file, size)
10023 Lisp_Object file;
10024 int *size;
10026 FILE *fp = NULL;
10027 char *buf = NULL;
10028 struct stat st;
10030 if (stat (XSTRING (file)->data, &st) == 0
10031 && (fp = fopen (XSTRING (file)->data, "r")) != NULL
10032 && (buf = (char *) xmalloc (st.st_size),
10033 fread (buf, 1, st.st_size, fp) == st.st_size))
10035 *size = st.st_size;
10036 fclose (fp);
10038 else
10040 if (fp)
10041 fclose (fp);
10042 if (buf)
10044 xfree (buf);
10045 buf = NULL;
10049 return buf;
10053 /* Load PBM image IMG for use on frame F. */
10055 static int
10056 pbm_load (f, img)
10057 struct frame *f;
10058 struct image *img;
10060 int raw_p, x, y;
10061 int width, height, max_color_idx = 0;
10062 XImage *ximg;
10063 Lisp_Object file, specified_file;
10064 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
10065 struct gcpro gcpro1;
10066 unsigned char *contents = NULL;
10067 unsigned char *end, *p;
10068 int size;
10070 specified_file = image_spec_value (img->spec, QCfile, NULL);
10071 file = Qnil;
10072 GCPRO1 (file);
10074 if (STRINGP (specified_file))
10076 file = x_find_image_file (specified_file);
10077 if (!STRINGP (file))
10079 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10080 UNGCPRO;
10081 return 0;
10084 contents = pbm_read_file (file, &size);
10085 if (contents == NULL)
10087 image_error ("Error reading `%s'", file, Qnil);
10088 UNGCPRO;
10089 return 0;
10092 p = contents;
10093 end = contents + size;
10095 else
10097 Lisp_Object data;
10098 data = image_spec_value (img->spec, QCdata, NULL);
10099 p = XSTRING (data)->data;
10100 end = p + STRING_BYTES (XSTRING (data));
10103 /* Check magic number. */
10104 if (end - p < 2 || *p++ != 'P')
10106 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10107 error:
10108 xfree (contents);
10109 UNGCPRO;
10110 return 0;
10113 switch (*p++)
10115 case '1':
10116 raw_p = 0, type = PBM_MONO;
10117 break;
10119 case '2':
10120 raw_p = 0, type = PBM_GRAY;
10121 break;
10123 case '3':
10124 raw_p = 0, type = PBM_COLOR;
10125 break;
10127 case '4':
10128 raw_p = 1, type = PBM_MONO;
10129 break;
10131 case '5':
10132 raw_p = 1, type = PBM_GRAY;
10133 break;
10135 case '6':
10136 raw_p = 1, type = PBM_COLOR;
10137 break;
10139 default:
10140 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10141 goto error;
10144 /* Read width, height, maximum color-component. Characters
10145 starting with `#' up to the end of a line are ignored. */
10146 width = pbm_scan_number (&p, end);
10147 height = pbm_scan_number (&p, end);
10149 if (type != PBM_MONO)
10151 max_color_idx = pbm_scan_number (&p, end);
10152 if (raw_p && max_color_idx > 255)
10153 max_color_idx = 255;
10156 if (width < 0
10157 || height < 0
10158 || (type != PBM_MONO && max_color_idx < 0))
10159 goto error;
10161 BLOCK_INPUT;
10162 if (!x_create_x_image_and_pixmap (f, width, height, 0,
10163 &ximg, &img->pixmap))
10165 UNBLOCK_INPUT;
10166 goto error;
10169 /* Initialize the color hash table. */
10170 init_color_table ();
10172 if (type == PBM_MONO)
10174 int c = 0, g;
10176 for (y = 0; y < height; ++y)
10177 for (x = 0; x < width; ++x)
10179 if (raw_p)
10181 if ((x & 7) == 0)
10182 c = *p++;
10183 g = c & 0x80;
10184 c <<= 1;
10186 else
10187 g = pbm_scan_number (&p, end);
10189 XPutPixel (ximg, x, y, (g
10190 ? FRAME_FOREGROUND_PIXEL (f)
10191 : FRAME_BACKGROUND_PIXEL (f)));
10194 else
10196 for (y = 0; y < height; ++y)
10197 for (x = 0; x < width; ++x)
10199 int r, g, b;
10201 if (type == PBM_GRAY)
10202 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
10203 else if (raw_p)
10205 r = *p++;
10206 g = *p++;
10207 b = *p++;
10209 else
10211 r = pbm_scan_number (&p, end);
10212 g = pbm_scan_number (&p, end);
10213 b = pbm_scan_number (&p, end);
10216 if (r < 0 || g < 0 || b < 0)
10218 xfree (ximg->data);
10219 ximg->data = NULL;
10220 XDestroyImage (ximg);
10221 UNBLOCK_INPUT;
10222 image_error ("Invalid pixel value in image `%s'",
10223 img->spec, Qnil);
10224 goto error;
10227 /* RGB values are now in the range 0..max_color_idx.
10228 Scale this to the range 0..0xffff supported by X. */
10229 r = (double) r * 65535 / max_color_idx;
10230 g = (double) g * 65535 / max_color_idx;
10231 b = (double) b * 65535 / max_color_idx;
10232 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10236 /* Store in IMG->colors the colors allocated for the image, and
10237 free the color table. */
10238 img->colors = colors_in_color_table (&img->ncolors);
10239 free_color_table ();
10241 /* Put the image into a pixmap. */
10242 x_put_x_image (f, ximg, img->pixmap, width, height);
10243 x_destroy_x_image (ximg);
10244 UNBLOCK_INPUT;
10246 img->width = width;
10247 img->height = height;
10249 UNGCPRO;
10250 xfree (contents);
10251 return 1;
10253 #endif /* HAVE_PBM */
10256 /***********************************************************************
10258 ***********************************************************************/
10260 #if HAVE_PNG
10262 #include <png.h>
10264 /* Function prototypes. */
10266 static int png_image_p P_ ((Lisp_Object object));
10267 static int png_load P_ ((struct frame *f, struct image *img));
10269 /* The symbol `png' identifying images of this type. */
10271 Lisp_Object Qpng;
10273 /* Indices of image specification fields in png_format, below. */
10275 enum png_keyword_index
10277 PNG_TYPE,
10278 PNG_DATA,
10279 PNG_FILE,
10280 PNG_ASCENT,
10281 PNG_MARGIN,
10282 PNG_RELIEF,
10283 PNG_ALGORITHM,
10284 PNG_HEURISTIC_MASK,
10285 PNG_LAST
10288 /* Vector of image_keyword structures describing the format
10289 of valid user-defined image specifications. */
10291 static struct image_keyword png_format[PNG_LAST] =
10293 {":type", IMAGE_SYMBOL_VALUE, 1},
10294 {":data", IMAGE_STRING_VALUE, 0},
10295 {":file", IMAGE_STRING_VALUE, 0},
10296 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10297 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10298 {":relief", IMAGE_INTEGER_VALUE, 0},
10299 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10300 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10303 /* Structure describing the image type `png'. */
10305 static struct image_type png_type =
10307 &Qpng,
10308 png_image_p,
10309 png_load,
10310 x_clear_image,
10311 NULL
10315 /* Return non-zero if OBJECT is a valid PNG image specification. */
10317 static int
10318 png_image_p (object)
10319 Lisp_Object object;
10321 struct image_keyword fmt[PNG_LAST];
10322 bcopy (png_format, fmt, sizeof fmt);
10324 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
10325 || (fmt[PNG_ASCENT].count
10326 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
10327 return 0;
10329 /* Must specify either the :data or :file keyword. */
10330 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
10334 /* Error and warning handlers installed when the PNG library
10335 is initialized. */
10337 static void
10338 my_png_error (png_ptr, msg)
10339 png_struct *png_ptr;
10340 char *msg;
10342 xassert (png_ptr != NULL);
10343 image_error ("PNG error: %s", build_string (msg), Qnil);
10344 longjmp (png_ptr->jmpbuf, 1);
10348 static void
10349 my_png_warning (png_ptr, msg)
10350 png_struct *png_ptr;
10351 char *msg;
10353 xassert (png_ptr != NULL);
10354 image_error ("PNG warning: %s", build_string (msg), Qnil);
10357 /* Memory source for PNG decoding. */
10359 struct png_memory_storage
10361 unsigned char *bytes; /* The data */
10362 size_t len; /* How big is it? */
10363 int index; /* Where are we? */
10367 /* Function set as reader function when reading PNG image from memory.
10368 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
10369 bytes from the input to DATA. */
10371 static void
10372 png_read_from_memory (png_ptr, data, length)
10373 png_structp png_ptr;
10374 png_bytep data;
10375 png_size_t length;
10377 struct png_memory_storage *tbr
10378 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
10380 if (length > tbr->len - tbr->index)
10381 png_error (png_ptr, "Read error");
10383 bcopy (tbr->bytes + tbr->index, data, length);
10384 tbr->index = tbr->index + length;
10387 /* Load PNG image IMG for use on frame F. Value is non-zero if
10388 successful. */
10390 static int
10391 png_load (f, img)
10392 struct frame *f;
10393 struct image *img;
10395 Lisp_Object file, specified_file;
10396 Lisp_Object specified_data;
10397 int x, y, i;
10398 XImage *ximg, *mask_img = NULL;
10399 struct gcpro gcpro1;
10400 png_struct *png_ptr = NULL;
10401 png_info *info_ptr = NULL, *end_info = NULL;
10402 FILE *fp = NULL;
10403 png_byte sig[8];
10404 png_byte *pixels = NULL;
10405 png_byte **rows = NULL;
10406 png_uint_32 width, height;
10407 int bit_depth, color_type, interlace_type;
10408 png_byte channels;
10409 png_uint_32 row_bytes;
10410 int transparent_p;
10411 char *gamma_str;
10412 double screen_gamma, image_gamma;
10413 int intent;
10414 struct png_memory_storage tbr; /* Data to be read */
10416 /* Find out what file to load. */
10417 specified_file = image_spec_value (img->spec, QCfile, NULL);
10418 specified_data = image_spec_value (img->spec, QCdata, NULL);
10419 file = Qnil;
10420 GCPRO1 (file);
10422 if (NILP (specified_data))
10424 file = x_find_image_file (specified_file);
10425 if (!STRINGP (file))
10427 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10428 UNGCPRO;
10429 return 0;
10432 /* Open the image file. */
10433 fp = fopen (XSTRING (file)->data, "rb");
10434 if (!fp)
10436 image_error ("Cannot open image file `%s'", file, Qnil);
10437 UNGCPRO;
10438 fclose (fp);
10439 return 0;
10442 /* Check PNG signature. */
10443 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
10444 || !png_check_sig (sig, sizeof sig))
10446 image_error ("Not a PNG file:` %s'", file, Qnil);
10447 UNGCPRO;
10448 fclose (fp);
10449 return 0;
10452 else
10454 /* Read from memory. */
10455 tbr.bytes = XSTRING (specified_data)->data;
10456 tbr.len = STRING_BYTES (XSTRING (specified_data));
10457 tbr.index = 0;
10459 /* Check PNG signature. */
10460 if (tbr.len < sizeof sig
10461 || !png_check_sig (tbr.bytes, sizeof sig))
10463 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10464 UNGCPRO;
10465 return 0;
10468 /* Need to skip past the signature. */
10469 tbr.bytes += sizeof (sig);
10472 /* Initialize read and info structs for PNG lib. */
10473 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10474 my_png_error, my_png_warning);
10475 if (!png_ptr)
10477 if (fp) fclose (fp);
10478 UNGCPRO;
10479 return 0;
10482 info_ptr = png_create_info_struct (png_ptr);
10483 if (!info_ptr)
10485 png_destroy_read_struct (&png_ptr, NULL, NULL);
10486 if (fp) fclose (fp);
10487 UNGCPRO;
10488 return 0;
10491 end_info = png_create_info_struct (png_ptr);
10492 if (!end_info)
10494 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
10495 if (fp) fclose (fp);
10496 UNGCPRO;
10497 return 0;
10500 /* Set error jump-back. We come back here when the PNG library
10501 detects an error. */
10502 if (setjmp (png_ptr->jmpbuf))
10504 error:
10505 if (png_ptr)
10506 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10507 xfree (pixels);
10508 xfree (rows);
10509 if (fp) fclose (fp);
10510 UNGCPRO;
10511 return 0;
10514 /* Read image info. */
10515 if (!NILP (specified_data))
10516 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
10517 else
10518 png_init_io (png_ptr, fp);
10520 png_set_sig_bytes (png_ptr, sizeof sig);
10521 png_read_info (png_ptr, info_ptr);
10522 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10523 &interlace_type, NULL, NULL);
10525 /* If image contains simply transparency data, we prefer to
10526 construct a clipping mask. */
10527 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
10528 transparent_p = 1;
10529 else
10530 transparent_p = 0;
10532 /* This function is easier to write if we only have to handle
10533 one data format: RGB or RGBA with 8 bits per channel. Let's
10534 transform other formats into that format. */
10536 /* Strip more than 8 bits per channel. */
10537 if (bit_depth == 16)
10538 png_set_strip_16 (png_ptr);
10540 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10541 if available. */
10542 png_set_expand (png_ptr);
10544 /* Convert grayscale images to RGB. */
10545 if (color_type == PNG_COLOR_TYPE_GRAY
10546 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
10547 png_set_gray_to_rgb (png_ptr);
10549 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
10550 gamma_str = getenv ("SCREEN_GAMMA");
10551 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
10553 /* Tell the PNG lib to handle gamma correction for us. */
10555 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10556 if (png_get_sRGB (png_ptr, info_ptr, &intent))
10557 /* There is a special chunk in the image specifying the gamma. */
10558 png_set_sRGB (png_ptr, info_ptr, intent);
10559 else
10560 #endif
10561 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10562 /* Image contains gamma information. */
10563 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10564 else
10565 /* Use a default of 0.5 for the image gamma. */
10566 png_set_gamma (png_ptr, screen_gamma, 0.5);
10568 /* Handle alpha channel by combining the image with a background
10569 color. Do this only if a real alpha channel is supplied. For
10570 simple transparency, we prefer a clipping mask. */
10571 if (!transparent_p)
10573 png_color_16 *image_background;
10575 if (png_get_bKGD (png_ptr, info_ptr, &image_background))
10576 /* Image contains a background color with which to
10577 combine the image. */
10578 png_set_background (png_ptr, image_background,
10579 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
10580 else
10582 /* Image does not contain a background color with which
10583 to combine the image data via an alpha channel. Use
10584 the frame's background instead. */
10585 XColor color;
10586 Colormap cmap;
10587 png_color_16 frame_background;
10589 BLOCK_INPUT;
10590 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10591 color.pixel = FRAME_BACKGROUND_PIXEL (f);
10592 XQueryColor (FRAME_W32_DISPLAY (f), cmap, &color);
10593 UNBLOCK_INPUT;
10595 bzero (&frame_background, sizeof frame_background);
10596 frame_background.red = color.red;
10597 frame_background.green = color.green;
10598 frame_background.blue = color.blue;
10600 png_set_background (png_ptr, &frame_background,
10601 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10605 /* Update info structure. */
10606 png_read_update_info (png_ptr, info_ptr);
10608 /* Get number of channels. Valid values are 1 for grayscale images
10609 and images with a palette, 2 for grayscale images with transparency
10610 information (alpha channel), 3 for RGB images, and 4 for RGB
10611 images with alpha channel, i.e. RGBA. If conversions above were
10612 sufficient we should only have 3 or 4 channels here. */
10613 channels = png_get_channels (png_ptr, info_ptr);
10614 xassert (channels == 3 || channels == 4);
10616 /* Number of bytes needed for one row of the image. */
10617 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
10619 /* Allocate memory for the image. */
10620 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10621 rows = (png_byte **) xmalloc (height * sizeof *rows);
10622 for (i = 0; i < height; ++i)
10623 rows[i] = pixels + i * row_bytes;
10625 /* Read the entire image. */
10626 png_read_image (png_ptr, rows);
10627 png_read_end (png_ptr, info_ptr);
10628 if (fp)
10630 fclose (fp);
10631 fp = NULL;
10634 BLOCK_INPUT;
10636 /* Create the X image and pixmap. */
10637 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10638 &img->pixmap))
10640 UNBLOCK_INPUT;
10641 goto error;
10644 /* Create an image and pixmap serving as mask if the PNG image
10645 contains an alpha channel. */
10646 if (channels == 4
10647 && !transparent_p
10648 && !x_create_x_image_and_pixmap (f, width, height, 1,
10649 &mask_img, &img->mask))
10651 x_destroy_x_image (ximg);
10652 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
10653 img->pixmap = 0;
10654 UNBLOCK_INPUT;
10655 goto error;
10658 /* Fill the X image and mask from PNG data. */
10659 init_color_table ();
10661 for (y = 0; y < height; ++y)
10663 png_byte *p = rows[y];
10665 for (x = 0; x < width; ++x)
10667 unsigned r, g, b;
10669 r = *p++ << 8;
10670 g = *p++ << 8;
10671 b = *p++ << 8;
10672 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10674 /* An alpha channel, aka mask channel, associates variable
10675 transparency with an image. Where other image formats
10676 support binary transparency---fully transparent or fully
10677 opaque---PNG allows up to 254 levels of partial transparency.
10678 The PNG library implements partial transparency by combining
10679 the image with a specified background color.
10681 I'm not sure how to handle this here nicely: because the
10682 background on which the image is displayed may change, for
10683 real alpha channel support, it would be necessary to create
10684 a new image for each possible background.
10686 What I'm doing now is that a mask is created if we have
10687 boolean transparency information. Otherwise I'm using
10688 the frame's background color to combine the image with. */
10690 if (channels == 4)
10692 if (mask_img)
10693 XPutPixel (mask_img, x, y, *p > 0);
10694 ++p;
10699 /* Remember colors allocated for this image. */
10700 img->colors = colors_in_color_table (&img->ncolors);
10701 free_color_table ();
10703 /* Clean up. */
10704 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10705 xfree (rows);
10706 xfree (pixels);
10708 img->width = width;
10709 img->height = height;
10711 /* Put the image into the pixmap, then free the X image and its buffer. */
10712 x_put_x_image (f, ximg, img->pixmap, width, height);
10713 x_destroy_x_image (ximg);
10715 /* Same for the mask. */
10716 if (mask_img)
10718 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10719 x_destroy_x_image (mask_img);
10722 UNBLOCK_INPUT;
10723 UNGCPRO;
10724 return 1;
10727 #endif /* HAVE_PNG != 0 */
10731 /***********************************************************************
10732 JPEG
10733 ***********************************************************************/
10735 #if HAVE_JPEG
10737 /* Work around a warning about HAVE_STDLIB_H being redefined in
10738 jconfig.h. */
10739 #ifdef HAVE_STDLIB_H
10740 #define HAVE_STDLIB_H_1
10741 #undef HAVE_STDLIB_H
10742 #endif /* HAVE_STLIB_H */
10744 #include <jpeglib.h>
10745 #include <jerror.h>
10746 #include <setjmp.h>
10748 #ifdef HAVE_STLIB_H_1
10749 #define HAVE_STDLIB_H 1
10750 #endif
10752 static int jpeg_image_p P_ ((Lisp_Object object));
10753 static int jpeg_load P_ ((struct frame *f, struct image *img));
10755 /* The symbol `jpeg' identifying images of this type. */
10757 Lisp_Object Qjpeg;
10759 /* Indices of image specification fields in gs_format, below. */
10761 enum jpeg_keyword_index
10763 JPEG_TYPE,
10764 JPEG_DATA,
10765 JPEG_FILE,
10766 JPEG_ASCENT,
10767 JPEG_MARGIN,
10768 JPEG_RELIEF,
10769 JPEG_ALGORITHM,
10770 JPEG_HEURISTIC_MASK,
10771 JPEG_LAST
10774 /* Vector of image_keyword structures describing the format
10775 of valid user-defined image specifications. */
10777 static struct image_keyword jpeg_format[JPEG_LAST] =
10779 {":type", IMAGE_SYMBOL_VALUE, 1},
10780 {":data", IMAGE_STRING_VALUE, 0},
10781 {":file", IMAGE_STRING_VALUE, 0},
10782 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10783 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10784 {":relief", IMAGE_INTEGER_VALUE, 0},
10785 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10786 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10789 /* Structure describing the image type `jpeg'. */
10791 static struct image_type jpeg_type =
10793 &Qjpeg,
10794 jpeg_image_p,
10795 jpeg_load,
10796 x_clear_image,
10797 NULL
10801 /* Return non-zero if OBJECT is a valid JPEG image specification. */
10803 static int
10804 jpeg_image_p (object)
10805 Lisp_Object object;
10807 struct image_keyword fmt[JPEG_LAST];
10809 bcopy (jpeg_format, fmt, sizeof fmt);
10811 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
10812 || (fmt[JPEG_ASCENT].count
10813 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
10814 return 0;
10816 /* Must specify either the :data or :file keyword. */
10817 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
10821 struct my_jpeg_error_mgr
10823 struct jpeg_error_mgr pub;
10824 jmp_buf setjmp_buffer;
10827 static void
10828 my_error_exit (cinfo)
10829 j_common_ptr cinfo;
10831 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
10832 longjmp (mgr->setjmp_buffer, 1);
10835 /* Init source method for JPEG data source manager. Called by
10836 jpeg_read_header() before any data is actually read. See
10837 libjpeg.doc from the JPEG lib distribution. */
10839 static void
10840 our_init_source (cinfo)
10841 j_decompress_ptr cinfo;
10846 /* Fill input buffer method for JPEG data source manager. Called
10847 whenever more data is needed. We read the whole image in one step,
10848 so this only adds a fake end of input marker at the end. */
10850 static boolean
10851 our_fill_input_buffer (cinfo)
10852 j_decompress_ptr cinfo;
10854 /* Insert a fake EOI marker. */
10855 struct jpeg_source_mgr *src = cinfo->src;
10856 static JOCTET buffer[2];
10858 buffer[0] = (JOCTET) 0xFF;
10859 buffer[1] = (JOCTET) JPEG_EOI;
10861 src->next_input_byte = buffer;
10862 src->bytes_in_buffer = 2;
10863 return TRUE;
10867 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
10868 is the JPEG data source manager. */
10870 static void
10871 our_skip_input_data (cinfo, num_bytes)
10872 j_decompress_ptr cinfo;
10873 long num_bytes;
10875 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
10877 if (src)
10879 if (num_bytes > src->bytes_in_buffer)
10880 ERREXIT (cinfo, JERR_INPUT_EOF);
10882 src->bytes_in_buffer -= num_bytes;
10883 src->next_input_byte += num_bytes;
10888 /* Method to terminate data source. Called by
10889 jpeg_finish_decompress() after all data has been processed. */
10891 static void
10892 our_term_source (cinfo)
10893 j_decompress_ptr cinfo;
10898 /* Set up the JPEG lib for reading an image from DATA which contains
10899 LEN bytes. CINFO is the decompression info structure created for
10900 reading the image. */
10902 static void
10903 jpeg_memory_src (cinfo, data, len)
10904 j_decompress_ptr cinfo;
10905 JOCTET *data;
10906 unsigned int len;
10908 struct jpeg_source_mgr *src;
10910 if (cinfo->src == NULL)
10912 /* First time for this JPEG object? */
10913 cinfo->src = (struct jpeg_source_mgr *)
10914 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
10915 sizeof (struct jpeg_source_mgr));
10916 src = (struct jpeg_source_mgr *) cinfo->src;
10917 src->next_input_byte = data;
10920 src = (struct jpeg_source_mgr *) cinfo->src;
10921 src->init_source = our_init_source;
10922 src->fill_input_buffer = our_fill_input_buffer;
10923 src->skip_input_data = our_skip_input_data;
10924 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
10925 src->term_source = our_term_source;
10926 src->bytes_in_buffer = len;
10927 src->next_input_byte = data;
10931 /* Load image IMG for use on frame F. Patterned after example.c
10932 from the JPEG lib. */
10934 static int
10935 jpeg_load (f, img)
10936 struct frame *f;
10937 struct image *img;
10939 struct jpeg_decompress_struct cinfo;
10940 struct my_jpeg_error_mgr mgr;
10941 Lisp_Object file, specified_file;
10942 Lisp_Object specified_data;
10943 FILE *fp = NULL;
10944 JSAMPARRAY buffer;
10945 int row_stride, x, y;
10946 XImage *ximg = NULL;
10947 int rc;
10948 unsigned long *colors;
10949 int width, height;
10950 struct gcpro gcpro1;
10952 /* Open the JPEG file. */
10953 specified_file = image_spec_value (img->spec, QCfile, NULL);
10954 specified_data = image_spec_value (img->spec, QCdata, NULL);
10955 file = Qnil;
10956 GCPRO1 (file);
10958 if (NILP (specified_data))
10960 file = x_find_image_file (specified_file);
10961 if (!STRINGP (file))
10963 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10964 UNGCPRO;
10965 return 0;
10968 fp = fopen (XSTRING (file)->data, "r");
10969 if (fp == NULL)
10971 image_error ("Cannot open `%s'", file, Qnil);
10972 UNGCPRO;
10973 return 0;
10977 /* Customize libjpeg's error handling to call my_error_exit when an
10978 error is detected. This function will perform a longjmp. */
10979 mgr.pub.error_exit = my_error_exit;
10980 cinfo.err = jpeg_std_error (&mgr.pub);
10982 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
10984 if (rc == 1)
10986 /* Called from my_error_exit. Display a JPEG error. */
10987 char buffer[JMSG_LENGTH_MAX];
10988 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
10989 image_error ("Error reading JPEG image `%s': %s", img->spec,
10990 build_string (buffer));
10993 /* Close the input file and destroy the JPEG object. */
10994 if (fp)
10995 fclose (fp);
10996 jpeg_destroy_decompress (&cinfo);
10998 BLOCK_INPUT;
11000 /* If we already have an XImage, free that. */
11001 x_destroy_x_image (ximg);
11003 /* Free pixmap and colors. */
11004 x_clear_image (f, img);
11006 UNBLOCK_INPUT;
11007 UNGCPRO;
11008 return 0;
11011 /* Create the JPEG decompression object. Let it read from fp.
11012 Read the JPEG image header. */
11013 jpeg_create_decompress (&cinfo);
11015 if (NILP (specified_data))
11016 jpeg_stdio_src (&cinfo, fp);
11017 else
11018 jpeg_memory_src (&cinfo, XSTRING (specified_data)->data,
11019 STRING_BYTES (XSTRING (specified_data)));
11021 jpeg_read_header (&cinfo, TRUE);
11023 /* Customize decompression so that color quantization will be used.
11024 Start decompression. */
11025 cinfo.quantize_colors = TRUE;
11026 jpeg_start_decompress (&cinfo);
11027 width = img->width = cinfo.output_width;
11028 height = img->height = cinfo.output_height;
11030 BLOCK_INPUT;
11032 /* Create X image and pixmap. */
11033 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11034 &img->pixmap))
11036 UNBLOCK_INPUT;
11037 longjmp (mgr.setjmp_buffer, 2);
11040 /* Allocate colors. When color quantization is used,
11041 cinfo.actual_number_of_colors has been set with the number of
11042 colors generated, and cinfo.colormap is a two-dimensional array
11043 of color indices in the range 0..cinfo.actual_number_of_colors.
11044 No more than 255 colors will be generated. */
11046 int i, ir, ig, ib;
11048 if (cinfo.out_color_components > 2)
11049 ir = 0, ig = 1, ib = 2;
11050 else if (cinfo.out_color_components > 1)
11051 ir = 0, ig = 1, ib = 0;
11052 else
11053 ir = 0, ig = 0, ib = 0;
11055 /* Use the color table mechanism because it handles colors that
11056 cannot be allocated nicely. Such colors will be replaced with
11057 a default color, and we don't have to care about which colors
11058 can be freed safely, and which can't. */
11059 init_color_table ();
11060 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
11061 * sizeof *colors);
11063 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
11065 /* Multiply RGB values with 255 because X expects RGB values
11066 in the range 0..0xffff. */
11067 int r = cinfo.colormap[ir][i] << 8;
11068 int g = cinfo.colormap[ig][i] << 8;
11069 int b = cinfo.colormap[ib][i] << 8;
11070 colors[i] = lookup_rgb_color (f, r, g, b);
11073 /* Remember those colors actually allocated. */
11074 img->colors = colors_in_color_table (&img->ncolors);
11075 free_color_table ();
11078 /* Read pixels. */
11079 row_stride = width * cinfo.output_components;
11080 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
11081 row_stride, 1);
11082 for (y = 0; y < height; ++y)
11084 jpeg_read_scanlines (&cinfo, buffer, 1);
11085 for (x = 0; x < cinfo.output_width; ++x)
11086 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
11089 /* Clean up. */
11090 jpeg_finish_decompress (&cinfo);
11091 jpeg_destroy_decompress (&cinfo);
11092 if (fp)
11093 fclose (fp);
11095 /* Put the image into the pixmap. */
11096 x_put_x_image (f, ximg, img->pixmap, width, height);
11097 x_destroy_x_image (ximg);
11098 UNBLOCK_INPUT;
11099 UNGCPRO;
11100 return 1;
11103 #endif /* HAVE_JPEG */
11107 /***********************************************************************
11108 TIFF
11109 ***********************************************************************/
11111 #if HAVE_TIFF
11113 #include <tiffio.h>
11115 static int tiff_image_p P_ ((Lisp_Object object));
11116 static int tiff_load P_ ((struct frame *f, struct image *img));
11118 /* The symbol `tiff' identifying images of this type. */
11120 Lisp_Object Qtiff;
11122 /* Indices of image specification fields in tiff_format, below. */
11124 enum tiff_keyword_index
11126 TIFF_TYPE,
11127 TIFF_DATA,
11128 TIFF_FILE,
11129 TIFF_ASCENT,
11130 TIFF_MARGIN,
11131 TIFF_RELIEF,
11132 TIFF_ALGORITHM,
11133 TIFF_HEURISTIC_MASK,
11134 TIFF_LAST
11137 /* Vector of image_keyword structures describing the format
11138 of valid user-defined image specifications. */
11140 static struct image_keyword tiff_format[TIFF_LAST] =
11142 {":type", IMAGE_SYMBOL_VALUE, 1},
11143 {":data", IMAGE_STRING_VALUE, 0},
11144 {":file", IMAGE_STRING_VALUE, 0},
11145 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11146 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11147 {":relief", IMAGE_INTEGER_VALUE, 0},
11148 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11149 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11152 /* Structure describing the image type `tiff'. */
11154 static struct image_type tiff_type =
11156 &Qtiff,
11157 tiff_image_p,
11158 tiff_load,
11159 x_clear_image,
11160 NULL
11164 /* Return non-zero if OBJECT is a valid TIFF image specification. */
11166 static int
11167 tiff_image_p (object)
11168 Lisp_Object object;
11170 struct image_keyword fmt[TIFF_LAST];
11171 bcopy (tiff_format, fmt, sizeof fmt);
11173 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
11174 || (fmt[TIFF_ASCENT].count
11175 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
11176 return 0;
11178 /* Must specify either the :data or :file keyword. */
11179 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
11183 /* Reading from a memory buffer for TIFF images Based on the PNG
11184 memory source, but we have to provide a lot of extra functions.
11185 Blah.
11187 We really only need to implement read and seek, but I am not
11188 convinced that the TIFF library is smart enough not to destroy
11189 itself if we only hand it the function pointers we need to
11190 override. */
11192 typedef struct
11194 unsigned char *bytes;
11195 size_t len;
11196 int index;
11198 tiff_memory_source;
11200 static size_t
11201 tiff_read_from_memory (data, buf, size)
11202 thandle_t data;
11203 tdata_t buf;
11204 tsize_t size;
11206 tiff_memory_source *src = (tiff_memory_source *) data;
11208 if (size > src->len - src->index)
11209 return (size_t) -1;
11210 bcopy (src->bytes + src->index, buf, size);
11211 src->index += size;
11212 return size;
11215 static size_t
11216 tiff_write_from_memory (data, buf, size)
11217 thandle_t data;
11218 tdata_t buf;
11219 tsize_t size;
11221 return (size_t) -1;
11224 static toff_t
11225 tiff_seek_in_memory (data, off, whence)
11226 thandle_t data;
11227 toff_t off;
11228 int whence;
11230 tiff_memory_source *src = (tiff_memory_source *) data;
11231 int idx;
11233 switch (whence)
11235 case SEEK_SET: /* Go from beginning of source. */
11236 idx = off;
11237 break;
11239 case SEEK_END: /* Go from end of source. */
11240 idx = src->len + off;
11241 break;
11243 case SEEK_CUR: /* Go from current position. */
11244 idx = src->index + off;
11245 break;
11247 default: /* Invalid `whence'. */
11248 return -1;
11251 if (idx > src->len || idx < 0)
11252 return -1;
11254 src->index = idx;
11255 return src->index;
11258 static int
11259 tiff_close_memory (data)
11260 thandle_t data;
11262 /* NOOP */
11263 return 0;
11266 static int
11267 tiff_mmap_memory (data, pbase, psize)
11268 thandle_t data;
11269 tdata_t *pbase;
11270 toff_t *psize;
11272 /* It is already _IN_ memory. */
11273 return 0;
11276 static void
11277 tiff_unmap_memory (data, base, size)
11278 thandle_t data;
11279 tdata_t base;
11280 toff_t size;
11282 /* We don't need to do this. */
11285 static toff_t
11286 tiff_size_of_memory (data)
11287 thandle_t data;
11289 return ((tiff_memory_source *) data)->len;
11292 /* Load TIFF image IMG for use on frame F. Value is non-zero if
11293 successful. */
11295 static int
11296 tiff_load (f, img)
11297 struct frame *f;
11298 struct image *img;
11300 Lisp_Object file, specified_file;
11301 Lisp_Object specified_data;
11302 TIFF *tiff;
11303 int width, height, x, y;
11304 uint32 *buf;
11305 int rc;
11306 XImage *ximg;
11307 struct gcpro gcpro1;
11308 tiff_memory_source memsrc;
11310 specified_file = image_spec_value (img->spec, QCfile, NULL);
11311 specified_data = image_spec_value (img->spec, QCdata, NULL);
11312 file = Qnil;
11313 GCPRO1 (file);
11315 if (NILP (specified_data))
11317 /* Read from a file */
11318 file = x_find_image_file (specified_file);
11319 if (!STRINGP (file))
11321 image_error ("Cannot find image file `%s'", file, Qnil);
11322 UNGCPRO;
11323 return 0;
11326 /* Try to open the image file. */
11327 tiff = TIFFOpen (XSTRING (file)->data, "r");
11328 if (tiff == NULL)
11330 image_error ("Cannot open `%s'", file, Qnil);
11331 UNGCPRO;
11332 return 0;
11335 else
11337 /* Memory source! */
11338 memsrc.bytes = XSTRING (specified_data)->data;
11339 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11340 memsrc.index = 0;
11342 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
11343 (TIFFReadWriteProc) tiff_read_from_memory,
11344 (TIFFReadWriteProc) tiff_write_from_memory,
11345 tiff_seek_in_memory,
11346 tiff_close_memory,
11347 tiff_size_of_memory,
11348 tiff_mmap_memory,
11349 tiff_unmap_memory);
11351 if (!tiff)
11353 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
11354 UNGCPRO;
11355 return 0;
11359 /* Get width and height of the image, and allocate a raster buffer
11360 of width x height 32-bit values. */
11361 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
11362 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
11363 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
11365 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
11366 TIFFClose (tiff);
11367 if (!rc)
11369 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
11370 xfree (buf);
11371 UNGCPRO;
11372 return 0;
11375 BLOCK_INPUT;
11377 /* Create the X image and pixmap. */
11378 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11380 UNBLOCK_INPUT;
11381 xfree (buf);
11382 UNGCPRO;
11383 return 0;
11386 /* Initialize the color table. */
11387 init_color_table ();
11389 /* Process the pixel raster. Origin is in the lower-left corner. */
11390 for (y = 0; y < height; ++y)
11392 uint32 *row = buf + y * width;
11394 for (x = 0; x < width; ++x)
11396 uint32 abgr = row[x];
11397 int r = TIFFGetR (abgr) << 8;
11398 int g = TIFFGetG (abgr) << 8;
11399 int b = TIFFGetB (abgr) << 8;
11400 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
11404 /* Remember the colors allocated for the image. Free the color table. */
11405 img->colors = colors_in_color_table (&img->ncolors);
11406 free_color_table ();
11408 /* Put the image into the pixmap, then free the X image and its buffer. */
11409 x_put_x_image (f, ximg, img->pixmap, width, height);
11410 x_destroy_x_image (ximg);
11411 xfree (buf);
11412 UNBLOCK_INPUT;
11414 img->width = width;
11415 img->height = height;
11417 UNGCPRO;
11418 return 1;
11421 #endif /* HAVE_TIFF != 0 */
11425 /***********************************************************************
11427 ***********************************************************************/
11429 #if HAVE_GIF
11431 #include <gif_lib.h>
11433 static int gif_image_p P_ ((Lisp_Object object));
11434 static int gif_load P_ ((struct frame *f, struct image *img));
11436 /* The symbol `gif' identifying images of this type. */
11438 Lisp_Object Qgif;
11440 /* Indices of image specification fields in gif_format, below. */
11442 enum gif_keyword_index
11444 GIF_TYPE,
11445 GIF_DATA,
11446 GIF_FILE,
11447 GIF_ASCENT,
11448 GIF_MARGIN,
11449 GIF_RELIEF,
11450 GIF_ALGORITHM,
11451 GIF_HEURISTIC_MASK,
11452 GIF_IMAGE,
11453 GIF_LAST
11456 /* Vector of image_keyword structures describing the format
11457 of valid user-defined image specifications. */
11459 static struct image_keyword gif_format[GIF_LAST] =
11461 {":type", IMAGE_SYMBOL_VALUE, 1},
11462 {":data", IMAGE_STRING_VALUE, 0},
11463 {":file", IMAGE_STRING_VALUE, 0},
11464 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11465 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11466 {":relief", IMAGE_INTEGER_VALUE, 0},
11467 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11468 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11469 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
11472 /* Structure describing the image type `gif'. */
11474 static struct image_type gif_type =
11476 &Qgif,
11477 gif_image_p,
11478 gif_load,
11479 x_clear_image,
11480 NULL
11483 /* Return non-zero if OBJECT is a valid GIF image specification. */
11485 static int
11486 gif_image_p (object)
11487 Lisp_Object object;
11489 struct image_keyword fmt[GIF_LAST];
11490 bcopy (gif_format, fmt, sizeof fmt);
11492 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
11493 || (fmt[GIF_ASCENT].count
11494 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
11495 return 0;
11497 /* Must specify either the :data or :file keyword. */
11498 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11501 /* Reading a GIF image from memory
11502 Based on the PNG memory stuff to a certain extent. */
11504 typedef struct
11506 unsigned char *bytes;
11507 size_t len;
11508 int index;
11510 gif_memory_source;
11512 /* Make the current memory source available to gif_read_from_memory.
11513 It's done this way because not all versions of libungif support
11514 a UserData field in the GifFileType structure. */
11515 static gif_memory_source *current_gif_memory_src;
11517 static int
11518 gif_read_from_memory (file, buf, len)
11519 GifFileType *file;
11520 GifByteType *buf;
11521 int len;
11523 gif_memory_source *src = current_gif_memory_src;
11525 if (len > src->len - src->index)
11526 return -1;
11528 bcopy (src->bytes + src->index, buf, len);
11529 src->index += len;
11530 return len;
11534 /* Load GIF image IMG for use on frame F. Value is non-zero if
11535 successful. */
11537 static int
11538 gif_load (f, img)
11539 struct frame *f;
11540 struct image *img;
11542 Lisp_Object file, specified_file;
11543 Lisp_Object specified_data;
11544 int rc, width, height, x, y, i;
11545 XImage *ximg;
11546 ColorMapObject *gif_color_map;
11547 unsigned long pixel_colors[256];
11548 GifFileType *gif;
11549 struct gcpro gcpro1;
11550 Lisp_Object image;
11551 int ino, image_left, image_top, image_width, image_height;
11552 gif_memory_source memsrc;
11553 unsigned char *raster;
11555 specified_file = image_spec_value (img->spec, QCfile, NULL);
11556 specified_data = image_spec_value (img->spec, QCdata, NULL);
11557 file = Qnil;
11558 GCPRO1 (file);
11560 if (NILP (specified_data))
11562 file = x_find_image_file (specified_file);
11563 if (!STRINGP (file))
11565 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11566 UNGCPRO;
11567 return 0;
11570 /* Open the GIF file. */
11571 gif = DGifOpenFileName (XSTRING (file)->data);
11572 if (gif == NULL)
11574 image_error ("Cannot open `%s'", file, Qnil);
11575 UNGCPRO;
11576 return 0;
11579 else
11581 /* Read from memory! */
11582 current_gif_memory_src = &memsrc;
11583 memsrc.bytes = XSTRING (specified_data)->data;
11584 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11585 memsrc.index = 0;
11587 gif = DGifOpen(&memsrc, gif_read_from_memory);
11588 if (!gif)
11590 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11591 UNGCPRO;
11592 return 0;
11596 /* Read entire contents. */
11597 rc = DGifSlurp (gif);
11598 if (rc == GIF_ERROR)
11600 image_error ("Error reading `%s'", img->spec, Qnil);
11601 DGifCloseFile (gif);
11602 UNGCPRO;
11603 return 0;
11606 image = image_spec_value (img->spec, QCindex, NULL);
11607 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11608 if (ino >= gif->ImageCount)
11610 image_error ("Invalid image number `%s' in image `%s'",
11611 image, img->spec);
11612 DGifCloseFile (gif);
11613 UNGCPRO;
11614 return 0;
11617 width = img->width = gif->SWidth;
11618 height = img->height = gif->SHeight;
11620 BLOCK_INPUT;
11622 /* Create the X image and pixmap. */
11623 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11625 UNBLOCK_INPUT;
11626 DGifCloseFile (gif);
11627 UNGCPRO;
11628 return 0;
11631 /* Allocate colors. */
11632 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11633 if (!gif_color_map)
11634 gif_color_map = gif->SColorMap;
11635 init_color_table ();
11636 bzero (pixel_colors, sizeof pixel_colors);
11638 for (i = 0; i < gif_color_map->ColorCount; ++i)
11640 int r = gif_color_map->Colors[i].Red << 8;
11641 int g = gif_color_map->Colors[i].Green << 8;
11642 int b = gif_color_map->Colors[i].Blue << 8;
11643 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
11646 img->colors = colors_in_color_table (&img->ncolors);
11647 free_color_table ();
11649 /* Clear the part of the screen image that are not covered by
11650 the image from the GIF file. Full animated GIF support
11651 requires more than can be done here (see the gif89 spec,
11652 disposal methods). Let's simply assume that the part
11653 not covered by a sub-image is in the frame's background color. */
11654 image_top = gif->SavedImages[ino].ImageDesc.Top;
11655 image_left = gif->SavedImages[ino].ImageDesc.Left;
11656 image_width = gif->SavedImages[ino].ImageDesc.Width;
11657 image_height = gif->SavedImages[ino].ImageDesc.Height;
11659 for (y = 0; y < image_top; ++y)
11660 for (x = 0; x < width; ++x)
11661 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11663 for (y = image_top + image_height; y < height; ++y)
11664 for (x = 0; x < width; ++x)
11665 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11667 for (y = image_top; y < image_top + image_height; ++y)
11669 for (x = 0; x < image_left; ++x)
11670 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11671 for (x = image_left + image_width; x < width; ++x)
11672 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11675 /* Read the GIF image into the X image. We use a local variable
11676 `raster' here because RasterBits below is a char *, and invites
11677 problems with bytes >= 0x80. */
11678 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
11680 if (gif->SavedImages[ino].ImageDesc.Interlace)
11682 static int interlace_start[] = {0, 4, 2, 1};
11683 static int interlace_increment[] = {8, 8, 4, 2};
11684 int pass, inc;
11685 int row = interlace_start[0];
11687 pass = 0;
11689 for (y = 0; y < image_height; y++)
11691 if (row >= image_height)
11693 row = interlace_start[++pass];
11694 while (row >= image_height)
11695 row = interlace_start[++pass];
11698 for (x = 0; x < image_width; x++)
11700 int i = raster[(y * image_width) + x];
11701 XPutPixel (ximg, x + image_left, row + image_top,
11702 pixel_colors[i]);
11705 row += interlace_increment[pass];
11708 else
11710 for (y = 0; y < image_height; ++y)
11711 for (x = 0; x < image_width; ++x)
11713 int i = raster[y* image_width + x];
11714 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
11718 DGifCloseFile (gif);
11720 /* Put the image into the pixmap, then free the X image and its buffer. */
11721 x_put_x_image (f, ximg, img->pixmap, width, height);
11722 x_destroy_x_image (ximg);
11723 UNBLOCK_INPUT;
11725 UNGCPRO;
11726 return 1;
11729 #endif /* HAVE_GIF != 0 */
11733 /***********************************************************************
11734 Ghostscript
11735 ***********************************************************************/
11737 #ifdef HAVE_GHOSTSCRIPT
11738 static int gs_image_p P_ ((Lisp_Object object));
11739 static int gs_load P_ ((struct frame *f, struct image *img));
11740 static void gs_clear_image P_ ((struct frame *f, struct image *img));
11742 /* The symbol `postscript' identifying images of this type. */
11744 Lisp_Object Qpostscript;
11746 /* Keyword symbols. */
11748 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
11750 /* Indices of image specification fields in gs_format, below. */
11752 enum gs_keyword_index
11754 GS_TYPE,
11755 GS_PT_WIDTH,
11756 GS_PT_HEIGHT,
11757 GS_FILE,
11758 GS_LOADER,
11759 GS_BOUNDING_BOX,
11760 GS_ASCENT,
11761 GS_MARGIN,
11762 GS_RELIEF,
11763 GS_ALGORITHM,
11764 GS_HEURISTIC_MASK,
11765 GS_LAST
11768 /* Vector of image_keyword structures describing the format
11769 of valid user-defined image specifications. */
11771 static struct image_keyword gs_format[GS_LAST] =
11773 {":type", IMAGE_SYMBOL_VALUE, 1},
11774 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11775 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11776 {":file", IMAGE_STRING_VALUE, 1},
11777 {":loader", IMAGE_FUNCTION_VALUE, 0},
11778 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
11779 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11780 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11781 {":relief", IMAGE_INTEGER_VALUE, 0},
11782 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11783 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11786 /* Structure describing the image type `ghostscript'. */
11788 static struct image_type gs_type =
11790 &Qpostscript,
11791 gs_image_p,
11792 gs_load,
11793 gs_clear_image,
11794 NULL
11798 /* Free X resources of Ghostscript image IMG which is used on frame F. */
11800 static void
11801 gs_clear_image (f, img)
11802 struct frame *f;
11803 struct image *img;
11805 /* IMG->data.ptr_val may contain a recorded colormap. */
11806 xfree (img->data.ptr_val);
11807 x_clear_image (f, img);
11811 /* Return non-zero if OBJECT is a valid Ghostscript image
11812 specification. */
11814 static int
11815 gs_image_p (object)
11816 Lisp_Object object;
11818 struct image_keyword fmt[GS_LAST];
11819 Lisp_Object tem;
11820 int i;
11822 bcopy (gs_format, fmt, sizeof fmt);
11824 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
11825 || (fmt[GS_ASCENT].count
11826 && XFASTINT (fmt[GS_ASCENT].value) > 100))
11827 return 0;
11829 /* Bounding box must be a list or vector containing 4 integers. */
11830 tem = fmt[GS_BOUNDING_BOX].value;
11831 if (CONSP (tem))
11833 for (i = 0; i < 4; ++i, tem = XCDR (tem))
11834 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
11835 return 0;
11836 if (!NILP (tem))
11837 return 0;
11839 else if (VECTORP (tem))
11841 if (XVECTOR (tem)->size != 4)
11842 return 0;
11843 for (i = 0; i < 4; ++i)
11844 if (!INTEGERP (XVECTOR (tem)->contents[i]))
11845 return 0;
11847 else
11848 return 0;
11850 return 1;
11854 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
11855 if successful. */
11857 static int
11858 gs_load (f, img)
11859 struct frame *f;
11860 struct image *img;
11862 char buffer[100];
11863 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
11864 struct gcpro gcpro1, gcpro2;
11865 Lisp_Object frame;
11866 double in_width, in_height;
11867 Lisp_Object pixel_colors = Qnil;
11869 /* Compute pixel size of pixmap needed from the given size in the
11870 image specification. Sizes in the specification are in pt. 1 pt
11871 = 1/72 in, xdpi and ydpi are stored in the frame's X display
11872 info. */
11873 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
11874 in_width = XFASTINT (pt_width) / 72.0;
11875 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
11876 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
11877 in_height = XFASTINT (pt_height) / 72.0;
11878 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
11880 /* Create the pixmap. */
11881 BLOCK_INPUT;
11882 xassert (img->pixmap == 0);
11883 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11884 img->width, img->height,
11885 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
11886 UNBLOCK_INPUT;
11888 if (!img->pixmap)
11890 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
11891 return 0;
11894 /* Call the loader to fill the pixmap. It returns a process object
11895 if successful. We do not record_unwind_protect here because
11896 other places in redisplay like calling window scroll functions
11897 don't either. Let the Lisp loader use `unwind-protect' instead. */
11898 GCPRO2 (window_and_pixmap_id, pixel_colors);
11900 sprintf (buffer, "%lu %lu",
11901 (unsigned long) FRAME_W32_WINDOW (f),
11902 (unsigned long) img->pixmap);
11903 window_and_pixmap_id = build_string (buffer);
11905 sprintf (buffer, "%lu %lu",
11906 FRAME_FOREGROUND_PIXEL (f),
11907 FRAME_BACKGROUND_PIXEL (f));
11908 pixel_colors = build_string (buffer);
11910 XSETFRAME (frame, f);
11911 loader = image_spec_value (img->spec, QCloader, NULL);
11912 if (NILP (loader))
11913 loader = intern ("gs-load-image");
11915 img->data.lisp_val = call6 (loader, frame, img->spec,
11916 make_number (img->width),
11917 make_number (img->height),
11918 window_and_pixmap_id,
11919 pixel_colors);
11920 UNGCPRO;
11921 return PROCESSP (img->data.lisp_val);
11925 /* Kill the Ghostscript process that was started to fill PIXMAP on
11926 frame F. Called from XTread_socket when receiving an event
11927 telling Emacs that Ghostscript has finished drawing. */
11929 void
11930 x_kill_gs_process (pixmap, f)
11931 Pixmap pixmap;
11932 struct frame *f;
11934 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
11935 int class, i;
11936 struct image *img;
11938 /* Find the image containing PIXMAP. */
11939 for (i = 0; i < c->used; ++i)
11940 if (c->images[i]->pixmap == pixmap)
11941 break;
11943 /* Kill the GS process. We should have found PIXMAP in the image
11944 cache and its image should contain a process object. */
11945 xassert (i < c->used);
11946 img = c->images[i];
11947 xassert (PROCESSP (img->data.lisp_val));
11948 Fkill_process (img->data.lisp_val, Qnil);
11949 img->data.lisp_val = Qnil;
11951 /* On displays with a mutable colormap, figure out the colors
11952 allocated for the image by looking at the pixels of an XImage for
11953 img->pixmap. */
11954 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
11955 if (class != StaticColor && class != StaticGray && class != TrueColor)
11957 XImage *ximg;
11959 BLOCK_INPUT;
11961 /* Try to get an XImage for img->pixmep. */
11962 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
11963 0, 0, img->width, img->height, ~0, ZPixmap);
11964 if (ximg)
11966 int x, y;
11968 /* Initialize the color table. */
11969 init_color_table ();
11971 /* For each pixel of the image, look its color up in the
11972 color table. After having done so, the color table will
11973 contain an entry for each color used by the image. */
11974 for (y = 0; y < img->height; ++y)
11975 for (x = 0; x < img->width; ++x)
11977 unsigned long pixel = XGetPixel (ximg, x, y);
11978 lookup_pixel_color (f, pixel);
11981 /* Record colors in the image. Free color table and XImage. */
11982 img->colors = colors_in_color_table (&img->ncolors);
11983 free_color_table ();
11984 XDestroyImage (ximg);
11986 #if 0 /* This doesn't seem to be the case. If we free the colors
11987 here, we get a BadAccess later in x_clear_image when
11988 freeing the colors. */
11989 /* We have allocated colors once, but Ghostscript has also
11990 allocated colors on behalf of us. So, to get the
11991 reference counts right, free them once. */
11992 if (img->ncolors)
11994 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
11995 XFreeColors (FRAME_W32_DISPLAY (f), cmap,
11996 img->colors, img->ncolors, 0);
11998 #endif
12000 else
12001 image_error ("Cannot get X image of `%s'; colors will not be freed",
12002 img->spec, Qnil);
12004 UNBLOCK_INPUT;
12008 #endif /* HAVE_GHOSTSCRIPT */
12011 /***********************************************************************
12012 Window properties
12013 ***********************************************************************/
12015 DEFUN ("x-change-window-property", Fx_change_window_property,
12016 Sx_change_window_property, 2, 3, 0,
12017 "Change window property PROP to VALUE on the X window of FRAME.\n\
12018 PROP and VALUE must be strings. FRAME nil or omitted means use the\n\
12019 selected frame. Value is VALUE.")
12020 (prop, value, frame)
12021 Lisp_Object frame, prop, value;
12023 #if 0 /* TODO : port window properties to W32 */
12024 struct frame *f = check_x_frame (frame);
12025 Atom prop_atom;
12027 CHECK_STRING (prop, 1);
12028 CHECK_STRING (value, 2);
12030 BLOCK_INPUT;
12031 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12032 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12033 prop_atom, XA_STRING, 8, PropModeReplace,
12034 XSTRING (value)->data, XSTRING (value)->size);
12036 /* Make sure the property is set when we return. */
12037 XFlush (FRAME_W32_DISPLAY (f));
12038 UNBLOCK_INPUT;
12040 #endif /* TODO */
12042 return value;
12046 DEFUN ("x-delete-window-property", Fx_delete_window_property,
12047 Sx_delete_window_property, 1, 2, 0,
12048 "Remove window property PROP from X window of FRAME.\n\
12049 FRAME nil or omitted means use the selected frame. Value is PROP.")
12050 (prop, frame)
12051 Lisp_Object prop, frame;
12053 #if 0 /* TODO : port window properties to W32 */
12055 struct frame *f = check_x_frame (frame);
12056 Atom prop_atom;
12058 CHECK_STRING (prop, 1);
12059 BLOCK_INPUT;
12060 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12061 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
12063 /* Make sure the property is removed when we return. */
12064 XFlush (FRAME_W32_DISPLAY (f));
12065 UNBLOCK_INPUT;
12066 #endif /* TODO */
12068 return prop;
12072 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
12073 1, 2, 0,
12074 "Value is the value of window property PROP on FRAME.\n\
12075 If FRAME is nil or omitted, use the selected frame. Value is nil\n\
12076 if FRAME hasn't a property with name PROP or if PROP has no string\n\
12077 value.")
12078 (prop, frame)
12079 Lisp_Object prop, frame;
12081 #if 0 /* TODO : port window properties to W32 */
12083 struct frame *f = check_x_frame (frame);
12084 Atom prop_atom;
12085 int rc;
12086 Lisp_Object prop_value = Qnil;
12087 char *tmp_data = NULL;
12088 Atom actual_type;
12089 int actual_format;
12090 unsigned long actual_size, bytes_remaining;
12092 CHECK_STRING (prop, 1);
12093 BLOCK_INPUT;
12094 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12095 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12096 prop_atom, 0, 0, False, XA_STRING,
12097 &actual_type, &actual_format, &actual_size,
12098 &bytes_remaining, (unsigned char **) &tmp_data);
12099 if (rc == Success)
12101 int size = bytes_remaining;
12103 XFree (tmp_data);
12104 tmp_data = NULL;
12106 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12107 prop_atom, 0, bytes_remaining,
12108 False, XA_STRING,
12109 &actual_type, &actual_format,
12110 &actual_size, &bytes_remaining,
12111 (unsigned char **) &tmp_data);
12112 if (rc == Success)
12113 prop_value = make_string (tmp_data, size);
12115 XFree (tmp_data);
12118 UNBLOCK_INPUT;
12120 return prop_value;
12122 #endif /* TODO */
12123 return Qnil;
12128 /***********************************************************************
12129 Busy cursor
12130 ***********************************************************************/
12132 /* If non-null, an asynchronous timer that, when it expires, displays
12133 an hourglass cursor on all frames. */
12135 static struct atimer *hourglass_atimer;
12137 /* Non-zero means an hourglass cursor is currently shown. */
12139 static int hourglass_shown_p;
12141 /* Number of seconds to wait before displaying an hourglass cursor. */
12143 static Lisp_Object Vhourglass_delay;
12145 /* Default number of seconds to wait before displaying an hourglass
12146 cursor. */
12148 #define DEFAULT_HOURGLASS_DELAY 1
12150 /* Function prototypes. */
12152 static void show_hourglass P_ ((struct atimer *));
12153 static void hide_hourglass P_ ((void));
12156 /* Cancel a currently active hourglass timer, and start a new one. */
12158 void
12159 start_hourglass ()
12161 #if 0 /* TODO: cursor shape changes. */
12162 EMACS_TIME delay;
12163 int secs, usecs = 0;
12165 cancel_hourglass ();
12167 if (INTEGERP (Vhourglass_delay)
12168 && XINT (Vhourglass_delay) > 0)
12169 secs = XFASTINT (Vhourglass_delay);
12170 else if (FLOATP (Vhourglass_delay)
12171 && XFLOAT_DATA (Vhourglass_delay) > 0)
12173 Lisp_Object tem;
12174 tem = Ftruncate (Vhourglass_delay, Qnil);
12175 secs = XFASTINT (tem);
12176 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
12178 else
12179 secs = DEFAULT_HOURGLASS_DELAY;
12181 EMACS_SET_SECS_USECS (delay, secs, usecs);
12182 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
12183 show_hourglass, NULL);
12184 #endif
12188 /* Cancel the hourglass cursor timer if active, hide an hourglass
12189 cursor if shown. */
12191 void
12192 cancel_hourglass ()
12194 if (hourglass_atimer)
12196 cancel_atimer (hourglass_atimer);
12197 hourglass_atimer = NULL;
12200 if (hourglass_shown_p)
12201 hide_hourglass ();
12205 /* Timer function of hourglass_atimer. TIMER is equal to
12206 hourglass_atimer.
12208 Display an hourglass cursor on all frames by mapping the frames'
12209 hourglass_window. Set the hourglass_p flag in the frames'
12210 output_data.x structure to indicate that an hourglass cursor is
12211 shown on the frames. */
12213 static void
12214 show_hourglass (timer)
12215 struct atimer *timer;
12217 #if 0 /* TODO: cursor shape changes. */
12218 /* The timer implementation will cancel this timer automatically
12219 after this function has run. Set hourglass_atimer to null
12220 so that we know the timer doesn't have to be canceled. */
12221 hourglass_atimer = NULL;
12223 if (!hourglass_shown_p)
12225 Lisp_Object rest, frame;
12227 BLOCK_INPUT;
12229 FOR_EACH_FRAME (rest, frame)
12230 if (FRAME_W32_P (XFRAME (frame)))
12232 struct frame *f = XFRAME (frame);
12234 f->output_data.w32->hourglass_p = 1;
12236 if (!f->output_data.w32->hourglass_window)
12238 unsigned long mask = CWCursor;
12239 XSetWindowAttributes attrs;
12241 attrs.cursor = f->output_data.w32->hourglass_cursor;
12243 f->output_data.w32->hourglass_window
12244 = XCreateWindow (FRAME_X_DISPLAY (f),
12245 FRAME_OUTER_WINDOW (f),
12246 0, 0, 32000, 32000, 0, 0,
12247 InputOnly,
12248 CopyFromParent,
12249 mask, &attrs);
12252 XMapRaised (FRAME_X_DISPLAY (f),
12253 f->output_data.w32->hourglass_window);
12254 XFlush (FRAME_X_DISPLAY (f));
12257 hourglass_shown_p = 1;
12258 UNBLOCK_INPUT;
12260 #endif
12264 /* Hide the hourglass cursor on all frames, if it is currently shown. */
12266 static void
12267 hide_hourglass ()
12269 #if 0 /* TODO: cursor shape changes. */
12270 if (hourglass_shown_p)
12272 Lisp_Object rest, frame;
12274 BLOCK_INPUT;
12275 FOR_EACH_FRAME (rest, frame)
12277 struct frame *f = XFRAME (frame);
12279 if (FRAME_W32_P (f)
12280 /* Watch out for newly created frames. */
12281 && f->output_data.x->hourglass_window)
12283 XUnmapWindow (FRAME_X_DISPLAY (f),
12284 f->output_data.x->hourglass_window);
12285 /* Sync here because XTread_socket looks at the
12286 hourglass_p flag that is reset to zero below. */
12287 XSync (FRAME_X_DISPLAY (f), False);
12288 f->output_data.x->hourglass_p = 0;
12292 hourglass_shown_p = 0;
12293 UNBLOCK_INPUT;
12295 #endif
12300 /***********************************************************************
12301 Tool tips
12302 ***********************************************************************/
12304 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
12305 Lisp_Object));
12307 /* The frame of a currently visible tooltip, or null. */
12309 Lisp_Object tip_frame;
12311 /* If non-nil, a timer started that hides the last tooltip when it
12312 fires. */
12314 Lisp_Object tip_timer;
12315 Window tip_window;
12317 static Lisp_Object
12318 unwind_create_tip_frame (frame)
12319 Lisp_Object frame;
12321 Lisp_Object deleted;
12323 deleted = unwind_create_frame (frame);
12324 if (EQ (deleted, Qt))
12326 tip_window = NULL;
12327 tip_frame = Qnil;
12330 return deleted;
12334 /* Create a frame for a tooltip on the display described by DPYINFO.
12335 PARMS is a list of frame parameters. Value is the frame.
12337 Note that functions called here, esp. x_default_parameter can
12338 signal errors, for instance when a specified color name is
12339 undefined. We have to make sure that we're in a consistent state
12340 when this happens. */
12342 static Lisp_Object
12343 x_create_tip_frame (dpyinfo, parms)
12344 struct w32_display_info *dpyinfo;
12345 Lisp_Object parms;
12347 #if 0 /* TODO : w32 version */
12348 struct frame *f;
12349 Lisp_Object frame, tem;
12350 Lisp_Object name;
12351 long window_prompting = 0;
12352 int width, height;
12353 int count = BINDING_STACK_SIZE ();
12354 struct gcpro gcpro1, gcpro2, gcpro3;
12355 struct kboard *kb;
12357 check_x ();
12359 /* Use this general default value to start with until we know if
12360 this frame has a specified name. */
12361 Vx_resource_name = Vinvocation_name;
12363 #ifdef MULTI_KBOARD
12364 kb = dpyinfo->kboard;
12365 #else
12366 kb = &the_only_kboard;
12367 #endif
12369 /* Get the name of the frame to use for resource lookup. */
12370 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
12371 if (!STRINGP (name)
12372 && !EQ (name, Qunbound)
12373 && !NILP (name))
12374 error ("Invalid frame name--not a string or nil");
12375 Vx_resource_name = name;
12377 frame = Qnil;
12378 GCPRO3 (parms, name, frame);
12379 f = make_frame (1);
12380 XSETFRAME (frame, f);
12381 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
12382 record_unwind_protect (unwind_create_tip_frame, frame);
12384 f->output_method = output_w32;
12385 f->output_data.w32 =
12386 (struct w32_output *) xmalloc (sizeof (struct w32_output));
12387 bzero (f->output_data.w32, sizeof (struct w32_output));
12388 #if 0
12389 f->output_data.w32->icon_bitmap = -1;
12390 #endif
12391 f->output_data.w32->fontset = -1;
12392 f->icon_name = Qnil;
12394 #ifdef GLYPH_DEBUG
12395 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
12396 dpyinfo_refcount = dpyinfo->reference_count;
12397 #endif /* GLYPH_DEBUG */
12398 #ifdef MULTI_KBOARD
12399 FRAME_KBOARD (f) = kb;
12400 #endif
12401 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12402 f->output_data.w32->explicit_parent = 0;
12404 /* Set the name; the functions to which we pass f expect the name to
12405 be set. */
12406 if (EQ (name, Qunbound) || NILP (name))
12408 f->name = build_string (dpyinfo->x_id_name);
12409 f->explicit_name = 0;
12411 else
12413 f->name = name;
12414 f->explicit_name = 1;
12415 /* use the frame's title when getting resources for this frame. */
12416 specbind (Qx_resource_name, name);
12419 /* Extract the window parameters from the supplied values
12420 that are needed to determine window geometry. */
12422 Lisp_Object font;
12424 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12426 BLOCK_INPUT;
12427 /* First, try whatever font the caller has specified. */
12428 if (STRINGP (font))
12430 tem = Fquery_fontset (font, Qnil);
12431 if (STRINGP (tem))
12432 font = x_new_fontset (f, XSTRING (tem)->data);
12433 else
12434 font = x_new_font (f, XSTRING (font)->data);
12437 /* Try out a font which we hope has bold and italic variations. */
12438 if (!STRINGP (font))
12439 font = x_new_font (f, "-*-courier new-normal-r-*-*-*-100-*-*-*-*-iso8859-1");
12440 if (!STRINGP (font))
12441 font = x_new_font (f, "-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12442 if (! STRINGP (font))
12443 font = x_new_font (f, "-*-*-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12444 if (! STRINGP (font))
12445 /* This was formerly the first thing tried, but it finds too many fonts
12446 and takes too long. */
12447 font = x_new_font (f, "-*-*-medium-r-*-*-*-*-*-*-c-*-iso8859-1");
12448 /* If those didn't work, look for something which will at least work. */
12449 if (! STRINGP (font))
12450 font = x_new_font (f, "-*-fixed-*-*-*-*-*-140-*-*-c-*-iso8859-1");
12451 UNBLOCK_INPUT;
12452 if (! STRINGP (font))
12453 font = build_string ("fixed");
12455 x_default_parameter (f, parms, Qfont, font,
12456 "font", "Font", RES_TYPE_STRING);
12459 x_default_parameter (f, parms, Qborder_width, make_number (2),
12460 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
12462 /* This defaults to 2 in order to match xterm. We recognize either
12463 internalBorderWidth or internalBorder (which is what xterm calls
12464 it). */
12465 if (NILP (Fassq (Qinternal_border_width, parms)))
12467 Lisp_Object value;
12469 value = w32_get_arg (parms, Qinternal_border_width,
12470 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12471 if (! EQ (value, Qunbound))
12472 parms = Fcons (Fcons (Qinternal_border_width, value),
12473 parms);
12476 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
12477 "internalBorderWidth", "internalBorderWidth",
12478 RES_TYPE_NUMBER);
12480 /* Also do the stuff which must be set before the window exists. */
12481 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12482 "foreground", "Foreground", RES_TYPE_STRING);
12483 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12484 "background", "Background", RES_TYPE_STRING);
12485 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12486 "pointerColor", "Foreground", RES_TYPE_STRING);
12487 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12488 "cursorColor", "Foreground", RES_TYPE_STRING);
12489 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12490 "borderColor", "BorderColor", RES_TYPE_STRING);
12492 /* Init faces before x_default_parameter is called for scroll-bar
12493 parameters because that function calls x_set_scroll_bar_width,
12494 which calls change_frame_size, which calls Fset_window_buffer,
12495 which runs hooks, which call Fvertical_motion. At the end, we
12496 end up in init_iterator with a null face cache, which should not
12497 happen. */
12498 init_frame_faces (f);
12500 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12501 window_prompting = x_figure_window_size (f, parms);
12503 if (window_prompting & XNegative)
12505 if (window_prompting & YNegative)
12506 f->output_data.w32->win_gravity = SouthEastGravity;
12507 else
12508 f->output_data.w32->win_gravity = NorthEastGravity;
12510 else
12512 if (window_prompting & YNegative)
12513 f->output_data.w32->win_gravity = SouthWestGravity;
12514 else
12515 f->output_data.w32->win_gravity = NorthWestGravity;
12518 f->output_data.w32->size_hint_flags = window_prompting;
12520 XSetWindowAttributes attrs;
12521 unsigned long mask;
12523 BLOCK_INPUT;
12524 mask = CWBackPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask;
12525 /* Window managers looks at the override-redirect flag to
12526 determine whether or net to give windows a decoration (Xlib
12527 3.2.8). */
12528 attrs.override_redirect = True;
12529 attrs.save_under = True;
12530 attrs.background_pixel = FRAME_BACKGROUND_PIXEL (f);
12531 /* Arrange for getting MapNotify and UnmapNotify events. */
12532 attrs.event_mask = StructureNotifyMask;
12533 tip_window
12534 = FRAME_W32_WINDOW (f)
12535 = XCreateWindow (FRAME_W32_DISPLAY (f),
12536 FRAME_W32_DISPLAY_INFO (f)->root_window,
12537 /* x, y, width, height */
12538 0, 0, 1, 1,
12539 /* Border. */
12541 CopyFromParent, InputOutput, CopyFromParent,
12542 mask, &attrs);
12543 UNBLOCK_INPUT;
12546 x_make_gc (f);
12548 x_default_parameter (f, parms, Qauto_raise, Qnil,
12549 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12550 x_default_parameter (f, parms, Qauto_lower, Qnil,
12551 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12552 x_default_parameter (f, parms, Qcursor_type, Qbox,
12553 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12555 /* Dimensions, especially f->height, must be done via change_frame_size.
12556 Change will not be effected unless different from the current
12557 f->height. */
12558 width = f->width;
12559 height = f->height;
12560 f->height = 0;
12561 SET_FRAME_WIDTH (f, 0);
12562 change_frame_size (f, height, width, 1, 0, 0);
12564 f->no_split = 1;
12566 UNGCPRO;
12568 /* It is now ok to make the frame official even if we get an error
12569 below. And the frame needs to be on Vframe_list or making it
12570 visible won't work. */
12571 Vframe_list = Fcons (frame, Vframe_list);
12572 tip_frame = frame;
12574 /* Now that the frame is official, it counts as a reference to
12575 its display. */
12576 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
12578 return unbind_to (count, frame);
12579 #endif /* TODO */
12580 return Qnil;
12583 #ifdef TODO /* Tooltip support not complete. */
12584 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
12585 "Show STRING in a \"tooltip\" window on frame FRAME.\n\
12586 A tooltip window is a small window displaying a string.\n\
12588 FRAME nil or omitted means use the selected frame.\n\
12590 PARMS is an optional list of frame parameters which can be\n\
12591 used to change the tooltip's appearance.\n\
12593 Automatically hide the tooltip after TIMEOUT seconds.\n\
12594 TIMEOUT nil means use the default timeout of 5 seconds.\n\
12596 If the list of frame parameters PARAMS contains a `left' parameters,\n\
12597 the tooltip is displayed at that x-position. Otherwise it is\n\
12598 displayed at the mouse position, with offset DX added (default is 5 if\n\
12599 DX isn't specified). Likewise for the y-position; if a `top' frame\n\
12600 parameter is specified, it determines the y-position of the tooltip\n\
12601 window, otherwise it is displayed at the mouse position, with offset\n\
12602 DY added (default is 10).")
12603 (string, frame, parms, timeout, dx, dy)
12604 Lisp_Object string, frame, parms, timeout, dx, dy;
12606 struct frame *f;
12607 struct window *w;
12608 Window root, child;
12609 Lisp_Object buffer, top, left;
12610 struct buffer *old_buffer;
12611 struct text_pos pos;
12612 int i, width, height;
12613 int root_x, root_y, win_x, win_y;
12614 unsigned pmask;
12615 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
12616 int old_windows_or_buffers_changed = windows_or_buffers_changed;
12617 int count = specpdl_ptr - specpdl;
12619 specbind (Qinhibit_redisplay, Qt);
12621 GCPRO4 (string, parms, frame, timeout);
12623 CHECK_STRING (string, 0);
12624 f = check_x_frame (frame);
12625 if (NILP (timeout))
12626 timeout = make_number (5);
12627 else
12628 CHECK_NATNUM (timeout, 2);
12630 if (NILP (dx))
12631 dx = make_number (5);
12632 else
12633 CHECK_NUMBER (dx, 5);
12635 if (NILP (dy))
12636 dy = make_number (-10);
12637 else
12638 CHECK_NUMBER (dy, 6);
12640 if (NILP (last_show_tip_args))
12641 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
12643 if (!NILP (tip_frame))
12645 Lisp_Object last_string = AREF (last_show_tip_args, 0);
12646 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
12647 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
12649 if (EQ (frame, last_frame)
12650 && !NILP (Fequal (last_string, string))
12651 && !NILP (Fequal (last_parms, parms)))
12653 struct frame *f = XFRAME (tip_frame);
12655 /* Only DX and DY have changed. */
12656 if (!NILP (tip_timer))
12658 Lisp_Object timer = tip_timer;
12659 tip_timer = Qnil;
12660 call1 (Qcancel_timer, timer);
12663 BLOCK_INPUT;
12664 compute_tip_xy (f, parms, dx, dy, &root_x, &root_y);
12665 XMoveWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12666 root_x, root_y - PIXEL_HEIGHT (f));
12667 UNBLOCK_INPUT;
12668 goto start_timer;
12672 /* Hide a previous tip, if any. */
12673 Fx_hide_tip ();
12675 ASET (last_show_tip_args, 0, string);
12676 ASET (last_show_tip_args, 1, frame);
12677 ASET (last_show_tip_args, 2, parms);
12679 /* Add default values to frame parameters. */
12680 if (NILP (Fassq (Qname, parms)))
12681 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
12682 if (NILP (Fassq (Qinternal_border_width, parms)))
12683 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
12684 if (NILP (Fassq (Qborder_width, parms)))
12685 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
12686 if (NILP (Fassq (Qborder_color, parms)))
12687 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
12688 if (NILP (Fassq (Qbackground_color, parms)))
12689 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
12690 parms);
12692 /* Create a frame for the tooltip, and record it in the global
12693 variable tip_frame. */
12694 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms);
12695 f = XFRAME (frame);
12697 /* Set up the frame's root window. Currently we use a size of 80
12698 columns x 40 lines. If someone wants to show a larger tip, he
12699 will loose. I don't think this is a realistic case. */
12700 w = XWINDOW (FRAME_ROOT_WINDOW (f));
12701 w->left = w->top = make_number (0);
12702 w->width = make_number (80);
12703 w->height = make_number (40);
12704 adjust_glyphs (f);
12705 w->pseudo_window_p = 1;
12707 /* Display the tooltip text in a temporary buffer. */
12708 buffer = Fget_buffer_create (build_string (" *tip*"));
12709 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
12710 old_buffer = current_buffer;
12711 set_buffer_internal_1 (XBUFFER (buffer));
12712 Ferase_buffer ();
12713 Finsert (1, &string);
12714 clear_glyph_matrix (w->desired_matrix);
12715 clear_glyph_matrix (w->current_matrix);
12716 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
12717 try_window (FRAME_ROOT_WINDOW (f), pos);
12719 /* Compute width and height of the tooltip. */
12720 width = height = 0;
12721 for (i = 0; i < w->desired_matrix->nrows; ++i)
12723 struct glyph_row *row = &w->desired_matrix->rows[i];
12724 struct glyph *last;
12725 int row_width;
12727 /* Stop at the first empty row at the end. */
12728 if (!row->enabled_p || !row->displays_text_p)
12729 break;
12731 /* Let the row go over the full width of the frame. */
12732 row->full_width_p = 1;
12734 /* There's a glyph at the end of rows that is use to place
12735 the cursor there. Don't include the width of this glyph. */
12736 if (row->used[TEXT_AREA])
12738 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
12739 row_width = row->pixel_width - last->pixel_width;
12741 else
12742 row_width = row->pixel_width;
12744 height += row->height;
12745 width = max (width, row_width);
12748 /* Add the frame's internal border to the width and height the X
12749 window should have. */
12750 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12751 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12753 /* Move the tooltip window where the mouse pointer is. Resize and
12754 show it. */
12755 compute_tip_xy (f, parms, dx, dy, &root_x, &root_y);
12757 #if 0 /* TODO : W32 specifics */
12758 BLOCK_INPUT;
12759 XMoveResizeWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12760 root_x, root_y - height, width, height);
12761 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12762 UNBLOCK_INPUT;
12763 #endif /* TODO */
12765 /* Draw into the window. */
12766 w->must_be_updated_p = 1;
12767 update_single_window (w, 1);
12769 /* Restore original current buffer. */
12770 set_buffer_internal_1 (old_buffer);
12771 windows_or_buffers_changed = old_windows_or_buffers_changed;
12773 start_timer:
12774 /* Let the tip disappear after timeout seconds. */
12775 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
12776 intern ("x-hide-tip"));
12778 UNGCPRO;
12779 return unbind_to (count, Qnil);
12783 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
12784 "Hide the current tooltip window, if there is any.\n\
12785 Value is t is tooltip was open, nil otherwise.")
12788 int count;
12789 Lisp_Object deleted, frame, timer;
12790 struct gcpro gcpro1, gcpro2;
12792 /* Return quickly if nothing to do. */
12793 if (NILP (tip_timer) && NILP (tip_frame))
12794 return Qnil;
12796 frame = tip_frame;
12797 timer = tip_timer;
12798 GCPRO2 (frame, timer);
12799 tip_frame = tip_timer = deleted = Qnil;
12801 count = BINDING_STACK_SIZE ();
12802 specbind (Qinhibit_redisplay, Qt);
12803 specbind (Qinhibit_quit, Qt);
12805 if (!NILP (timer))
12806 call1 (Qcancel_timer, timer);
12808 if (FRAMEP (frame))
12810 Fdelete_frame (frame, Qnil);
12811 deleted = Qt;
12814 UNGCPRO;
12815 return unbind_to (count, deleted);
12817 #endif
12821 /***********************************************************************
12822 File selection dialog
12823 ***********************************************************************/
12825 extern Lisp_Object Qfile_name_history;
12827 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
12828 "Read file name, prompting with PROMPT in directory DIR.\n\
12829 Use a file selection dialog.\n\
12830 Select DEFAULT-FILENAME in the dialog's file selection box, if\n\
12831 specified. Don't let the user enter a file name in the file\n\
12832 selection dialog's entry field, if MUSTMATCH is non-nil.")
12833 (prompt, dir, default_filename, mustmatch)
12834 Lisp_Object prompt, dir, default_filename, mustmatch;
12836 struct frame *f = SELECTED_FRAME ();
12837 Lisp_Object file = Qnil;
12838 int count = specpdl_ptr - specpdl;
12839 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
12840 char filename[MAX_PATH + 1];
12841 char init_dir[MAX_PATH + 1];
12842 int use_dialog_p = 1;
12844 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
12845 CHECK_STRING (prompt, 0);
12846 CHECK_STRING (dir, 1);
12848 /* Create the dialog with PROMPT as title, using DIR as initial
12849 directory and using "*" as pattern. */
12850 dir = Fexpand_file_name (dir, Qnil);
12851 strncpy (init_dir, XSTRING (dir)->data, MAX_PATH);
12852 init_dir[MAX_PATH] = '\0';
12853 unixtodos_filename (init_dir);
12855 if (STRINGP (default_filename))
12857 char *file_name_only;
12858 char *full_path_name = XSTRING (default_filename)->data;
12860 unixtodos_filename (full_path_name);
12862 file_name_only = strrchr (full_path_name, '\\');
12863 if (!file_name_only)
12864 file_name_only = full_path_name;
12865 else
12867 file_name_only++;
12869 /* If default_file_name is a directory, don't use the open
12870 file dialog, as it does not support selecting
12871 directories. */
12872 if (!(*file_name_only))
12873 use_dialog_p = 0;
12876 strncpy (filename, file_name_only, MAX_PATH);
12877 filename[MAX_PATH] = '\0';
12879 else
12880 filename[0] = '\0';
12882 if (use_dialog_p)
12884 OPENFILENAME file_details;
12886 /* Prevent redisplay. */
12887 specbind (Qinhibit_redisplay, Qt);
12888 BLOCK_INPUT;
12890 bzero (&file_details, sizeof (file_details));
12891 file_details.lStructSize = sizeof (file_details);
12892 file_details.hwndOwner = FRAME_W32_WINDOW (f);
12893 file_details.lpstrFile = filename;
12894 file_details.nMaxFile = sizeof (filename);
12895 file_details.lpstrInitialDir = init_dir;
12896 file_details.lpstrTitle = XSTRING (prompt)->data;
12897 file_details.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
12899 if (!NILP (mustmatch))
12900 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
12902 if (GetOpenFileName (&file_details))
12904 dostounix_filename (filename);
12905 file = build_string (filename);
12907 else
12908 file = Qnil;
12910 UNBLOCK_INPUT;
12911 file = unbind_to (count, file);
12913 /* Open File dialog will not allow folders to be selected, so resort
12914 to minibuffer completing reads for directories. */
12915 else
12916 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
12917 dir, mustmatch, dir, Qfile_name_history,
12918 default_filename, Qnil);
12920 UNGCPRO;
12922 /* Make "Cancel" equivalent to C-g. */
12923 if (NILP (file))
12924 Fsignal (Qquit, Qnil);
12926 return unbind_to (count, file);
12931 /***********************************************************************
12932 Tests
12933 ***********************************************************************/
12935 #if GLYPH_DEBUG
12937 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
12938 "Value is non-nil if SPEC is a valid image specification.")
12939 (spec)
12940 Lisp_Object spec;
12942 return valid_image_p (spec) ? Qt : Qnil;
12946 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
12947 (spec)
12948 Lisp_Object spec;
12950 int id = -1;
12952 if (valid_image_p (spec))
12953 id = lookup_image (SELECTED_FRAME (), spec);
12955 debug_print (spec);
12956 return make_number (id);
12959 #endif /* GLYPH_DEBUG != 0 */
12963 /***********************************************************************
12964 w32 specialized functions
12965 ***********************************************************************/
12967 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 1, 0,
12968 "This will display the W32 font dialog and return an X font string corresponding to the selection.")
12969 (frame)
12970 Lisp_Object frame;
12972 FRAME_PTR f = check_x_frame (frame);
12973 CHOOSEFONT cf;
12974 LOGFONT lf;
12975 TEXTMETRIC tm;
12976 HDC hdc;
12977 HANDLE oldobj;
12978 char buf[100];
12980 bzero (&cf, sizeof (cf));
12981 bzero (&lf, sizeof (lf));
12983 cf.lStructSize = sizeof (cf);
12984 cf.hwndOwner = FRAME_W32_WINDOW (f);
12985 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS;
12986 cf.lpLogFont = &lf;
12988 /* Initialize as much of the font details as we can from the current
12989 default font. */
12990 hdc = GetDC (FRAME_W32_WINDOW (f));
12991 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
12992 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
12993 if (GetTextMetrics (hdc, &tm))
12995 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
12996 lf.lfWeight = tm.tmWeight;
12997 lf.lfItalic = tm.tmItalic;
12998 lf.lfUnderline = tm.tmUnderlined;
12999 lf.lfStrikeOut = tm.tmStruckOut;
13000 lf.lfCharSet = tm.tmCharSet;
13001 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
13003 SelectObject (hdc, oldobj);
13004 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
13006 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
13007 return Qnil;
13009 return build_string (buf);
13012 DEFUN ("w32-send-sys-command", Fw32_send_sys_command, Sw32_send_sys_command, 1, 2, 0,
13013 "Send frame a Windows WM_SYSCOMMAND message of type COMMAND.\n\
13014 Some useful values for command are 0xf030 to maximise frame (0xf020\n\
13015 to minimize), 0xf120 to restore frame to original size, and 0xf100\n\
13016 to activate the menubar for keyboard access. 0xf140 activates the\n\
13017 screen saver if defined.\n\
13019 If optional parameter FRAME is not specified, use selected frame.")
13020 (command, frame)
13021 Lisp_Object command, frame;
13023 FRAME_PTR f = check_x_frame (frame);
13025 CHECK_NUMBER (command, 0);
13027 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
13029 return Qnil;
13032 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
13033 "Get Windows to perform OPERATION on DOCUMENT.\n\
13034 This is a wrapper around the ShellExecute system function, which\n\
13035 invokes the application registered to handle OPERATION for DOCUMENT.\n\
13036 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be\n\
13037 nil for the default action), and DOCUMENT is typically the name of a\n\
13038 document file or URL, but can also be a program executable to run or\n\
13039 a directory to open in the Windows Explorer.\n\
13041 If DOCUMENT is a program executable, PARAMETERS can be a string\n\
13042 containing command line parameters, but otherwise should be nil.\n\
13044 SHOW-FLAG can be used to control whether the invoked application is hidden\n\
13045 or minimized. If SHOW-FLAG is nil, the application is displayed normally,\n\
13046 otherwise it is an integer representing a ShowWindow flag:\n\
13048 0 - start hidden\n\
13049 1 - start normally\n\
13050 3 - start maximized\n\
13051 6 - start minimized")
13052 (operation, document, parameters, show_flag)
13053 Lisp_Object operation, document, parameters, show_flag;
13055 Lisp_Object current_dir;
13057 CHECK_STRING (document, 0);
13059 /* Encode filename and current directory. */
13060 current_dir = ENCODE_FILE (current_buffer->directory);
13061 document = ENCODE_FILE (document);
13062 if ((int) ShellExecute (NULL,
13063 (STRINGP (operation) ?
13064 XSTRING (operation)->data : NULL),
13065 XSTRING (document)->data,
13066 (STRINGP (parameters) ?
13067 XSTRING (parameters)->data : NULL),
13068 XSTRING (current_dir)->data,
13069 (INTEGERP (show_flag) ?
13070 XINT (show_flag) : SW_SHOWDEFAULT))
13071 > 32)
13072 return Qt;
13073 error ("ShellExecute failed: %s", w32_strerror (0));
13076 /* Lookup virtual keycode from string representing the name of a
13077 non-ascii keystroke into the corresponding virtual key, using
13078 lispy_function_keys. */
13079 static int
13080 lookup_vk_code (char *key)
13082 int i;
13084 for (i = 0; i < 256; i++)
13085 if (lispy_function_keys[i] != 0
13086 && strcmp (lispy_function_keys[i], key) == 0)
13087 return i;
13089 return -1;
13092 /* Convert a one-element vector style key sequence to a hot key
13093 definition. */
13094 static int
13095 w32_parse_hot_key (key)
13096 Lisp_Object key;
13098 /* Copied from Fdefine_key and store_in_keymap. */
13099 register Lisp_Object c;
13100 int vk_code;
13101 int lisp_modifiers;
13102 int w32_modifiers;
13103 struct gcpro gcpro1;
13105 CHECK_VECTOR (key, 0);
13107 if (XFASTINT (Flength (key)) != 1)
13108 return Qnil;
13110 GCPRO1 (key);
13112 c = Faref (key, make_number (0));
13114 if (CONSP (c) && lucid_event_type_list_p (c))
13115 c = Fevent_convert_list (c);
13117 UNGCPRO;
13119 if (! INTEGERP (c) && ! SYMBOLP (c))
13120 error ("Key definition is invalid");
13122 /* Work out the base key and the modifiers. */
13123 if (SYMBOLP (c))
13125 c = parse_modifiers (c);
13126 lisp_modifiers = Fcar (Fcdr (c));
13127 c = Fcar (c);
13128 if (!SYMBOLP (c))
13129 abort ();
13130 vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
13132 else if (INTEGERP (c))
13134 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
13135 /* Many ascii characters are their own virtual key code. */
13136 vk_code = XINT (c) & CHARACTERBITS;
13139 if (vk_code < 0 || vk_code > 255)
13140 return Qnil;
13142 if ((lisp_modifiers & meta_modifier) != 0
13143 && !NILP (Vw32_alt_is_meta))
13144 lisp_modifiers |= alt_modifier;
13146 /* Supply defs missing from mingw32. */
13147 #ifndef MOD_ALT
13148 #define MOD_ALT 0x0001
13149 #define MOD_CONTROL 0x0002
13150 #define MOD_SHIFT 0x0004
13151 #define MOD_WIN 0x0008
13152 #endif
13154 /* Convert lisp modifiers to Windows hot-key form. */
13155 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
13156 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
13157 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
13158 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
13160 return HOTKEY (vk_code, w32_modifiers);
13163 DEFUN ("w32-register-hot-key", Fw32_register_hot_key, Sw32_register_hot_key, 1, 1, 0,
13164 "Register KEY as a hot-key combination.\n\
13165 Certain key combinations like Alt-Tab are reserved for system use on\n\
13166 Windows, and therefore are normally intercepted by the system. However,\n\
13167 most of these key combinations can be received by registering them as\n\
13168 hot-keys, overriding their special meaning.\n\
13170 KEY must be a one element key definition in vector form that would be\n\
13171 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta\n\
13172 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper\n\
13173 is always interpreted as the Windows modifier keys.\n\
13175 The return value is the hotkey-id if registered, otherwise nil.")
13176 (key)
13177 Lisp_Object key;
13179 key = w32_parse_hot_key (key);
13181 if (NILP (Fmemq (key, w32_grabbed_keys)))
13183 /* Reuse an empty slot if possible. */
13184 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
13186 /* Safe to add new key to list, even if we have focus. */
13187 if (NILP (item))
13188 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
13189 else
13190 XCAR (item) = key;
13192 /* Notify input thread about new hot-key definition, so that it
13193 takes effect without needing to switch focus. */
13194 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
13195 (WPARAM) key, 0);
13198 return key;
13201 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key, Sw32_unregister_hot_key, 1, 1, 0,
13202 "Unregister HOTKEY as a hot-key combination.")
13203 (key)
13204 Lisp_Object key;
13206 Lisp_Object item;
13208 if (!INTEGERP (key))
13209 key = w32_parse_hot_key (key);
13211 item = Fmemq (key, w32_grabbed_keys);
13213 if (!NILP (item))
13215 /* Notify input thread about hot-key definition being removed, so
13216 that it takes effect without needing focus switch. */
13217 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
13218 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
13220 MSG msg;
13221 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13223 return Qt;
13225 return Qnil;
13228 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys, Sw32_registered_hot_keys, 0, 0, 0,
13229 "Return list of registered hot-key IDs.")
13232 return Fcopy_sequence (w32_grabbed_keys);
13235 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key, Sw32_reconstruct_hot_key, 1, 1, 0,
13236 "Convert hot-key ID to a lisp key combination.")
13237 (hotkeyid)
13238 Lisp_Object hotkeyid;
13240 int vk_code, w32_modifiers;
13241 Lisp_Object key;
13243 CHECK_NUMBER (hotkeyid, 0);
13245 vk_code = HOTKEY_VK_CODE (hotkeyid);
13246 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
13248 if (lispy_function_keys[vk_code])
13249 key = intern (lispy_function_keys[vk_code]);
13250 else
13251 key = make_number (vk_code);
13253 key = Fcons (key, Qnil);
13254 if (w32_modifiers & MOD_SHIFT)
13255 key = Fcons (Qshift, key);
13256 if (w32_modifiers & MOD_CONTROL)
13257 key = Fcons (Qctrl, key);
13258 if (w32_modifiers & MOD_ALT)
13259 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
13260 if (w32_modifiers & MOD_WIN)
13261 key = Fcons (Qhyper, key);
13263 return key;
13266 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key, Sw32_toggle_lock_key, 1, 2, 0,
13267 "Toggle the state of the lock key KEY.\n\
13268 KEY can be `capslock', `kp-numlock', or `scroll'.\n\
13269 If the optional parameter NEW-STATE is a number, then the state of KEY\n\
13270 is set to off if the low bit of NEW-STATE is zero, otherwise on.")
13271 (key, new_state)
13272 Lisp_Object key, new_state;
13274 int vk_code;
13276 if (EQ (key, intern ("capslock")))
13277 vk_code = VK_CAPITAL;
13278 else if (EQ (key, intern ("kp-numlock")))
13279 vk_code = VK_NUMLOCK;
13280 else if (EQ (key, intern ("scroll")))
13281 vk_code = VK_SCROLL;
13282 else
13283 return Qnil;
13285 if (!dwWindowsThreadId)
13286 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
13288 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
13289 (WPARAM) vk_code, (LPARAM) new_state))
13291 MSG msg;
13292 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13293 return make_number (msg.wParam);
13295 return Qnil;
13298 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
13299 "Return storage information about the file system FILENAME is on.\n\
13300 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total\n\
13301 storage of the file system, FREE is the free storage, and AVAIL is the\n\
13302 storage available to a non-superuser. All 3 numbers are in bytes.\n\
13303 If the underlying system call fails, value is nil.")
13304 (filename)
13305 Lisp_Object filename;
13307 Lisp_Object encoded, value;
13309 CHECK_STRING (filename, 0);
13310 filename = Fexpand_file_name (filename, Qnil);
13311 encoded = ENCODE_FILE (filename);
13313 value = Qnil;
13315 /* Determining the required information on Windows turns out, sadly,
13316 to be more involved than one would hope. The original Win32 api
13317 call for this will return bogus information on some systems, but we
13318 must dynamically probe for the replacement api, since that was
13319 added rather late on. */
13321 HMODULE hKernel = GetModuleHandle ("kernel32");
13322 BOOL (*pfn_GetDiskFreeSpaceEx)
13323 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
13324 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
13326 /* On Windows, we may need to specify the root directory of the
13327 volume holding FILENAME. */
13328 char rootname[MAX_PATH];
13329 char *name = XSTRING (encoded)->data;
13331 /* find the root name of the volume if given */
13332 if (isalpha (name[0]) && name[1] == ':')
13334 rootname[0] = name[0];
13335 rootname[1] = name[1];
13336 rootname[2] = '\\';
13337 rootname[3] = 0;
13339 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
13341 char *str = rootname;
13342 int slashes = 4;
13345 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
13346 break;
13347 *str++ = *name++;
13349 while ( *name );
13351 *str++ = '\\';
13352 *str = 0;
13355 if (pfn_GetDiskFreeSpaceEx)
13357 LARGE_INTEGER availbytes;
13358 LARGE_INTEGER freebytes;
13359 LARGE_INTEGER totalbytes;
13361 if (pfn_GetDiskFreeSpaceEx(rootname,
13362 &availbytes,
13363 &totalbytes,
13364 &freebytes))
13365 value = list3 (make_float ((double) totalbytes.QuadPart),
13366 make_float ((double) freebytes.QuadPart),
13367 make_float ((double) availbytes.QuadPart));
13369 else
13371 DWORD sectors_per_cluster;
13372 DWORD bytes_per_sector;
13373 DWORD free_clusters;
13374 DWORD total_clusters;
13376 if (GetDiskFreeSpace(rootname,
13377 &sectors_per_cluster,
13378 &bytes_per_sector,
13379 &free_clusters,
13380 &total_clusters))
13381 value = list3 (make_float ((double) total_clusters
13382 * sectors_per_cluster * bytes_per_sector),
13383 make_float ((double) free_clusters
13384 * sectors_per_cluster * bytes_per_sector),
13385 make_float ((double) free_clusters
13386 * sectors_per_cluster * bytes_per_sector));
13390 return value;
13393 syms_of_w32fns ()
13395 /* This is zero if not using MS-Windows. */
13396 w32_in_use = 0;
13398 /* The section below is built by the lisp expression at the top of the file,
13399 just above where these variables are declared. */
13400 /*&&& init symbols here &&&*/
13401 Qauto_raise = intern ("auto-raise");
13402 staticpro (&Qauto_raise);
13403 Qauto_lower = intern ("auto-lower");
13404 staticpro (&Qauto_lower);
13405 Qbar = intern ("bar");
13406 staticpro (&Qbar);
13407 Qborder_color = intern ("border-color");
13408 staticpro (&Qborder_color);
13409 Qborder_width = intern ("border-width");
13410 staticpro (&Qborder_width);
13411 Qbox = intern ("box");
13412 staticpro (&Qbox);
13413 Qcursor_color = intern ("cursor-color");
13414 staticpro (&Qcursor_color);
13415 Qcursor_type = intern ("cursor-type");
13416 staticpro (&Qcursor_type);
13417 Qgeometry = intern ("geometry");
13418 staticpro (&Qgeometry);
13419 Qicon_left = intern ("icon-left");
13420 staticpro (&Qicon_left);
13421 Qicon_top = intern ("icon-top");
13422 staticpro (&Qicon_top);
13423 Qicon_type = intern ("icon-type");
13424 staticpro (&Qicon_type);
13425 Qicon_name = intern ("icon-name");
13426 staticpro (&Qicon_name);
13427 Qinternal_border_width = intern ("internal-border-width");
13428 staticpro (&Qinternal_border_width);
13429 Qleft = intern ("left");
13430 staticpro (&Qleft);
13431 Qright = intern ("right");
13432 staticpro (&Qright);
13433 Qmouse_color = intern ("mouse-color");
13434 staticpro (&Qmouse_color);
13435 Qnone = intern ("none");
13436 staticpro (&Qnone);
13437 Qparent_id = intern ("parent-id");
13438 staticpro (&Qparent_id);
13439 Qscroll_bar_width = intern ("scroll-bar-width");
13440 staticpro (&Qscroll_bar_width);
13441 Qsuppress_icon = intern ("suppress-icon");
13442 staticpro (&Qsuppress_icon);
13443 Qundefined_color = intern ("undefined-color");
13444 staticpro (&Qundefined_color);
13445 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
13446 staticpro (&Qvertical_scroll_bars);
13447 Qvisibility = intern ("visibility");
13448 staticpro (&Qvisibility);
13449 Qwindow_id = intern ("window-id");
13450 staticpro (&Qwindow_id);
13451 Qx_frame_parameter = intern ("x-frame-parameter");
13452 staticpro (&Qx_frame_parameter);
13453 Qx_resource_name = intern ("x-resource-name");
13454 staticpro (&Qx_resource_name);
13455 Quser_position = intern ("user-position");
13456 staticpro (&Quser_position);
13457 Quser_size = intern ("user-size");
13458 staticpro (&Quser_size);
13459 Qscreen_gamma = intern ("screen-gamma");
13460 staticpro (&Qscreen_gamma);
13461 Qline_spacing = intern ("line-spacing");
13462 staticpro (&Qline_spacing);
13463 Qcenter = intern ("center");
13464 staticpro (&Qcenter);
13465 Qcancel_timer = intern ("cancel-timer");
13466 staticpro (&Qcancel_timer);
13467 /* This is the end of symbol initialization. */
13469 Qhyper = intern ("hyper");
13470 staticpro (&Qhyper);
13471 Qsuper = intern ("super");
13472 staticpro (&Qsuper);
13473 Qmeta = intern ("meta");
13474 staticpro (&Qmeta);
13475 Qalt = intern ("alt");
13476 staticpro (&Qalt);
13477 Qctrl = intern ("ctrl");
13478 staticpro (&Qctrl);
13479 Qcontrol = intern ("control");
13480 staticpro (&Qcontrol);
13481 Qshift = intern ("shift");
13482 staticpro (&Qshift);
13484 /* Text property `display' should be nonsticky by default. */
13485 Vtext_property_default_nonsticky
13486 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
13489 Qlaplace = intern ("laplace");
13490 staticpro (&Qlaplace);
13492 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
13493 staticpro (&Qface_set_after_frame_default);
13495 Fput (Qundefined_color, Qerror_conditions,
13496 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
13497 Fput (Qundefined_color, Qerror_message,
13498 build_string ("Undefined color"));
13500 staticpro (&w32_grabbed_keys);
13501 w32_grabbed_keys = Qnil;
13503 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
13504 "An array of color name mappings for windows.");
13505 Vw32_color_map = Qnil;
13507 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
13508 "Non-nil if alt key presses are passed on to Windows.\n\
13509 When non-nil, for example, alt pressed and released and then space will\n\
13510 open the System menu. When nil, Emacs silently swallows alt key events.");
13511 Vw32_pass_alt_to_system = Qnil;
13513 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
13514 "Non-nil if the alt key is to be considered the same as the meta key.\n\
13515 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta.");
13516 Vw32_alt_is_meta = Qt;
13518 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
13519 "If non-zero, the virtual key code for an alternative quit key.");
13520 XSETINT (Vw32_quit_key, 0);
13522 DEFVAR_LISP ("w32-pass-lwindow-to-system",
13523 &Vw32_pass_lwindow_to_system,
13524 "Non-nil if the left \"Windows\" key is passed on to Windows.\n\
13525 When non-nil, the Start menu is opened by tapping the key.");
13526 Vw32_pass_lwindow_to_system = Qt;
13528 DEFVAR_LISP ("w32-pass-rwindow-to-system",
13529 &Vw32_pass_rwindow_to_system,
13530 "Non-nil if the right \"Windows\" key is passed on to Windows.\n\
13531 When non-nil, the Start menu is opened by tapping the key.");
13532 Vw32_pass_rwindow_to_system = Qt;
13534 DEFVAR_INT ("w32-phantom-key-code",
13535 &Vw32_phantom_key_code,
13536 "Virtual key code used to generate \"phantom\" key presses.\n\
13537 Value is a number between 0 and 255.\n\
13539 Phantom key presses are generated in order to stop the system from\n\
13540 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or\n\
13541 `w32-pass-rwindow-to-system' is nil.");
13542 /* Although 255 is technically not a valid key code, it works and
13543 means that this hack won't interfere with any real key code. */
13544 Vw32_phantom_key_code = 255;
13546 DEFVAR_LISP ("w32-enable-num-lock",
13547 &Vw32_enable_num_lock,
13548 "Non-nil if Num Lock should act normally.\n\
13549 Set to nil to see Num Lock as the key `kp-numlock'.");
13550 Vw32_enable_num_lock = Qt;
13552 DEFVAR_LISP ("w32-enable-caps-lock",
13553 &Vw32_enable_caps_lock,
13554 "Non-nil if Caps Lock should act normally.\n\
13555 Set to nil to see Caps Lock as the key `capslock'.");
13556 Vw32_enable_caps_lock = Qt;
13558 DEFVAR_LISP ("w32-scroll-lock-modifier",
13559 &Vw32_scroll_lock_modifier,
13560 "Modifier to use for the Scroll Lock on state.\n\
13561 The value can be hyper, super, meta, alt, control or shift for the\n\
13562 respective modifier, or nil to see Scroll Lock as the key `scroll'.\n\
13563 Any other value will cause the key to be ignored.");
13564 Vw32_scroll_lock_modifier = Qt;
13566 DEFVAR_LISP ("w32-lwindow-modifier",
13567 &Vw32_lwindow_modifier,
13568 "Modifier to use for the left \"Windows\" key.\n\
13569 The value can be hyper, super, meta, alt, control or shift for the\n\
13570 respective modifier, or nil to appear as the key `lwindow'.\n\
13571 Any other value will cause the key to be ignored.");
13572 Vw32_lwindow_modifier = Qnil;
13574 DEFVAR_LISP ("w32-rwindow-modifier",
13575 &Vw32_rwindow_modifier,
13576 "Modifier to use for the right \"Windows\" key.\n\
13577 The value can be hyper, super, meta, alt, control or shift for the\n\
13578 respective modifier, or nil to appear as the key `rwindow'.\n\
13579 Any other value will cause the key to be ignored.");
13580 Vw32_rwindow_modifier = Qnil;
13582 DEFVAR_LISP ("w32-apps-modifier",
13583 &Vw32_apps_modifier,
13584 "Modifier to use for the \"Apps\" key.\n\
13585 The value can be hyper, super, meta, alt, control or shift for the\n\
13586 respective modifier, or nil to appear as the key `apps'.\n\
13587 Any other value will cause the key to be ignored.");
13588 Vw32_apps_modifier = Qnil;
13590 DEFVAR_LISP ("w32-enable-synthesized-fonts", &Vw32_enable_synthesized_fonts,
13591 "Non-nil enables selection of artificially italicized and bold fonts.");
13592 Vw32_enable_synthesized_fonts = Qnil;
13594 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
13595 "Non-nil enables Windows palette management to map colors exactly.");
13596 Vw32_enable_palette = Qt;
13598 DEFVAR_INT ("w32-mouse-button-tolerance",
13599 &Vw32_mouse_button_tolerance,
13600 "Analogue of double click interval for faking middle mouse events.\n\
13601 The value is the minimum time in milliseconds that must elapse between\n\
13602 left/right button down events before they are considered distinct events.\n\
13603 If both mouse buttons are depressed within this interval, a middle mouse\n\
13604 button down event is generated instead.");
13605 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
13607 DEFVAR_INT ("w32-mouse-move-interval",
13608 &Vw32_mouse_move_interval,
13609 "Minimum interval between mouse move events.\n\
13610 The value is the minimum time in milliseconds that must elapse between\n\
13611 successive mouse move (or scroll bar drag) events before they are\n\
13612 reported as lisp events.");
13613 XSETINT (Vw32_mouse_move_interval, 0);
13615 init_x_parm_symbols ();
13617 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
13618 "List of directories to search for bitmap files for w32.");
13619 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
13621 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
13622 "The shape of the pointer when over text.\n\
13623 Changing the value does not affect existing frames\n\
13624 unless you set the mouse color.");
13625 Vx_pointer_shape = Qnil;
13627 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
13628 "The name Emacs uses to look up resources; for internal use only.\n\
13629 `x-get-resource' uses this as the first component of the instance name\n\
13630 when requesting resource values.\n\
13631 Emacs initially sets `x-resource-name' to the name under which Emacs\n\
13632 was invoked, or to the value specified with the `-name' or `-rn'\n\
13633 switches, if present.");
13634 Vx_resource_name = Qnil;
13636 Vx_nontext_pointer_shape = Qnil;
13638 Vx_mode_pointer_shape = Qnil;
13640 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
13641 "The shape of the pointer when Emacs is busy.\n\
13642 This variable takes effect when you create a new frame\n\
13643 or when you set the mouse color.");
13644 Vx_hourglass_pointer_shape = Qnil;
13646 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
13647 "Non-zero means Emacs displays an hourglass pointer on window systems.");
13648 display_hourglass_p = 1;
13650 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
13651 "*Seconds to wait before displaying an hourglass pointer.\n\
13652 Value must be an integer or float.");
13653 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
13655 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
13656 &Vx_sensitive_text_pointer_shape,
13657 "The shape of the pointer when over mouse-sensitive text.\n\
13658 This variable takes effect when you create a new frame\n\
13659 or when you set the mouse color.");
13660 Vx_sensitive_text_pointer_shape = Qnil;
13662 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
13663 &Vx_window_horizontal_drag_shape,
13664 "Pointer shape to use for indicating a window can be dragged horizontally.\n\
13665 This variable takes effect when you create a new frame\n\
13666 or when you set the mouse color.");
13667 Vx_window_horizontal_drag_shape = Qnil;
13669 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
13670 "A string indicating the foreground color of the cursor box.");
13671 Vx_cursor_fore_pixel = Qnil;
13673 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
13674 "Non-nil if no window manager is in use.\n\
13675 Emacs doesn't try to figure this out; this is always nil\n\
13676 unless you set it to something else.");
13677 /* We don't have any way to find this out, so set it to nil
13678 and maybe the user would like to set it to t. */
13679 Vx_no_window_manager = Qnil;
13681 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
13682 &Vx_pixel_size_width_font_regexp,
13683 "Regexp matching a font name whose width is the same as `PIXEL_SIZE'.\n\
13685 Since Emacs gets width of a font matching with this regexp from\n\
13686 PIXEL_SIZE field of the name, font finding mechanism gets faster for\n\
13687 such a font. This is especially effective for such large fonts as\n\
13688 Chinese, Japanese, and Korean.");
13689 Vx_pixel_size_width_font_regexp = Qnil;
13691 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
13692 "Time after which cached images are removed from the cache.\n\
13693 When an image has not been displayed this many seconds, remove it\n\
13694 from the image cache. Value must be an integer or nil with nil\n\
13695 meaning don't clear the cache.");
13696 Vimage_cache_eviction_delay = make_number (30 * 60);
13698 DEFVAR_LISP ("w32-bdf-filename-alist",
13699 &Vw32_bdf_filename_alist,
13700 "List of bdf fonts and their corresponding filenames.");
13701 Vw32_bdf_filename_alist = Qnil;
13703 DEFVAR_BOOL ("w32-strict-fontnames",
13704 &w32_strict_fontnames,
13705 "Non-nil means only use fonts that are exact matches for those requested.\n\
13706 Default is nil, which allows old fontnames that are not XLFD compliant,\n\
13707 and allows third-party CJK display to work by specifying false charset\n\
13708 fields to trick Emacs into translating to Big5, SJIS etc.\n\
13709 Setting this to t will prevent wrong fonts being selected when\n\
13710 fontsets are automatically created.");
13711 w32_strict_fontnames = 0;
13713 DEFVAR_BOOL ("w32-strict-painting",
13714 &w32_strict_painting,
13715 "Non-nil means use strict rules for repainting frames.\n\
13716 Set this to nil to get the old behaviour for repainting; this should\n\
13717 only be necessary if the default setting causes problems.");
13718 w32_strict_painting = 1;
13720 DEFVAR_LISP ("w32-system-coding-system",
13721 &Vw32_system_coding_system,
13722 "Coding system used by Windows system functions, such as for font names.");
13723 Vw32_system_coding_system = Qnil;
13725 DEFVAR_LISP ("w32-charset-info-alist",
13726 &Vw32_charset_info_alist,
13727 "Alist linking Emacs character sets to Windows fonts\n\
13728 and codepages. Each entry should be of the form:\n\
13730 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))\n\
13732 where CHARSET_NAME is a string used in font names to identify the charset,\n\
13733 WINDOWS_CHARSET is a symbol that can be one of:\n\
13734 w32-charset-ansi, w32-charset-default, w32-charset-symbol,\n\
13735 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,\n\
13736 w32-charset-chinesebig5, "
13737 #ifdef JOHAB_CHARSET
13738 "w32-charset-johab, w32-charset-hebrew,\n\
13739 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,\n\
13740 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,\n\
13741 w32-charset-russian, w32-charset-mac, w32-charset-baltic,\n"
13742 #endif
13743 #ifdef UNICODE_CHARSET
13744 "w32-charset-unicode, "
13745 #endif
13746 "or w32-charset-oem.\n\
13747 CODEPAGE should be an integer specifying the codepage that should be used\n\
13748 to display the character set, t to do no translation and output as Unicode,\n\
13749 or nil to do no translation and output as 8 bit (or multibyte on far-east\n\
13750 versions of Windows) characters.");
13751 Vw32_charset_info_alist = Qnil;
13753 staticpro (&Qw32_charset_ansi);
13754 Qw32_charset_ansi = intern ("w32-charset-ansi");
13755 staticpro (&Qw32_charset_symbol);
13756 Qw32_charset_symbol = intern ("w32-charset-symbol");
13757 staticpro (&Qw32_charset_shiftjis);
13758 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
13759 staticpro (&Qw32_charset_hangeul);
13760 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
13761 staticpro (&Qw32_charset_chinesebig5);
13762 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
13763 staticpro (&Qw32_charset_gb2312);
13764 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
13765 staticpro (&Qw32_charset_oem);
13766 Qw32_charset_oem = intern ("w32-charset-oem");
13768 #ifdef JOHAB_CHARSET
13770 static int w32_extra_charsets_defined = 1;
13771 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined, "");
13773 staticpro (&Qw32_charset_johab);
13774 Qw32_charset_johab = intern ("w32-charset-johab");
13775 staticpro (&Qw32_charset_easteurope);
13776 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
13777 staticpro (&Qw32_charset_turkish);
13778 Qw32_charset_turkish = intern ("w32-charset-turkish");
13779 staticpro (&Qw32_charset_baltic);
13780 Qw32_charset_baltic = intern ("w32-charset-baltic");
13781 staticpro (&Qw32_charset_russian);
13782 Qw32_charset_russian = intern ("w32-charset-russian");
13783 staticpro (&Qw32_charset_arabic);
13784 Qw32_charset_arabic = intern ("w32-charset-arabic");
13785 staticpro (&Qw32_charset_greek);
13786 Qw32_charset_greek = intern ("w32-charset-greek");
13787 staticpro (&Qw32_charset_hebrew);
13788 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
13789 staticpro (&Qw32_charset_vietnamese);
13790 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
13791 staticpro (&Qw32_charset_thai);
13792 Qw32_charset_thai = intern ("w32-charset-thai");
13793 staticpro (&Qw32_charset_mac);
13794 Qw32_charset_mac = intern ("w32-charset-mac");
13796 #endif
13798 #ifdef UNICODE_CHARSET
13800 static int w32_unicode_charset_defined = 1;
13801 DEFVAR_BOOL ("w32-unicode-charset-defined",
13802 &w32_unicode_charset_defined, "");
13804 staticpro (&Qw32_charset_unicode);
13805 Qw32_charset_unicode = intern ("w32-charset-unicode");
13806 #endif
13808 defsubr (&Sx_get_resource);
13809 #if 0 /* TODO: Port to W32 */
13810 defsubr (&Sx_change_window_property);
13811 defsubr (&Sx_delete_window_property);
13812 defsubr (&Sx_window_property);
13813 #endif
13814 defsubr (&Sxw_display_color_p);
13815 defsubr (&Sx_display_grayscale_p);
13816 defsubr (&Sxw_color_defined_p);
13817 defsubr (&Sxw_color_values);
13818 defsubr (&Sx_server_max_request_size);
13819 defsubr (&Sx_server_vendor);
13820 defsubr (&Sx_server_version);
13821 defsubr (&Sx_display_pixel_width);
13822 defsubr (&Sx_display_pixel_height);
13823 defsubr (&Sx_display_mm_width);
13824 defsubr (&Sx_display_mm_height);
13825 defsubr (&Sx_display_screens);
13826 defsubr (&Sx_display_planes);
13827 defsubr (&Sx_display_color_cells);
13828 defsubr (&Sx_display_visual_class);
13829 defsubr (&Sx_display_backing_store);
13830 defsubr (&Sx_display_save_under);
13831 defsubr (&Sx_parse_geometry);
13832 defsubr (&Sx_create_frame);
13833 defsubr (&Sx_open_connection);
13834 defsubr (&Sx_close_connection);
13835 defsubr (&Sx_display_list);
13836 defsubr (&Sx_synchronize);
13838 /* W32 specific functions */
13840 defsubr (&Sw32_focus_frame);
13841 defsubr (&Sw32_select_font);
13842 defsubr (&Sw32_define_rgb_color);
13843 defsubr (&Sw32_default_color_map);
13844 defsubr (&Sw32_load_color_file);
13845 defsubr (&Sw32_send_sys_command);
13846 defsubr (&Sw32_shell_execute);
13847 defsubr (&Sw32_register_hot_key);
13848 defsubr (&Sw32_unregister_hot_key);
13849 defsubr (&Sw32_registered_hot_keys);
13850 defsubr (&Sw32_reconstruct_hot_key);
13851 defsubr (&Sw32_toggle_lock_key);
13852 defsubr (&Sw32_find_bdf_fonts);
13854 defsubr (&Sfile_system_info);
13856 /* Setting callback functions for fontset handler. */
13857 get_font_info_func = w32_get_font_info;
13859 #if 0 /* This function pointer doesn't seem to be used anywhere.
13860 And the pointer assigned has the wrong type, anyway. */
13861 list_fonts_func = w32_list_fonts;
13862 #endif
13864 load_font_func = w32_load_font;
13865 find_ccl_program_func = w32_find_ccl_program;
13866 query_font_func = w32_query_font;
13867 set_frame_fontset_func = x_set_font;
13868 check_window_system_func = check_w32;
13870 #if 0 /* TODO Image support for W32 */
13871 /* Images. */
13872 Qxbm = intern ("xbm");
13873 staticpro (&Qxbm);
13874 QCtype = intern (":type");
13875 staticpro (&QCtype);
13876 QCconversion = intern (":conversion");
13877 staticpro (&QCconversion);
13878 QCheuristic_mask = intern (":heuristic-mask");
13879 staticpro (&QCheuristic_mask);
13880 QCcolor_symbols = intern (":color-symbols");
13881 staticpro (&QCcolor_symbols);
13882 QCascent = intern (":ascent");
13883 staticpro (&QCascent);
13884 QCmargin = intern (":margin");
13885 staticpro (&QCmargin);
13886 QCrelief = intern (":relief");
13887 staticpro (&QCrelief);
13888 Qpostscript = intern ("postscript");
13889 staticpro (&Qpostscript);
13890 QCloader = intern (":loader");
13891 staticpro (&QCloader);
13892 QCbounding_box = intern (":bounding-box");
13893 staticpro (&QCbounding_box);
13894 QCpt_width = intern (":pt-width");
13895 staticpro (&QCpt_width);
13896 QCpt_height = intern (":pt-height");
13897 staticpro (&QCpt_height);
13898 QCindex = intern (":index");
13899 staticpro (&QCindex);
13900 Qpbm = intern ("pbm");
13901 staticpro (&Qpbm);
13903 #if HAVE_XPM
13904 Qxpm = intern ("xpm");
13905 staticpro (&Qxpm);
13906 #endif
13908 #if HAVE_JPEG
13909 Qjpeg = intern ("jpeg");
13910 staticpro (&Qjpeg);
13911 #endif
13913 #if HAVE_TIFF
13914 Qtiff = intern ("tiff");
13915 staticpro (&Qtiff);
13916 #endif
13918 #if HAVE_GIF
13919 Qgif = intern ("gif");
13920 staticpro (&Qgif);
13921 #endif
13923 #if HAVE_PNG
13924 Qpng = intern ("png");
13925 staticpro (&Qpng);
13926 #endif
13928 defsubr (&Sclear_image_cache);
13930 #if GLYPH_DEBUG
13931 defsubr (&Simagep);
13932 defsubr (&Slookup_image);
13933 #endif
13934 #endif /* TODO */
13936 hourglass_atimer = NULL;
13937 hourglass_shown_p = 0;
13938 #ifdef TODO /* Tooltip support not complete. */
13939 defsubr (&Sx_show_tip);
13940 defsubr (&Sx_hide_tip);
13941 #endif
13942 tip_timer = Qnil;
13943 staticpro (&tip_timer);
13944 tip_frame = Qnil;
13945 staticpro (&tip_frame);
13947 defsubr (&Sx_file_dialog);
13951 void
13952 init_xfns ()
13954 image_types = NULL;
13955 Vimage_types = Qnil;
13957 #if 0 /* TODO : Image support for W32 */
13958 define_image_type (&xbm_type);
13959 define_image_type (&gs_type);
13960 define_image_type (&pbm_type);
13962 #if HAVE_XPM
13963 define_image_type (&xpm_type);
13964 #endif
13966 #if HAVE_JPEG
13967 define_image_type (&jpeg_type);
13968 #endif
13970 #if HAVE_TIFF
13971 define_image_type (&tiff_type);
13972 #endif
13974 #if HAVE_GIF
13975 define_image_type (&gif_type);
13976 #endif
13978 #if HAVE_PNG
13979 define_image_type (&png_type);
13980 #endif
13981 #endif /* TODO */
13984 #undef abort
13986 void
13987 w32_abort()
13989 int button;
13990 button = MessageBox (NULL,
13991 "A fatal error has occurred!\n\n"
13992 "Select Abort to exit, Retry to debug, Ignore to continue",
13993 "Emacs Abort Dialog",
13994 MB_ICONEXCLAMATION | MB_TASKMODAL
13995 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
13996 switch (button)
13998 case IDRETRY:
13999 DebugBreak ();
14000 break;
14001 case IDIGNORE:
14002 break;
14003 case IDABORT:
14004 default:
14005 abort ();
14006 break;
14010 /* For convenience when debugging. */
14012 w32_last_error()
14014 return GetLastError ();