Remove cus-load.el.
[emacs.git] / src / w32fns.c
blob5b8074ca7ab93fbc4167dbbab963fb3017b4c825
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 busy cursor. */
151 int display_busy_cursor_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_busy_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
200 /* Evaluate this expression to rebuild the section of syms_of_w32fns
201 that initializes and staticpros the symbols declared below. Note
202 that Emacs 18 has a bug that keeps C-x C-e from being able to
203 evaluate this expression.
205 (progn
206 ;; Accumulate a list of the symbols we want to initialize from the
207 ;; declarations at the top of the file.
208 (goto-char (point-min))
209 (search-forward "/\*&&& symbols declared here &&&*\/\n")
210 (let (symbol-list)
211 (while (looking-at "Lisp_Object \\(Q[a-z_]+\\)")
212 (setq symbol-list
213 (cons (buffer-substring (match-beginning 1) (match-end 1))
214 symbol-list))
215 (forward-line 1))
216 (setq symbol-list (nreverse symbol-list))
217 ;; Delete the section of syms_of_... where we initialize the symbols.
218 (search-forward "\n /\*&&& init symbols here &&&*\/\n")
219 (let ((start (point)))
220 (while (looking-at "^ Q")
221 (forward-line 2))
222 (kill-region start (point)))
223 ;; Write a new symbol initialization section.
224 (while symbol-list
225 (insert (format " %s = intern (\"" (car symbol-list)))
226 (let ((start (point)))
227 (insert (substring (car symbol-list) 1))
228 (subst-char-in-region start (point) ?_ ?-))
229 (insert (format "\");\n staticpro (&%s);\n" (car symbol-list)))
230 (setq symbol-list (cdr symbol-list)))))
234 /*&&& symbols declared here &&&*/
235 Lisp_Object Qauto_raise;
236 Lisp_Object Qauto_lower;
237 Lisp_Object Qbar;
238 Lisp_Object Qborder_color;
239 Lisp_Object Qborder_width;
240 Lisp_Object Qbox;
241 Lisp_Object Qcursor_color;
242 Lisp_Object Qcursor_type;
243 Lisp_Object Qgeometry;
244 Lisp_Object Qicon_left;
245 Lisp_Object Qicon_top;
246 Lisp_Object Qicon_type;
247 Lisp_Object Qicon_name;
248 Lisp_Object Qinternal_border_width;
249 Lisp_Object Qleft;
250 Lisp_Object Qright;
251 Lisp_Object Qmouse_color;
252 Lisp_Object Qnone;
253 Lisp_Object Qparent_id;
254 Lisp_Object Qscroll_bar_width;
255 Lisp_Object Qsuppress_icon;
256 Lisp_Object Qundefined_color;
257 Lisp_Object Qvertical_scroll_bars;
258 Lisp_Object Qvisibility;
259 Lisp_Object Qwindow_id;
260 Lisp_Object Qx_frame_parameter;
261 Lisp_Object Qx_resource_name;
262 Lisp_Object Quser_position;
263 Lisp_Object Quser_size;
264 Lisp_Object Qscreen_gamma;
265 Lisp_Object Qline_spacing;
266 Lisp_Object Qcenter;
267 Lisp_Object Qhyper;
268 Lisp_Object Qsuper;
269 Lisp_Object Qmeta;
270 Lisp_Object Qalt;
271 Lisp_Object Qctrl;
272 Lisp_Object Qcontrol;
273 Lisp_Object Qshift;
275 Lisp_Object Qw32_charset_ansi;
276 Lisp_Object Qw32_charset_default;
277 Lisp_Object Qw32_charset_symbol;
278 Lisp_Object Qw32_charset_shiftjis;
279 Lisp_Object Qw32_charset_hangeul;
280 Lisp_Object Qw32_charset_gb2312;
281 Lisp_Object Qw32_charset_chinesebig5;
282 Lisp_Object Qw32_charset_oem;
284 #ifndef JOHAB_CHARSET
285 #define JOHAB_CHARSET 130
286 #endif
287 #ifdef JOHAB_CHARSET
288 Lisp_Object Qw32_charset_easteurope;
289 Lisp_Object Qw32_charset_turkish;
290 Lisp_Object Qw32_charset_baltic;
291 Lisp_Object Qw32_charset_russian;
292 Lisp_Object Qw32_charset_arabic;
293 Lisp_Object Qw32_charset_greek;
294 Lisp_Object Qw32_charset_hebrew;
295 Lisp_Object Qw32_charset_vietnamese;
296 Lisp_Object Qw32_charset_thai;
297 Lisp_Object Qw32_charset_johab;
298 Lisp_Object Qw32_charset_mac;
299 #endif
301 #ifdef UNICODE_CHARSET
302 Lisp_Object Qw32_charset_unicode;
303 #endif
305 extern Lisp_Object Qtop;
306 extern Lisp_Object Qdisplay;
307 extern Lisp_Object Qtool_bar_lines;
309 /* State variables for emulating a three button mouse. */
310 #define LMOUSE 1
311 #define MMOUSE 2
312 #define RMOUSE 4
314 static int button_state = 0;
315 static W32Msg saved_mouse_button_msg;
316 static unsigned mouse_button_timer; /* non-zero when timer is active */
317 static W32Msg saved_mouse_move_msg;
318 static unsigned mouse_move_timer;
320 /* W95 mousewheel handler */
321 unsigned int msh_mousewheel = 0;
323 #define MOUSE_BUTTON_ID 1
324 #define MOUSE_MOVE_ID 2
326 /* The below are defined in frame.c. */
328 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
329 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
330 extern Lisp_Object Qtool_bar_lines;
332 extern Lisp_Object Vwindow_system_version;
334 Lisp_Object Qface_set_after_frame_default;
336 #ifdef GLYPH_DEBUG
337 int image_cache_refcount, dpyinfo_refcount;
338 #endif
341 /* From w32term.c. */
342 extern Lisp_Object Vw32_num_mouse_buttons;
343 extern Lisp_Object Vw32_recognize_altgr;
346 /* Error if we are not connected to MS-Windows. */
347 void
348 check_w32 ()
350 if (! w32_in_use)
351 error ("MS-Windows not in use or not initialized");
354 /* Nonzero if we can use mouse menus.
355 You should not call this unless HAVE_MENUS is defined. */
358 have_menus_p ()
360 return w32_in_use;
363 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
364 and checking validity for W32. */
366 FRAME_PTR
367 check_x_frame (frame)
368 Lisp_Object frame;
370 FRAME_PTR f;
372 if (NILP (frame))
373 frame = selected_frame;
374 CHECK_LIVE_FRAME (frame, 0);
375 f = XFRAME (frame);
376 if (! FRAME_W32_P (f))
377 error ("non-w32 frame used");
378 return f;
381 /* Let the user specify an display with a frame.
382 nil stands for the selected frame--or, if that is not a w32 frame,
383 the first display on the list. */
385 static struct w32_display_info *
386 check_x_display_info (frame)
387 Lisp_Object frame;
389 if (NILP (frame))
391 struct frame *sf = XFRAME (selected_frame);
393 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
394 return FRAME_W32_DISPLAY_INFO (sf);
395 else
396 return &one_w32_display_info;
398 else if (STRINGP (frame))
399 return x_display_info_for_name (frame);
400 else
402 FRAME_PTR f;
404 CHECK_LIVE_FRAME (frame, 0);
405 f = XFRAME (frame);
406 if (! FRAME_W32_P (f))
407 error ("non-w32 frame used");
408 return FRAME_W32_DISPLAY_INFO (f);
412 /* Return the Emacs frame-object corresponding to an w32 window.
413 It could be the frame's main window or an icon window. */
415 /* This function can be called during GC, so use GC_xxx type test macros. */
417 struct frame *
418 x_window_to_frame (dpyinfo, wdesc)
419 struct w32_display_info *dpyinfo;
420 HWND wdesc;
422 Lisp_Object tail, frame;
423 struct frame *f;
425 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
427 frame = XCAR (tail);
428 if (!GC_FRAMEP (frame))
429 continue;
430 f = XFRAME (frame);
431 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
432 continue;
433 if (f->output_data.w32->busy_window == wdesc)
434 return f;
436 /* TODO: Check tooltips when supported. */
437 if (FRAME_W32_WINDOW (f) == wdesc)
438 return f;
440 return 0;
445 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
446 id, which is just an int that this section returns. Bitmaps are
447 reference counted so they can be shared among frames.
449 Bitmap indices are guaranteed to be > 0, so a negative number can
450 be used to indicate no bitmap.
452 If you use x_create_bitmap_from_data, then you must keep track of
453 the bitmaps yourself. That is, creating a bitmap from the same
454 data more than once will not be caught. */
457 /* Functions to access the contents of a bitmap, given an id. */
460 x_bitmap_height (f, id)
461 FRAME_PTR f;
462 int id;
464 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
468 x_bitmap_width (f, id)
469 FRAME_PTR f;
470 int id;
472 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
476 x_bitmap_pixmap (f, id)
477 FRAME_PTR f;
478 int id;
480 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
484 /* Allocate a new bitmap record. Returns index of new record. */
486 static int
487 x_allocate_bitmap_record (f)
488 FRAME_PTR f;
490 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
491 int i;
493 if (dpyinfo->bitmaps == NULL)
495 dpyinfo->bitmaps_size = 10;
496 dpyinfo->bitmaps
497 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
498 dpyinfo->bitmaps_last = 1;
499 return 1;
502 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
503 return ++dpyinfo->bitmaps_last;
505 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
506 if (dpyinfo->bitmaps[i].refcount == 0)
507 return i + 1;
509 dpyinfo->bitmaps_size *= 2;
510 dpyinfo->bitmaps
511 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
512 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
513 return ++dpyinfo->bitmaps_last;
516 /* Add one reference to the reference count of the bitmap with id ID. */
518 void
519 x_reference_bitmap (f, id)
520 FRAME_PTR f;
521 int id;
523 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
526 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
529 x_create_bitmap_from_data (f, bits, width, height)
530 struct frame *f;
531 char *bits;
532 unsigned int width, height;
534 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
535 Pixmap bitmap;
536 int id;
538 bitmap = CreateBitmap (width, height,
539 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
540 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
541 bits);
543 if (! bitmap)
544 return -1;
546 id = x_allocate_bitmap_record (f);
547 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
548 dpyinfo->bitmaps[id - 1].file = NULL;
549 dpyinfo->bitmaps[id - 1].hinst = NULL;
550 dpyinfo->bitmaps[id - 1].refcount = 1;
551 dpyinfo->bitmaps[id - 1].depth = 1;
552 dpyinfo->bitmaps[id - 1].height = height;
553 dpyinfo->bitmaps[id - 1].width = width;
555 return id;
558 /* Create bitmap from file FILE for frame F. */
561 x_create_bitmap_from_file (f, file)
562 struct frame *f;
563 Lisp_Object file;
565 return -1;
566 #if 0 /* TODO : bitmap support */
567 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
568 unsigned int width, height;
569 HBITMAP bitmap;
570 int xhot, yhot, result, id;
571 Lisp_Object found;
572 int fd;
573 char *filename;
574 HINSTANCE hinst;
576 /* Look for an existing bitmap with the same name. */
577 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
579 if (dpyinfo->bitmaps[id].refcount
580 && dpyinfo->bitmaps[id].file
581 && !strcmp (dpyinfo->bitmaps[id].file, (char *) XSTRING (file)->data))
583 ++dpyinfo->bitmaps[id].refcount;
584 return id + 1;
588 /* Search bitmap-file-path for the file, if appropriate. */
589 fd = openp (Vx_bitmap_file_path, file, "", &found, 0);
590 if (fd < 0)
591 return -1;
592 emacs_close (fd);
594 filename = (char *) XSTRING (found)->data;
596 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
598 if (hinst == NULL)
599 return -1;
602 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
603 filename, &width, &height, &bitmap, &xhot, &yhot);
604 if (result != BitmapSuccess)
605 return -1;
607 id = x_allocate_bitmap_record (f);
608 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
609 dpyinfo->bitmaps[id - 1].refcount = 1;
610 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (XSTRING (file)->size + 1);
611 dpyinfo->bitmaps[id - 1].depth = 1;
612 dpyinfo->bitmaps[id - 1].height = height;
613 dpyinfo->bitmaps[id - 1].width = width;
614 strcpy (dpyinfo->bitmaps[id - 1].file, XSTRING (file)->data);
616 return id;
617 #endif /* TODO */
620 /* Remove reference to bitmap with id number ID. */
622 void
623 x_destroy_bitmap (f, id)
624 FRAME_PTR f;
625 int id;
627 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
629 if (id > 0)
631 --dpyinfo->bitmaps[id - 1].refcount;
632 if (dpyinfo->bitmaps[id - 1].refcount == 0)
634 BLOCK_INPUT;
635 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
636 if (dpyinfo->bitmaps[id - 1].file)
638 xfree (dpyinfo->bitmaps[id - 1].file);
639 dpyinfo->bitmaps[id - 1].file = NULL;
641 UNBLOCK_INPUT;
646 /* Free all the bitmaps for the display specified by DPYINFO. */
648 static void
649 x_destroy_all_bitmaps (dpyinfo)
650 struct w32_display_info *dpyinfo;
652 int i;
653 for (i = 0; i < dpyinfo->bitmaps_last; i++)
654 if (dpyinfo->bitmaps[i].refcount > 0)
656 DeleteObject (dpyinfo->bitmaps[i].pixmap);
657 if (dpyinfo->bitmaps[i].file)
658 xfree (dpyinfo->bitmaps[i].file);
660 dpyinfo->bitmaps_last = 0;
663 /* Connect the frame-parameter names for W32 frames
664 to the ways of passing the parameter values to the window system.
666 The name of a parameter, as a Lisp symbol,
667 has an `x-frame-parameter' property which is an integer in Lisp
668 but can be interpreted as an `enum x_frame_parm' in C. */
670 enum x_frame_parm
672 X_PARM_FOREGROUND_COLOR,
673 X_PARM_BACKGROUND_COLOR,
674 X_PARM_MOUSE_COLOR,
675 X_PARM_CURSOR_COLOR,
676 X_PARM_BORDER_COLOR,
677 X_PARM_ICON_TYPE,
678 X_PARM_FONT,
679 X_PARM_BORDER_WIDTH,
680 X_PARM_INTERNAL_BORDER_WIDTH,
681 X_PARM_NAME,
682 X_PARM_AUTORAISE,
683 X_PARM_AUTOLOWER,
684 X_PARM_VERT_SCROLL_BAR,
685 X_PARM_VISIBILITY,
686 X_PARM_MENU_BAR_LINES
690 struct x_frame_parm_table
692 char *name;
693 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
696 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
697 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
698 static void x_change_window_heights P_ ((Lisp_Object, int));
699 /* TODO: Native Input Method support; see x_create_im. */
700 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
701 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
702 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
703 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
704 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
705 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
706 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
707 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
708 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
709 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
710 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
711 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
712 Lisp_Object));
713 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
714 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
715 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
716 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
717 Lisp_Object));
718 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
719 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
720 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
721 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
722 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
723 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
724 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
726 static struct x_frame_parm_table x_frame_parms[] =
728 "auto-raise", x_set_autoraise,
729 "auto-lower", x_set_autolower,
730 "background-color", x_set_background_color,
731 "border-color", x_set_border_color,
732 "border-width", x_set_border_width,
733 "cursor-color", x_set_cursor_color,
734 "cursor-type", x_set_cursor_type,
735 "font", x_set_font,
736 "foreground-color", x_set_foreground_color,
737 "icon-name", x_set_icon_name,
738 "icon-type", x_set_icon_type,
739 "internal-border-width", x_set_internal_border_width,
740 "menu-bar-lines", x_set_menu_bar_lines,
741 "mouse-color", x_set_mouse_color,
742 "name", x_explicitly_set_name,
743 "scroll-bar-width", x_set_scroll_bar_width,
744 "title", x_set_title,
745 "unsplittable", x_set_unsplittable,
746 "vertical-scroll-bars", x_set_vertical_scroll_bars,
747 "visibility", x_set_visibility,
748 "tool-bar-lines", x_set_tool_bar_lines,
749 "screen-gamma", x_set_screen_gamma,
750 "line-spacing", x_set_line_spacing
753 /* Attach the `x-frame-parameter' properties to
754 the Lisp symbol names of parameters relevant to W32. */
756 void
757 init_x_parm_symbols ()
759 int i;
761 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
762 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
763 make_number (i));
766 /* Change the parameters of frame F as specified by ALIST.
767 If a parameter is not specially recognized, do nothing;
768 otherwise call the `x_set_...' function for that parameter. */
770 void
771 x_set_frame_parameters (f, alist)
772 FRAME_PTR f;
773 Lisp_Object alist;
775 Lisp_Object tail;
777 /* If both of these parameters are present, it's more efficient to
778 set them both at once. So we wait until we've looked at the
779 entire list before we set them. */
780 int width, height;
782 /* Same here. */
783 Lisp_Object left, top;
785 /* Same with these. */
786 Lisp_Object icon_left, icon_top;
788 /* Record in these vectors all the parms specified. */
789 Lisp_Object *parms;
790 Lisp_Object *values;
791 int i, p;
792 int left_no_change = 0, top_no_change = 0;
793 int icon_left_no_change = 0, icon_top_no_change = 0;
795 struct gcpro gcpro1, gcpro2;
797 i = 0;
798 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
799 i++;
801 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
802 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
804 /* Extract parm names and values into those vectors. */
806 i = 0;
807 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
809 Lisp_Object elt;
811 elt = Fcar (tail);
812 parms[i] = Fcar (elt);
813 values[i] = Fcdr (elt);
814 i++;
816 /* TAIL and ALIST are not used again below here. */
817 alist = tail = Qnil;
819 GCPRO2 (*parms, *values);
820 gcpro1.nvars = i;
821 gcpro2.nvars = i;
823 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
824 because their values appear in VALUES and strings are not valid. */
825 top = left = Qunbound;
826 icon_left = icon_top = Qunbound;
828 /* Provide default values for HEIGHT and WIDTH. */
829 if (FRAME_NEW_WIDTH (f))
830 width = FRAME_NEW_WIDTH (f);
831 else
832 width = FRAME_WIDTH (f);
834 if (FRAME_NEW_HEIGHT (f))
835 height = FRAME_NEW_HEIGHT (f);
836 else
837 height = FRAME_HEIGHT (f);
839 /* Process foreground_color and background_color before anything else.
840 They are independent of other properties, but other properties (e.g.,
841 cursor_color) are dependent upon them. */
842 for (p = 0; p < i; p++)
844 Lisp_Object prop, val;
846 prop = parms[p];
847 val = values[p];
848 if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
850 register Lisp_Object param_index, old_value;
852 param_index = Fget (prop, Qx_frame_parameter);
853 old_value = get_frame_param (f, prop);
854 store_frame_param (f, prop, val);
855 if (NATNUMP (param_index)
856 && (XFASTINT (param_index)
857 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
858 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
862 /* Now process them in reverse of specified order. */
863 for (i--; i >= 0; i--)
865 Lisp_Object prop, val;
867 prop = parms[i];
868 val = values[i];
870 if (EQ (prop, Qwidth) && NUMBERP (val))
871 width = XFASTINT (val);
872 else if (EQ (prop, Qheight) && NUMBERP (val))
873 height = XFASTINT (val);
874 else if (EQ (prop, Qtop))
875 top = val;
876 else if (EQ (prop, Qleft))
877 left = val;
878 else if (EQ (prop, Qicon_top))
879 icon_top = val;
880 else if (EQ (prop, Qicon_left))
881 icon_left = val;
882 else if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
883 /* Processed above. */
884 continue;
885 else
887 register Lisp_Object param_index, old_value;
889 param_index = Fget (prop, Qx_frame_parameter);
890 old_value = get_frame_param (f, prop);
891 store_frame_param (f, prop, val);
892 if (NATNUMP (param_index)
893 && (XFASTINT (param_index)
894 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
895 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
899 /* Don't die if just one of these was set. */
900 if (EQ (left, Qunbound))
902 left_no_change = 1;
903 if (f->output_data.w32->left_pos < 0)
904 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
905 else
906 XSETINT (left, f->output_data.w32->left_pos);
908 if (EQ (top, Qunbound))
910 top_no_change = 1;
911 if (f->output_data.w32->top_pos < 0)
912 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
913 else
914 XSETINT (top, f->output_data.w32->top_pos);
917 /* If one of the icon positions was not set, preserve or default it. */
918 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
920 icon_left_no_change = 1;
921 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
922 if (NILP (icon_left))
923 XSETINT (icon_left, 0);
925 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
927 icon_top_no_change = 1;
928 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
929 if (NILP (icon_top))
930 XSETINT (icon_top, 0);
933 /* Don't set these parameters unless they've been explicitly
934 specified. The window might be mapped or resized while we're in
935 this function, and we don't want to override that unless the lisp
936 code has asked for it.
938 Don't set these parameters unless they actually differ from the
939 window's current parameters; the window may not actually exist
940 yet. */
942 Lisp_Object frame;
944 check_frame_size (f, &height, &width);
946 XSETFRAME (frame, f);
948 if (width != FRAME_WIDTH (f)
949 || height != FRAME_HEIGHT (f)
950 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
951 Fset_frame_size (frame, make_number (width), make_number (height));
953 if ((!NILP (left) || !NILP (top))
954 && ! (left_no_change && top_no_change)
955 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
956 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
958 int leftpos = 0;
959 int toppos = 0;
961 /* Record the signs. */
962 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
963 if (EQ (left, Qminus))
964 f->output_data.w32->size_hint_flags |= XNegative;
965 else if (INTEGERP (left))
967 leftpos = XINT (left);
968 if (leftpos < 0)
969 f->output_data.w32->size_hint_flags |= XNegative;
971 else if (CONSP (left) && EQ (XCAR (left), Qminus)
972 && CONSP (XCDR (left))
973 && INTEGERP (XCAR (XCDR (left))))
975 leftpos = - XINT (XCAR (XCDR (left)));
976 f->output_data.w32->size_hint_flags |= XNegative;
978 else if (CONSP (left) && EQ (XCAR (left), Qplus)
979 && CONSP (XCDR (left))
980 && INTEGERP (XCAR (XCDR (left))))
982 leftpos = XINT (XCAR (XCDR (left)));
985 if (EQ (top, Qminus))
986 f->output_data.w32->size_hint_flags |= YNegative;
987 else if (INTEGERP (top))
989 toppos = XINT (top);
990 if (toppos < 0)
991 f->output_data.w32->size_hint_flags |= YNegative;
993 else if (CONSP (top) && EQ (XCAR (top), Qminus)
994 && CONSP (XCDR (top))
995 && INTEGERP (XCAR (XCDR (top))))
997 toppos = - XINT (XCAR (XCDR (top)));
998 f->output_data.w32->size_hint_flags |= YNegative;
1000 else if (CONSP (top) && EQ (XCAR (top), Qplus)
1001 && CONSP (XCDR (top))
1002 && INTEGERP (XCAR (XCDR (top))))
1004 toppos = XINT (XCAR (XCDR (top)));
1008 /* Store the numeric value of the position. */
1009 f->output_data.w32->top_pos = toppos;
1010 f->output_data.w32->left_pos = leftpos;
1012 f->output_data.w32->win_gravity = NorthWestGravity;
1014 /* Actually set that position, and convert to absolute. */
1015 x_set_offset (f, leftpos, toppos, -1);
1018 if ((!NILP (icon_left) || !NILP (icon_top))
1019 && ! (icon_left_no_change && icon_top_no_change))
1020 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1023 UNGCPRO;
1026 /* Store the screen positions of frame F into XPTR and YPTR.
1027 These are the positions of the containing window manager window,
1028 not Emacs's own window. */
1030 void
1031 x_real_positions (f, xptr, yptr)
1032 FRAME_PTR f;
1033 int *xptr, *yptr;
1035 POINT pt;
1038 RECT rect;
1040 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1041 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1043 pt.x = rect.left;
1044 pt.y = rect.top;
1047 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1049 *xptr = pt.x;
1050 *yptr = pt.y;
1053 /* Insert a description of internally-recorded parameters of frame X
1054 into the parameter alist *ALISTPTR that is to be given to the user.
1055 Only parameters that are specific to W32
1056 and whose values are not correctly recorded in the frame's
1057 param_alist need to be considered here. */
1059 void
1060 x_report_frame_params (f, alistptr)
1061 struct frame *f;
1062 Lisp_Object *alistptr;
1064 char buf[16];
1065 Lisp_Object tem;
1067 /* Represent negative positions (off the top or left screen edge)
1068 in a way that Fmodify_frame_parameters will understand correctly. */
1069 XSETINT (tem, f->output_data.w32->left_pos);
1070 if (f->output_data.w32->left_pos >= 0)
1071 store_in_alist (alistptr, Qleft, tem);
1072 else
1073 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1075 XSETINT (tem, f->output_data.w32->top_pos);
1076 if (f->output_data.w32->top_pos >= 0)
1077 store_in_alist (alistptr, Qtop, tem);
1078 else
1079 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1081 store_in_alist (alistptr, Qborder_width,
1082 make_number (f->output_data.w32->border_width));
1083 store_in_alist (alistptr, Qinternal_border_width,
1084 make_number (f->output_data.w32->internal_border_width));
1085 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1086 store_in_alist (alistptr, Qwindow_id,
1087 build_string (buf));
1088 store_in_alist (alistptr, Qicon_name, f->icon_name);
1089 FRAME_SAMPLE_VISIBILITY (f);
1090 store_in_alist (alistptr, Qvisibility,
1091 (FRAME_VISIBLE_P (f) ? Qt
1092 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1093 store_in_alist (alistptr, Qdisplay,
1094 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1098 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color, Sw32_define_rgb_color, 4, 4, 0,
1099 "Convert RGB numbers to a windows color reference and associate with NAME (a string).\n\
1100 This adds or updates a named color to w32-color-map, making it available for use.\n\
1101 The original entry's RGB ref is returned, or nil if the entry is new.")
1102 (red, green, blue, name)
1103 Lisp_Object red, green, blue, name;
1105 Lisp_Object rgb;
1106 Lisp_Object oldrgb = Qnil;
1107 Lisp_Object entry;
1109 CHECK_NUMBER (red, 0);
1110 CHECK_NUMBER (green, 0);
1111 CHECK_NUMBER (blue, 0);
1112 CHECK_STRING (name, 0);
1114 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1116 BLOCK_INPUT;
1118 /* replace existing entry in w32-color-map or add new entry. */
1119 entry = Fassoc (name, Vw32_color_map);
1120 if (NILP (entry))
1122 entry = Fcons (name, rgb);
1123 Vw32_color_map = Fcons (entry, Vw32_color_map);
1125 else
1127 oldrgb = Fcdr (entry);
1128 Fsetcdr (entry, rgb);
1131 UNBLOCK_INPUT;
1133 return (oldrgb);
1136 DEFUN ("w32-load-color-file", Fw32_load_color_file, Sw32_load_color_file, 1, 1, 0,
1137 "Create an alist of color entries from an external file (ie. rgb.txt).\n\
1138 Assign this value to w32-color-map to replace the existing color map.\n\
1140 The file should define one named RGB color per line like so:\
1141 R G B name\n\
1142 where R,G,B are numbers between 0 and 255 and name is an arbitrary string.")
1143 (filename)
1144 Lisp_Object filename;
1146 FILE *fp;
1147 Lisp_Object cmap = Qnil;
1148 Lisp_Object abspath;
1150 CHECK_STRING (filename, 0);
1151 abspath = Fexpand_file_name (filename, Qnil);
1153 fp = fopen (XSTRING (filename)->data, "rt");
1154 if (fp)
1156 char buf[512];
1157 int red, green, blue;
1158 int num;
1160 BLOCK_INPUT;
1162 while (fgets (buf, sizeof (buf), fp) != NULL) {
1163 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1165 char *name = buf + num;
1166 num = strlen (name) - 1;
1167 if (name[num] == '\n')
1168 name[num] = 0;
1169 cmap = Fcons (Fcons (build_string (name),
1170 make_number (RGB (red, green, blue))),
1171 cmap);
1174 fclose (fp);
1176 UNBLOCK_INPUT;
1179 return cmap;
1182 /* The default colors for the w32 color map */
1183 typedef struct colormap_t
1185 char *name;
1186 COLORREF colorref;
1187 } colormap_t;
1189 colormap_t w32_color_map[] =
1191 {"snow" , PALETTERGB (255,250,250)},
1192 {"ghost white" , PALETTERGB (248,248,255)},
1193 {"GhostWhite" , PALETTERGB (248,248,255)},
1194 {"white smoke" , PALETTERGB (245,245,245)},
1195 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1196 {"gainsboro" , PALETTERGB (220,220,220)},
1197 {"floral white" , PALETTERGB (255,250,240)},
1198 {"FloralWhite" , PALETTERGB (255,250,240)},
1199 {"old lace" , PALETTERGB (253,245,230)},
1200 {"OldLace" , PALETTERGB (253,245,230)},
1201 {"linen" , PALETTERGB (250,240,230)},
1202 {"antique white" , PALETTERGB (250,235,215)},
1203 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1204 {"papaya whip" , PALETTERGB (255,239,213)},
1205 {"PapayaWhip" , PALETTERGB (255,239,213)},
1206 {"blanched almond" , PALETTERGB (255,235,205)},
1207 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1208 {"bisque" , PALETTERGB (255,228,196)},
1209 {"peach puff" , PALETTERGB (255,218,185)},
1210 {"PeachPuff" , PALETTERGB (255,218,185)},
1211 {"navajo white" , PALETTERGB (255,222,173)},
1212 {"NavajoWhite" , PALETTERGB (255,222,173)},
1213 {"moccasin" , PALETTERGB (255,228,181)},
1214 {"cornsilk" , PALETTERGB (255,248,220)},
1215 {"ivory" , PALETTERGB (255,255,240)},
1216 {"lemon chiffon" , PALETTERGB (255,250,205)},
1217 {"LemonChiffon" , PALETTERGB (255,250,205)},
1218 {"seashell" , PALETTERGB (255,245,238)},
1219 {"honeydew" , PALETTERGB (240,255,240)},
1220 {"mint cream" , PALETTERGB (245,255,250)},
1221 {"MintCream" , PALETTERGB (245,255,250)},
1222 {"azure" , PALETTERGB (240,255,255)},
1223 {"alice blue" , PALETTERGB (240,248,255)},
1224 {"AliceBlue" , PALETTERGB (240,248,255)},
1225 {"lavender" , PALETTERGB (230,230,250)},
1226 {"lavender blush" , PALETTERGB (255,240,245)},
1227 {"LavenderBlush" , PALETTERGB (255,240,245)},
1228 {"misty rose" , PALETTERGB (255,228,225)},
1229 {"MistyRose" , PALETTERGB (255,228,225)},
1230 {"white" , PALETTERGB (255,255,255)},
1231 {"black" , PALETTERGB ( 0, 0, 0)},
1232 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1233 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1234 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1235 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1236 {"dim gray" , PALETTERGB (105,105,105)},
1237 {"DimGray" , PALETTERGB (105,105,105)},
1238 {"dim grey" , PALETTERGB (105,105,105)},
1239 {"DimGrey" , PALETTERGB (105,105,105)},
1240 {"slate gray" , PALETTERGB (112,128,144)},
1241 {"SlateGray" , PALETTERGB (112,128,144)},
1242 {"slate grey" , PALETTERGB (112,128,144)},
1243 {"SlateGrey" , PALETTERGB (112,128,144)},
1244 {"light slate gray" , PALETTERGB (119,136,153)},
1245 {"LightSlateGray" , PALETTERGB (119,136,153)},
1246 {"light slate grey" , PALETTERGB (119,136,153)},
1247 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1248 {"gray" , PALETTERGB (190,190,190)},
1249 {"grey" , PALETTERGB (190,190,190)},
1250 {"light grey" , PALETTERGB (211,211,211)},
1251 {"LightGrey" , PALETTERGB (211,211,211)},
1252 {"light gray" , PALETTERGB (211,211,211)},
1253 {"LightGray" , PALETTERGB (211,211,211)},
1254 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1255 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1256 {"navy" , PALETTERGB ( 0, 0,128)},
1257 {"navy blue" , PALETTERGB ( 0, 0,128)},
1258 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1259 {"cornflower blue" , PALETTERGB (100,149,237)},
1260 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1261 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1262 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1263 {"slate blue" , PALETTERGB (106, 90,205)},
1264 {"SlateBlue" , PALETTERGB (106, 90,205)},
1265 {"medium slate blue" , PALETTERGB (123,104,238)},
1266 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1267 {"light slate blue" , PALETTERGB (132,112,255)},
1268 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1269 {"medium blue" , PALETTERGB ( 0, 0,205)},
1270 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1271 {"royal blue" , PALETTERGB ( 65,105,225)},
1272 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1273 {"blue" , PALETTERGB ( 0, 0,255)},
1274 {"dodger blue" , PALETTERGB ( 30,144,255)},
1275 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1276 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1277 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1278 {"sky blue" , PALETTERGB (135,206,235)},
1279 {"SkyBlue" , PALETTERGB (135,206,235)},
1280 {"light sky blue" , PALETTERGB (135,206,250)},
1281 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1282 {"steel blue" , PALETTERGB ( 70,130,180)},
1283 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1284 {"light steel blue" , PALETTERGB (176,196,222)},
1285 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1286 {"light blue" , PALETTERGB (173,216,230)},
1287 {"LightBlue" , PALETTERGB (173,216,230)},
1288 {"powder blue" , PALETTERGB (176,224,230)},
1289 {"PowderBlue" , PALETTERGB (176,224,230)},
1290 {"pale turquoise" , PALETTERGB (175,238,238)},
1291 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1292 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1293 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1294 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1295 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1296 {"turquoise" , PALETTERGB ( 64,224,208)},
1297 {"cyan" , PALETTERGB ( 0,255,255)},
1298 {"light cyan" , PALETTERGB (224,255,255)},
1299 {"LightCyan" , PALETTERGB (224,255,255)},
1300 {"cadet blue" , PALETTERGB ( 95,158,160)},
1301 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1302 {"medium aquamarine" , PALETTERGB (102,205,170)},
1303 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1304 {"aquamarine" , PALETTERGB (127,255,212)},
1305 {"dark green" , PALETTERGB ( 0,100, 0)},
1306 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1307 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1308 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1309 {"dark sea green" , PALETTERGB (143,188,143)},
1310 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1311 {"sea green" , PALETTERGB ( 46,139, 87)},
1312 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1313 {"medium sea green" , PALETTERGB ( 60,179,113)},
1314 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1315 {"light sea green" , PALETTERGB ( 32,178,170)},
1316 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1317 {"pale green" , PALETTERGB (152,251,152)},
1318 {"PaleGreen" , PALETTERGB (152,251,152)},
1319 {"spring green" , PALETTERGB ( 0,255,127)},
1320 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1321 {"lawn green" , PALETTERGB (124,252, 0)},
1322 {"LawnGreen" , PALETTERGB (124,252, 0)},
1323 {"green" , PALETTERGB ( 0,255, 0)},
1324 {"chartreuse" , PALETTERGB (127,255, 0)},
1325 {"medium spring green" , PALETTERGB ( 0,250,154)},
1326 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1327 {"green yellow" , PALETTERGB (173,255, 47)},
1328 {"GreenYellow" , PALETTERGB (173,255, 47)},
1329 {"lime green" , PALETTERGB ( 50,205, 50)},
1330 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1331 {"yellow green" , PALETTERGB (154,205, 50)},
1332 {"YellowGreen" , PALETTERGB (154,205, 50)},
1333 {"forest green" , PALETTERGB ( 34,139, 34)},
1334 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1335 {"olive drab" , PALETTERGB (107,142, 35)},
1336 {"OliveDrab" , PALETTERGB (107,142, 35)},
1337 {"dark khaki" , PALETTERGB (189,183,107)},
1338 {"DarkKhaki" , PALETTERGB (189,183,107)},
1339 {"khaki" , PALETTERGB (240,230,140)},
1340 {"pale goldenrod" , PALETTERGB (238,232,170)},
1341 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1342 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1343 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1344 {"light yellow" , PALETTERGB (255,255,224)},
1345 {"LightYellow" , PALETTERGB (255,255,224)},
1346 {"yellow" , PALETTERGB (255,255, 0)},
1347 {"gold" , PALETTERGB (255,215, 0)},
1348 {"light goldenrod" , PALETTERGB (238,221,130)},
1349 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1350 {"goldenrod" , PALETTERGB (218,165, 32)},
1351 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1352 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1353 {"rosy brown" , PALETTERGB (188,143,143)},
1354 {"RosyBrown" , PALETTERGB (188,143,143)},
1355 {"indian red" , PALETTERGB (205, 92, 92)},
1356 {"IndianRed" , PALETTERGB (205, 92, 92)},
1357 {"saddle brown" , PALETTERGB (139, 69, 19)},
1358 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1359 {"sienna" , PALETTERGB (160, 82, 45)},
1360 {"peru" , PALETTERGB (205,133, 63)},
1361 {"burlywood" , PALETTERGB (222,184,135)},
1362 {"beige" , PALETTERGB (245,245,220)},
1363 {"wheat" , PALETTERGB (245,222,179)},
1364 {"sandy brown" , PALETTERGB (244,164, 96)},
1365 {"SandyBrown" , PALETTERGB (244,164, 96)},
1366 {"tan" , PALETTERGB (210,180,140)},
1367 {"chocolate" , PALETTERGB (210,105, 30)},
1368 {"firebrick" , PALETTERGB (178,34, 34)},
1369 {"brown" , PALETTERGB (165,42, 42)},
1370 {"dark salmon" , PALETTERGB (233,150,122)},
1371 {"DarkSalmon" , PALETTERGB (233,150,122)},
1372 {"salmon" , PALETTERGB (250,128,114)},
1373 {"light salmon" , PALETTERGB (255,160,122)},
1374 {"LightSalmon" , PALETTERGB (255,160,122)},
1375 {"orange" , PALETTERGB (255,165, 0)},
1376 {"dark orange" , PALETTERGB (255,140, 0)},
1377 {"DarkOrange" , PALETTERGB (255,140, 0)},
1378 {"coral" , PALETTERGB (255,127, 80)},
1379 {"light coral" , PALETTERGB (240,128,128)},
1380 {"LightCoral" , PALETTERGB (240,128,128)},
1381 {"tomato" , PALETTERGB (255, 99, 71)},
1382 {"orange red" , PALETTERGB (255, 69, 0)},
1383 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1384 {"red" , PALETTERGB (255, 0, 0)},
1385 {"hot pink" , PALETTERGB (255,105,180)},
1386 {"HotPink" , PALETTERGB (255,105,180)},
1387 {"deep pink" , PALETTERGB (255, 20,147)},
1388 {"DeepPink" , PALETTERGB (255, 20,147)},
1389 {"pink" , PALETTERGB (255,192,203)},
1390 {"light pink" , PALETTERGB (255,182,193)},
1391 {"LightPink" , PALETTERGB (255,182,193)},
1392 {"pale violet red" , PALETTERGB (219,112,147)},
1393 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1394 {"maroon" , PALETTERGB (176, 48, 96)},
1395 {"medium violet red" , PALETTERGB (199, 21,133)},
1396 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1397 {"violet red" , PALETTERGB (208, 32,144)},
1398 {"VioletRed" , PALETTERGB (208, 32,144)},
1399 {"magenta" , PALETTERGB (255, 0,255)},
1400 {"violet" , PALETTERGB (238,130,238)},
1401 {"plum" , PALETTERGB (221,160,221)},
1402 {"orchid" , PALETTERGB (218,112,214)},
1403 {"medium orchid" , PALETTERGB (186, 85,211)},
1404 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1405 {"dark orchid" , PALETTERGB (153, 50,204)},
1406 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1407 {"dark violet" , PALETTERGB (148, 0,211)},
1408 {"DarkViolet" , PALETTERGB (148, 0,211)},
1409 {"blue violet" , PALETTERGB (138, 43,226)},
1410 {"BlueViolet" , PALETTERGB (138, 43,226)},
1411 {"purple" , PALETTERGB (160, 32,240)},
1412 {"medium purple" , PALETTERGB (147,112,219)},
1413 {"MediumPurple" , PALETTERGB (147,112,219)},
1414 {"thistle" , PALETTERGB (216,191,216)},
1415 {"gray0" , PALETTERGB ( 0, 0, 0)},
1416 {"grey0" , PALETTERGB ( 0, 0, 0)},
1417 {"dark grey" , PALETTERGB (169,169,169)},
1418 {"DarkGrey" , PALETTERGB (169,169,169)},
1419 {"dark gray" , PALETTERGB (169,169,169)},
1420 {"DarkGray" , PALETTERGB (169,169,169)},
1421 {"dark blue" , PALETTERGB ( 0, 0,139)},
1422 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1423 {"dark cyan" , PALETTERGB ( 0,139,139)},
1424 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1425 {"dark magenta" , PALETTERGB (139, 0,139)},
1426 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1427 {"dark red" , PALETTERGB (139, 0, 0)},
1428 {"DarkRed" , PALETTERGB (139, 0, 0)},
1429 {"light green" , PALETTERGB (144,238,144)},
1430 {"LightGreen" , PALETTERGB (144,238,144)},
1433 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1434 0, 0, 0, "Return the default color map.")
1437 int i;
1438 colormap_t *pc = w32_color_map;
1439 Lisp_Object cmap;
1441 BLOCK_INPUT;
1443 cmap = Qnil;
1445 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1446 pc++, i++)
1447 cmap = Fcons (Fcons (build_string (pc->name),
1448 make_number (pc->colorref)),
1449 cmap);
1451 UNBLOCK_INPUT;
1453 return (cmap);
1456 Lisp_Object
1457 w32_to_x_color (rgb)
1458 Lisp_Object rgb;
1460 Lisp_Object color;
1462 CHECK_NUMBER (rgb, 0);
1464 BLOCK_INPUT;
1466 color = Frassq (rgb, Vw32_color_map);
1468 UNBLOCK_INPUT;
1470 if (!NILP (color))
1471 return (Fcar (color));
1472 else
1473 return Qnil;
1476 COLORREF
1477 w32_color_map_lookup (colorname)
1478 char *colorname;
1480 Lisp_Object tail, ret = Qnil;
1482 BLOCK_INPUT;
1484 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1486 register Lisp_Object elt, tem;
1488 elt = Fcar (tail);
1489 if (!CONSP (elt)) continue;
1491 tem = Fcar (elt);
1493 if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
1495 ret = XUINT (Fcdr (elt));
1496 break;
1499 QUIT;
1503 UNBLOCK_INPUT;
1505 return ret;
1508 COLORREF
1509 x_to_w32_color (colorname)
1510 char * colorname;
1512 register Lisp_Object ret = Qnil;
1514 BLOCK_INPUT;
1516 if (colorname[0] == '#')
1518 /* Could be an old-style RGB Device specification. */
1519 char *color;
1520 int size;
1521 color = colorname + 1;
1523 size = strlen(color);
1524 if (size == 3 || size == 6 || size == 9 || size == 12)
1526 UINT colorval;
1527 int i, pos;
1528 pos = 0;
1529 size /= 3;
1530 colorval = 0;
1532 for (i = 0; i < 3; i++)
1534 char *end;
1535 char t;
1536 unsigned long value;
1538 /* The check for 'x' in the following conditional takes into
1539 account the fact that strtol allows a "0x" in front of
1540 our numbers, and we don't. */
1541 if (!isxdigit(color[0]) || color[1] == 'x')
1542 break;
1543 t = color[size];
1544 color[size] = '\0';
1545 value = strtoul(color, &end, 16);
1546 color[size] = t;
1547 if (errno == ERANGE || end - color != size)
1548 break;
1549 switch (size)
1551 case 1:
1552 value = value * 0x10;
1553 break;
1554 case 2:
1555 break;
1556 case 3:
1557 value /= 0x10;
1558 break;
1559 case 4:
1560 value /= 0x100;
1561 break;
1563 colorval |= (value << pos);
1564 pos += 0x8;
1565 if (i == 2)
1567 UNBLOCK_INPUT;
1568 return (colorval);
1570 color = end;
1574 else if (strnicmp(colorname, "rgb:", 4) == 0)
1576 char *color;
1577 UINT colorval;
1578 int i, pos;
1579 pos = 0;
1581 colorval = 0;
1582 color = colorname + 4;
1583 for (i = 0; i < 3; i++)
1585 char *end;
1586 unsigned long value;
1588 /* The check for 'x' in the following conditional takes into
1589 account the fact that strtol allows a "0x" in front of
1590 our numbers, and we don't. */
1591 if (!isxdigit(color[0]) || color[1] == 'x')
1592 break;
1593 value = strtoul(color, &end, 16);
1594 if (errno == ERANGE)
1595 break;
1596 switch (end - color)
1598 case 1:
1599 value = value * 0x10 + value;
1600 break;
1601 case 2:
1602 break;
1603 case 3:
1604 value /= 0x10;
1605 break;
1606 case 4:
1607 value /= 0x100;
1608 break;
1609 default:
1610 value = ULONG_MAX;
1612 if (value == ULONG_MAX)
1613 break;
1614 colorval |= (value << pos);
1615 pos += 0x8;
1616 if (i == 2)
1618 if (*end != '\0')
1619 break;
1620 UNBLOCK_INPUT;
1621 return (colorval);
1623 if (*end != '/')
1624 break;
1625 color = end + 1;
1628 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1630 /* This is an RGB Intensity specification. */
1631 char *color;
1632 UINT colorval;
1633 int i, pos;
1634 pos = 0;
1636 colorval = 0;
1637 color = colorname + 5;
1638 for (i = 0; i < 3; i++)
1640 char *end;
1641 double value;
1642 UINT val;
1644 value = strtod(color, &end);
1645 if (errno == ERANGE)
1646 break;
1647 if (value < 0.0 || value > 1.0)
1648 break;
1649 val = (UINT)(0x100 * value);
1650 /* We used 0x100 instead of 0xFF to give an continuous
1651 range between 0.0 and 1.0 inclusive. The next statement
1652 fixes the 1.0 case. */
1653 if (val == 0x100)
1654 val = 0xFF;
1655 colorval |= (val << pos);
1656 pos += 0x8;
1657 if (i == 2)
1659 if (*end != '\0')
1660 break;
1661 UNBLOCK_INPUT;
1662 return (colorval);
1664 if (*end != '/')
1665 break;
1666 color = end + 1;
1669 /* I am not going to attempt to handle any of the CIE color schemes
1670 or TekHVC, since I don't know the algorithms for conversion to
1671 RGB. */
1673 /* If we fail to lookup the color name in w32_color_map, then check the
1674 colorname to see if it can be crudely approximated: If the X color
1675 ends in a number (e.g., "darkseagreen2"), strip the number and
1676 return the result of looking up the base color name. */
1677 ret = w32_color_map_lookup (colorname);
1678 if (NILP (ret))
1680 int len = strlen (colorname);
1682 if (isdigit (colorname[len - 1]))
1684 char *ptr, *approx = alloca (len);
1686 strcpy (approx, colorname);
1687 ptr = &approx[len - 1];
1688 while (ptr > approx && isdigit (*ptr))
1689 *ptr-- = '\0';
1691 ret = w32_color_map_lookup (approx);
1695 UNBLOCK_INPUT;
1696 return ret;
1700 void
1701 w32_regenerate_palette (FRAME_PTR f)
1703 struct w32_palette_entry * list;
1704 LOGPALETTE * log_palette;
1705 HPALETTE new_palette;
1706 int i;
1708 /* don't bother trying to create palette if not supported */
1709 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1710 return;
1712 log_palette = (LOGPALETTE *)
1713 alloca (sizeof (LOGPALETTE) +
1714 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1715 log_palette->palVersion = 0x300;
1716 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1718 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1719 for (i = 0;
1720 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1721 i++, list = list->next)
1722 log_palette->palPalEntry[i] = list->entry;
1724 new_palette = CreatePalette (log_palette);
1726 enter_crit ();
1728 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1729 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1730 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1732 /* Realize display palette and garbage all frames. */
1733 release_frame_dc (f, get_frame_dc (f));
1735 leave_crit ();
1738 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1739 #define SET_W32_COLOR(pe, color) \
1740 do \
1742 pe.peRed = GetRValue (color); \
1743 pe.peGreen = GetGValue (color); \
1744 pe.peBlue = GetBValue (color); \
1745 pe.peFlags = 0; \
1746 } while (0)
1748 #if 0
1749 /* Keep these around in case we ever want to track color usage. */
1750 void
1751 w32_map_color (FRAME_PTR f, COLORREF color)
1753 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1755 if (NILP (Vw32_enable_palette))
1756 return;
1758 /* check if color is already mapped */
1759 while (list)
1761 if (W32_COLOR (list->entry) == color)
1763 ++list->refcount;
1764 return;
1766 list = list->next;
1769 /* not already mapped, so add to list and recreate Windows palette */
1770 list = (struct w32_palette_entry *)
1771 xmalloc (sizeof (struct w32_palette_entry));
1772 SET_W32_COLOR (list->entry, color);
1773 list->refcount = 1;
1774 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1775 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1776 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1778 /* set flag that palette must be regenerated */
1779 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1782 void
1783 w32_unmap_color (FRAME_PTR f, COLORREF color)
1785 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1786 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1788 if (NILP (Vw32_enable_palette))
1789 return;
1791 /* check if color is already mapped */
1792 while (list)
1794 if (W32_COLOR (list->entry) == color)
1796 if (--list->refcount == 0)
1798 *prev = list->next;
1799 xfree (list);
1800 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1801 break;
1803 else
1804 return;
1806 prev = &list->next;
1807 list = list->next;
1810 /* set flag that palette must be regenerated */
1811 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1813 #endif
1816 /* Gamma-correct COLOR on frame F. */
1818 void
1819 gamma_correct (f, color)
1820 struct frame *f;
1821 COLORREF *color;
1823 if (f->gamma)
1825 *color = PALETTERGB (
1826 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1827 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1828 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1833 /* Decide if color named COLOR is valid for the display associated with
1834 the selected frame; if so, return the rgb values in COLOR_DEF.
1835 If ALLOC is nonzero, allocate a new colormap cell. */
1838 w32_defined_color (f, color, color_def, alloc)
1839 FRAME_PTR f;
1840 char *color;
1841 XColor *color_def;
1842 int alloc;
1844 register Lisp_Object tem;
1845 COLORREF w32_color_ref;
1847 tem = x_to_w32_color (color);
1849 if (!NILP (tem))
1851 if (f)
1853 /* Apply gamma correction. */
1854 w32_color_ref = XUINT (tem);
1855 gamma_correct (f, &w32_color_ref);
1856 XSETINT (tem, w32_color_ref);
1859 /* Map this color to the palette if it is enabled. */
1860 if (!NILP (Vw32_enable_palette))
1862 struct w32_palette_entry * entry =
1863 one_w32_display_info.color_list;
1864 struct w32_palette_entry ** prev =
1865 &one_w32_display_info.color_list;
1867 /* check if color is already mapped */
1868 while (entry)
1870 if (W32_COLOR (entry->entry) == XUINT (tem))
1871 break;
1872 prev = &entry->next;
1873 entry = entry->next;
1876 if (entry == NULL && alloc)
1878 /* not already mapped, so add to list */
1879 entry = (struct w32_palette_entry *)
1880 xmalloc (sizeof (struct w32_palette_entry));
1881 SET_W32_COLOR (entry->entry, XUINT (tem));
1882 entry->next = NULL;
1883 *prev = entry;
1884 one_w32_display_info.num_colors++;
1886 /* set flag that palette must be regenerated */
1887 one_w32_display_info.regen_palette = TRUE;
1890 /* Ensure COLORREF value is snapped to nearest color in (default)
1891 palette by simulating the PALETTERGB macro. This works whether
1892 or not the display device has a palette. */
1893 w32_color_ref = XUINT (tem) | 0x2000000;
1895 color_def->pixel = w32_color_ref;
1896 color_def->red = GetRValue (w32_color_ref);
1897 color_def->green = GetGValue (w32_color_ref);
1898 color_def->blue = GetBValue (w32_color_ref);
1900 return 1;
1902 else
1904 return 0;
1908 /* Given a string ARG naming a color, compute a pixel value from it
1909 suitable for screen F.
1910 If F is not a color screen, return DEF (default) regardless of what
1911 ARG says. */
1914 x_decode_color (f, arg, def)
1915 FRAME_PTR f;
1916 Lisp_Object arg;
1917 int def;
1919 XColor cdef;
1921 CHECK_STRING (arg, 0);
1923 if (strcmp (XSTRING (arg)->data, "black") == 0)
1924 return BLACK_PIX_DEFAULT (f);
1925 else if (strcmp (XSTRING (arg)->data, "white") == 0)
1926 return WHITE_PIX_DEFAULT (f);
1928 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1929 return def;
1931 /* w32_defined_color is responsible for coping with failures
1932 by looking for a near-miss. */
1933 if (w32_defined_color (f, XSTRING (arg)->data, &cdef, 1))
1934 return cdef.pixel;
1936 /* defined_color failed; return an ultimate default. */
1937 return def;
1940 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
1941 the previous value of that parameter, NEW_VALUE is the new value. */
1943 static void
1944 x_set_line_spacing (f, new_value, old_value)
1945 struct frame *f;
1946 Lisp_Object new_value, old_value;
1948 if (NILP (new_value))
1949 f->extra_line_spacing = 0;
1950 else if (NATNUMP (new_value))
1951 f->extra_line_spacing = XFASTINT (new_value);
1952 else
1953 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
1954 Fcons (new_value, Qnil)));
1955 if (FRAME_VISIBLE_P (f))
1956 redraw_frame (f);
1960 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
1961 the previous value of that parameter, NEW_VALUE is the new value. */
1963 static void
1964 x_set_screen_gamma (f, new_value, old_value)
1965 struct frame *f;
1966 Lisp_Object new_value, old_value;
1968 if (NILP (new_value))
1969 f->gamma = 0;
1970 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
1971 /* The value 0.4545 is the normal viewing gamma. */
1972 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
1973 else
1974 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
1975 Fcons (new_value, Qnil)));
1977 clear_face_cache (0);
1981 /* Functions called only from `x_set_frame_param'
1982 to set individual parameters.
1984 If FRAME_W32_WINDOW (f) is 0,
1985 the frame is being created and its window does not exist yet.
1986 In that case, just record the parameter's new value
1987 in the standard place; do not attempt to change the window. */
1989 void
1990 x_set_foreground_color (f, arg, oldval)
1991 struct frame *f;
1992 Lisp_Object arg, oldval;
1994 FRAME_FOREGROUND_PIXEL (f)
1995 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1997 if (FRAME_W32_WINDOW (f) != 0)
1999 update_face_from_frame_parameter (f, Qforeground_color, arg);
2000 if (FRAME_VISIBLE_P (f))
2001 redraw_frame (f);
2005 void
2006 x_set_background_color (f, arg, oldval)
2007 struct frame *f;
2008 Lisp_Object arg, oldval;
2010 FRAME_BACKGROUND_PIXEL (f)
2011 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2013 if (FRAME_W32_WINDOW (f) != 0)
2015 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2016 FRAME_BACKGROUND_PIXEL (f));
2018 update_face_from_frame_parameter (f, Qbackground_color, arg);
2020 if (FRAME_VISIBLE_P (f))
2021 redraw_frame (f);
2025 void
2026 x_set_mouse_color (f, arg, oldval)
2027 struct frame *f;
2028 Lisp_Object arg, oldval;
2030 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2031 int count;
2032 int mask_color;
2034 if (!EQ (Qnil, arg))
2035 f->output_data.w32->mouse_pixel
2036 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2037 mask_color = FRAME_BACKGROUND_PIXEL (f);
2039 /* Don't let pointers be invisible. */
2040 if (mask_color == f->output_data.w32->mouse_pixel
2041 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2042 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2044 #if 0 /* TODO : cursor changes */
2045 BLOCK_INPUT;
2047 /* It's not okay to crash if the user selects a screwy cursor. */
2048 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2050 if (!EQ (Qnil, Vx_pointer_shape))
2052 CHECK_NUMBER (Vx_pointer_shape, 0);
2053 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2055 else
2056 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2057 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2059 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2061 CHECK_NUMBER (Vx_nontext_pointer_shape, 0);
2062 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2063 XINT (Vx_nontext_pointer_shape));
2065 else
2066 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2067 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2069 if (!EQ (Qnil, Vx_busy_pointer_shape))
2071 CHECK_NUMBER (Vx_busy_pointer_shape, 0);
2072 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2073 XINT (Vx_busy_pointer_shape));
2075 else
2076 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2077 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2079 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2080 if (!EQ (Qnil, Vx_mode_pointer_shape))
2082 CHECK_NUMBER (Vx_mode_pointer_shape, 0);
2083 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2084 XINT (Vx_mode_pointer_shape));
2086 else
2087 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2088 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2090 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2092 CHECK_NUMBER (Vx_sensitive_text_pointer_shape, 0);
2093 cross_cursor
2094 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2095 XINT (Vx_sensitive_text_pointer_shape));
2097 else
2098 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2100 if (!NILP (Vx_window_horizontal_drag_shape))
2102 CHECK_NUMBER (Vx_window_horizontal_drag_shape, 0);
2103 horizontal_drag_cursor
2104 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2105 XINT (Vx_window_horizontal_drag_shape));
2107 else
2108 horizontal_drag_cursor
2109 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2111 /* Check and report errors with the above calls. */
2112 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2113 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2116 XColor fore_color, back_color;
2118 fore_color.pixel = f->output_data.w32->mouse_pixel;
2119 back_color.pixel = mask_color;
2120 XQueryColor (FRAME_W32_DISPLAY (f),
2121 DefaultColormap (FRAME_W32_DISPLAY (f),
2122 DefaultScreen (FRAME_W32_DISPLAY (f))),
2123 &fore_color);
2124 XQueryColor (FRAME_W32_DISPLAY (f),
2125 DefaultColormap (FRAME_W32_DISPLAY (f),
2126 DefaultScreen (FRAME_W32_DISPLAY (f))),
2127 &back_color);
2128 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2129 &fore_color, &back_color);
2130 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2131 &fore_color, &back_color);
2132 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2133 &fore_color, &back_color);
2134 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2135 &fore_color, &back_color);
2136 XRecolorCursor (FRAME_W32_DISPLAY (f), busy_cursor,
2137 &fore_color, &back_color);
2140 if (FRAME_W32_WINDOW (f) != 0)
2141 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2143 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2144 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2145 f->output_data.w32->text_cursor = cursor;
2147 if (nontext_cursor != f->output_data.w32->nontext_cursor
2148 && f->output_data.w32->nontext_cursor != 0)
2149 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2150 f->output_data.w32->nontext_cursor = nontext_cursor;
2152 if (busy_cursor != f->output_data.w32->busy_cursor
2153 && f->output_data.w32->busy_cursor != 0)
2154 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->busy_cursor);
2155 f->output_data.w32->busy_cursor = busy_cursor;
2157 if (mode_cursor != f->output_data.w32->modeline_cursor
2158 && f->output_data.w32->modeline_cursor != 0)
2159 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2160 f->output_data.w32->modeline_cursor = mode_cursor;
2162 if (cross_cursor != f->output_data.w32->cross_cursor
2163 && f->output_data.w32->cross_cursor != 0)
2164 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2165 f->output_data.w32->cross_cursor = cross_cursor;
2167 XFlush (FRAME_W32_DISPLAY (f));
2168 UNBLOCK_INPUT;
2170 update_face_from_frame_parameter (f, Qmouse_color, arg);
2171 #endif /* TODO */
2174 /* Defined in w32term.c. */
2175 void x_update_cursor (struct frame *f, int on_p);
2177 void
2178 x_set_cursor_color (f, arg, oldval)
2179 struct frame *f;
2180 Lisp_Object arg, oldval;
2182 unsigned long fore_pixel, pixel;
2184 if (!NILP (Vx_cursor_fore_pixel))
2185 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2186 WHITE_PIX_DEFAULT (f));
2187 else
2188 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2190 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2192 /* Make sure that the cursor color differs from the background color. */
2193 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2195 pixel = f->output_data.w32->mouse_pixel;
2196 if (pixel == fore_pixel)
2197 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2200 FRAME_FOREGROUND_PIXEL (f) = fore_pixel;
2201 f->output_data.w32->cursor_pixel = pixel;
2203 if (FRAME_W32_WINDOW (f) != 0)
2205 if (FRAME_VISIBLE_P (f))
2207 x_update_cursor (f, 0);
2208 x_update_cursor (f, 1);
2212 update_face_from_frame_parameter (f, Qcursor_color, arg);
2215 /* Set the border-color of frame F to pixel value PIX.
2216 Note that this does not fully take effect if done before
2217 F has an window. */
2218 void
2219 x_set_border_pixel (f, pix)
2220 struct frame *f;
2221 int pix;
2223 f->output_data.w32->border_pixel = pix;
2225 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2227 if (FRAME_VISIBLE_P (f))
2228 redraw_frame (f);
2232 /* Set the border-color of frame F to value described by ARG.
2233 ARG can be a string naming a color.
2234 The border-color is used for the border that is drawn by the server.
2235 Note that this does not fully take effect if done before
2236 F has a window; it must be redone when the window is created. */
2238 void
2239 x_set_border_color (f, arg, oldval)
2240 struct frame *f;
2241 Lisp_Object arg, oldval;
2243 int pix;
2245 CHECK_STRING (arg, 0);
2246 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2247 x_set_border_pixel (f, pix);
2248 update_face_from_frame_parameter (f, Qborder_color, arg);
2251 /* Value is the internal representation of the specified cursor type
2252 ARG. If type is BAR_CURSOR, return in *WIDTH the specified width
2253 of the bar cursor. */
2255 enum text_cursor_kinds
2256 x_specified_cursor_type (arg, width)
2257 Lisp_Object arg;
2258 int *width;
2260 enum text_cursor_kinds type;
2262 if (EQ (arg, Qbar))
2264 type = BAR_CURSOR;
2265 *width = 2;
2267 else if (CONSP (arg)
2268 && EQ (XCAR (arg), Qbar)
2269 && INTEGERP (XCDR (arg))
2270 && XINT (XCDR (arg)) >= 0)
2272 type = BAR_CURSOR;
2273 *width = XINT (XCDR (arg));
2275 else if (NILP (arg))
2276 type = NO_CURSOR;
2277 else
2278 /* Treat anything unknown as "box cursor".
2279 It was bad to signal an error; people have trouble fixing
2280 .Xdefaults with Emacs, when it has something bad in it. */
2281 type = FILLED_BOX_CURSOR;
2283 return type;
2286 void
2287 x_set_cursor_type (f, arg, oldval)
2288 FRAME_PTR f;
2289 Lisp_Object arg, oldval;
2291 int width;
2293 FRAME_DESIRED_CURSOR (f) = x_specified_cursor_type (arg, &width);
2294 f->output_data.w32->cursor_width = width;
2296 /* Make sure the cursor gets redrawn. This is overkill, but how
2297 often do people change cursor types? */
2298 update_mode_lines++;
2301 void
2302 x_set_icon_type (f, arg, oldval)
2303 struct frame *f;
2304 Lisp_Object arg, oldval;
2306 int result;
2308 if (NILP (arg) && NILP (oldval))
2309 return;
2311 if (STRINGP (arg) && STRINGP (oldval)
2312 && EQ (Fstring_equal (oldval, arg), Qt))
2313 return;
2315 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2316 return;
2318 BLOCK_INPUT;
2320 result = x_bitmap_icon (f, arg);
2321 if (result)
2323 UNBLOCK_INPUT;
2324 error ("No icon window available");
2327 UNBLOCK_INPUT;
2330 /* Return non-nil if frame F wants a bitmap icon. */
2332 Lisp_Object
2333 x_icon_type (f)
2334 FRAME_PTR f;
2336 Lisp_Object tem;
2338 tem = assq_no_quit (Qicon_type, f->param_alist);
2339 if (CONSP (tem))
2340 return XCDR (tem);
2341 else
2342 return Qnil;
2345 void
2346 x_set_icon_name (f, arg, oldval)
2347 struct frame *f;
2348 Lisp_Object arg, oldval;
2350 if (STRINGP (arg))
2352 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2353 return;
2355 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2356 return;
2358 f->icon_name = arg;
2360 #if 0
2361 if (f->output_data.w32->icon_bitmap != 0)
2362 return;
2364 BLOCK_INPUT;
2366 result = x_text_icon (f,
2367 (char *) XSTRING ((!NILP (f->icon_name)
2368 ? f->icon_name
2369 : !NILP (f->title)
2370 ? f->title
2371 : f->name))->data);
2373 if (result)
2375 UNBLOCK_INPUT;
2376 error ("No icon window available");
2379 /* If the window was unmapped (and its icon was mapped),
2380 the new icon is not mapped, so map the window in its stead. */
2381 if (FRAME_VISIBLE_P (f))
2383 #ifdef USE_X_TOOLKIT
2384 XtPopup (f->output_data.w32->widget, XtGrabNone);
2385 #endif
2386 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2389 XFlush (FRAME_W32_DISPLAY (f));
2390 UNBLOCK_INPUT;
2391 #endif
2394 extern Lisp_Object x_new_font ();
2395 extern Lisp_Object x_new_fontset();
2397 void
2398 x_set_font (f, arg, oldval)
2399 struct frame *f;
2400 Lisp_Object arg, oldval;
2402 Lisp_Object result;
2403 Lisp_Object fontset_name;
2404 Lisp_Object frame;
2406 CHECK_STRING (arg, 1);
2408 fontset_name = Fquery_fontset (arg, Qnil);
2410 BLOCK_INPUT;
2411 result = (STRINGP (fontset_name)
2412 ? x_new_fontset (f, XSTRING (fontset_name)->data)
2413 : x_new_font (f, XSTRING (arg)->data));
2414 UNBLOCK_INPUT;
2416 if (EQ (result, Qnil))
2417 error ("Font `%s' is not defined", XSTRING (arg)->data);
2418 else if (EQ (result, Qt))
2419 error ("The characters of the given font have varying widths");
2420 else if (STRINGP (result))
2422 store_frame_param (f, Qfont, result);
2423 recompute_basic_faces (f);
2425 else
2426 abort ();
2428 do_pending_window_change (0);
2430 /* Don't call `face-set-after-frame-default' when faces haven't been
2431 initialized yet. This is the case when called from
2432 Fx_create_frame. In that case, the X widget or window doesn't
2433 exist either, and we can end up in x_report_frame_params with a
2434 null widget which gives a segfault. */
2435 if (FRAME_FACE_CACHE (f))
2437 XSETFRAME (frame, f);
2438 call1 (Qface_set_after_frame_default, frame);
2442 void
2443 x_set_border_width (f, arg, oldval)
2444 struct frame *f;
2445 Lisp_Object arg, oldval;
2447 CHECK_NUMBER (arg, 0);
2449 if (XINT (arg) == f->output_data.w32->border_width)
2450 return;
2452 if (FRAME_W32_WINDOW (f) != 0)
2453 error ("Cannot change the border width of a window");
2455 f->output_data.w32->border_width = XINT (arg);
2458 void
2459 x_set_internal_border_width (f, arg, oldval)
2460 struct frame *f;
2461 Lisp_Object arg, oldval;
2463 int old = f->output_data.w32->internal_border_width;
2465 CHECK_NUMBER (arg, 0);
2466 f->output_data.w32->internal_border_width = XINT (arg);
2467 if (f->output_data.w32->internal_border_width < 0)
2468 f->output_data.w32->internal_border_width = 0;
2470 if (f->output_data.w32->internal_border_width == old)
2471 return;
2473 if (FRAME_W32_WINDOW (f) != 0)
2475 x_set_window_size (f, 0, f->width, f->height);
2476 SET_FRAME_GARBAGED (f);
2477 do_pending_window_change (0);
2481 void
2482 x_set_visibility (f, value, oldval)
2483 struct frame *f;
2484 Lisp_Object value, oldval;
2486 Lisp_Object frame;
2487 XSETFRAME (frame, f);
2489 if (NILP (value))
2490 Fmake_frame_invisible (frame, Qt);
2491 else if (EQ (value, Qicon))
2492 Ficonify_frame (frame);
2493 else
2494 Fmake_frame_visible (frame);
2498 /* Change window heights in windows rooted in WINDOW by N lines. */
2500 static void
2501 x_change_window_heights (window, n)
2502 Lisp_Object window;
2503 int n;
2505 struct window *w = XWINDOW (window);
2507 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2508 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2510 if (INTEGERP (w->orig_top))
2511 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2512 if (INTEGERP (w->orig_height))
2513 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2515 /* Handle just the top child in a vertical split. */
2516 if (!NILP (w->vchild))
2517 x_change_window_heights (w->vchild, n);
2519 /* Adjust all children in a horizontal split. */
2520 for (window = w->hchild; !NILP (window); window = w->next)
2522 w = XWINDOW (window);
2523 x_change_window_heights (window, n);
2527 void
2528 x_set_menu_bar_lines (f, value, oldval)
2529 struct frame *f;
2530 Lisp_Object value, oldval;
2532 int nlines;
2533 int olines = FRAME_MENU_BAR_LINES (f);
2535 /* Right now, menu bars don't work properly in minibuf-only frames;
2536 most of the commands try to apply themselves to the minibuffer
2537 frame itself, and get an error because you can't switch buffers
2538 in or split the minibuffer window. */
2539 if (FRAME_MINIBUF_ONLY_P (f))
2540 return;
2542 if (INTEGERP (value))
2543 nlines = XINT (value);
2544 else
2545 nlines = 0;
2547 FRAME_MENU_BAR_LINES (f) = 0;
2548 if (nlines)
2549 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2550 else
2552 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2553 free_frame_menubar (f);
2554 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2556 /* Adjust the frame size so that the client (text) dimensions
2557 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2558 set correctly. */
2559 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2560 do_pending_window_change (0);
2562 adjust_glyphs (f);
2566 /* Set the number of lines used for the tool bar of frame F to VALUE.
2567 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2568 is the old number of tool bar lines. This function changes the
2569 height of all windows on frame F to match the new tool bar height.
2570 The frame's height doesn't change. */
2572 void
2573 x_set_tool_bar_lines (f, value, oldval)
2574 struct frame *f;
2575 Lisp_Object value, oldval;
2577 int delta, nlines, root_height;
2578 Lisp_Object root_window;
2580 /* Use VALUE only if an integer >= 0. */
2581 if (INTEGERP (value) && XINT (value) >= 0)
2582 nlines = XFASTINT (value);
2583 else
2584 nlines = 0;
2586 /* Make sure we redisplay all windows in this frame. */
2587 ++windows_or_buffers_changed;
2589 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2591 /* Don't resize the tool-bar to more than we have room for. */
2592 root_window = FRAME_ROOT_WINDOW (f);
2593 root_height = XINT (XWINDOW (root_window)->height);
2594 if (root_height - delta < 1)
2596 delta = root_height - 1;
2597 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2600 FRAME_TOOL_BAR_LINES (f) = nlines;
2601 x_change_window_heights (root_window, delta);
2602 adjust_glyphs (f);
2604 /* We also have to make sure that the internal border at the top of
2605 the frame, below the menu bar or tool bar, is redrawn when the
2606 tool bar disappears. This is so because the internal border is
2607 below the tool bar if one is displayed, but is below the menu bar
2608 if there isn't a tool bar. The tool bar draws into the area
2609 below the menu bar. */
2610 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2612 updating_frame = f;
2613 clear_frame ();
2614 clear_current_matrices (f);
2615 updating_frame = NULL;
2618 /* If the tool bar gets smaller, the internal border below it
2619 has to be cleared. It was formerly part of the display
2620 of the larger tool bar, and updating windows won't clear it. */
2621 if (delta < 0)
2623 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2624 int width = PIXEL_WIDTH (f);
2625 int y = nlines * CANON_Y_UNIT (f);
2627 BLOCK_INPUT;
2629 HDC hdc = get_frame_dc (f);
2630 w32_clear_area (f, hdc, 0, y, width, height);
2631 release_frame_dc (f, hdc);
2633 UNBLOCK_INPUT;
2638 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2639 w32_id_name.
2641 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2642 name; if NAME is a string, set F's name to NAME and set
2643 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2645 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2646 suggesting a new name, which lisp code should override; if
2647 F->explicit_name is set, ignore the new name; otherwise, set it. */
2649 void
2650 x_set_name (f, name, explicit)
2651 struct frame *f;
2652 Lisp_Object name;
2653 int explicit;
2655 /* Make sure that requests from lisp code override requests from
2656 Emacs redisplay code. */
2657 if (explicit)
2659 /* If we're switching from explicit to implicit, we had better
2660 update the mode lines and thereby update the title. */
2661 if (f->explicit_name && NILP (name))
2662 update_mode_lines = 1;
2664 f->explicit_name = ! NILP (name);
2666 else if (f->explicit_name)
2667 return;
2669 /* If NAME is nil, set the name to the w32_id_name. */
2670 if (NILP (name))
2672 /* Check for no change needed in this very common case
2673 before we do any consing. */
2674 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2675 XSTRING (f->name)->data))
2676 return;
2677 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2679 else
2680 CHECK_STRING (name, 0);
2682 /* Don't change the name if it's already NAME. */
2683 if (! NILP (Fstring_equal (name, f->name)))
2684 return;
2686 f->name = name;
2688 /* For setting the frame title, the title parameter should override
2689 the name parameter. */
2690 if (! NILP (f->title))
2691 name = f->title;
2693 if (FRAME_W32_WINDOW (f))
2695 if (STRING_MULTIBYTE (name))
2696 name = ENCODE_SYSTEM (name);
2698 BLOCK_INPUT;
2699 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2700 UNBLOCK_INPUT;
2704 /* This function should be called when the user's lisp code has
2705 specified a name for the frame; the name will override any set by the
2706 redisplay code. */
2707 void
2708 x_explicitly_set_name (f, arg, oldval)
2709 FRAME_PTR f;
2710 Lisp_Object arg, oldval;
2712 x_set_name (f, arg, 1);
2715 /* This function should be called by Emacs redisplay code to set the
2716 name; names set this way will never override names set by the user's
2717 lisp code. */
2718 void
2719 x_implicitly_set_name (f, arg, oldval)
2720 FRAME_PTR f;
2721 Lisp_Object arg, oldval;
2723 x_set_name (f, arg, 0);
2726 /* Change the title of frame F to NAME.
2727 If NAME is nil, use the frame name as the title.
2729 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2730 name; if NAME is a string, set F's name to NAME and set
2731 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2733 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2734 suggesting a new name, which lisp code should override; if
2735 F->explicit_name is set, ignore the new name; otherwise, set it. */
2737 void
2738 x_set_title (f, name, old_name)
2739 struct frame *f;
2740 Lisp_Object name, old_name;
2742 /* Don't change the title if it's already NAME. */
2743 if (EQ (name, f->title))
2744 return;
2746 update_mode_lines = 1;
2748 f->title = name;
2750 if (NILP (name))
2751 name = f->name;
2753 if (FRAME_W32_WINDOW (f))
2755 if (STRING_MULTIBYTE (name))
2756 name = ENCODE_SYSTEM (name);
2758 BLOCK_INPUT;
2759 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2760 UNBLOCK_INPUT;
2764 void
2765 x_set_autoraise (f, arg, oldval)
2766 struct frame *f;
2767 Lisp_Object arg, oldval;
2769 f->auto_raise = !EQ (Qnil, arg);
2772 void
2773 x_set_autolower (f, arg, oldval)
2774 struct frame *f;
2775 Lisp_Object arg, oldval;
2777 f->auto_lower = !EQ (Qnil, arg);
2780 void
2781 x_set_unsplittable (f, arg, oldval)
2782 struct frame *f;
2783 Lisp_Object arg, oldval;
2785 f->no_split = !NILP (arg);
2788 void
2789 x_set_vertical_scroll_bars (f, arg, oldval)
2790 struct frame *f;
2791 Lisp_Object arg, oldval;
2793 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2794 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2795 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2796 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2798 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2799 vertical_scroll_bar_none :
2800 /* Put scroll bars on the right by default, as is conventional
2801 on MS-Windows. */
2802 EQ (Qleft, arg)
2803 ? vertical_scroll_bar_left
2804 : vertical_scroll_bar_right;
2806 /* We set this parameter before creating the window for the
2807 frame, so we can get the geometry right from the start.
2808 However, if the window hasn't been created yet, we shouldn't
2809 call x_set_window_size. */
2810 if (FRAME_W32_WINDOW (f))
2811 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2812 do_pending_window_change (0);
2816 void
2817 x_set_scroll_bar_width (f, arg, oldval)
2818 struct frame *f;
2819 Lisp_Object arg, oldval;
2821 int wid = FONT_WIDTH (f->output_data.w32->font);
2823 if (NILP (arg))
2825 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2826 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2827 wid - 1) / wid;
2828 if (FRAME_W32_WINDOW (f))
2829 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2830 do_pending_window_change (0);
2832 else if (INTEGERP (arg) && XINT (arg) > 0
2833 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2835 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2836 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2837 + wid-1) / wid;
2838 if (FRAME_W32_WINDOW (f))
2839 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2840 do_pending_window_change (0);
2842 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2843 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2844 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2847 /* Subroutines of creating an frame. */
2849 /* Make sure that Vx_resource_name is set to a reasonable value.
2850 Fix it up, or set it to `emacs' if it is too hopeless. */
2852 static void
2853 validate_x_resource_name ()
2855 int len = 0;
2856 /* Number of valid characters in the resource name. */
2857 int good_count = 0;
2858 /* Number of invalid characters in the resource name. */
2859 int bad_count = 0;
2860 Lisp_Object new;
2861 int i;
2863 if (STRINGP (Vx_resource_name))
2865 unsigned char *p = XSTRING (Vx_resource_name)->data;
2866 int i;
2868 len = STRING_BYTES (XSTRING (Vx_resource_name));
2870 /* Only letters, digits, - and _ are valid in resource names.
2871 Count the valid characters and count the invalid ones. */
2872 for (i = 0; i < len; i++)
2874 int c = p[i];
2875 if (! ((c >= 'a' && c <= 'z')
2876 || (c >= 'A' && c <= 'Z')
2877 || (c >= '0' && c <= '9')
2878 || c == '-' || c == '_'))
2879 bad_count++;
2880 else
2881 good_count++;
2884 else
2885 /* Not a string => completely invalid. */
2886 bad_count = 5, good_count = 0;
2888 /* If name is valid already, return. */
2889 if (bad_count == 0)
2890 return;
2892 /* If name is entirely invalid, or nearly so, use `emacs'. */
2893 if (good_count == 0
2894 || (good_count == 1 && bad_count > 0))
2896 Vx_resource_name = build_string ("emacs");
2897 return;
2900 /* Name is partly valid. Copy it and replace the invalid characters
2901 with underscores. */
2903 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2905 for (i = 0; i < len; i++)
2907 int c = XSTRING (new)->data[i];
2908 if (! ((c >= 'a' && c <= 'z')
2909 || (c >= 'A' && c <= 'Z')
2910 || (c >= '0' && c <= '9')
2911 || c == '-' || c == '_'))
2912 XSTRING (new)->data[i] = '_';
2917 extern char *x_get_string_resource ();
2919 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2920 "Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.\n\
2921 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the\n\
2922 class, where INSTANCE is the name under which Emacs was invoked, or\n\
2923 the name specified by the `-name' or `-rn' command-line arguments.\n\
2925 The optional arguments COMPONENT and SUBCLASS add to the key and the\n\
2926 class, respectively. You must specify both of them or neither.\n\
2927 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'\n\
2928 and the class is `Emacs.CLASS.SUBCLASS'.")
2929 (attribute, class, component, subclass)
2930 Lisp_Object attribute, class, component, subclass;
2932 register char *value;
2933 char *name_key;
2934 char *class_key;
2936 CHECK_STRING (attribute, 0);
2937 CHECK_STRING (class, 0);
2939 if (!NILP (component))
2940 CHECK_STRING (component, 1);
2941 if (!NILP (subclass))
2942 CHECK_STRING (subclass, 2);
2943 if (NILP (component) != NILP (subclass))
2944 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
2946 validate_x_resource_name ();
2948 /* Allocate space for the components, the dots which separate them,
2949 and the final '\0'. Make them big enough for the worst case. */
2950 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vx_resource_name))
2951 + (STRINGP (component)
2952 ? STRING_BYTES (XSTRING (component)) : 0)
2953 + STRING_BYTES (XSTRING (attribute))
2954 + 3);
2956 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2957 + STRING_BYTES (XSTRING (class))
2958 + (STRINGP (subclass)
2959 ? STRING_BYTES (XSTRING (subclass)) : 0)
2960 + 3);
2962 /* Start with emacs.FRAMENAME for the name (the specific one)
2963 and with `Emacs' for the class key (the general one). */
2964 strcpy (name_key, XSTRING (Vx_resource_name)->data);
2965 strcpy (class_key, EMACS_CLASS);
2967 strcat (class_key, ".");
2968 strcat (class_key, XSTRING (class)->data);
2970 if (!NILP (component))
2972 strcat (class_key, ".");
2973 strcat (class_key, XSTRING (subclass)->data);
2975 strcat (name_key, ".");
2976 strcat (name_key, XSTRING (component)->data);
2979 strcat (name_key, ".");
2980 strcat (name_key, XSTRING (attribute)->data);
2982 value = x_get_string_resource (Qnil,
2983 name_key, class_key);
2985 if (value != (char *) 0)
2986 return build_string (value);
2987 else
2988 return Qnil;
2991 /* Used when C code wants a resource value. */
2993 char *
2994 x_get_resource_string (attribute, class)
2995 char *attribute, *class;
2997 char *name_key;
2998 char *class_key;
2999 struct frame *sf = SELECTED_FRAME ();
3001 /* Allocate space for the components, the dots which separate them,
3002 and the final '\0'. */
3003 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vinvocation_name))
3004 + strlen (attribute) + 2);
3005 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3006 + strlen (class) + 2);
3008 sprintf (name_key, "%s.%s",
3009 XSTRING (Vinvocation_name)->data,
3010 attribute);
3011 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
3013 return x_get_string_resource (sf, name_key, class_key);
3016 /* Types we might convert a resource string into. */
3017 enum resource_types
3019 RES_TYPE_NUMBER,
3020 RES_TYPE_FLOAT,
3021 RES_TYPE_BOOLEAN,
3022 RES_TYPE_STRING,
3023 RES_TYPE_SYMBOL
3026 /* Return the value of parameter PARAM.
3028 First search ALIST, then Vdefault_frame_alist, then the X defaults
3029 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3031 Convert the resource to the type specified by desired_type.
3033 If no default is specified, return Qunbound. If you call
3034 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3035 and don't let it get stored in any Lisp-visible variables! */
3037 static Lisp_Object
3038 w32_get_arg (alist, param, attribute, class, type)
3039 Lisp_Object alist, param;
3040 char *attribute;
3041 char *class;
3042 enum resource_types type;
3044 register Lisp_Object tem;
3046 tem = Fassq (param, alist);
3047 if (EQ (tem, Qnil))
3048 tem = Fassq (param, Vdefault_frame_alist);
3049 if (EQ (tem, Qnil))
3052 if (attribute)
3054 tem = Fx_get_resource (build_string (attribute),
3055 build_string (class),
3056 Qnil, Qnil);
3058 if (NILP (tem))
3059 return Qunbound;
3061 switch (type)
3063 case RES_TYPE_NUMBER:
3064 return make_number (atoi (XSTRING (tem)->data));
3066 case RES_TYPE_FLOAT:
3067 return make_float (atof (XSTRING (tem)->data));
3069 case RES_TYPE_BOOLEAN:
3070 tem = Fdowncase (tem);
3071 if (!strcmp (XSTRING (tem)->data, "on")
3072 || !strcmp (XSTRING (tem)->data, "true"))
3073 return Qt;
3074 else
3075 return Qnil;
3077 case RES_TYPE_STRING:
3078 return tem;
3080 case RES_TYPE_SYMBOL:
3081 /* As a special case, we map the values `true' and `on'
3082 to Qt, and `false' and `off' to Qnil. */
3084 Lisp_Object lower;
3085 lower = Fdowncase (tem);
3086 if (!strcmp (XSTRING (lower)->data, "on")
3087 || !strcmp (XSTRING (lower)->data, "true"))
3088 return Qt;
3089 else if (!strcmp (XSTRING (lower)->data, "off")
3090 || !strcmp (XSTRING (lower)->data, "false"))
3091 return Qnil;
3092 else
3093 return Fintern (tem, Qnil);
3096 default:
3097 abort ();
3100 else
3101 return Qunbound;
3103 return Fcdr (tem);
3106 /* Record in frame F the specified or default value according to ALIST
3107 of the parameter named PROP (a Lisp symbol).
3108 If no value is specified for PROP, look for an X default for XPROP
3109 on the frame named NAME.
3110 If that is not found either, use the value DEFLT. */
3112 static Lisp_Object
3113 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3114 struct frame *f;
3115 Lisp_Object alist;
3116 Lisp_Object prop;
3117 Lisp_Object deflt;
3118 char *xprop;
3119 char *xclass;
3120 enum resource_types type;
3122 Lisp_Object tem;
3124 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3125 if (EQ (tem, Qunbound))
3126 tem = deflt;
3127 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3128 return tem;
3131 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3132 "Parse an X-style geometry string STRING.\n\
3133 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).\n\
3134 The properties returned may include `top', `left', `height', and `width'.\n\
3135 The value of `left' or `top' may be an integer,\n\
3136 or a list (+ N) meaning N pixels relative to top/left corner,\n\
3137 or a list (- N) meaning -N pixels relative to bottom/right corner.")
3138 (string)
3139 Lisp_Object string;
3141 int geometry, x, y;
3142 unsigned int width, height;
3143 Lisp_Object result;
3145 CHECK_STRING (string, 0);
3147 geometry = XParseGeometry ((char *) XSTRING (string)->data,
3148 &x, &y, &width, &height);
3150 result = Qnil;
3151 if (geometry & XValue)
3153 Lisp_Object element;
3155 if (x >= 0 && (geometry & XNegative))
3156 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3157 else if (x < 0 && ! (geometry & XNegative))
3158 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3159 else
3160 element = Fcons (Qleft, make_number (x));
3161 result = Fcons (element, result);
3164 if (geometry & YValue)
3166 Lisp_Object element;
3168 if (y >= 0 && (geometry & YNegative))
3169 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3170 else if (y < 0 && ! (geometry & YNegative))
3171 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3172 else
3173 element = Fcons (Qtop, make_number (y));
3174 result = Fcons (element, result);
3177 if (geometry & WidthValue)
3178 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3179 if (geometry & HeightValue)
3180 result = Fcons (Fcons (Qheight, make_number (height)), result);
3182 return result;
3185 /* Calculate the desired size and position of this window,
3186 and return the flags saying which aspects were specified.
3188 This function does not make the coordinates positive. */
3190 #define DEFAULT_ROWS 40
3191 #define DEFAULT_COLS 80
3193 static int
3194 x_figure_window_size (f, parms)
3195 struct frame *f;
3196 Lisp_Object parms;
3198 register Lisp_Object tem0, tem1, tem2;
3199 long window_prompting = 0;
3201 /* Default values if we fall through.
3202 Actually, if that happens we should get
3203 window manager prompting. */
3204 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3205 f->height = DEFAULT_ROWS;
3206 /* Window managers expect that if program-specified
3207 positions are not (0,0), they're intentional, not defaults. */
3208 f->output_data.w32->top_pos = 0;
3209 f->output_data.w32->left_pos = 0;
3211 /* Ensure that old new_width and new_height will not override the
3212 values set here. */
3213 FRAME_NEW_WIDTH (f) = 0;
3214 FRAME_NEW_HEIGHT (f) = 0;
3216 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3217 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3218 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3219 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3221 if (!EQ (tem0, Qunbound))
3223 CHECK_NUMBER (tem0, 0);
3224 f->height = XINT (tem0);
3226 if (!EQ (tem1, Qunbound))
3228 CHECK_NUMBER (tem1, 0);
3229 SET_FRAME_WIDTH (f, XINT (tem1));
3231 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3232 window_prompting |= USSize;
3233 else
3234 window_prompting |= PSize;
3237 f->output_data.w32->vertical_scroll_bar_extra
3238 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3240 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3241 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3242 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3243 f->output_data.w32->flags_areas_extra
3244 = FRAME_FLAGS_AREA_WIDTH (f);
3245 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3246 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3248 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3249 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3250 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3251 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3253 if (EQ (tem0, Qminus))
3255 f->output_data.w32->top_pos = 0;
3256 window_prompting |= YNegative;
3258 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3259 && CONSP (XCDR (tem0))
3260 && INTEGERP (XCAR (XCDR (tem0))))
3262 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3263 window_prompting |= YNegative;
3265 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3266 && CONSP (XCDR (tem0))
3267 && INTEGERP (XCAR (XCDR (tem0))))
3269 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3271 else if (EQ (tem0, Qunbound))
3272 f->output_data.w32->top_pos = 0;
3273 else
3275 CHECK_NUMBER (tem0, 0);
3276 f->output_data.w32->top_pos = XINT (tem0);
3277 if (f->output_data.w32->top_pos < 0)
3278 window_prompting |= YNegative;
3281 if (EQ (tem1, Qminus))
3283 f->output_data.w32->left_pos = 0;
3284 window_prompting |= XNegative;
3286 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3287 && CONSP (XCDR (tem1))
3288 && INTEGERP (XCAR (XCDR (tem1))))
3290 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3291 window_prompting |= XNegative;
3293 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3294 && CONSP (XCDR (tem1))
3295 && INTEGERP (XCAR (XCDR (tem1))))
3297 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3299 else if (EQ (tem1, Qunbound))
3300 f->output_data.w32->left_pos = 0;
3301 else
3303 CHECK_NUMBER (tem1, 0);
3304 f->output_data.w32->left_pos = XINT (tem1);
3305 if (f->output_data.w32->left_pos < 0)
3306 window_prompting |= XNegative;
3309 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3310 window_prompting |= USPosition;
3311 else
3312 window_prompting |= PPosition;
3315 return window_prompting;
3320 extern LRESULT CALLBACK w32_wnd_proc ();
3322 BOOL
3323 w32_init_class (hinst)
3324 HINSTANCE hinst;
3326 WNDCLASS wc;
3328 wc.style = CS_HREDRAW | CS_VREDRAW;
3329 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3330 wc.cbClsExtra = 0;
3331 wc.cbWndExtra = WND_EXTRA_BYTES;
3332 wc.hInstance = hinst;
3333 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3334 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3335 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3336 wc.lpszMenuName = NULL;
3337 wc.lpszClassName = EMACS_CLASS;
3339 return (RegisterClass (&wc));
3342 HWND
3343 w32_createscrollbar (f, bar)
3344 struct frame *f;
3345 struct scroll_bar * bar;
3347 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3348 /* Position and size of scroll bar. */
3349 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3350 XINT(bar->top),
3351 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3352 XINT(bar->height),
3353 FRAME_W32_WINDOW (f),
3354 NULL,
3355 hinst,
3356 NULL));
3359 void
3360 w32_createwindow (f)
3361 struct frame *f;
3363 HWND hwnd;
3364 RECT rect;
3366 rect.left = rect.top = 0;
3367 rect.right = PIXEL_WIDTH (f);
3368 rect.bottom = PIXEL_HEIGHT (f);
3370 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3371 FRAME_EXTERNAL_MENU_BAR (f));
3373 /* Do first time app init */
3375 if (!hprevinst)
3377 w32_init_class (hinst);
3380 FRAME_W32_WINDOW (f) = hwnd
3381 = CreateWindow (EMACS_CLASS,
3382 f->namebuf,
3383 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3384 f->output_data.w32->left_pos,
3385 f->output_data.w32->top_pos,
3386 rect.right - rect.left,
3387 rect.bottom - rect.top,
3388 NULL,
3389 NULL,
3390 hinst,
3391 NULL);
3393 if (hwnd)
3395 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3396 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3397 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3398 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3399 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3401 /* Enable drag-n-drop. */
3402 DragAcceptFiles (hwnd, TRUE);
3404 /* Do this to discard the default setting specified by our parent. */
3405 ShowWindow (hwnd, SW_HIDE);
3409 void
3410 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3411 W32Msg * wmsg;
3412 HWND hwnd;
3413 UINT msg;
3414 WPARAM wParam;
3415 LPARAM lParam;
3417 wmsg->msg.hwnd = hwnd;
3418 wmsg->msg.message = msg;
3419 wmsg->msg.wParam = wParam;
3420 wmsg->msg.lParam = lParam;
3421 wmsg->msg.time = GetMessageTime ();
3423 post_msg (wmsg);
3426 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3427 between left and right keys as advertised. We test for this
3428 support dynamically, and set a flag when the support is absent. If
3429 absent, we keep track of the left and right control and alt keys
3430 ourselves. This is particularly necessary on keyboards that rely
3431 upon the AltGr key, which is represented as having the left control
3432 and right alt keys pressed. For these keyboards, we need to know
3433 when the left alt key has been pressed in addition to the AltGr key
3434 so that we can properly support M-AltGr-key sequences (such as M-@
3435 on Swedish keyboards). */
3437 #define EMACS_LCONTROL 0
3438 #define EMACS_RCONTROL 1
3439 #define EMACS_LMENU 2
3440 #define EMACS_RMENU 3
3442 static int modifiers[4];
3443 static int modifiers_recorded;
3444 static int modifier_key_support_tested;
3446 static void
3447 test_modifier_support (unsigned int wparam)
3449 unsigned int l, r;
3451 if (wparam != VK_CONTROL && wparam != VK_MENU)
3452 return;
3453 if (wparam == VK_CONTROL)
3455 l = VK_LCONTROL;
3456 r = VK_RCONTROL;
3458 else
3460 l = VK_LMENU;
3461 r = VK_RMENU;
3463 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3464 modifiers_recorded = 1;
3465 else
3466 modifiers_recorded = 0;
3467 modifier_key_support_tested = 1;
3470 static void
3471 record_keydown (unsigned int wparam, unsigned int lparam)
3473 int i;
3475 if (!modifier_key_support_tested)
3476 test_modifier_support (wparam);
3478 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3479 return;
3481 if (wparam == VK_CONTROL)
3482 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3483 else
3484 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3486 modifiers[i] = 1;
3489 static void
3490 record_keyup (unsigned int wparam, unsigned int lparam)
3492 int i;
3494 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3495 return;
3497 if (wparam == VK_CONTROL)
3498 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3499 else
3500 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3502 modifiers[i] = 0;
3505 /* Emacs can lose focus while a modifier key has been pressed. When
3506 it regains focus, be conservative and clear all modifiers since
3507 we cannot reconstruct the left and right modifier state. */
3508 static void
3509 reset_modifiers ()
3511 SHORT ctrl, alt;
3513 if (GetFocus () == NULL)
3514 /* Emacs doesn't have keyboard focus. Do nothing. */
3515 return;
3517 ctrl = GetAsyncKeyState (VK_CONTROL);
3518 alt = GetAsyncKeyState (VK_MENU);
3520 if (!(ctrl & 0x08000))
3521 /* Clear any recorded control modifier state. */
3522 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3524 if (!(alt & 0x08000))
3525 /* Clear any recorded alt modifier state. */
3526 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3528 /* Update the state of all modifier keys, because modifiers used in
3529 hot-key combinations can get stuck on if Emacs loses focus as a
3530 result of a hot-key being pressed. */
3532 BYTE keystate[256];
3534 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3536 GetKeyboardState (keystate);
3537 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3538 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3539 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3540 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3541 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3542 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3543 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3544 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3545 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3546 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3547 SetKeyboardState (keystate);
3551 /* Synchronize modifier state with what is reported with the current
3552 keystroke. Even if we cannot distinguish between left and right
3553 modifier keys, we know that, if no modifiers are set, then neither
3554 the left or right modifier should be set. */
3555 static void
3556 sync_modifiers ()
3558 if (!modifiers_recorded)
3559 return;
3561 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3562 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3564 if (!(GetKeyState (VK_MENU) & 0x8000))
3565 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3568 static int
3569 modifier_set (int vkey)
3571 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3572 return (GetKeyState (vkey) & 0x1);
3573 if (!modifiers_recorded)
3574 return (GetKeyState (vkey) & 0x8000);
3576 switch (vkey)
3578 case VK_LCONTROL:
3579 return modifiers[EMACS_LCONTROL];
3580 case VK_RCONTROL:
3581 return modifiers[EMACS_RCONTROL];
3582 case VK_LMENU:
3583 return modifiers[EMACS_LMENU];
3584 case VK_RMENU:
3585 return modifiers[EMACS_RMENU];
3587 return (GetKeyState (vkey) & 0x8000);
3590 /* Convert between the modifier bits W32 uses and the modifier bits
3591 Emacs uses. */
3593 unsigned int
3594 w32_key_to_modifier (int key)
3596 Lisp_Object key_mapping;
3598 switch (key)
3600 case VK_LWIN:
3601 key_mapping = Vw32_lwindow_modifier;
3602 break;
3603 case VK_RWIN:
3604 key_mapping = Vw32_rwindow_modifier;
3605 break;
3606 case VK_APPS:
3607 key_mapping = Vw32_apps_modifier;
3608 break;
3609 case VK_SCROLL:
3610 key_mapping = Vw32_scroll_lock_modifier;
3611 break;
3612 default:
3613 key_mapping = Qnil;
3616 /* NB. This code runs in the input thread, asychronously to the lisp
3617 thread, so we must be careful to ensure access to lisp data is
3618 thread-safe. The following code is safe because the modifier
3619 variable values are updated atomically from lisp and symbols are
3620 not relocated by GC. Also, we don't have to worry about seeing GC
3621 markbits here. */
3622 if (EQ (key_mapping, Qhyper))
3623 return hyper_modifier;
3624 if (EQ (key_mapping, Qsuper))
3625 return super_modifier;
3626 if (EQ (key_mapping, Qmeta))
3627 return meta_modifier;
3628 if (EQ (key_mapping, Qalt))
3629 return alt_modifier;
3630 if (EQ (key_mapping, Qctrl))
3631 return ctrl_modifier;
3632 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3633 return ctrl_modifier;
3634 if (EQ (key_mapping, Qshift))
3635 return shift_modifier;
3637 /* Don't generate any modifier if not explicitly requested. */
3638 return 0;
3641 unsigned int
3642 w32_get_modifiers ()
3644 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3645 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3646 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3647 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3648 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3649 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3650 (modifier_set (VK_MENU) ?
3651 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3654 /* We map the VK_* modifiers into console modifier constants
3655 so that we can use the same routines to handle both console
3656 and window input. */
3658 static int
3659 construct_console_modifiers ()
3661 int mods;
3663 mods = 0;
3664 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3665 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3666 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3667 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3668 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3669 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3670 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3671 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3672 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3673 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3674 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3676 return mods;
3679 static int
3680 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3682 int mods;
3684 /* Convert to emacs modifiers. */
3685 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3687 return mods;
3690 unsigned int
3691 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3693 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3694 return virt_key;
3696 if (virt_key == VK_RETURN)
3697 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3699 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3700 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3702 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3703 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3705 if (virt_key == VK_CLEAR)
3706 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3708 return virt_key;
3711 /* List of special key combinations which w32 would normally capture,
3712 but emacs should grab instead. Not directly visible to lisp, to
3713 simplify synchronization. Each item is an integer encoding a virtual
3714 key code and modifier combination to capture. */
3715 Lisp_Object w32_grabbed_keys;
3717 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3718 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3719 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3720 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3722 /* Register hot-keys for reserved key combinations when Emacs has
3723 keyboard focus, since this is the only way Emacs can receive key
3724 combinations like Alt-Tab which are used by the system. */
3726 static void
3727 register_hot_keys (hwnd)
3728 HWND hwnd;
3730 Lisp_Object keylist;
3732 /* Use GC_CONSP, since we are called asynchronously. */
3733 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3735 Lisp_Object key = XCAR (keylist);
3737 /* Deleted entries get set to nil. */
3738 if (!INTEGERP (key))
3739 continue;
3741 RegisterHotKey (hwnd, HOTKEY_ID (key),
3742 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3746 static void
3747 unregister_hot_keys (hwnd)
3748 HWND hwnd;
3750 Lisp_Object keylist;
3752 /* Use GC_CONSP, since we are called asynchronously. */
3753 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3755 Lisp_Object key = XCAR (keylist);
3757 if (!INTEGERP (key))
3758 continue;
3760 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3764 /* Main message dispatch loop. */
3766 static void
3767 w32_msg_pump (deferred_msg * msg_buf)
3769 MSG msg;
3770 int result;
3771 HWND focus_window;
3773 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3775 while (GetMessage (&msg, NULL, 0, 0))
3777 if (msg.hwnd == NULL)
3779 switch (msg.message)
3781 case WM_NULL:
3782 /* Produced by complete_deferred_msg; just ignore. */
3783 break;
3784 case WM_EMACS_CREATEWINDOW:
3785 w32_createwindow ((struct frame *) msg.wParam);
3786 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3787 abort ();
3788 break;
3789 case WM_EMACS_SETLOCALE:
3790 SetThreadLocale (msg.wParam);
3791 /* Reply is not expected. */
3792 break;
3793 case WM_EMACS_SETKEYBOARDLAYOUT:
3794 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3795 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3796 result, 0))
3797 abort ();
3798 break;
3799 case WM_EMACS_REGISTER_HOT_KEY:
3800 focus_window = GetFocus ();
3801 if (focus_window != NULL)
3802 RegisterHotKey (focus_window,
3803 HOTKEY_ID (msg.wParam),
3804 HOTKEY_MODIFIERS (msg.wParam),
3805 HOTKEY_VK_CODE (msg.wParam));
3806 /* Reply is not expected. */
3807 break;
3808 case WM_EMACS_UNREGISTER_HOT_KEY:
3809 focus_window = GetFocus ();
3810 if (focus_window != NULL)
3811 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3812 /* Mark item as erased. NB: this code must be
3813 thread-safe. The next line is okay because the cons
3814 cell is never made into garbage and is not relocated by
3815 GC. */
3816 XCAR ((Lisp_Object) msg.lParam) = Qnil;
3817 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3818 abort ();
3819 break;
3820 case WM_EMACS_TOGGLE_LOCK_KEY:
3822 int vk_code = (int) msg.wParam;
3823 int cur_state = (GetKeyState (vk_code) & 1);
3824 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3826 /* NB: This code must be thread-safe. It is safe to
3827 call NILP because symbols are not relocated by GC,
3828 and pointer here is not touched by GC (so the markbit
3829 can't be set). Numbers are safe because they are
3830 immediate values. */
3831 if (NILP (new_state)
3832 || (NUMBERP (new_state)
3833 && ((XUINT (new_state)) & 1) != cur_state))
3835 one_w32_display_info.faked_key = vk_code;
3837 keybd_event ((BYTE) vk_code,
3838 (BYTE) MapVirtualKey (vk_code, 0),
3839 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3840 keybd_event ((BYTE) vk_code,
3841 (BYTE) MapVirtualKey (vk_code, 0),
3842 KEYEVENTF_EXTENDEDKEY | 0, 0);
3843 keybd_event ((BYTE) vk_code,
3844 (BYTE) MapVirtualKey (vk_code, 0),
3845 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3846 cur_state = !cur_state;
3848 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3849 cur_state, 0))
3850 abort ();
3852 break;
3853 default:
3854 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3857 else
3859 DispatchMessage (&msg);
3862 /* Exit nested loop when our deferred message has completed. */
3863 if (msg_buf->completed)
3864 break;
3868 deferred_msg * deferred_msg_head;
3870 static deferred_msg *
3871 find_deferred_msg (HWND hwnd, UINT msg)
3873 deferred_msg * item;
3875 /* Don't actually need synchronization for read access, since
3876 modification of single pointer is always atomic. */
3877 /* enter_crit (); */
3879 for (item = deferred_msg_head; item != NULL; item = item->next)
3880 if (item->w32msg.msg.hwnd == hwnd
3881 && item->w32msg.msg.message == msg)
3882 break;
3884 /* leave_crit (); */
3886 return item;
3889 static LRESULT
3890 send_deferred_msg (deferred_msg * msg_buf,
3891 HWND hwnd,
3892 UINT msg,
3893 WPARAM wParam,
3894 LPARAM lParam)
3896 /* Only input thread can send deferred messages. */
3897 if (GetCurrentThreadId () != dwWindowsThreadId)
3898 abort ();
3900 /* It is an error to send a message that is already deferred. */
3901 if (find_deferred_msg (hwnd, msg) != NULL)
3902 abort ();
3904 /* Enforced synchronization is not needed because this is the only
3905 function that alters deferred_msg_head, and the following critical
3906 section is guaranteed to only be serially reentered (since only the
3907 input thread can call us). */
3909 /* enter_crit (); */
3911 msg_buf->completed = 0;
3912 msg_buf->next = deferred_msg_head;
3913 deferred_msg_head = msg_buf;
3914 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3916 /* leave_crit (); */
3918 /* Start a new nested message loop to process other messages until
3919 this one is completed. */
3920 w32_msg_pump (msg_buf);
3922 deferred_msg_head = msg_buf->next;
3924 return msg_buf->result;
3927 void
3928 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3930 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3932 if (msg_buf == NULL)
3933 /* Message may have been cancelled, so don't abort(). */
3934 return;
3936 msg_buf->result = result;
3937 msg_buf->completed = 1;
3939 /* Ensure input thread is woken so it notices the completion. */
3940 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3943 void
3944 cancel_all_deferred_msgs ()
3946 deferred_msg * item;
3948 /* Don't actually need synchronization for read access, since
3949 modification of single pointer is always atomic. */
3950 /* enter_crit (); */
3952 for (item = deferred_msg_head; item != NULL; item = item->next)
3954 item->result = 0;
3955 item->completed = 1;
3958 /* leave_crit (); */
3960 /* Ensure input thread is woken so it notices the completion. */
3961 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3964 DWORD
3965 w32_msg_worker (dw)
3966 DWORD dw;
3968 MSG msg;
3969 deferred_msg dummy_buf;
3971 /* Ensure our message queue is created */
3973 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3975 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3976 abort ();
3978 memset (&dummy_buf, 0, sizeof (dummy_buf));
3979 dummy_buf.w32msg.msg.hwnd = NULL;
3980 dummy_buf.w32msg.msg.message = WM_NULL;
3982 /* This is the inital message loop which should only exit when the
3983 application quits. */
3984 w32_msg_pump (&dummy_buf);
3986 return 0;
3989 static void
3990 post_character_message (hwnd, msg, wParam, lParam, modifiers)
3991 HWND hwnd;
3992 UINT msg;
3993 WPARAM wParam;
3994 LPARAM lParam;
3995 DWORD modifiers;
3998 W32Msg wmsg;
4000 wmsg.dwModifiers = modifiers;
4002 /* Detect quit_char and set quit-flag directly. Note that we
4003 still need to post a message to ensure the main thread will be
4004 woken up if blocked in sys_select(), but we do NOT want to post
4005 the quit_char message itself (because it will usually be as if
4006 the user had typed quit_char twice). Instead, we post a dummy
4007 message that has no particular effect. */
4009 int c = wParam;
4010 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
4011 c = make_ctrl_char (c) & 0377;
4012 if (c == quit_char
4013 || (wmsg.dwModifiers == 0 &&
4014 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
4016 Vquit_flag = Qt;
4018 /* The choice of message is somewhat arbitrary, as long as
4019 the main thread handler just ignores it. */
4020 msg = WM_NULL;
4022 /* Interrupt any blocking system calls. */
4023 signal_quit ();
4025 /* As a safety precaution, forcibly complete any deferred
4026 messages. This is a kludge, but I don't see any particularly
4027 clean way to handle the situation where a deferred message is
4028 "dropped" in the lisp thread, and will thus never be
4029 completed, eg. by the user trying to activate the menubar
4030 when the lisp thread is busy, and then typing C-g when the
4031 menubar doesn't open promptly (with the result that the
4032 menubar never responds at all because the deferred
4033 WM_INITMENU message is never completed). Another problem
4034 situation is when the lisp thread calls SendMessage (to send
4035 a window manager command) when a message has been deferred;
4036 the lisp thread gets blocked indefinitely waiting for the
4037 deferred message to be completed, which itself is waiting for
4038 the lisp thread to respond.
4040 Note that we don't want to block the input thread waiting for
4041 a reponse from the lisp thread (although that would at least
4042 solve the deadlock problem above), because we want to be able
4043 to receive C-g to interrupt the lisp thread. */
4044 cancel_all_deferred_msgs ();
4048 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4051 /* Main window procedure */
4053 LRESULT CALLBACK
4054 w32_wnd_proc (hwnd, msg, wParam, lParam)
4055 HWND hwnd;
4056 UINT msg;
4057 WPARAM wParam;
4058 LPARAM lParam;
4060 struct frame *f;
4061 struct w32_display_info *dpyinfo = &one_w32_display_info;
4062 W32Msg wmsg;
4063 int windows_translate;
4064 int key;
4066 /* Note that it is okay to call x_window_to_frame, even though we are
4067 not running in the main lisp thread, because frame deletion
4068 requires the lisp thread to synchronize with this thread. Thus, if
4069 a frame struct is returned, it can be used without concern that the
4070 lisp thread might make it disappear while we are using it.
4072 NB. Walking the frame list in this thread is safe (as long as
4073 writes of Lisp_Object slots are atomic, which they are on Windows).
4074 Although delete-frame can destructively modify the frame list while
4075 we are walking it, a garbage collection cannot occur until after
4076 delete-frame has synchronized with this thread.
4078 It is also safe to use functions that make GDI calls, such as
4079 w32_clear_rect, because these functions must obtain a DC handle
4080 from the frame struct using get_frame_dc which is thread-aware. */
4082 switch (msg)
4084 case WM_ERASEBKGND:
4085 f = x_window_to_frame (dpyinfo, hwnd);
4086 if (f)
4088 HDC hdc = get_frame_dc (f);
4089 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4090 w32_clear_rect (f, hdc, &wmsg.rect);
4091 release_frame_dc (f, hdc);
4093 #if defined (W32_DEBUG_DISPLAY)
4094 DebPrint (("WM_ERASEBKGND: erasing %d,%d-%d,%d\n",
4095 wmsg.rect.left, wmsg.rect.top, wmsg.rect.right,
4096 wmsg.rect.bottom));
4097 #endif /* W32_DEBUG_DISPLAY */
4099 return 1;
4100 case WM_PALETTECHANGED:
4101 /* ignore our own changes */
4102 if ((HWND)wParam != hwnd)
4104 f = x_window_to_frame (dpyinfo, hwnd);
4105 if (f)
4106 /* get_frame_dc will realize our palette and force all
4107 frames to be redrawn if needed. */
4108 release_frame_dc (f, get_frame_dc (f));
4110 return 0;
4111 case WM_PAINT:
4113 PAINTSTRUCT paintStruct;
4114 RECT update_rect;
4116 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4117 fails. Apparently this can happen under some
4118 circumstances. */
4119 if (!w32_strict_painting || GetUpdateRect (hwnd, &update_rect, FALSE))
4121 enter_crit ();
4122 BeginPaint (hwnd, &paintStruct);
4124 if (w32_strict_painting)
4125 /* The rectangles returned by GetUpdateRect and BeginPaint
4126 do not always match. GetUpdateRect seems to be the
4127 more reliable of the two. */
4128 wmsg.rect = update_rect;
4129 else
4130 wmsg.rect = paintStruct.rcPaint;
4132 #if defined (W32_DEBUG_DISPLAY)
4133 DebPrint (("WM_PAINT: painting %d,%d-%d,%d\n", wmsg.rect.left,
4134 wmsg.rect.top, wmsg.rect.right, wmsg.rect.bottom));
4135 DebPrint (("WM_PAINT: update region is %d,%d-%d,%d\n",
4136 update_rect.left, update_rect.top,
4137 update_rect.right, update_rect.bottom));
4138 #endif
4139 EndPaint (hwnd, &paintStruct);
4140 leave_crit ();
4142 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4144 return 0;
4147 /* If GetUpdateRect returns 0 (meaning there is no update
4148 region), assume the whole window needs to be repainted. */
4149 GetClientRect(hwnd, &wmsg.rect);
4150 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4151 return 0;
4154 case WM_INPUTLANGCHANGE:
4155 /* Inform lisp thread of keyboard layout changes. */
4156 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4158 /* Clear dead keys in the keyboard state; for simplicity only
4159 preserve modifier key states. */
4161 int i;
4162 BYTE keystate[256];
4164 GetKeyboardState (keystate);
4165 for (i = 0; i < 256; i++)
4166 if (1
4167 && i != VK_SHIFT
4168 && i != VK_LSHIFT
4169 && i != VK_RSHIFT
4170 && i != VK_CAPITAL
4171 && i != VK_NUMLOCK
4172 && i != VK_SCROLL
4173 && i != VK_CONTROL
4174 && i != VK_LCONTROL
4175 && i != VK_RCONTROL
4176 && i != VK_MENU
4177 && i != VK_LMENU
4178 && i != VK_RMENU
4179 && i != VK_LWIN
4180 && i != VK_RWIN)
4181 keystate[i] = 0;
4182 SetKeyboardState (keystate);
4184 goto dflt;
4186 case WM_HOTKEY:
4187 /* Synchronize hot keys with normal input. */
4188 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4189 return (0);
4191 case WM_KEYUP:
4192 case WM_SYSKEYUP:
4193 record_keyup (wParam, lParam);
4194 goto dflt;
4196 case WM_KEYDOWN:
4197 case WM_SYSKEYDOWN:
4198 /* Ignore keystrokes we fake ourself; see below. */
4199 if (dpyinfo->faked_key == wParam)
4201 dpyinfo->faked_key = 0;
4202 /* Make sure TranslateMessage sees them though (as long as
4203 they don't produce WM_CHAR messages). This ensures that
4204 indicator lights are toggled promptly on Windows 9x, for
4205 example. */
4206 if (lispy_function_keys[wParam] != 0)
4208 windows_translate = 1;
4209 goto translate;
4211 return 0;
4214 /* Synchronize modifiers with current keystroke. */
4215 sync_modifiers ();
4216 record_keydown (wParam, lParam);
4217 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4219 windows_translate = 0;
4221 switch (wParam)
4223 case VK_LWIN:
4224 if (NILP (Vw32_pass_lwindow_to_system))
4226 /* Prevent system from acting on keyup (which opens the
4227 Start menu if no other key was pressed) by simulating a
4228 press of Space which we will ignore. */
4229 if (GetAsyncKeyState (wParam) & 1)
4231 if (NUMBERP (Vw32_phantom_key_code))
4232 key = XUINT (Vw32_phantom_key_code) & 255;
4233 else
4234 key = VK_SPACE;
4235 dpyinfo->faked_key = key;
4236 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4239 if (!NILP (Vw32_lwindow_modifier))
4240 return 0;
4241 break;
4242 case VK_RWIN:
4243 if (NILP (Vw32_pass_rwindow_to_system))
4245 if (GetAsyncKeyState (wParam) & 1)
4247 if (NUMBERP (Vw32_phantom_key_code))
4248 key = XUINT (Vw32_phantom_key_code) & 255;
4249 else
4250 key = VK_SPACE;
4251 dpyinfo->faked_key = key;
4252 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4255 if (!NILP (Vw32_rwindow_modifier))
4256 return 0;
4257 break;
4258 case VK_APPS:
4259 if (!NILP (Vw32_apps_modifier))
4260 return 0;
4261 break;
4262 case VK_MENU:
4263 if (NILP (Vw32_pass_alt_to_system))
4264 /* Prevent DefWindowProc from activating the menu bar if an
4265 Alt key is pressed and released by itself. */
4266 return 0;
4267 windows_translate = 1;
4268 break;
4269 case VK_CAPITAL:
4270 /* Decide whether to treat as modifier or function key. */
4271 if (NILP (Vw32_enable_caps_lock))
4272 goto disable_lock_key;
4273 windows_translate = 1;
4274 break;
4275 case VK_NUMLOCK:
4276 /* Decide whether to treat as modifier or function key. */
4277 if (NILP (Vw32_enable_num_lock))
4278 goto disable_lock_key;
4279 windows_translate = 1;
4280 break;
4281 case VK_SCROLL:
4282 /* Decide whether to treat as modifier or function key. */
4283 if (NILP (Vw32_scroll_lock_modifier))
4284 goto disable_lock_key;
4285 windows_translate = 1;
4286 break;
4287 disable_lock_key:
4288 /* Ensure the appropriate lock key state (and indicator light)
4289 remains in the same state. We do this by faking another
4290 press of the relevant key. Apparently, this really is the
4291 only way to toggle the state of the indicator lights. */
4292 dpyinfo->faked_key = wParam;
4293 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4294 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4295 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4296 KEYEVENTF_EXTENDEDKEY | 0, 0);
4297 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4298 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4299 /* Ensure indicator lights are updated promptly on Windows 9x
4300 (TranslateMessage apparently does this), after forwarding
4301 input event. */
4302 post_character_message (hwnd, msg, wParam, lParam,
4303 w32_get_key_modifiers (wParam, lParam));
4304 windows_translate = 1;
4305 break;
4306 case VK_CONTROL:
4307 case VK_SHIFT:
4308 case VK_PROCESSKEY: /* Generated by IME. */
4309 windows_translate = 1;
4310 break;
4311 case VK_CANCEL:
4312 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4313 which is confusing for purposes of key binding; convert
4314 VK_CANCEL events into VK_PAUSE events. */
4315 wParam = VK_PAUSE;
4316 break;
4317 case VK_PAUSE:
4318 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4319 for purposes of key binding; convert these back into
4320 VK_NUMLOCK events, at least when we want to see NumLock key
4321 presses. (Note that there is never any possibility that
4322 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4323 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4324 wParam = VK_NUMLOCK;
4325 break;
4326 default:
4327 /* If not defined as a function key, change it to a WM_CHAR message. */
4328 if (lispy_function_keys[wParam] == 0)
4330 DWORD modifiers = construct_console_modifiers ();
4332 if (!NILP (Vw32_recognize_altgr)
4333 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4335 /* Always let TranslateMessage handle AltGr key chords;
4336 for some reason, ToAscii doesn't always process AltGr
4337 chords correctly. */
4338 windows_translate = 1;
4340 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4342 /* Handle key chords including any modifiers other
4343 than shift directly, in order to preserve as much
4344 modifier information as possible. */
4345 if ('A' <= wParam && wParam <= 'Z')
4347 /* Don't translate modified alphabetic keystrokes,
4348 so the user doesn't need to constantly switch
4349 layout to type control or meta keystrokes when
4350 the normal layout translates alphabetic
4351 characters to non-ascii characters. */
4352 if (!modifier_set (VK_SHIFT))
4353 wParam += ('a' - 'A');
4354 msg = WM_CHAR;
4356 else
4358 /* Try to handle other keystrokes by determining the
4359 base character (ie. translating the base key plus
4360 shift modifier). */
4361 int add;
4362 int isdead = 0;
4363 KEY_EVENT_RECORD key;
4365 key.bKeyDown = TRUE;
4366 key.wRepeatCount = 1;
4367 key.wVirtualKeyCode = wParam;
4368 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4369 key.uChar.AsciiChar = 0;
4370 key.dwControlKeyState = modifiers;
4372 add = w32_kbd_patch_key (&key);
4373 /* 0 means an unrecognised keycode, negative means
4374 dead key. Ignore both. */
4375 while (--add >= 0)
4377 /* Forward asciified character sequence. */
4378 post_character_message
4379 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4380 w32_get_key_modifiers (wParam, lParam));
4381 w32_kbd_patch_key (&key);
4383 return 0;
4386 else
4388 /* Let TranslateMessage handle everything else. */
4389 windows_translate = 1;
4394 translate:
4395 if (windows_translate)
4397 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4399 windows_msg.time = GetMessageTime ();
4400 TranslateMessage (&windows_msg);
4401 goto dflt;
4404 /* Fall through */
4406 case WM_SYSCHAR:
4407 case WM_CHAR:
4408 post_character_message (hwnd, msg, wParam, lParam,
4409 w32_get_key_modifiers (wParam, lParam));
4410 break;
4412 /* Simulate middle mouse button events when left and right buttons
4413 are used together, but only if user has two button mouse. */
4414 case WM_LBUTTONDOWN:
4415 case WM_RBUTTONDOWN:
4416 if (XINT (Vw32_num_mouse_buttons) > 2)
4417 goto handle_plain_button;
4420 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4421 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4423 if (button_state & this)
4424 return 0;
4426 if (button_state == 0)
4427 SetCapture (hwnd);
4429 button_state |= this;
4431 if (button_state & other)
4433 if (mouse_button_timer)
4435 KillTimer (hwnd, mouse_button_timer);
4436 mouse_button_timer = 0;
4438 /* Generate middle mouse event instead. */
4439 msg = WM_MBUTTONDOWN;
4440 button_state |= MMOUSE;
4442 else if (button_state & MMOUSE)
4444 /* Ignore button event if we've already generated a
4445 middle mouse down event. This happens if the
4446 user releases and press one of the two buttons
4447 after we've faked a middle mouse event. */
4448 return 0;
4450 else
4452 /* Flush out saved message. */
4453 post_msg (&saved_mouse_button_msg);
4455 wmsg.dwModifiers = w32_get_modifiers ();
4456 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4458 /* Clear message buffer. */
4459 saved_mouse_button_msg.msg.hwnd = 0;
4461 else
4463 /* Hold onto message for now. */
4464 mouse_button_timer =
4465 SetTimer (hwnd, MOUSE_BUTTON_ID,
4466 XINT (Vw32_mouse_button_tolerance), NULL);
4467 saved_mouse_button_msg.msg.hwnd = hwnd;
4468 saved_mouse_button_msg.msg.message = msg;
4469 saved_mouse_button_msg.msg.wParam = wParam;
4470 saved_mouse_button_msg.msg.lParam = lParam;
4471 saved_mouse_button_msg.msg.time = GetMessageTime ();
4472 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4475 return 0;
4477 case WM_LBUTTONUP:
4478 case WM_RBUTTONUP:
4479 if (XINT (Vw32_num_mouse_buttons) > 2)
4480 goto handle_plain_button;
4483 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4484 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4486 if ((button_state & this) == 0)
4487 return 0;
4489 button_state &= ~this;
4491 if (button_state & MMOUSE)
4493 /* Only generate event when second button is released. */
4494 if ((button_state & other) == 0)
4496 msg = WM_MBUTTONUP;
4497 button_state &= ~MMOUSE;
4499 if (button_state) abort ();
4501 else
4502 return 0;
4504 else
4506 /* Flush out saved message if necessary. */
4507 if (saved_mouse_button_msg.msg.hwnd)
4509 post_msg (&saved_mouse_button_msg);
4512 wmsg.dwModifiers = w32_get_modifiers ();
4513 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4515 /* Always clear message buffer and cancel timer. */
4516 saved_mouse_button_msg.msg.hwnd = 0;
4517 KillTimer (hwnd, mouse_button_timer);
4518 mouse_button_timer = 0;
4520 if (button_state == 0)
4521 ReleaseCapture ();
4523 return 0;
4525 case WM_MBUTTONDOWN:
4526 case WM_MBUTTONUP:
4527 handle_plain_button:
4529 BOOL up;
4530 int button;
4532 if (parse_button (msg, &button, &up))
4534 if (up) ReleaseCapture ();
4535 else SetCapture (hwnd);
4536 button = (button == 0) ? LMOUSE :
4537 ((button == 1) ? MMOUSE : RMOUSE);
4538 if (up)
4539 button_state &= ~button;
4540 else
4541 button_state |= button;
4545 wmsg.dwModifiers = w32_get_modifiers ();
4546 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4547 return 0;
4549 case WM_VSCROLL:
4550 case WM_MOUSEMOVE:
4551 if (XINT (Vw32_mouse_move_interval) <= 0
4552 || (msg == WM_MOUSEMOVE && button_state == 0))
4554 wmsg.dwModifiers = w32_get_modifiers ();
4555 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4556 return 0;
4559 /* Hang onto mouse move and scroll messages for a bit, to avoid
4560 sending such events to Emacs faster than it can process them.
4561 If we get more events before the timer from the first message
4562 expires, we just replace the first message. */
4564 if (saved_mouse_move_msg.msg.hwnd == 0)
4565 mouse_move_timer =
4566 SetTimer (hwnd, MOUSE_MOVE_ID,
4567 XINT (Vw32_mouse_move_interval), NULL);
4569 /* Hold onto message for now. */
4570 saved_mouse_move_msg.msg.hwnd = hwnd;
4571 saved_mouse_move_msg.msg.message = msg;
4572 saved_mouse_move_msg.msg.wParam = wParam;
4573 saved_mouse_move_msg.msg.lParam = lParam;
4574 saved_mouse_move_msg.msg.time = GetMessageTime ();
4575 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4577 return 0;
4579 case WM_MOUSEWHEEL:
4580 wmsg.dwModifiers = w32_get_modifiers ();
4581 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4582 return 0;
4584 case WM_DROPFILES:
4585 wmsg.dwModifiers = w32_get_modifiers ();
4586 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4587 return 0;
4589 case WM_TIMER:
4590 /* Flush out saved messages if necessary. */
4591 if (wParam == mouse_button_timer)
4593 if (saved_mouse_button_msg.msg.hwnd)
4595 post_msg (&saved_mouse_button_msg);
4596 saved_mouse_button_msg.msg.hwnd = 0;
4598 KillTimer (hwnd, mouse_button_timer);
4599 mouse_button_timer = 0;
4601 else if (wParam == mouse_move_timer)
4603 if (saved_mouse_move_msg.msg.hwnd)
4605 post_msg (&saved_mouse_move_msg);
4606 saved_mouse_move_msg.msg.hwnd = 0;
4608 KillTimer (hwnd, mouse_move_timer);
4609 mouse_move_timer = 0;
4611 return 0;
4613 case WM_NCACTIVATE:
4614 /* Windows doesn't send us focus messages when putting up and
4615 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4616 The only indication we get that something happened is receiving
4617 this message afterwards. So this is a good time to reset our
4618 keyboard modifiers' state. */
4619 reset_modifiers ();
4620 goto dflt;
4622 case WM_INITMENU:
4623 button_state = 0;
4624 ReleaseCapture ();
4625 /* We must ensure menu bar is fully constructed and up to date
4626 before allowing user interaction with it. To achieve this
4627 we send this message to the lisp thread and wait for a
4628 reply (whose value is not actually needed) to indicate that
4629 the menu bar is now ready for use, so we can now return.
4631 To remain responsive in the meantime, we enter a nested message
4632 loop that can process all other messages.
4634 However, we skip all this if the message results from calling
4635 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4636 thread a message because it is blocked on us at this point. We
4637 set menubar_active before calling TrackPopupMenu to indicate
4638 this (there is no possibility of confusion with real menubar
4639 being active). */
4641 f = x_window_to_frame (dpyinfo, hwnd);
4642 if (f
4643 && (f->output_data.w32->menubar_active
4644 /* We can receive this message even in the absence of a
4645 menubar (ie. when the system menu is activated) - in this
4646 case we do NOT want to forward the message, otherwise it
4647 will cause the menubar to suddenly appear when the user
4648 had requested it to be turned off! */
4649 || f->output_data.w32->menubar_widget == NULL))
4650 return 0;
4653 deferred_msg msg_buf;
4655 /* Detect if message has already been deferred; in this case
4656 we cannot return any sensible value to ignore this. */
4657 if (find_deferred_msg (hwnd, msg) != NULL)
4658 abort ();
4660 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4663 case WM_EXITMENULOOP:
4664 f = x_window_to_frame (dpyinfo, hwnd);
4666 /* Indicate that menubar can be modified again. */
4667 if (f)
4668 f->output_data.w32->menubar_active = 0;
4669 goto dflt;
4671 case WM_MENUSELECT:
4672 wmsg.dwModifiers = w32_get_modifiers ();
4673 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4674 return 0;
4676 case WM_MEASUREITEM:
4677 f = x_window_to_frame (dpyinfo, hwnd);
4678 if (f)
4680 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4682 if (pMis->CtlType == ODT_MENU)
4684 /* Work out dimensions for popup menu titles. */
4685 char * title = (char *) pMis->itemData;
4686 HDC hdc = GetDC (hwnd);
4687 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4688 LOGFONT menu_logfont;
4689 HFONT old_font;
4690 SIZE size;
4692 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4693 menu_logfont.lfWeight = FW_BOLD;
4694 menu_font = CreateFontIndirect (&menu_logfont);
4695 old_font = SelectObject (hdc, menu_font);
4697 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4698 if (title)
4700 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4701 pMis->itemWidth = size.cx;
4702 if (pMis->itemHeight < size.cy)
4703 pMis->itemHeight = size.cy;
4705 else
4706 pMis->itemWidth = 0;
4708 SelectObject (hdc, old_font);
4709 DeleteObject (menu_font);
4710 ReleaseDC (hwnd, hdc);
4711 return TRUE;
4714 return 0;
4716 case WM_DRAWITEM:
4717 f = x_window_to_frame (dpyinfo, hwnd);
4718 if (f)
4720 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4722 if (pDis->CtlType == ODT_MENU)
4724 /* Draw popup menu title. */
4725 char * title = (char *) pDis->itemData;
4726 if (title)
4728 HDC hdc = pDis->hDC;
4729 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4730 LOGFONT menu_logfont;
4731 HFONT old_font;
4733 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4734 menu_logfont.lfWeight = FW_BOLD;
4735 menu_font = CreateFontIndirect (&menu_logfont);
4736 old_font = SelectObject (hdc, menu_font);
4738 /* Always draw title as if not selected. */
4739 ExtTextOut (hdc,
4740 pDis->rcItem.left
4741 + GetSystemMetrics (SM_CXMENUCHECK),
4742 pDis->rcItem.top,
4743 ETO_OPAQUE, &pDis->rcItem,
4744 title, strlen (title), NULL);
4746 SelectObject (hdc, old_font);
4747 DeleteObject (menu_font);
4749 return TRUE;
4752 return 0;
4754 #if 0
4755 /* Still not right - can't distinguish between clicks in the
4756 client area of the frame from clicks forwarded from the scroll
4757 bars - may have to hook WM_NCHITTEST to remember the mouse
4758 position and then check if it is in the client area ourselves. */
4759 case WM_MOUSEACTIVATE:
4760 /* Discard the mouse click that activates a frame, allowing the
4761 user to click anywhere without changing point (or worse!).
4762 Don't eat mouse clicks on scrollbars though!! */
4763 if (LOWORD (lParam) == HTCLIENT )
4764 return MA_ACTIVATEANDEAT;
4765 goto dflt;
4766 #endif
4768 case WM_ACTIVATEAPP:
4769 case WM_ACTIVATE:
4770 case WM_WINDOWPOSCHANGED:
4771 case WM_SHOWWINDOW:
4772 /* Inform lisp thread that a frame might have just been obscured
4773 or exposed, so should recheck visibility of all frames. */
4774 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4775 goto dflt;
4777 case WM_SETFOCUS:
4778 dpyinfo->faked_key = 0;
4779 reset_modifiers ();
4780 register_hot_keys (hwnd);
4781 goto command;
4782 case WM_KILLFOCUS:
4783 unregister_hot_keys (hwnd);
4784 button_state = 0;
4785 ReleaseCapture ();
4786 case WM_MOVE:
4787 case WM_SIZE:
4788 case WM_COMMAND:
4789 command:
4790 wmsg.dwModifiers = w32_get_modifiers ();
4791 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4792 goto dflt;
4794 case WM_CLOSE:
4795 wmsg.dwModifiers = w32_get_modifiers ();
4796 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4797 return 0;
4799 case WM_WINDOWPOSCHANGING:
4801 WINDOWPLACEMENT wp;
4802 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4804 wp.length = sizeof (WINDOWPLACEMENT);
4805 GetWindowPlacement (hwnd, &wp);
4807 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4809 RECT rect;
4810 int wdiff;
4811 int hdiff;
4812 DWORD font_width;
4813 DWORD line_height;
4814 DWORD internal_border;
4815 DWORD scrollbar_extra;
4816 RECT wr;
4818 wp.length = sizeof(wp);
4819 GetWindowRect (hwnd, &wr);
4821 enter_crit ();
4823 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4824 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4825 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4826 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
4828 leave_crit ();
4830 memset (&rect, 0, sizeof (rect));
4831 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4832 GetMenu (hwnd) != NULL);
4834 /* Force width and height of client area to be exact
4835 multiples of the character cell dimensions. */
4836 wdiff = (lppos->cx - (rect.right - rect.left)
4837 - 2 * internal_border - scrollbar_extra)
4838 % font_width;
4839 hdiff = (lppos->cy - (rect.bottom - rect.top)
4840 - 2 * internal_border)
4841 % line_height;
4843 if (wdiff || hdiff)
4845 /* For right/bottom sizing we can just fix the sizes.
4846 However for top/left sizing we will need to fix the X
4847 and Y positions as well. */
4849 lppos->cx -= wdiff;
4850 lppos->cy -= hdiff;
4852 if (wp.showCmd != SW_SHOWMAXIMIZED
4853 && (lppos->flags & SWP_NOMOVE) == 0)
4855 if (lppos->x != wr.left || lppos->y != wr.top)
4857 lppos->x += wdiff;
4858 lppos->y += hdiff;
4860 else
4862 lppos->flags |= SWP_NOMOVE;
4866 return 0;
4871 goto dflt;
4873 case WM_GETMINMAXINFO:
4874 /* Hack to correct bug that allows Emacs frames to be resized
4875 below the Minimum Tracking Size. */
4876 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
4877 return 0;
4879 case WM_EMACS_CREATESCROLLBAR:
4880 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
4881 (struct scroll_bar *) lParam);
4883 case WM_EMACS_SHOWWINDOW:
4884 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4886 case WM_EMACS_SETFOREGROUND:
4888 HWND foreground_window;
4889 DWORD foreground_thread, retval;
4891 /* On NT 5.0, and apparently Windows 98, it is necessary to
4892 attach to the thread that currently has focus in order to
4893 pull the focus away from it. */
4894 foreground_window = GetForegroundWindow ();
4895 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4896 if (!foreground_window
4897 || foreground_thread == GetCurrentThreadId ()
4898 || !AttachThreadInput (GetCurrentThreadId (),
4899 foreground_thread, TRUE))
4900 foreground_thread = 0;
4902 retval = SetForegroundWindow ((HWND) wParam);
4904 /* Detach from the previous foreground thread. */
4905 if (foreground_thread)
4906 AttachThreadInput (GetCurrentThreadId (),
4907 foreground_thread, FALSE);
4909 return retval;
4912 case WM_EMACS_SETWINDOWPOS:
4914 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4915 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4916 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4919 case WM_EMACS_DESTROYWINDOW:
4920 DragAcceptFiles ((HWND) wParam, FALSE);
4921 return DestroyWindow ((HWND) wParam);
4923 case WM_EMACS_TRACKPOPUPMENU:
4925 UINT flags;
4926 POINT *pos;
4927 int retval;
4928 pos = (POINT *)lParam;
4929 flags = TPM_CENTERALIGN;
4930 if (button_state & LMOUSE)
4931 flags |= TPM_LEFTBUTTON;
4932 else if (button_state & RMOUSE)
4933 flags |= TPM_RIGHTBUTTON;
4935 /* Remember we did a SetCapture on the initial mouse down event,
4936 so for safety, we make sure the capture is cancelled now. */
4937 ReleaseCapture ();
4938 button_state = 0;
4940 /* Use menubar_active to indicate that WM_INITMENU is from
4941 TrackPopupMenu below, and should be ignored. */
4942 f = x_window_to_frame (dpyinfo, hwnd);
4943 if (f)
4944 f->output_data.w32->menubar_active = 1;
4946 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4947 0, hwnd, NULL))
4949 MSG amsg;
4950 /* Eat any mouse messages during popupmenu */
4951 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4952 PM_REMOVE));
4953 /* Get the menu selection, if any */
4954 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4956 retval = LOWORD (amsg.wParam);
4958 else
4960 retval = 0;
4963 else
4965 retval = -1;
4968 return retval;
4971 default:
4972 /* Check for messages registered at runtime. */
4973 if (msg == msh_mousewheel)
4975 wmsg.dwModifiers = w32_get_modifiers ();
4976 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4977 return 0;
4980 dflt:
4981 return DefWindowProc (hwnd, msg, wParam, lParam);
4985 /* The most common default return code for handled messages is 0. */
4986 return 0;
4989 void
4990 my_create_window (f)
4991 struct frame * f;
4993 MSG msg;
4995 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4996 abort ();
4997 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5000 /* Create and set up the w32 window for frame F. */
5002 static void
5003 w32_window (f, window_prompting, minibuffer_only)
5004 struct frame *f;
5005 long window_prompting;
5006 int minibuffer_only;
5008 BLOCK_INPUT;
5010 /* Use the resource name as the top-level window name
5011 for looking up resources. Make a non-Lisp copy
5012 for the window manager, so GC relocation won't bother it.
5014 Elsewhere we specify the window name for the window manager. */
5017 char *str = (char *) XSTRING (Vx_resource_name)->data;
5018 f->namebuf = (char *) xmalloc (strlen (str) + 1);
5019 strcpy (f->namebuf, str);
5022 my_create_window (f);
5024 validate_x_resource_name ();
5026 /* x_set_name normally ignores requests to set the name if the
5027 requested name is the same as the current name. This is the one
5028 place where that assumption isn't correct; f->name is set, but
5029 the server hasn't been told. */
5031 Lisp_Object name;
5032 int explicit = f->explicit_name;
5034 f->explicit_name = 0;
5035 name = f->name;
5036 f->name = Qnil;
5037 x_set_name (f, name, explicit);
5040 UNBLOCK_INPUT;
5042 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5043 initialize_frame_menubar (f);
5045 if (FRAME_W32_WINDOW (f) == 0)
5046 error ("Unable to create window");
5049 /* Handle the icon stuff for this window. Perhaps later we might
5050 want an x_set_icon_position which can be called interactively as
5051 well. */
5053 static void
5054 x_icon (f, parms)
5055 struct frame *f;
5056 Lisp_Object parms;
5058 Lisp_Object icon_x, icon_y;
5060 /* Set the position of the icon. Note that Windows 95 groups all
5061 icons in the tray. */
5062 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5063 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5064 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5066 CHECK_NUMBER (icon_x, 0);
5067 CHECK_NUMBER (icon_y, 0);
5069 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5070 error ("Both left and top icon corners of icon must be specified");
5072 BLOCK_INPUT;
5074 if (! EQ (icon_x, Qunbound))
5075 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5077 #if 0 /* TODO */
5078 /* Start up iconic or window? */
5079 x_wm_set_window_state
5080 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5081 ? IconicState
5082 : NormalState));
5084 x_text_icon (f, (char *) XSTRING ((!NILP (f->icon_name)
5085 ? f->icon_name
5086 : f->name))->data);
5087 #endif
5089 UNBLOCK_INPUT;
5093 static void
5094 x_make_gc (f)
5095 struct frame *f;
5097 XGCValues gc_values;
5099 BLOCK_INPUT;
5101 /* Create the GC's of this frame.
5102 Note that many default values are used. */
5104 /* Normal video */
5105 gc_values.font = f->output_data.w32->font;
5107 /* Cursor has cursor-color background, background-color foreground. */
5108 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5109 gc_values.background = f->output_data.w32->cursor_pixel;
5110 f->output_data.w32->cursor_gc
5111 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5112 (GCFont | GCForeground | GCBackground),
5113 &gc_values);
5115 /* Reliefs. */
5116 f->output_data.w32->white_relief.gc = 0;
5117 f->output_data.w32->black_relief.gc = 0;
5119 UNBLOCK_INPUT;
5123 /* Handler for signals raised during x_create_frame and
5124 x_create_top_frame. FRAME is the frame which is partially
5125 constructed. */
5127 static Lisp_Object
5128 unwind_create_frame (frame)
5129 Lisp_Object frame;
5131 struct frame *f = XFRAME (frame);
5133 /* If frame is ``official'', nothing to do. */
5134 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
5136 #ifdef GLYPH_DEBUG
5137 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5138 #endif
5140 x_free_frame_resources (f);
5142 /* Check that reference counts are indeed correct. */
5143 xassert (dpyinfo->reference_count == dpyinfo_refcount);
5144 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
5146 return Qt;
5149 return Qnil;
5153 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5154 1, 1, 0,
5155 "Make a new window, which is called a \"frame\" in Emacs terms.\n\
5156 Returns an Emacs frame object.\n\
5157 ALIST is an alist of frame parameters.\n\
5158 If the parameters specify that the frame should not have a minibuffer,\n\
5159 and do not specify a specific minibuffer window to use,\n\
5160 then `default-minibuffer-frame' must be a frame whose minibuffer can\n\
5161 be shared by the new frame.\n\
5163 This function is an internal primitive--use `make-frame' instead.")
5164 (parms)
5165 Lisp_Object parms;
5167 struct frame *f;
5168 Lisp_Object frame, tem;
5169 Lisp_Object name;
5170 int minibuffer_only = 0;
5171 long window_prompting = 0;
5172 int width, height;
5173 int count = specpdl_ptr - specpdl;
5174 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5175 Lisp_Object display;
5176 struct w32_display_info *dpyinfo = NULL;
5177 Lisp_Object parent;
5178 struct kboard *kb;
5180 check_w32 ();
5182 /* Use this general default value to start with
5183 until we know if this frame has a specified name. */
5184 Vx_resource_name = Vinvocation_name;
5186 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5187 if (EQ (display, Qunbound))
5188 display = Qnil;
5189 dpyinfo = check_x_display_info (display);
5190 #ifdef MULTI_KBOARD
5191 kb = dpyinfo->kboard;
5192 #else
5193 kb = &the_only_kboard;
5194 #endif
5196 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5197 if (!STRINGP (name)
5198 && ! EQ (name, Qunbound)
5199 && ! NILP (name))
5200 error ("Invalid frame name--not a string or nil");
5202 if (STRINGP (name))
5203 Vx_resource_name = name;
5205 /* See if parent window is specified. */
5206 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5207 if (EQ (parent, Qunbound))
5208 parent = Qnil;
5209 if (! NILP (parent))
5210 CHECK_NUMBER (parent, 0);
5212 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5213 /* No need to protect DISPLAY because that's not used after passing
5214 it to make_frame_without_minibuffer. */
5215 frame = Qnil;
5216 GCPRO4 (parms, parent, name, frame);
5217 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5218 RES_TYPE_SYMBOL);
5219 if (EQ (tem, Qnone) || NILP (tem))
5220 f = make_frame_without_minibuffer (Qnil, kb, display);
5221 else if (EQ (tem, Qonly))
5223 f = make_minibuffer_frame ();
5224 minibuffer_only = 1;
5226 else if (WINDOWP (tem))
5227 f = make_frame_without_minibuffer (tem, kb, display);
5228 else
5229 f = make_frame (1);
5231 XSETFRAME (frame, f);
5233 /* Note that Windows does support scroll bars. */
5234 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5235 /* By default, make scrollbars the system standard width. */
5236 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5238 f->output_method = output_w32;
5239 f->output_data.w32 =
5240 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5241 bzero (f->output_data.w32, sizeof (struct w32_output));
5242 FRAME_FONTSET (f) = -1;
5243 record_unwind_protect (unwind_create_frame, frame);
5245 f->icon_name
5246 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5247 if (! STRINGP (f->icon_name))
5248 f->icon_name = Qnil;
5250 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5251 #ifdef MULTI_KBOARD
5252 FRAME_KBOARD (f) = kb;
5253 #endif
5255 /* Specify the parent under which to make this window. */
5257 if (!NILP (parent))
5259 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5260 f->output_data.w32->explicit_parent = 1;
5262 else
5264 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5265 f->output_data.w32->explicit_parent = 0;
5268 /* Set the name; the functions to which we pass f expect the name to
5269 be set. */
5270 if (EQ (name, Qunbound) || NILP (name))
5272 f->name = build_string (dpyinfo->w32_id_name);
5273 f->explicit_name = 0;
5275 else
5277 f->name = name;
5278 f->explicit_name = 1;
5279 /* use the frame's title when getting resources for this frame. */
5280 specbind (Qx_resource_name, name);
5283 /* Extract the window parameters from the supplied values
5284 that are needed to determine window geometry. */
5286 Lisp_Object font;
5288 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5290 BLOCK_INPUT;
5291 /* First, try whatever font the caller has specified. */
5292 if (STRINGP (font))
5294 tem = Fquery_fontset (font, Qnil);
5295 if (STRINGP (tem))
5296 font = x_new_fontset (f, XSTRING (tem)->data);
5297 else
5298 font = x_new_font (f, XSTRING (font)->data);
5300 /* Try out a font which we hope has bold and italic variations. */
5301 if (!STRINGP (font))
5302 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5303 if (! STRINGP (font))
5304 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5305 /* If those didn't work, look for something which will at least work. */
5306 if (! STRINGP (font))
5307 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5308 UNBLOCK_INPUT;
5309 if (! STRINGP (font))
5310 font = build_string ("Fixedsys");
5312 x_default_parameter (f, parms, Qfont, font,
5313 "font", "Font", RES_TYPE_STRING);
5316 x_default_parameter (f, parms, Qborder_width, make_number (2),
5317 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5318 /* This defaults to 2 in order to match xterm. We recognize either
5319 internalBorderWidth or internalBorder (which is what xterm calls
5320 it). */
5321 if (NILP (Fassq (Qinternal_border_width, parms)))
5323 Lisp_Object value;
5325 value = w32_get_arg (parms, Qinternal_border_width,
5326 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5327 if (! EQ (value, Qunbound))
5328 parms = Fcons (Fcons (Qinternal_border_width, value),
5329 parms);
5331 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5332 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5333 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5334 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5335 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5337 /* Also do the stuff which must be set before the window exists. */
5338 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5339 "foreground", "Foreground", RES_TYPE_STRING);
5340 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5341 "background", "Background", RES_TYPE_STRING);
5342 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5343 "pointerColor", "Foreground", RES_TYPE_STRING);
5344 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5345 "cursorColor", "Foreground", RES_TYPE_STRING);
5346 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5347 "borderColor", "BorderColor", RES_TYPE_STRING);
5348 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5349 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5350 x_default_parameter (f, parms, Qline_spacing, Qnil,
5351 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5354 /* Init faces before x_default_parameter is called for scroll-bar
5355 parameters because that function calls x_set_scroll_bar_width,
5356 which calls change_frame_size, which calls Fset_window_buffer,
5357 which runs hooks, which call Fvertical_motion. At the end, we
5358 end up in init_iterator with a null face cache, which should not
5359 happen. */
5360 init_frame_faces (f);
5362 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5363 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5364 x_default_parameter (f, parms, Qtool_bar_lines, make_number (0),
5365 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5366 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5367 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5368 x_default_parameter (f, parms, Qtitle, Qnil,
5369 "title", "Title", RES_TYPE_STRING);
5371 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5372 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5373 window_prompting = x_figure_window_size (f, parms);
5375 if (window_prompting & XNegative)
5377 if (window_prompting & YNegative)
5378 f->output_data.w32->win_gravity = SouthEastGravity;
5379 else
5380 f->output_data.w32->win_gravity = NorthEastGravity;
5382 else
5384 if (window_prompting & YNegative)
5385 f->output_data.w32->win_gravity = SouthWestGravity;
5386 else
5387 f->output_data.w32->win_gravity = NorthWestGravity;
5390 f->output_data.w32->size_hint_flags = window_prompting;
5392 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5393 f->no_split = minibuffer_only || EQ (tem, Qt);
5395 /* Create the window. Add the tool-bar height to the initial frame
5396 height so that the user gets a text display area of the size he
5397 specified with -g or via the registry. Later changes of the
5398 tool-bar height don't change the frame size. This is done so that
5399 users can create tall Emacs frames without having to guess how
5400 tall the tool-bar will get. */
5401 f->height += FRAME_TOOL_BAR_LINES (f);
5402 w32_window (f, window_prompting, minibuffer_only);
5403 x_icon (f, parms);
5405 x_make_gc (f);
5407 /* Now consider the frame official. */
5408 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5409 Vframe_list = Fcons (frame, Vframe_list);
5411 /* We need to do this after creating the window, so that the
5412 icon-creation functions can say whose icon they're describing. */
5413 x_default_parameter (f, parms, Qicon_type, Qnil,
5414 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5416 x_default_parameter (f, parms, Qauto_raise, Qnil,
5417 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5418 x_default_parameter (f, parms, Qauto_lower, Qnil,
5419 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5420 x_default_parameter (f, parms, Qcursor_type, Qbox,
5421 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5422 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5423 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5425 /* Dimensions, especially f->height, must be done via change_frame_size.
5426 Change will not be effected unless different from the current
5427 f->height. */
5428 width = f->width;
5429 height = f->height;
5430 f->height = 0;
5431 SET_FRAME_WIDTH (f, 0);
5432 change_frame_size (f, height, width, 1, 0, 0);
5434 /* Tell the server what size and position, etc, we want, and how
5435 badly we want them. This should be done after we have the menu
5436 bar so that its size can be taken into account. */
5437 BLOCK_INPUT;
5438 x_wm_set_size_hint (f, window_prompting, 0);
5439 UNBLOCK_INPUT;
5441 /* Set up faces after all frame parameters are known. This call
5442 also merges in face attributes specified for new frames. If we
5443 don't do this, the `menu' face for instance won't have the right
5444 colors, and the menu bar won't appear in the specified colors for
5445 new frames. */
5446 call1 (Qface_set_after_frame_default, frame);
5448 /* Make the window appear on the frame and enable display, unless
5449 the caller says not to. However, with explicit parent, Emacs
5450 cannot control visibility, so don't try. */
5451 if (! f->output_data.w32->explicit_parent)
5453 Lisp_Object visibility;
5455 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5456 if (EQ (visibility, Qunbound))
5457 visibility = Qt;
5459 if (EQ (visibility, Qicon))
5460 x_iconify_frame (f);
5461 else if (! NILP (visibility))
5462 x_make_frame_visible (f);
5463 else
5464 /* Must have been Qnil. */
5467 UNGCPRO;
5468 return unbind_to (count, frame);
5471 /* FRAME is used only to get a handle on the X display. We don't pass the
5472 display info directly because we're called from frame.c, which doesn't
5473 know about that structure. */
5474 Lisp_Object
5475 x_get_focus_frame (frame)
5476 struct frame *frame;
5478 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5479 Lisp_Object xfocus;
5480 if (! dpyinfo->w32_focus_frame)
5481 return Qnil;
5483 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5484 return xfocus;
5487 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5488 "Give FRAME input focus, raising to foreground if necessary.")
5489 (frame)
5490 Lisp_Object frame;
5492 x_focus_on_frame (check_x_frame (frame));
5493 return Qnil;
5497 /* Return the charset portion of a font name. */
5498 char * xlfd_charset_of_font (char * fontname)
5500 char *charset, *encoding;
5502 encoding = strrchr(fontname, '-');
5503 if (!encoding || encoding == fontname)
5504 return NULL;
5506 for (charset = encoding - 1; charset >= fontname; charset--)
5507 if (*charset == '-')
5508 break;
5510 if (charset == fontname || strcmp(charset, "-*-*") == 0)
5511 return NULL;
5513 return charset + 1;
5516 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5517 int size, char* filename);
5518 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
5519 BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len, char * charset);
5521 static struct font_info *
5522 w32_load_system_font (f,fontname,size)
5523 struct frame *f;
5524 char * fontname;
5525 int size;
5527 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5528 Lisp_Object font_names;
5530 /* Get a list of all the fonts that match this name. Once we
5531 have a list of matching fonts, we compare them against the fonts
5532 we already have loaded by comparing names. */
5533 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5535 if (!NILP (font_names))
5537 Lisp_Object tail;
5538 int i;
5540 /* First check if any are already loaded, as that is cheaper
5541 than loading another one. */
5542 for (i = 0; i < dpyinfo->n_fonts; i++)
5543 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5544 if (dpyinfo->font_table[i].name
5545 && (!strcmp (dpyinfo->font_table[i].name,
5546 XSTRING (XCAR (tail))->data)
5547 || !strcmp (dpyinfo->font_table[i].full_name,
5548 XSTRING (XCAR (tail))->data)))
5549 return (dpyinfo->font_table + i);
5551 fontname = (char *) XSTRING (XCAR (font_names))->data;
5553 else if (w32_strict_fontnames)
5555 /* If EnumFontFamiliesEx was available, we got a full list of
5556 fonts back so stop now to avoid the possibility of loading a
5557 random font. If we had to fall back to EnumFontFamilies, the
5558 list is incomplete, so continue whether the font we want was
5559 listed or not. */
5560 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5561 FARPROC enum_font_families_ex
5562 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5563 if (enum_font_families_ex)
5564 return NULL;
5567 /* Load the font and add it to the table. */
5569 char *full_name, *encoding, *charset;
5570 XFontStruct *font;
5571 struct font_info *fontp;
5572 LOGFONT lf;
5573 BOOL ok;
5574 int i;
5576 if (!fontname || !x_to_w32_font (fontname, &lf))
5577 return (NULL);
5579 if (!*lf.lfFaceName)
5580 /* If no name was specified for the font, we get a random font
5581 from CreateFontIndirect - this is not particularly
5582 desirable, especially since CreateFontIndirect does not
5583 fill out the missing name in lf, so we never know what we
5584 ended up with. */
5585 return NULL;
5587 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5588 bzero (font, sizeof (*font));
5590 /* Set bdf to NULL to indicate that this is a Windows font. */
5591 font->bdf = NULL;
5593 BLOCK_INPUT;
5595 font->hfont = CreateFontIndirect (&lf);
5597 if (font->hfont == NULL)
5599 ok = FALSE;
5601 else
5603 HDC hdc;
5604 HANDLE oldobj;
5605 int codepage = w32_codepage_for_font (fontname);
5607 hdc = GetDC (dpyinfo->root_window);
5608 oldobj = SelectObject (hdc, font->hfont);
5610 ok = GetTextMetrics (hdc, &font->tm);
5611 if (codepage == CP_UNICODE)
5612 font->double_byte_p = 1;
5613 else
5614 font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS;
5616 SelectObject (hdc, oldobj);
5617 ReleaseDC (dpyinfo->root_window, hdc);
5618 /* Fill out details in lf according to the font that was
5619 actually loaded. */
5620 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5621 lf.lfWidth = font->tm.tmAveCharWidth;
5622 lf.lfWeight = font->tm.tmWeight;
5623 lf.lfItalic = font->tm.tmItalic;
5624 lf.lfCharSet = font->tm.tmCharSet;
5625 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5626 ? VARIABLE_PITCH : FIXED_PITCH);
5627 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5628 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5630 w32_cache_char_metrics (font);
5633 UNBLOCK_INPUT;
5635 if (!ok)
5637 w32_unload_font (dpyinfo, font);
5638 return (NULL);
5641 /* Find a free slot in the font table. */
5642 for (i = 0; i < dpyinfo->n_fonts; ++i)
5643 if (dpyinfo->font_table[i].name == NULL)
5644 break;
5646 /* If no free slot found, maybe enlarge the font table. */
5647 if (i == dpyinfo->n_fonts
5648 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5650 int sz;
5651 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5652 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5653 dpyinfo->font_table
5654 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5657 fontp = dpyinfo->font_table + i;
5658 if (i == dpyinfo->n_fonts)
5659 ++dpyinfo->n_fonts;
5661 /* Now fill in the slots of *FONTP. */
5662 BLOCK_INPUT;
5663 fontp->font = font;
5664 fontp->font_idx = i;
5665 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5666 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5668 charset = xlfd_charset_of_font (fontname);
5670 /* Work out the font's full name. */
5671 full_name = (char *)xmalloc (100);
5672 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
5673 fontp->full_name = full_name;
5674 else
5676 /* If all else fails - just use the name we used to load it. */
5677 xfree (full_name);
5678 fontp->full_name = fontp->name;
5681 fontp->size = FONT_WIDTH (font);
5682 fontp->height = FONT_HEIGHT (font);
5684 /* The slot `encoding' specifies how to map a character
5685 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
5686 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
5687 (0:0x20..0x7F, 1:0xA0..0xFF,
5688 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
5689 2:0xA020..0xFF7F). For the moment, we don't know which charset
5690 uses this font. So, we set information in fontp->encoding[1]
5691 which is never used by any charset. If mapping can't be
5692 decided, set FONT_ENCODING_NOT_DECIDED. */
5694 /* SJIS fonts need to be set to type 4, all others seem to work as
5695 type FONT_ENCODING_NOT_DECIDED. */
5696 encoding = strrchr (fontp->name, '-');
5697 if (encoding && stricmp (encoding+1, "sjis") == 0)
5698 fontp->encoding[1] = 4;
5699 else
5700 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
5702 /* The following three values are set to 0 under W32, which is
5703 what they get set to if XGetFontProperty fails under X. */
5704 fontp->baseline_offset = 0;
5705 fontp->relative_compose = 0;
5706 fontp->default_ascent = 0;
5708 /* Set global flag fonts_changed_p to non-zero if the font loaded
5709 has a character with a smaller width than any other character
5710 before, or if the font loaded has a smalle>r height than any
5711 other font loaded before. If this happens, it will make a
5712 glyph matrix reallocation necessary. */
5713 fonts_changed_p = x_compute_min_glyph_bounds (f);
5714 UNBLOCK_INPUT;
5715 return fontp;
5719 /* Load font named FONTNAME of size SIZE for frame F, and return a
5720 pointer to the structure font_info while allocating it dynamically.
5721 If loading fails, return NULL. */
5722 struct font_info *
5723 w32_load_font (f,fontname,size)
5724 struct frame *f;
5725 char * fontname;
5726 int size;
5728 Lisp_Object bdf_fonts;
5729 struct font_info *retval = NULL;
5731 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
5733 while (!retval && CONSP (bdf_fonts))
5735 char *bdf_name, *bdf_file;
5736 Lisp_Object bdf_pair;
5738 bdf_name = XSTRING (XCAR (bdf_fonts))->data;
5739 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
5740 bdf_file = XSTRING (XCDR (bdf_pair))->data;
5742 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
5744 bdf_fonts = XCDR (bdf_fonts);
5747 if (retval)
5748 return retval;
5750 return w32_load_system_font(f, fontname, size);
5754 void
5755 w32_unload_font (dpyinfo, font)
5756 struct w32_display_info *dpyinfo;
5757 XFontStruct * font;
5759 if (font)
5761 if (font->per_char) xfree (font->per_char);
5762 if (font->bdf) w32_free_bdf_font (font->bdf);
5764 if (font->hfont) DeleteObject(font->hfont);
5765 xfree (font);
5769 /* The font conversion stuff between x and w32 */
5771 /* X font string is as follows (from faces.el)
5772 * (let ((- "[-?]")
5773 * (foundry "[^-]+")
5774 * (family "[^-]+")
5775 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
5776 * (weight\? "\\([^-]*\\)") ; 1
5777 * (slant "\\([ior]\\)") ; 2
5778 * (slant\? "\\([^-]?\\)") ; 2
5779 * (swidth "\\([^-]*\\)") ; 3
5780 * (adstyle "[^-]*") ; 4
5781 * (pixelsize "[0-9]+")
5782 * (pointsize "[0-9][0-9]+")
5783 * (resx "[0-9][0-9]+")
5784 * (resy "[0-9][0-9]+")
5785 * (spacing "[cmp?*]")
5786 * (avgwidth "[0-9]+")
5787 * (registry "[^-]+")
5788 * (encoding "[^-]+")
5792 static LONG
5793 x_to_w32_weight (lpw)
5794 char * lpw;
5796 if (!lpw) return (FW_DONTCARE);
5798 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
5799 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
5800 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
5801 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
5802 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5803 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
5804 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
5805 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
5806 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
5807 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
5808 else
5809 return FW_DONTCARE;
5813 static char *
5814 w32_to_x_weight (fnweight)
5815 int fnweight;
5817 if (fnweight >= FW_HEAVY) return "heavy";
5818 if (fnweight >= FW_EXTRABOLD) return "extrabold";
5819 if (fnweight >= FW_BOLD) return "bold";
5820 if (fnweight >= FW_SEMIBOLD) return "demibold";
5821 if (fnweight >= FW_MEDIUM) return "medium";
5822 if (fnweight >= FW_NORMAL) return "normal";
5823 if (fnweight >= FW_LIGHT) return "light";
5824 if (fnweight >= FW_EXTRALIGHT) return "extralight";
5825 if (fnweight >= FW_THIN) return "thin";
5826 else
5827 return "*";
5830 static LONG
5831 x_to_w32_charset (lpcs)
5832 char * lpcs;
5834 Lisp_Object this_entry, w32_charset;
5836 /* Look through w32-charset-info-alist for the character set.
5837 Format of each entry is
5838 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5840 this_entry = Fassoc (build_string(lpcs), Vw32_charset_info_alist);
5842 if (NILP(this_entry))
5844 /* At startup, we want iso8859-1 fonts to come up properly. */
5845 if (stricmp(lpcs, "iso8859-1") == 0)
5846 return ANSI_CHARSET;
5847 else
5848 return DEFAULT_CHARSET;
5851 w32_charset = Fcar (Fcdr (this_entry));
5853 // Translate Lisp symbol to number.
5854 if (w32_charset == Qw32_charset_ansi)
5855 return ANSI_CHARSET;
5856 if (w32_charset == Qw32_charset_symbol)
5857 return SYMBOL_CHARSET;
5858 if (w32_charset == Qw32_charset_shiftjis)
5859 return SHIFTJIS_CHARSET;
5860 if (w32_charset == Qw32_charset_hangeul)
5861 return HANGEUL_CHARSET;
5862 if (w32_charset == Qw32_charset_chinesebig5)
5863 return CHINESEBIG5_CHARSET;
5864 if (w32_charset == Qw32_charset_gb2312)
5865 return GB2312_CHARSET;
5866 if (w32_charset == Qw32_charset_oem)
5867 return OEM_CHARSET;
5868 #ifdef JOHAB_CHARSET
5869 if (w32_charset == Qw32_charset_johab)
5870 return JOHAB_CHARSET;
5871 if (w32_charset == Qw32_charset_easteurope)
5872 return EASTEUROPE_CHARSET;
5873 if (w32_charset == Qw32_charset_turkish)
5874 return TURKISH_CHARSET;
5875 if (w32_charset == Qw32_charset_baltic)
5876 return BALTIC_CHARSET;
5877 if (w32_charset == Qw32_charset_russian)
5878 return RUSSIAN_CHARSET;
5879 if (w32_charset == Qw32_charset_arabic)
5880 return ARABIC_CHARSET;
5881 if (w32_charset == Qw32_charset_greek)
5882 return GREEK_CHARSET;
5883 if (w32_charset == Qw32_charset_hebrew)
5884 return HEBREW_CHARSET;
5885 if (w32_charset == Qw32_charset_vietnamese)
5886 return VIETNAMESE_CHARSET;
5887 if (w32_charset == Qw32_charset_thai)
5888 return THAI_CHARSET;
5889 if (w32_charset == Qw32_charset_mac)
5890 return MAC_CHARSET;
5891 #endif /* JOHAB_CHARSET */
5892 #ifdef UNICODE_CHARSET
5893 if (w32_charset == Qw32_charset_unicode)
5894 return UNICODE_CHARSET;
5895 #endif
5897 return DEFAULT_CHARSET;
5901 static char *
5902 w32_to_x_charset (fncharset)
5903 int fncharset;
5905 static char buf[16];
5906 Lisp_Object charset_type;
5908 switch (fncharset)
5910 case ANSI_CHARSET:
5911 /* Handle startup case of w32-charset-info-alist not
5912 being set up yet. */
5913 if (NILP(Vw32_charset_info_alist))
5914 return "iso8859-1";
5915 charset_type = Qw32_charset_ansi;
5916 break;
5917 case DEFAULT_CHARSET:
5918 charset_type = Qw32_charset_default;
5919 break;
5920 case SYMBOL_CHARSET:
5921 charset_type = Qw32_charset_symbol;
5922 break;
5923 case SHIFTJIS_CHARSET:
5924 charset_type = Qw32_charset_shiftjis;
5925 break;
5926 case HANGEUL_CHARSET:
5927 charset_type = Qw32_charset_hangeul;
5928 break;
5929 case GB2312_CHARSET:
5930 charset_type = Qw32_charset_gb2312;
5931 break;
5932 case CHINESEBIG5_CHARSET:
5933 charset_type = Qw32_charset_chinesebig5;
5934 break;
5935 case OEM_CHARSET:
5936 charset_type = Qw32_charset_oem;
5937 break;
5939 /* More recent versions of Windows (95 and NT4.0) define more
5940 character sets. */
5941 #ifdef EASTEUROPE_CHARSET
5942 case EASTEUROPE_CHARSET:
5943 charset_type = Qw32_charset_easteurope;
5944 break;
5945 case TURKISH_CHARSET:
5946 charset_type = Qw32_charset_turkish;
5947 break;
5948 case BALTIC_CHARSET:
5949 charset_type = Qw32_charset_baltic;
5950 break;
5951 case RUSSIAN_CHARSET:
5952 charset_type = Qw32_charset_russian;
5953 break;
5954 case ARABIC_CHARSET:
5955 charset_type = Qw32_charset_arabic;
5956 break;
5957 case GREEK_CHARSET:
5958 charset_type = Qw32_charset_greek;
5959 break;
5960 case HEBREW_CHARSET:
5961 charset_type = Qw32_charset_hebrew;
5962 break;
5963 case VIETNAMESE_CHARSET:
5964 charset_type = Qw32_charset_vietnamese;
5965 break;
5966 case THAI_CHARSET:
5967 charset_type = Qw32_charset_thai;
5968 break;
5969 case MAC_CHARSET:
5970 charset_type = Qw32_charset_mac;
5971 break;
5972 case JOHAB_CHARSET:
5973 charset_type = Qw32_charset_johab;
5974 break;
5975 #endif
5977 #ifdef UNICODE_CHARSET
5978 case UNICODE_CHARSET:
5979 charset_type = Qw32_charset_unicode;
5980 break;
5981 #endif
5982 default:
5983 /* Encode numerical value of unknown charset. */
5984 sprintf (buf, "*-#%u", fncharset);
5985 return buf;
5989 Lisp_Object rest;
5990 char * best_match = NULL;
5992 /* Look through w32-charset-info-alist for the character set.
5993 Prefer ISO codepages, and prefer lower numbers in the ISO
5994 range. Only return charsets for codepages which are installed.
5996 Format of each entry is
5997 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5999 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6001 char * x_charset;
6002 Lisp_Object w32_charset;
6003 Lisp_Object codepage;
6005 Lisp_Object this_entry = XCAR (rest);
6007 /* Skip invalid entries in alist. */
6008 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6009 || !CONSP (XCDR (this_entry))
6010 || !SYMBOLP (XCAR (XCDR (this_entry))))
6011 continue;
6013 x_charset = XSTRING (XCAR (this_entry))->data;
6014 w32_charset = XCAR (XCDR (this_entry));
6015 codepage = XCDR (XCDR (this_entry));
6017 /* Look for Same charset and a valid codepage (or non-int
6018 which means ignore). */
6019 if (w32_charset == charset_type
6020 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6021 || IsValidCodePage (XINT (codepage))))
6023 /* If we don't have a match already, then this is the
6024 best. */
6025 if (!best_match)
6026 best_match = x_charset;
6027 /* If this is an ISO codepage, and the best so far isn't,
6028 then this is better. */
6029 else if (stricmp (best_match, "iso") != 0
6030 && stricmp (x_charset, "iso") == 0)
6031 best_match = x_charset;
6032 /* If both are ISO8859 codepages, choose the one with the
6033 lowest number in the encoding field. */
6034 else if (stricmp (best_match, "iso8859-") == 0
6035 && stricmp (x_charset, "iso8859-") == 0)
6037 int best_enc = atoi (best_match + 8);
6038 int this_enc = atoi (x_charset + 8);
6039 if (this_enc > 0 && this_enc < best_enc)
6040 best_match = x_charset;
6045 /* If no match, encode the numeric value. */
6046 if (!best_match)
6048 sprintf (buf, "*-#%u", fncharset);
6049 return buf;
6052 strncpy(buf, best_match, 15);
6053 buf[15] = '\0';
6054 return buf;
6059 /* Get the Windows codepage corresponding to the specified font. The
6060 charset info in the font name is used to look up
6061 w32-charset-to-codepage-alist. */
6062 int
6063 w32_codepage_for_font (char *fontname)
6065 Lisp_Object codepage, entry;
6066 char *charset_str, *charset, *end;
6068 if (NILP (Vw32_charset_info_alist))
6069 return CP_DEFAULT;
6071 /* Extract charset part of font string. */
6072 charset = xlfd_charset_of_font (fontname);
6074 if (!charset)
6075 return CP_UNKNOWN;
6077 charset_str = (char *) alloca (strlen (charset));
6078 strcpy (charset_str, charset);
6080 /* Remove leading "*-". */
6081 if (strncmp ("*-", charset_str, 2) == 0)
6082 charset = charset_str + 2;
6083 else
6084 charset = charset_str;
6086 /* Stop match at wildcard (including preceding '-'). */
6087 if (end = strchr (charset, '*'))
6089 if (end > charset && *(end-1) == '-')
6090 end--;
6091 *end = '\0';
6094 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6095 if (NILP (entry))
6096 return CP_UNKNOWN;
6098 codepage = Fcdr (Fcdr (entry));
6100 if (NILP (codepage))
6101 return CP_8BIT;
6102 else if (XFASTINT (codepage) == XFASTINT (Qt))
6103 return CP_UNICODE;
6104 else if (INTEGERP (codepage))
6105 return XINT (codepage);
6106 else
6107 return CP_UNKNOWN;
6111 static BOOL
6112 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6113 LOGFONT * lplogfont;
6114 char * lpxstr;
6115 int len;
6116 char * specific_charset;
6118 char* fonttype;
6119 char *fontname;
6120 char height_pixels[8];
6121 char height_dpi[8];
6122 char width_pixels[8];
6123 char *fontname_dash;
6124 int display_resy = one_w32_display_info.resy;
6125 int display_resx = one_w32_display_info.resx;
6126 int bufsz;
6127 struct coding_system coding;
6129 if (!lpxstr) abort ();
6131 if (!lplogfont)
6132 return FALSE;
6134 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6135 fonttype = "raster";
6136 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6137 fonttype = "outline";
6138 else
6139 fonttype = "unknown";
6141 setup_coding_system (Fcheck_coding_system (Vw32_system_coding_system),
6142 &coding);
6143 coding.src_multibyte = 0;
6144 coding.dst_multibyte = 1;
6145 coding.mode |= CODING_MODE_LAST_BLOCK;
6146 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6148 fontname = alloca(sizeof(*fontname) * bufsz);
6149 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6150 strlen(lplogfont->lfFaceName), bufsz - 1);
6151 *(fontname + coding.produced) = '\0';
6153 /* Replace dashes with underscores so the dashes are not
6154 misinterpreted. */
6155 fontname_dash = fontname;
6156 while (fontname_dash = strchr (fontname_dash, '-'))
6157 *fontname_dash = '_';
6159 if (lplogfont->lfHeight)
6161 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6162 sprintf (height_dpi, "%u",
6163 abs (lplogfont->lfHeight) * 720 / display_resy);
6165 else
6167 strcpy (height_pixels, "*");
6168 strcpy (height_dpi, "*");
6170 if (lplogfont->lfWidth)
6171 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6172 else
6173 strcpy (width_pixels, "*");
6175 _snprintf (lpxstr, len - 1,
6176 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6177 fonttype, /* foundry */
6178 fontname, /* family */
6179 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6180 lplogfont->lfItalic?'i':'r', /* slant */
6181 /* setwidth name */
6182 /* add style name */
6183 height_pixels, /* pixel size */
6184 height_dpi, /* point size */
6185 display_resx, /* resx */
6186 display_resy, /* resy */
6187 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6188 ? 'p' : 'c', /* spacing */
6189 width_pixels, /* avg width */
6190 specific_charset ? specific_charset
6191 : w32_to_x_charset (lplogfont->lfCharSet)
6192 /* charset registry and encoding */
6195 lpxstr[len - 1] = 0; /* just to be sure */
6196 return (TRUE);
6199 static BOOL
6200 x_to_w32_font (lpxstr, lplogfont)
6201 char * lpxstr;
6202 LOGFONT * lplogfont;
6204 struct coding_system coding;
6206 if (!lplogfont) return (FALSE);
6208 memset (lplogfont, 0, sizeof (*lplogfont));
6210 /* Set default value for each field. */
6211 #if 1
6212 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6213 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6214 lplogfont->lfQuality = DEFAULT_QUALITY;
6215 #else
6216 /* go for maximum quality */
6217 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6218 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6219 lplogfont->lfQuality = PROOF_QUALITY;
6220 #endif
6222 lplogfont->lfCharSet = DEFAULT_CHARSET;
6223 lplogfont->lfWeight = FW_DONTCARE;
6224 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6226 if (!lpxstr)
6227 return FALSE;
6229 /* Provide a simple escape mechanism for specifying Windows font names
6230 * directly -- if font spec does not beginning with '-', assume this
6231 * format:
6232 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6235 if (*lpxstr == '-')
6237 int fields, tem;
6238 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6239 width[10], resy[10], remainder[20];
6240 char * encoding;
6241 int dpi = one_w32_display_info.resy;
6243 fields = sscanf (lpxstr,
6244 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%19s",
6245 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6246 if (fields == EOF) return (FALSE);
6248 /* If wildcards cover more than one field, we don't know which
6249 field is which, so don't fill any in. */
6251 if (fields < 9)
6252 fields = 0;
6254 if (fields > 0 && name[0] != '*')
6256 int bufsize;
6257 unsigned char *buf;
6259 setup_coding_system
6260 (Fcheck_coding_system (Vw32_system_coding_system), &coding);
6261 coding.src_multibyte = 1;
6262 coding.dst_multibyte = 1;
6263 bufsize = encoding_buffer_size (&coding, strlen (name));
6264 buf = (unsigned char *) alloca (bufsize);
6265 coding.mode |= CODING_MODE_LAST_BLOCK;
6266 encode_coding (&coding, name, buf, strlen (name), bufsize);
6267 if (coding.produced >= LF_FACESIZE)
6268 coding.produced = LF_FACESIZE - 1;
6269 buf[coding.produced] = 0;
6270 strcpy (lplogfont->lfFaceName, buf);
6272 else
6274 lplogfont->lfFaceName[0] = '\0';
6277 fields--;
6279 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6281 fields--;
6283 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6285 fields--;
6287 if (fields > 0 && pixels[0] != '*')
6288 lplogfont->lfHeight = atoi (pixels);
6290 fields--;
6291 fields--;
6292 if (fields > 0 && resy[0] != '*')
6294 tem = atoi (resy);
6295 if (tem > 0) dpi = tem;
6298 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6299 lplogfont->lfHeight = atoi (height) * dpi / 720;
6301 if (fields > 0)
6302 lplogfont->lfPitchAndFamily =
6303 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6305 fields--;
6307 if (fields > 0 && width[0] != '*')
6308 lplogfont->lfWidth = atoi (width) / 10;
6310 fields--;
6312 /* Strip the trailing '-' if present. (it shouldn't be, as it
6313 fails the test against xlfd-tight-regexp in fontset.el). */
6315 int len = strlen (remainder);
6316 if (len > 0 && remainder[len-1] == '-')
6317 remainder[len-1] = 0;
6319 encoding = remainder;
6320 if (strncmp (encoding, "*-", 2) == 0)
6321 encoding += 2;
6322 lplogfont->lfCharSet = x_to_w32_charset (fields > 0 ? encoding : "");
6324 else
6326 int fields;
6327 char name[100], height[10], width[10], weight[20];
6329 fields = sscanf (lpxstr,
6330 "%99[^:]:%9[^:]:%9[^:]:%19s",
6331 name, height, width, weight);
6333 if (fields == EOF) return (FALSE);
6335 if (fields > 0)
6337 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6338 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6340 else
6342 lplogfont->lfFaceName[0] = 0;
6345 fields--;
6347 if (fields > 0)
6348 lplogfont->lfHeight = atoi (height);
6350 fields--;
6352 if (fields > 0)
6353 lplogfont->lfWidth = atoi (width);
6355 fields--;
6357 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6360 /* This makes TrueType fonts work better. */
6361 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6363 return (TRUE);
6366 /* Strip the pixel height and point height from the given xlfd, and
6367 return the pixel height. If no pixel height is specified, calculate
6368 one from the point height, or if that isn't defined either, return
6369 0 (which usually signifies a scalable font).
6371 static int
6372 xlfd_strip_height (char *fontname)
6374 int pixel_height, field_number;
6375 char *read_from, *write_to;
6377 xassert (fontname);
6379 pixel_height = field_number = 0;
6380 write_to = NULL;
6382 /* Look for height fields. */
6383 for (read_from = fontname; *read_from; read_from++)
6385 if (*read_from == '-')
6387 field_number++;
6388 if (field_number == 7) /* Pixel height. */
6390 read_from++;
6391 write_to = read_from;
6393 /* Find end of field. */
6394 for (;*read_from && *read_from != '-'; read_from++)
6397 /* Split the fontname at end of field. */
6398 if (*read_from)
6400 *read_from = '\0';
6401 read_from++;
6403 pixel_height = atoi (write_to);
6404 /* Blank out field. */
6405 if (read_from > write_to)
6407 *write_to = '-';
6408 write_to++;
6410 /* If the pixel height field is at the end (partial xlfd),
6411 return now. */
6412 else
6413 return pixel_height;
6415 /* If we got a pixel height, the point height can be
6416 ignored. Just blank it out and break now. */
6417 if (pixel_height)
6419 /* Find end of point size field. */
6420 for (; *read_from && *read_from != '-'; read_from++)
6423 if (*read_from)
6424 read_from++;
6426 /* Blank out the point size field. */
6427 if (read_from > write_to)
6429 *write_to = '-';
6430 write_to++;
6432 else
6433 return pixel_height;
6435 break;
6437 /* If the point height is already blank, break now. */
6438 if (*read_from == '-')
6440 read_from++;
6441 break;
6444 else if (field_number == 8)
6446 /* If we didn't get a pixel height, try to get the point
6447 height and convert that. */
6448 int point_size;
6449 char *point_size_start = read_from++;
6451 /* Find end of field. */
6452 for (; *read_from && *read_from != '-'; read_from++)
6455 if (*read_from)
6457 *read_from = '\0';
6458 read_from++;
6461 point_size = atoi (point_size_start);
6463 /* Convert to pixel height. */
6464 pixel_height = point_size
6465 * one_w32_display_info.height_in / 720;
6467 /* Blank out this field and break. */
6468 *write_to = '-';
6469 write_to++;
6470 break;
6475 /* Shift the rest of the font spec into place. */
6476 if (write_to && read_from > write_to)
6478 for (; *read_from; read_from++, write_to++)
6479 *write_to = *read_from;
6480 *write_to = '\0';
6483 return pixel_height;
6486 /* Assume parameter 1 is fully qualified, no wildcards. */
6487 static BOOL
6488 w32_font_match (fontname, pattern)
6489 char * fontname;
6490 char * pattern;
6492 char *regex = alloca (strlen (pattern) * 2 + 3);
6493 char *font_name_copy = alloca (strlen (fontname) + 1);
6494 char *ptr;
6496 /* Copy fontname so we can modify it during comparison. */
6497 strcpy (font_name_copy, fontname);
6499 ptr = regex;
6500 *ptr++ = '^';
6502 /* Turn pattern into a regexp and do a regexp match. */
6503 for (; *pattern; pattern++)
6505 if (*pattern == '?')
6506 *ptr++ = '.';
6507 else if (*pattern == '*')
6509 *ptr++ = '.';
6510 *ptr++ = '*';
6512 else
6513 *ptr++ = *pattern;
6515 *ptr = '$';
6516 *(ptr + 1) = '\0';
6518 /* Strip out font heights and compare them seperately, since
6519 rounding error can cause mismatches. This also allows a
6520 comparison between a font that declares only a pixel height and a
6521 pattern that declares the point height.
6524 int font_height, pattern_height;
6526 font_height = xlfd_strip_height (font_name_copy);
6527 pattern_height = xlfd_strip_height (regex);
6529 /* Compare now, and don't bother doing expensive regexp matching
6530 if the heights differ. */
6531 if (font_height && pattern_height && (font_height != pattern_height))
6532 return FALSE;
6535 return (fast_c_string_match_ignore_case (build_string (regex),
6536 font_name_copy) >= 0);
6539 /* Callback functions, and a structure holding info they need, for
6540 listing system fonts on W32. We need one set of functions to do the
6541 job properly, but these don't work on NT 3.51 and earlier, so we
6542 have a second set which don't handle character sets properly to
6543 fall back on.
6545 In both cases, there are two passes made. The first pass gets one
6546 font from each family, the second pass lists all the fonts from
6547 each family. */
6549 typedef struct enumfont_t
6551 HDC hdc;
6552 int numFonts;
6553 LOGFONT logfont;
6554 XFontStruct *size_ref;
6555 Lisp_Object *pattern;
6556 Lisp_Object *tail;
6557 } enumfont_t;
6559 static int CALLBACK
6560 enum_font_cb2 (lplf, lptm, FontType, lpef)
6561 ENUMLOGFONT * lplf;
6562 NEWTEXTMETRIC * lptm;
6563 int FontType;
6564 enumfont_t * lpef;
6566 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
6567 return (1);
6569 /* Check that the character set matches if it was specified */
6570 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
6571 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
6572 return (1);
6575 char buf[100];
6576 Lisp_Object width = Qnil;
6577 char *charset = NULL;
6579 /* Truetype fonts do not report their true metrics until loaded */
6580 if (FontType != RASTER_FONTTYPE)
6582 if (!NILP (*(lpef->pattern)))
6584 /* Scalable fonts are as big as you want them to be. */
6585 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
6586 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
6587 width = make_number (lpef->logfont.lfWidth);
6589 else
6591 lplf->elfLogFont.lfHeight = 0;
6592 lplf->elfLogFont.lfWidth = 0;
6596 /* Make sure the height used here is the same as everywhere
6597 else (ie character height, not cell height). */
6598 if (lplf->elfLogFont.lfHeight > 0)
6600 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
6601 if (FontType == RASTER_FONTTYPE)
6602 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
6603 else
6604 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
6607 if (!NILP (*(lpef->pattern)))
6609 charset = xlfd_charset_of_font (XSTRING(*(lpef->pattern))->data);
6611 /* Ensure that charset is valid for this font. */
6612 if (charset
6613 && (x_to_w32_charset (charset) != lplf->elfLogFont.lfCharSet))
6614 charset = NULL;
6617 /* TODO: List all relevant charsets if charset not specified. */
6618 if (!w32_to_x_font (&(lplf->elfLogFont), buf, 100, charset))
6619 return (0);
6621 if (NILP (*(lpef->pattern))
6622 || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
6624 *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
6625 lpef->tail = &(XCDR (*lpef->tail));
6626 lpef->numFonts++;
6630 return (1);
6633 static int CALLBACK
6634 enum_font_cb1 (lplf, lptm, FontType, lpef)
6635 ENUMLOGFONT * lplf;
6636 NEWTEXTMETRIC * lptm;
6637 int FontType;
6638 enumfont_t * lpef;
6640 return EnumFontFamilies (lpef->hdc,
6641 lplf->elfLogFont.lfFaceName,
6642 (FONTENUMPROC) enum_font_cb2,
6643 (LPARAM) lpef);
6647 static int CALLBACK
6648 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6649 ENUMLOGFONTEX * lplf;
6650 NEWTEXTMETRICEX * lptm;
6651 int font_type;
6652 enumfont_t * lpef;
6654 /* We are not interested in the extra info we get back from the 'Ex
6655 version - only the fact that we get character set variations
6656 enumerated seperately. */
6657 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6658 font_type, lpef);
6661 static int CALLBACK
6662 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6663 ENUMLOGFONTEX * lplf;
6664 NEWTEXTMETRICEX * lptm;
6665 int font_type;
6666 enumfont_t * lpef;
6668 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6669 FARPROC enum_font_families_ex
6670 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6671 /* We don't really expect EnumFontFamiliesEx to disappear once we
6672 get here, so don't bother handling it gracefully. */
6673 if (enum_font_families_ex == NULL)
6674 error ("gdi32.dll has disappeared!");
6675 return enum_font_families_ex (lpef->hdc,
6676 &lplf->elfLogFont,
6677 (FONTENUMPROC) enum_fontex_cb2,
6678 (LPARAM) lpef, 0);
6681 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6682 and xterm.c in Emacs 20.3) */
6684 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6686 char *fontname, *ptnstr;
6687 Lisp_Object list, tem, newlist = Qnil;
6688 int n_fonts = 0;
6690 list = Vw32_bdf_filename_alist;
6691 ptnstr = XSTRING (pattern)->data;
6693 for ( ; CONSP (list); list = XCDR (list))
6695 tem = XCAR (list);
6696 if (CONSP (tem))
6697 fontname = XSTRING (XCAR (tem))->data;
6698 else if (STRINGP (tem))
6699 fontname = XSTRING (tem)->data;
6700 else
6701 continue;
6703 if (w32_font_match (fontname, ptnstr))
6705 newlist = Fcons (XCAR (tem), newlist);
6706 n_fonts++;
6707 if (n_fonts >= max_names)
6708 break;
6712 return newlist;
6715 static Lisp_Object w32_list_synthesized_fonts (FRAME_PTR f,
6716 Lisp_Object pattern,
6717 int size, int max_names);
6719 /* Return a list of names of available fonts matching PATTERN on frame
6720 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6721 to be listed. Frame F NULL means we have not yet created any
6722 frame, which means we can't get proper size info, as we don't have
6723 a device context to use for GetTextMetrics.
6724 MAXNAMES sets a limit on how many fonts to match. */
6726 Lisp_Object
6727 w32_list_fonts (FRAME_PTR f, Lisp_Object pattern, int size, int maxnames )
6729 Lisp_Object patterns, key = Qnil, tem, tpat;
6730 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6731 struct w32_display_info *dpyinfo = &one_w32_display_info;
6732 int n_fonts = 0;
6734 patterns = Fassoc (pattern, Valternate_fontname_alist);
6735 if (NILP (patterns))
6736 patterns = Fcons (pattern, Qnil);
6738 for (; CONSP (patterns); patterns = XCDR (patterns))
6740 enumfont_t ef;
6741 int codepage;
6743 tpat = XCAR (patterns);
6745 if (!STRINGP (tpat))
6746 continue;
6748 /* Avoid expensive EnumFontFamilies functions if we are not
6749 going to be able to output one of these anyway. */
6750 codepage = w32_codepage_for_font (XSTRING (tpat)->data);
6751 if (codepage != CP_8BIT && codepage != CP_UNICODE
6752 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6753 && !IsValidCodePage(codepage))
6754 continue;
6756 /* See if we cached the result for this particular query.
6757 The cache is an alist of the form:
6758 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6760 if (tem = XCDR (dpyinfo->name_list_element),
6761 !NILP (list = Fassoc (tpat, tem)))
6763 list = Fcdr_safe (list);
6764 /* We have a cached list. Don't have to get the list again. */
6765 goto label_cached;
6768 BLOCK_INPUT;
6769 /* At first, put PATTERN in the cache. */
6770 list = Qnil;
6771 ef.pattern = &tpat;
6772 ef.tail = &list;
6773 ef.numFonts = 0;
6775 /* Use EnumFontFamiliesEx where it is available, as it knows
6776 about character sets. Fall back to EnumFontFamilies for
6777 older versions of NT that don't support the 'Ex function. */
6778 x_to_w32_font (XSTRING (tpat)->data, &ef.logfont);
6780 LOGFONT font_match_pattern;
6781 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6782 FARPROC enum_font_families_ex
6783 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6785 /* We do our own pattern matching so we can handle wildcards. */
6786 font_match_pattern.lfFaceName[0] = 0;
6787 font_match_pattern.lfPitchAndFamily = 0;
6788 /* We can use the charset, because if it is a wildcard it will
6789 be DEFAULT_CHARSET anyway. */
6790 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6792 ef.hdc = GetDC (dpyinfo->root_window);
6794 if (enum_font_families_ex)
6795 enum_font_families_ex (ef.hdc,
6796 &font_match_pattern,
6797 (FONTENUMPROC) enum_fontex_cb1,
6798 (LPARAM) &ef, 0);
6799 else
6800 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6801 (LPARAM)&ef);
6803 ReleaseDC (dpyinfo->root_window, ef.hdc);
6806 UNBLOCK_INPUT;
6808 /* Make a list of the fonts we got back.
6809 Store that in the font cache for the display. */
6810 XCDR (dpyinfo->name_list_element)
6811 = Fcons (Fcons (tpat, list),
6812 XCDR (dpyinfo->name_list_element));
6814 label_cached:
6815 if (NILP (list)) continue; /* Try the remaining alternatives. */
6817 newlist = second_best = Qnil;
6819 /* Make a list of the fonts that have the right width. */
6820 for (; CONSP (list); list = XCDR (list))
6822 int found_size;
6823 tem = XCAR (list);
6825 if (!CONSP (tem))
6826 continue;
6827 if (NILP (XCAR (tem)))
6828 continue;
6829 if (!size)
6831 newlist = Fcons (XCAR (tem), newlist);
6832 n_fonts++;
6833 if (n_fonts >= maxnames)
6834 break;
6835 else
6836 continue;
6838 if (!INTEGERP (XCDR (tem)))
6840 /* Since we don't yet know the size of the font, we must
6841 load it and try GetTextMetrics. */
6842 W32FontStruct thisinfo;
6843 LOGFONT lf;
6844 HDC hdc;
6845 HANDLE oldobj;
6847 if (!x_to_w32_font (XSTRING (XCAR (tem))->data, &lf))
6848 continue;
6850 BLOCK_INPUT;
6851 thisinfo.bdf = NULL;
6852 thisinfo.hfont = CreateFontIndirect (&lf);
6853 if (thisinfo.hfont == NULL)
6854 continue;
6856 hdc = GetDC (dpyinfo->root_window);
6857 oldobj = SelectObject (hdc, thisinfo.hfont);
6858 if (GetTextMetrics (hdc, &thisinfo.tm))
6859 XCDR (tem) = make_number (FONT_WIDTH (&thisinfo));
6860 else
6861 XCDR (tem) = make_number (0);
6862 SelectObject (hdc, oldobj);
6863 ReleaseDC (dpyinfo->root_window, hdc);
6864 DeleteObject(thisinfo.hfont);
6865 UNBLOCK_INPUT;
6867 found_size = XINT (XCDR (tem));
6868 if (found_size == size)
6870 newlist = Fcons (XCAR (tem), newlist);
6871 n_fonts++;
6872 if (n_fonts >= maxnames)
6873 break;
6875 /* keep track of the closest matching size in case
6876 no exact match is found. */
6877 else if (found_size > 0)
6879 if (NILP (second_best))
6880 second_best = tem;
6882 else if (found_size < size)
6884 if (XINT (XCDR (second_best)) > size
6885 || XINT (XCDR (second_best)) < found_size)
6886 second_best = tem;
6888 else
6890 if (XINT (XCDR (second_best)) > size
6891 && XINT (XCDR (second_best)) >
6892 found_size)
6893 second_best = tem;
6898 if (!NILP (newlist))
6899 break;
6900 else if (!NILP (second_best))
6902 newlist = Fcons (XCAR (second_best), Qnil);
6903 break;
6907 /* Include any bdf fonts. */
6908 if (n_fonts < maxnames)
6910 Lisp_Object combined[2];
6911 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6912 combined[1] = newlist;
6913 newlist = Fnconc(2, combined);
6916 /* If we can't find a font that matches, check if Windows would be
6917 able to synthesize it from a different style. */
6918 if (NILP (newlist) && !NILP (Vw32_enable_synthesized_fonts))
6919 newlist = w32_list_synthesized_fonts (f, pattern, size, maxnames);
6921 return newlist;
6924 static Lisp_Object
6925 w32_list_synthesized_fonts (f, pattern, size, max_names)
6926 FRAME_PTR f;
6927 Lisp_Object pattern;
6928 int size;
6929 int max_names;
6931 int fields;
6932 char *full_pattn, *new_pattn, foundary[50], family[50], *pattn_part2;
6933 char style[20], slant;
6934 Lisp_Object matches, tem, synthed_matches = Qnil;
6936 full_pattn = XSTRING (pattern)->data;
6938 pattn_part2 = alloca (XSTRING (pattern)->size);
6939 /* Allow some space for wildcard expansion. */
6940 new_pattn = alloca (XSTRING (pattern)->size + 100);
6942 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%19[^-]-%c-%s",
6943 foundary, family, style, &slant, pattn_part2);
6944 if (fields == EOF || fields < 5)
6945 return Qnil;
6947 /* If the style and slant are wildcards already there is no point
6948 checking again (and we don't want to keep recursing). */
6949 if (*style == '*' && slant == '*')
6950 return Qnil;
6952 sprintf (new_pattn, "-%s-%s-*-*-%s", foundary, family, pattn_part2);
6954 matches = w32_list_fonts (f, build_string (new_pattn), size, max_names);
6956 for ( ; CONSP (matches); matches = XCDR (matches))
6958 tem = XCAR (matches);
6959 if (!STRINGP (tem))
6960 continue;
6962 full_pattn = XSTRING (tem)->data;
6963 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%*[^-]-%*c-%s",
6964 foundary, family, pattn_part2);
6965 if (fields == EOF || fields < 3)
6966 continue;
6968 sprintf (new_pattn, "-%s-%s-%s-%c-%s", foundary, family, style,
6969 slant, pattn_part2);
6971 synthed_matches = Fcons (build_string (new_pattn),
6972 synthed_matches);
6975 return synthed_matches;
6979 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6980 struct font_info *
6981 w32_get_font_info (f, font_idx)
6982 FRAME_PTR f;
6983 int font_idx;
6985 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6989 struct font_info*
6990 w32_query_font (struct frame *f, char *fontname)
6992 int i;
6993 struct font_info *pfi;
6995 pfi = FRAME_W32_FONT_TABLE (f);
6997 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6999 if (strcmp(pfi->name, fontname) == 0) return pfi;
7002 return NULL;
7005 /* Find a CCL program for a font specified by FONTP, and set the member
7006 `encoder' of the structure. */
7008 void
7009 w32_find_ccl_program (fontp)
7010 struct font_info *fontp;
7012 Lisp_Object list, elt;
7014 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7016 elt = XCAR (list);
7017 if (CONSP (elt)
7018 && STRINGP (XCAR (elt))
7019 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7020 >= 0))
7021 break;
7023 if (! NILP (list))
7025 struct ccl_program *ccl
7026 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7028 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7029 xfree (ccl);
7030 else
7031 fontp->font_encoder = ccl;
7036 /* Find BDF files in a specified directory. (use GCPRO when calling,
7037 as this calls lisp to get a directory listing). */
7038 static Lisp_Object
7039 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
7041 Lisp_Object filelist, list = Qnil;
7042 char fontname[100];
7044 if (!STRINGP(directory))
7045 return Qnil;
7047 filelist = Fdirectory_files (directory, Qt,
7048 build_string (".*\\.[bB][dD][fF]"), Qt);
7050 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7052 Lisp_Object filename = XCAR (filelist);
7053 if (w32_BDF_to_x_font (XSTRING (filename)->data, fontname, 100))
7054 store_in_alist (&list, build_string (fontname), filename);
7056 return list;
7059 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
7060 1, 1, 0,
7061 "Return a list of BDF fonts in DIR, suitable for appending to\n\
7062 w32-bdf-filename-alist. Fonts which do not contain an xlfd description\n\
7063 will not be included in the list. DIR may be a list of directories.")
7064 (directory)
7065 Lisp_Object directory;
7067 Lisp_Object list = Qnil;
7068 struct gcpro gcpro1, gcpro2;
7070 if (!CONSP (directory))
7071 return w32_find_bdf_fonts_in_dir (directory);
7073 for ( ; CONSP (directory); directory = XCDR (directory))
7075 Lisp_Object pair[2];
7076 pair[0] = list;
7077 pair[1] = Qnil;
7078 GCPRO2 (directory, list);
7079 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7080 list = Fnconc( 2, pair );
7081 UNGCPRO;
7083 return list;
7087 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7088 "Internal function called by `color-defined-p', which see.")
7089 (color, frame)
7090 Lisp_Object color, frame;
7092 XColor foo;
7093 FRAME_PTR f = check_x_frame (frame);
7095 CHECK_STRING (color, 1);
7097 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7098 return Qt;
7099 else
7100 return Qnil;
7103 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7104 "Internal function called by `color-values', which see.")
7105 (color, frame)
7106 Lisp_Object color, frame;
7108 XColor foo;
7109 FRAME_PTR f = check_x_frame (frame);
7111 CHECK_STRING (color, 1);
7113 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7115 Lisp_Object rgb[3];
7117 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7118 | GetRValue (foo.pixel));
7119 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7120 | GetGValue (foo.pixel));
7121 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7122 | GetBValue (foo.pixel));
7123 return Flist (3, rgb);
7125 else
7126 return Qnil;
7129 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7130 "Internal function called by `display-color-p', which see.")
7131 (display)
7132 Lisp_Object display;
7134 struct w32_display_info *dpyinfo = check_x_display_info (display);
7136 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7137 return Qnil;
7139 return Qt;
7142 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
7143 0, 1, 0,
7144 "Return t if the X display supports shades of gray.\n\
7145 Note that color displays do support shades of gray.\n\
7146 The optional argument DISPLAY specifies which display to ask about.\n\
7147 DISPLAY should be either a frame or a display name (a string).\n\
7148 If omitted or nil, that stands for the selected frame's display.")
7149 (display)
7150 Lisp_Object display;
7152 struct w32_display_info *dpyinfo = check_x_display_info (display);
7154 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7155 return Qnil;
7157 return Qt;
7160 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
7161 0, 1, 0,
7162 "Returns the width in pixels of the X display DISPLAY.\n\
7163 The optional argument DISPLAY specifies which display to ask about.\n\
7164 DISPLAY should be either a frame or a display name (a string).\n\
7165 If omitted or nil, that stands for the selected frame's display.")
7166 (display)
7167 Lisp_Object display;
7169 struct w32_display_info *dpyinfo = check_x_display_info (display);
7171 return make_number (dpyinfo->width);
7174 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7175 Sx_display_pixel_height, 0, 1, 0,
7176 "Returns the height in pixels of the X display DISPLAY.\n\
7177 The optional argument DISPLAY specifies which display to ask about.\n\
7178 DISPLAY should be either a frame or a display name (a string).\n\
7179 If omitted or nil, that stands for the selected frame's display.")
7180 (display)
7181 Lisp_Object display;
7183 struct w32_display_info *dpyinfo = check_x_display_info (display);
7185 return make_number (dpyinfo->height);
7188 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7189 0, 1, 0,
7190 "Returns the number of bitplanes of the display DISPLAY.\n\
7191 The optional argument DISPLAY specifies which display to ask about.\n\
7192 DISPLAY should be either a frame or a display name (a string).\n\
7193 If omitted or nil, that stands for the selected frame's display.")
7194 (display)
7195 Lisp_Object display;
7197 struct w32_display_info *dpyinfo = check_x_display_info (display);
7199 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7202 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7203 0, 1, 0,
7204 "Returns the number of color cells of the display DISPLAY.\n\
7205 The optional argument DISPLAY specifies which display to ask about.\n\
7206 DISPLAY should be either a frame or a display name (a string).\n\
7207 If omitted or nil, that stands for the selected frame's display.")
7208 (display)
7209 Lisp_Object display;
7211 struct w32_display_info *dpyinfo = check_x_display_info (display);
7212 HDC hdc;
7213 int cap;
7215 hdc = GetDC (dpyinfo->root_window);
7216 if (dpyinfo->has_palette)
7217 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7218 else
7219 cap = GetDeviceCaps (hdc,NUMCOLORS);
7221 if (cap < 0)
7222 cap = 1 << (dpyinfo->n_planes * dpyinfo->n_cbits);
7224 ReleaseDC (dpyinfo->root_window, hdc);
7226 return make_number (cap);
7229 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7230 Sx_server_max_request_size,
7231 0, 1, 0,
7232 "Returns the maximum request size of the server of display DISPLAY.\n\
7233 The optional argument DISPLAY specifies which display to ask about.\n\
7234 DISPLAY should be either a frame or a display name (a string).\n\
7235 If omitted or nil, that stands for the selected frame's display.")
7236 (display)
7237 Lisp_Object display;
7239 struct w32_display_info *dpyinfo = check_x_display_info (display);
7241 return make_number (1);
7244 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7245 "Returns the vendor ID string of the W32 system (Microsoft).\n\
7246 The optional argument DISPLAY specifies which display to ask about.\n\
7247 DISPLAY should be either a frame or a display name (a string).\n\
7248 If omitted or nil, that stands for the selected frame's display.")
7249 (display)
7250 Lisp_Object display;
7252 return build_string ("Microsoft Corp.");
7255 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7256 "Returns the version numbers of the server of display DISPLAY.\n\
7257 The value is a list of three integers: the major and minor\n\
7258 version numbers, and the vendor-specific release\n\
7259 number. See also the function `x-server-vendor'.\n\n\
7260 The optional argument DISPLAY specifies which display to ask about.\n\
7261 DISPLAY should be either a frame or a display name (a string).\n\
7262 If omitted or nil, that stands for the selected frame's display.")
7263 (display)
7264 Lisp_Object display;
7266 return Fcons (make_number (w32_major_version),
7267 Fcons (make_number (w32_minor_version),
7268 Fcons (make_number (w32_build_number), Qnil)));
7271 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7272 "Returns the number of screens on the server of display DISPLAY.\n\
7273 The optional argument DISPLAY specifies which display to ask about.\n\
7274 DISPLAY should be either a frame or a display name (a string).\n\
7275 If omitted or nil, that stands for the selected frame's display.")
7276 (display)
7277 Lisp_Object display;
7279 return make_number (1);
7282 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
7283 "Returns the height in millimeters of the X display DISPLAY.\n\
7284 The optional argument DISPLAY specifies which display to ask about.\n\
7285 DISPLAY should be either a frame or a display name (a string).\n\
7286 If omitted or nil, that stands for the selected frame's display.")
7287 (display)
7288 Lisp_Object display;
7290 struct w32_display_info *dpyinfo = check_x_display_info (display);
7291 HDC hdc;
7292 int cap;
7294 hdc = GetDC (dpyinfo->root_window);
7296 cap = GetDeviceCaps (hdc, VERTSIZE);
7298 ReleaseDC (dpyinfo->root_window, hdc);
7300 return make_number (cap);
7303 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7304 "Returns the width in millimeters of the X display DISPLAY.\n\
7305 The optional argument DISPLAY specifies which display to ask about.\n\
7306 DISPLAY should be either a frame or a display name (a string).\n\
7307 If omitted or nil, that stands for the selected frame's display.")
7308 (display)
7309 Lisp_Object display;
7311 struct w32_display_info *dpyinfo = check_x_display_info (display);
7313 HDC hdc;
7314 int cap;
7316 hdc = GetDC (dpyinfo->root_window);
7318 cap = GetDeviceCaps (hdc, HORZSIZE);
7320 ReleaseDC (dpyinfo->root_window, hdc);
7322 return make_number (cap);
7325 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7326 Sx_display_backing_store, 0, 1, 0,
7327 "Returns an indication of whether display DISPLAY does backing store.\n\
7328 The value may be `always', `when-mapped', or `not-useful'.\n\
7329 The optional argument DISPLAY specifies which display to ask about.\n\
7330 DISPLAY should be either a frame or a display name (a string).\n\
7331 If omitted or nil, that stands for the selected frame's display.")
7332 (display)
7333 Lisp_Object display;
7335 return intern ("not-useful");
7338 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7339 Sx_display_visual_class, 0, 1, 0,
7340 "Returns the visual class of the display DISPLAY.\n\
7341 The value is one of the symbols `static-gray', `gray-scale',\n\
7342 `static-color', `pseudo-color', `true-color', or `direct-color'.\n\n\
7343 The optional argument DISPLAY specifies which display to ask about.\n\
7344 DISPLAY should be either a frame or a display name (a string).\n\
7345 If omitted or nil, that stands for the selected frame's display.")
7346 (display)
7347 Lisp_Object display;
7349 struct w32_display_info *dpyinfo = check_x_display_info (display);
7350 Lisp_Object result = Qnil;
7352 if (dpyinfo->has_palette)
7353 result = intern ("pseudo-color");
7354 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
7355 result = intern ("static-grey");
7356 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
7357 result = intern ("static-color");
7358 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
7359 result = intern ("true-color");
7361 return result;
7364 DEFUN ("x-display-save-under", Fx_display_save_under,
7365 Sx_display_save_under, 0, 1, 0,
7366 "Returns t if the display DISPLAY supports the save-under feature.\n\
7367 The optional argument DISPLAY specifies which display to ask about.\n\
7368 DISPLAY should be either a frame or a display name (a string).\n\
7369 If omitted or nil, that stands for the selected frame's display.")
7370 (display)
7371 Lisp_Object display;
7373 return Qnil;
7377 x_pixel_width (f)
7378 register struct frame *f;
7380 return PIXEL_WIDTH (f);
7384 x_pixel_height (f)
7385 register struct frame *f;
7387 return PIXEL_HEIGHT (f);
7391 x_char_width (f)
7392 register struct frame *f;
7394 return FONT_WIDTH (f->output_data.w32->font);
7398 x_char_height (f)
7399 register struct frame *f;
7401 return f->output_data.w32->line_height;
7405 x_screen_planes (f)
7406 register struct frame *f;
7408 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7411 /* Return the display structure for the display named NAME.
7412 Open a new connection if necessary. */
7414 struct w32_display_info *
7415 x_display_info_for_name (name)
7416 Lisp_Object name;
7418 Lisp_Object names;
7419 struct w32_display_info *dpyinfo;
7421 CHECK_STRING (name, 0);
7423 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7424 dpyinfo;
7425 dpyinfo = dpyinfo->next, names = XCDR (names))
7427 Lisp_Object tem;
7428 tem = Fstring_equal (XCAR (XCAR (names)), name);
7429 if (!NILP (tem))
7430 return dpyinfo;
7433 /* Use this general default value to start with. */
7434 Vx_resource_name = Vinvocation_name;
7436 validate_x_resource_name ();
7438 dpyinfo = w32_term_init (name, (unsigned char *)0,
7439 (char *) XSTRING (Vx_resource_name)->data);
7441 if (dpyinfo == 0)
7442 error ("Cannot connect to server %s", XSTRING (name)->data);
7444 w32_in_use = 1;
7445 XSETFASTINT (Vwindow_system_version, 3);
7447 return dpyinfo;
7450 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7451 1, 3, 0, "Open a connection to a server.\n\
7452 DISPLAY is the name of the display to connect to.\n\
7453 Optional second arg XRM-STRING is a string of resources in xrdb format.\n\
7454 If the optional third arg MUST-SUCCEED is non-nil,\n\
7455 terminate Emacs if we can't open the connection.")
7456 (display, xrm_string, must_succeed)
7457 Lisp_Object display, xrm_string, must_succeed;
7459 unsigned char *xrm_option;
7460 struct w32_display_info *dpyinfo;
7462 CHECK_STRING (display, 0);
7463 if (! NILP (xrm_string))
7464 CHECK_STRING (xrm_string, 1);
7466 if (! EQ (Vwindow_system, intern ("w32")))
7467 error ("Not using Microsoft Windows");
7469 /* Allow color mapping to be defined externally; first look in user's
7470 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
7472 Lisp_Object color_file;
7473 struct gcpro gcpro1;
7475 color_file = build_string("~/rgb.txt");
7477 GCPRO1 (color_file);
7479 if (NILP (Ffile_readable_p (color_file)))
7480 color_file =
7481 Fexpand_file_name (build_string ("rgb.txt"),
7482 Fsymbol_value (intern ("data-directory")));
7484 Vw32_color_map = Fw32_load_color_file (color_file);
7486 UNGCPRO;
7488 if (NILP (Vw32_color_map))
7489 Vw32_color_map = Fw32_default_color_map ();
7491 if (! NILP (xrm_string))
7492 xrm_option = (unsigned char *) XSTRING (xrm_string)->data;
7493 else
7494 xrm_option = (unsigned char *) 0;
7496 /* Use this general default value to start with. */
7497 /* First remove .exe suffix from invocation-name - it looks ugly. */
7499 char basename[ MAX_PATH ], *str;
7501 strcpy (basename, XSTRING (Vinvocation_name)->data);
7502 str = strrchr (basename, '.');
7503 if (str) *str = 0;
7504 Vinvocation_name = build_string (basename);
7506 Vx_resource_name = Vinvocation_name;
7508 validate_x_resource_name ();
7510 /* This is what opens the connection and sets x_current_display.
7511 This also initializes many symbols, such as those used for input. */
7512 dpyinfo = w32_term_init (display, xrm_option,
7513 (char *) XSTRING (Vx_resource_name)->data);
7515 if (dpyinfo == 0)
7517 if (!NILP (must_succeed))
7518 fatal ("Cannot connect to server %s.\n",
7519 XSTRING (display)->data);
7520 else
7521 error ("Cannot connect to server %s", XSTRING (display)->data);
7524 w32_in_use = 1;
7526 XSETFASTINT (Vwindow_system_version, 3);
7527 return Qnil;
7530 DEFUN ("x-close-connection", Fx_close_connection,
7531 Sx_close_connection, 1, 1, 0,
7532 "Close the connection to DISPLAY's server.\n\
7533 For DISPLAY, specify either a frame or a display name (a string).\n\
7534 If DISPLAY is nil, that stands for the selected frame's display.")
7535 (display)
7536 Lisp_Object display;
7538 struct w32_display_info *dpyinfo = check_x_display_info (display);
7539 int i;
7541 if (dpyinfo->reference_count > 0)
7542 error ("Display still has frames on it");
7544 BLOCK_INPUT;
7545 /* Free the fonts in the font table. */
7546 for (i = 0; i < dpyinfo->n_fonts; i++)
7547 if (dpyinfo->font_table[i].name)
7549 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
7550 xfree (dpyinfo->font_table[i].full_name);
7551 xfree (dpyinfo->font_table[i].name);
7552 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
7554 x_destroy_all_bitmaps (dpyinfo);
7556 x_delete_display (dpyinfo);
7557 UNBLOCK_INPUT;
7559 return Qnil;
7562 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
7563 "Return the list of display names that Emacs has connections to.")
7566 Lisp_Object tail, result;
7568 result = Qnil;
7569 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
7570 result = Fcons (XCAR (XCAR (tail)), result);
7572 return result;
7575 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7576 "If ON is non-nil, report errors as soon as the erring request is made.\n\
7577 If ON is nil, allow buffering of requests.\n\
7578 This is a noop on W32 systems.\n\
7579 The optional second argument DISPLAY specifies which display to act on.\n\
7580 DISPLAY should be either a frame or a display name (a string).\n\
7581 If DISPLAY is omitted or nil, that stands for the selected frame's display.")
7582 (on, display)
7583 Lisp_Object display, on;
7585 return Qnil;
7590 /***********************************************************************
7591 Image types
7592 ***********************************************************************/
7594 /* Value is the number of elements of vector VECTOR. */
7596 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
7598 /* List of supported image types. Use define_image_type to add new
7599 types. Use lookup_image_type to find a type for a given symbol. */
7601 static struct image_type *image_types;
7603 /* The symbol `image' which is the car of the lists used to represent
7604 images in Lisp. */
7606 extern Lisp_Object Qimage;
7608 /* The symbol `xbm' which is used as the type symbol for XBM images. */
7610 Lisp_Object Qxbm;
7612 /* Keywords. */
7614 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
7615 extern Lisp_Object QCdata;
7616 Lisp_Object QCtype, QCascent, QCmargin, QCrelief;
7617 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
7618 Lisp_Object QCindex;
7620 /* Other symbols. */
7622 Lisp_Object Qlaplace;
7624 /* Time in seconds after which images should be removed from the cache
7625 if not displayed. */
7627 Lisp_Object Vimage_cache_eviction_delay;
7629 /* Function prototypes. */
7631 static void define_image_type P_ ((struct image_type *type));
7632 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
7633 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
7634 static void x_laplace P_ ((struct frame *, struct image *));
7635 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
7636 Lisp_Object));
7639 /* Define a new image type from TYPE. This adds a copy of TYPE to
7640 image_types and adds the symbol *TYPE->type to Vimage_types. */
7642 static void
7643 define_image_type (type)
7644 struct image_type *type;
7646 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
7647 The initialized data segment is read-only. */
7648 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
7649 bcopy (type, p, sizeof *p);
7650 p->next = image_types;
7651 image_types = p;
7652 Vimage_types = Fcons (*p->type, Vimage_types);
7656 /* Look up image type SYMBOL, and return a pointer to its image_type
7657 structure. Value is null if SYMBOL is not a known image type. */
7659 static INLINE struct image_type *
7660 lookup_image_type (symbol)
7661 Lisp_Object symbol;
7663 struct image_type *type;
7665 for (type = image_types; type; type = type->next)
7666 if (EQ (symbol, *type->type))
7667 break;
7669 return type;
7673 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
7674 valid image specification is a list whose car is the symbol
7675 `image', and whose rest is a property list. The property list must
7676 contain a value for key `:type'. That value must be the name of a
7677 supported image type. The rest of the property list depends on the
7678 image type. */
7681 valid_image_p (object)
7682 Lisp_Object object;
7684 int valid_p = 0;
7686 if (CONSP (object) && EQ (XCAR (object), Qimage))
7688 Lisp_Object symbol = Fplist_get (XCDR (object), QCtype);
7689 struct image_type *type = lookup_image_type (symbol);
7691 if (type)
7692 valid_p = type->valid_p (object);
7695 return valid_p;
7699 /* Log error message with format string FORMAT and argument ARG.
7700 Signaling an error, e.g. when an image cannot be loaded, is not a
7701 good idea because this would interrupt redisplay, and the error
7702 message display would lead to another redisplay. This function
7703 therefore simply displays a message. */
7705 static void
7706 image_error (format, arg1, arg2)
7707 char *format;
7708 Lisp_Object arg1, arg2;
7710 add_to_log (format, arg1, arg2);
7715 /***********************************************************************
7716 Image specifications
7717 ***********************************************************************/
7719 enum image_value_type
7721 IMAGE_DONT_CHECK_VALUE_TYPE,
7722 IMAGE_STRING_VALUE,
7723 IMAGE_SYMBOL_VALUE,
7724 IMAGE_POSITIVE_INTEGER_VALUE,
7725 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
7726 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
7727 IMAGE_ASCENT_VALUE,
7728 IMAGE_INTEGER_VALUE,
7729 IMAGE_FUNCTION_VALUE,
7730 IMAGE_NUMBER_VALUE,
7731 IMAGE_BOOL_VALUE
7734 /* Structure used when parsing image specifications. */
7736 struct image_keyword
7738 /* Name of keyword. */
7739 char *name;
7741 /* The type of value allowed. */
7742 enum image_value_type type;
7744 /* Non-zero means key must be present. */
7745 int mandatory_p;
7747 /* Used to recognize duplicate keywords in a property list. */
7748 int count;
7750 /* The value that was found. */
7751 Lisp_Object value;
7755 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7756 int, Lisp_Object));
7757 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7760 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
7761 has the format (image KEYWORD VALUE ...). One of the keyword/
7762 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7763 image_keywords structures of size NKEYWORDS describing other
7764 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7766 static int
7767 parse_image_spec (spec, keywords, nkeywords, type)
7768 Lisp_Object spec;
7769 struct image_keyword *keywords;
7770 int nkeywords;
7771 Lisp_Object type;
7773 int i;
7774 Lisp_Object plist;
7776 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7777 return 0;
7779 plist = XCDR (spec);
7780 while (CONSP (plist))
7782 Lisp_Object key, value;
7784 /* First element of a pair must be a symbol. */
7785 key = XCAR (plist);
7786 plist = XCDR (plist);
7787 if (!SYMBOLP (key))
7788 return 0;
7790 /* There must follow a value. */
7791 if (!CONSP (plist))
7792 return 0;
7793 value = XCAR (plist);
7794 plist = XCDR (plist);
7796 /* Find key in KEYWORDS. Error if not found. */
7797 for (i = 0; i < nkeywords; ++i)
7798 if (strcmp (keywords[i].name, XSYMBOL (key)->name->data) == 0)
7799 break;
7801 if (i == nkeywords)
7802 continue;
7804 /* Record that we recognized the keyword. If a keywords
7805 was found more than once, it's an error. */
7806 keywords[i].value = value;
7807 ++keywords[i].count;
7809 if (keywords[i].count > 1)
7810 return 0;
7812 /* Check type of value against allowed type. */
7813 switch (keywords[i].type)
7815 case IMAGE_STRING_VALUE:
7816 if (!STRINGP (value))
7817 return 0;
7818 break;
7820 case IMAGE_SYMBOL_VALUE:
7821 if (!SYMBOLP (value))
7822 return 0;
7823 break;
7825 case IMAGE_POSITIVE_INTEGER_VALUE:
7826 if (!INTEGERP (value) || XINT (value) <= 0)
7827 return 0;
7828 break;
7830 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
7831 if (INTEGERP (value) && XINT (value) >= 0)
7832 break;
7833 if (CONSP (value)
7834 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
7835 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
7836 break;
7837 return 0;
7839 case IMAGE_ASCENT_VALUE:
7840 if (SYMBOLP (value) && EQ (value, Qcenter))
7841 break;
7842 else if (INTEGERP (value)
7843 && XINT (value) >= 0
7844 && XINT (value) <= 100)
7845 break;
7846 return 0;
7848 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7849 if (!INTEGERP (value) || XINT (value) < 0)
7850 return 0;
7851 break;
7853 case IMAGE_DONT_CHECK_VALUE_TYPE:
7854 break;
7856 case IMAGE_FUNCTION_VALUE:
7857 value = indirect_function (value);
7858 if (SUBRP (value)
7859 || COMPILEDP (value)
7860 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7861 break;
7862 return 0;
7864 case IMAGE_NUMBER_VALUE:
7865 if (!INTEGERP (value) && !FLOATP (value))
7866 return 0;
7867 break;
7869 case IMAGE_INTEGER_VALUE:
7870 if (!INTEGERP (value))
7871 return 0;
7872 break;
7874 case IMAGE_BOOL_VALUE:
7875 if (!NILP (value) && !EQ (value, Qt))
7876 return 0;
7877 break;
7879 default:
7880 abort ();
7881 break;
7884 if (EQ (key, QCtype) && !EQ (type, value))
7885 return 0;
7888 /* Check that all mandatory fields are present. */
7889 for (i = 0; i < nkeywords; ++i)
7890 if (keywords[i].mandatory_p && keywords[i].count == 0)
7891 return 0;
7893 return NILP (plist);
7897 /* Return the value of KEY in image specification SPEC. Value is nil
7898 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7899 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7901 static Lisp_Object
7902 image_spec_value (spec, key, found)
7903 Lisp_Object spec, key;
7904 int *found;
7906 Lisp_Object tail;
7908 xassert (valid_image_p (spec));
7910 for (tail = XCDR (spec);
7911 CONSP (tail) && CONSP (XCDR (tail));
7912 tail = XCDR (XCDR (tail)))
7914 if (EQ (XCAR (tail), key))
7916 if (found)
7917 *found = 1;
7918 return XCAR (XCDR (tail));
7922 if (found)
7923 *found = 0;
7924 return Qnil;
7930 /***********************************************************************
7931 Image type independent image structures
7932 ***********************************************************************/
7934 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7935 static void free_image P_ ((struct frame *f, struct image *img));
7938 /* Allocate and return a new image structure for image specification
7939 SPEC. SPEC has a hash value of HASH. */
7941 static struct image *
7942 make_image (spec, hash)
7943 Lisp_Object spec;
7944 unsigned hash;
7946 struct image *img = (struct image *) xmalloc (sizeof *img);
7948 xassert (valid_image_p (spec));
7949 bzero (img, sizeof *img);
7950 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7951 xassert (img->type != NULL);
7952 img->spec = spec;
7953 img->data.lisp_val = Qnil;
7954 img->ascent = DEFAULT_IMAGE_ASCENT;
7955 img->hash = hash;
7956 return img;
7960 /* Free image IMG which was used on frame F, including its resources. */
7962 static void
7963 free_image (f, img)
7964 struct frame *f;
7965 struct image *img;
7967 if (img)
7969 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7971 /* Remove IMG from the hash table of its cache. */
7972 if (img->prev)
7973 img->prev->next = img->next;
7974 else
7975 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7977 if (img->next)
7978 img->next->prev = img->prev;
7980 c->images[img->id] = NULL;
7982 /* Free resources, then free IMG. */
7983 img->type->free (f, img);
7984 xfree (img);
7989 /* Prepare image IMG for display on frame F. Must be called before
7990 drawing an image. */
7992 void
7993 prepare_image_for_display (f, img)
7994 struct frame *f;
7995 struct image *img;
7997 EMACS_TIME t;
7999 /* We're about to display IMG, so set its timestamp to `now'. */
8000 EMACS_GET_TIME (t);
8001 img->timestamp = EMACS_SECS (t);
8003 /* If IMG doesn't have a pixmap yet, load it now, using the image
8004 type dependent loader function. */
8005 if (img->pixmap == 0 && !img->load_failed_p)
8006 img->load_failed_p = img->type->load (f, img) == 0;
8010 /* Value is the number of pixels for the ascent of image IMG when
8011 drawn in face FACE. */
8014 image_ascent (img, face)
8015 struct image *img;
8016 struct face *face;
8018 int height = img->height + img->vmargin;
8019 int ascent;
8021 if (img->ascent == CENTERED_IMAGE_ASCENT)
8023 if (face->font)
8024 ascent = height / 2 - (FONT_DESCENT(face->font)
8025 - FONT_BASE(face->font)) / 2;
8026 else
8027 ascent = height / 2;
8029 else
8030 ascent = height * img->ascent / 100.0;
8032 return ascent;
8037 /***********************************************************************
8038 Helper functions for X image types
8039 ***********************************************************************/
8041 static void x_clear_image P_ ((struct frame *f, struct image *img));
8042 static unsigned long x_alloc_image_color P_ ((struct frame *f,
8043 struct image *img,
8044 Lisp_Object color_name,
8045 unsigned long dflt));
8047 /* Free X resources of image IMG which is used on frame F. */
8049 static void
8050 x_clear_image (f, img)
8051 struct frame *f;
8052 struct image *img;
8054 #if 0 /* TODO: W32 image support */
8056 if (img->pixmap)
8058 BLOCK_INPUT;
8059 XFreePixmap (NULL, img->pixmap);
8060 img->pixmap = 0;
8061 UNBLOCK_INPUT;
8064 if (img->ncolors)
8066 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8068 /* If display has an immutable color map, freeing colors is not
8069 necessary and some servers don't allow it. So don't do it. */
8070 if (class != StaticColor
8071 && class != StaticGray
8072 && class != TrueColor)
8074 Colormap cmap;
8075 BLOCK_INPUT;
8076 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8077 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8078 img->ncolors, 0);
8079 UNBLOCK_INPUT;
8082 xfree (img->colors);
8083 img->colors = NULL;
8084 img->ncolors = 0;
8086 #endif
8090 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8091 cannot be allocated, use DFLT. Add a newly allocated color to
8092 IMG->colors, so that it can be freed again. Value is the pixel
8093 color. */
8095 static unsigned long
8096 x_alloc_image_color (f, img, color_name, dflt)
8097 struct frame *f;
8098 struct image *img;
8099 Lisp_Object color_name;
8100 unsigned long dflt;
8102 #if 0 /* TODO: allocing colors. */
8103 XColor color;
8104 unsigned long result;
8106 xassert (STRINGP (color_name));
8108 if (w32_defined_color (f, XSTRING (color_name)->data, &color, 1))
8110 /* This isn't called frequently so we get away with simply
8111 reallocating the color vector to the needed size, here. */
8112 ++img->ncolors;
8113 img->colors =
8114 (unsigned long *) xrealloc (img->colors,
8115 img->ncolors * sizeof *img->colors);
8116 img->colors[img->ncolors - 1] = color.pixel;
8117 result = color.pixel;
8119 else
8120 result = dflt;
8121 return result;
8122 #endif
8123 return 0;
8128 /***********************************************************************
8129 Image Cache
8130 ***********************************************************************/
8132 static void cache_image P_ ((struct frame *f, struct image *img));
8135 /* Return a new, initialized image cache that is allocated from the
8136 heap. Call free_image_cache to free an image cache. */
8138 struct image_cache *
8139 make_image_cache ()
8141 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8142 int size;
8144 bzero (c, sizeof *c);
8145 c->size = 50;
8146 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8147 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8148 c->buckets = (struct image **) xmalloc (size);
8149 bzero (c->buckets, size);
8150 return c;
8154 /* Free image cache of frame F. Be aware that X frames share images
8155 caches. */
8157 void
8158 free_image_cache (f)
8159 struct frame *f;
8161 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8162 if (c)
8164 int i;
8166 /* Cache should not be referenced by any frame when freed. */
8167 xassert (c->refcount == 0);
8169 for (i = 0; i < c->used; ++i)
8170 free_image (f, c->images[i]);
8171 xfree (c->images);
8172 xfree (c);
8173 xfree (c->buckets);
8174 FRAME_X_IMAGE_CACHE (f) = NULL;
8179 /* Clear image cache of frame F. FORCE_P non-zero means free all
8180 images. FORCE_P zero means clear only images that haven't been
8181 displayed for some time. Should be called from time to time to
8182 reduce the number of loaded images. If image-eviction-seconds is
8183 non-nil, this frees images in the cache which weren't displayed for
8184 at least that many seconds. */
8186 void
8187 clear_image_cache (f, force_p)
8188 struct frame *f;
8189 int force_p;
8191 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8193 if (c && INTEGERP (Vimage_cache_eviction_delay))
8195 EMACS_TIME t;
8196 unsigned long old;
8197 int i, any_freed_p = 0;
8199 EMACS_GET_TIME (t);
8200 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8202 for (i = 0; i < c->used; ++i)
8204 struct image *img = c->images[i];
8205 if (img != NULL
8206 && (force_p
8207 || (img->timestamp > old)))
8209 free_image (f, img);
8210 any_freed_p = 1;
8214 /* We may be clearing the image cache because, for example,
8215 Emacs was iconified for a longer period of time. In that
8216 case, current matrices may still contain references to
8217 images freed above. So, clear these matrices. */
8218 if (any_freed_p)
8220 clear_current_matrices (f);
8221 ++windows_or_buffers_changed;
8227 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
8228 0, 1, 0,
8229 "Clear the image cache of FRAME.\n\
8230 FRAME nil or omitted means use the selected frame.\n\
8231 FRAME t means clear the image caches of all frames.")
8232 (frame)
8233 Lisp_Object frame;
8235 if (EQ (frame, Qt))
8237 Lisp_Object tail;
8239 FOR_EACH_FRAME (tail, frame)
8240 if (FRAME_W32_P (XFRAME (frame)))
8241 clear_image_cache (XFRAME (frame), 1);
8243 else
8244 clear_image_cache (check_x_frame (frame), 1);
8246 return Qnil;
8250 /* Return the id of image with Lisp specification SPEC on frame F.
8251 SPEC must be a valid Lisp image specification (see valid_image_p). */
8254 lookup_image (f, spec)
8255 struct frame *f;
8256 Lisp_Object spec;
8258 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8259 struct image *img;
8260 int i;
8261 unsigned hash;
8262 struct gcpro gcpro1;
8263 EMACS_TIME now;
8265 /* F must be a window-system frame, and SPEC must be a valid image
8266 specification. */
8267 xassert (FRAME_WINDOW_P (f));
8268 xassert (valid_image_p (spec));
8270 GCPRO1 (spec);
8272 /* Look up SPEC in the hash table of the image cache. */
8273 hash = sxhash (spec, 0);
8274 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
8276 for (img = c->buckets[i]; img; img = img->next)
8277 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
8278 break;
8280 /* If not found, create a new image and cache it. */
8281 if (img == NULL)
8283 BLOCK_INPUT;
8284 img = make_image (spec, hash);
8285 cache_image (f, img);
8286 img->load_failed_p = img->type->load (f, img) == 0;
8288 /* If we can't load the image, and we don't have a width and
8289 height, use some arbitrary width and height so that we can
8290 draw a rectangle for it. */
8291 if (img->load_failed_p)
8293 Lisp_Object value;
8295 value = image_spec_value (spec, QCwidth, NULL);
8296 img->width = (INTEGERP (value)
8297 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
8298 value = image_spec_value (spec, QCheight, NULL);
8299 img->height = (INTEGERP (value)
8300 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
8302 else
8304 /* Handle image type independent image attributes
8305 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF'. */
8306 Lisp_Object ascent, margin, relief;
8308 ascent = image_spec_value (spec, QCascent, NULL);
8309 if (INTEGERP (ascent))
8310 img->ascent = XFASTINT (ascent);
8311 else if (EQ (ascent, Qcenter))
8312 img->ascent = CENTERED_IMAGE_ASCENT;
8314 margin = image_spec_value (spec, QCmargin, NULL);
8315 if (INTEGERP (margin) && XINT (margin) >= 0)
8316 img->vmargin = img->hmargin = XFASTINT (margin);
8317 else if (CONSP (margin) && INTEGERP (XCAR (margin))
8318 && INTEGERP (XCDR (margin)))
8320 if (XINT (XCAR (margin)) > 0)
8321 img->hmargin = XFASTINT (XCAR (margin));
8322 if (XINT (XCDR (margin)) > 0)
8323 img->vmargin = XFASTINT (XCDR (margin));
8326 relief = image_spec_value (spec, QCrelief, NULL);
8327 if (INTEGERP (relief))
8329 img->relief = XINT (relief);
8330 img->hmargin += abs (img->relief);
8331 img->vmargin += abs (img->relief);
8334 #if 0 /* TODO: image mask and algorithm. */
8335 /* Manipulation of the image's mask. */
8336 if (img->pixmap)
8338 /* `:heuristic-mask t'
8339 `:mask heuristic'
8340 means build a mask heuristically.
8341 `:heuristic-mask (R G B)'
8342 `:mask (heuristic (R G B))'
8343 means build a mask from color (R G B) in the
8344 image.
8345 `:mask nil'
8346 means remove a mask, if any. */
8348 Lisp_Object mask;
8350 mask = image_spec_value (spec, QCheuristic_mask, NULL);
8351 if (!NILP (mask))
8352 x_build_heuristic_mask (f, img, mask);
8353 else
8355 int found_p;
8357 mask = image_spec_value (spec, QCmask, &found_p);
8359 if (EQ (mask, Qheuristic))
8360 x_build_heuristic_mask (f, img, Qt);
8361 else if (CONSP (mask)
8362 && EQ (XCAR (mask), Qheuristic))
8364 if (CONSP (XCDR (mask)))
8365 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
8366 else
8367 x_build_heuristic_mask (f, img, XCDR (mask));
8369 else if (NILP (mask) && found_p && img->mask)
8371 XFreePixmap (FRAME_X_DISPLAY (f), img->mask);
8372 img->mask = None;
8377 /* Should we apply an image transformation algorithm? */
8378 if (img->pixmap)
8380 Lisp_Object conversion;
8382 algorithm = image_spec_value (spec, QCconversion, NULL);
8383 if (EQ (conversion, Qdisabled))
8384 x_disable_image (f, img);
8385 else if (EQ (conversion, Qlaplace))
8386 x_laplace (f, img);
8387 else if (EQ (conversion, Qemboss))
8388 x_emboss (f, img);
8389 else if (CONSP (conversion)
8390 && EQ (XCAR (conversion), Qedge_detection))
8392 Lisp_Object tem;
8393 tem = XCDR (conversion);
8394 if (CONSP (tem))
8395 x_edge_detection (f, img,
8396 Fplist_get (tem, QCmatrix),
8397 Fplist_get (tem, QCcolor_adjustment));
8400 #endif /* TODO. */
8402 UNBLOCK_INPUT;
8403 xassert (!interrupt_input_blocked);
8406 /* We're using IMG, so set its timestamp to `now'. */
8407 EMACS_GET_TIME (now);
8408 img->timestamp = EMACS_SECS (now);
8410 UNGCPRO;
8412 /* Value is the image id. */
8413 return img->id;
8417 /* Cache image IMG in the image cache of frame F. */
8419 static void
8420 cache_image (f, img)
8421 struct frame *f;
8422 struct image *img;
8424 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8425 int i;
8427 /* Find a free slot in c->images. */
8428 for (i = 0; i < c->used; ++i)
8429 if (c->images[i] == NULL)
8430 break;
8432 /* If no free slot found, maybe enlarge c->images. */
8433 if (i == c->used && c->used == c->size)
8435 c->size *= 2;
8436 c->images = (struct image **) xrealloc (c->images,
8437 c->size * sizeof *c->images);
8440 /* Add IMG to c->images, and assign IMG an id. */
8441 c->images[i] = img;
8442 img->id = i;
8443 if (i == c->used)
8444 ++c->used;
8446 /* Add IMG to the cache's hash table. */
8447 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8448 img->next = c->buckets[i];
8449 if (img->next)
8450 img->next->prev = img;
8451 img->prev = NULL;
8452 c->buckets[i] = img;
8456 /* Call FN on every image in the image cache of frame F. Used to mark
8457 Lisp Objects in the image cache. */
8459 void
8460 forall_images_in_image_cache (f, fn)
8461 struct frame *f;
8462 void (*fn) P_ ((struct image *img));
8464 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8466 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8467 if (c)
8469 int i;
8470 for (i = 0; i < c->used; ++i)
8471 if (c->images[i])
8472 fn (c->images[i]);
8479 /***********************************************************************
8480 W32 support code
8481 ***********************************************************************/
8483 #if 0 /* TODO: W32 specific image code. */
8485 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8486 XImage **, Pixmap *));
8487 static void x_destroy_x_image P_ ((XImage *));
8488 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8491 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8492 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8493 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
8494 via xmalloc. Print error messages via image_error if an error
8495 occurs. Value is non-zero if successful. */
8497 static int
8498 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8499 struct frame *f;
8500 int width, height, depth;
8501 XImage **ximg;
8502 Pixmap *pixmap;
8504 #if 0 /* TODO: Image support for W32 */
8505 Display *display = FRAME_W32_DISPLAY (f);
8506 Screen *screen = FRAME_X_SCREEN (f);
8507 Window window = FRAME_W32_WINDOW (f);
8509 xassert (interrupt_input_blocked);
8511 if (depth <= 0)
8512 depth = DefaultDepthOfScreen (screen);
8513 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
8514 depth, ZPixmap, 0, NULL, width, height,
8515 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
8516 if (*ximg == NULL)
8518 image_error ("Unable to allocate X image", Qnil, Qnil);
8519 return 0;
8522 /* Allocate image raster. */
8523 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
8525 /* Allocate a pixmap of the same size. */
8526 *pixmap = XCreatePixmap (display, window, width, height, depth);
8527 if (*pixmap == 0)
8529 x_destroy_x_image (*ximg);
8530 *ximg = NULL;
8531 image_error ("Unable to create X pixmap", Qnil, Qnil);
8532 return 0;
8534 #endif
8535 return 1;
8539 /* Destroy XImage XIMG. Free XIMG->data. */
8541 static void
8542 x_destroy_x_image (ximg)
8543 XImage *ximg;
8545 xassert (interrupt_input_blocked);
8546 if (ximg)
8548 xfree (ximg->data);
8549 ximg->data = NULL;
8550 XDestroyImage (ximg);
8555 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8556 are width and height of both the image and pixmap. */
8558 static void
8559 x_put_x_image (f, ximg, pixmap, width, height)
8560 struct frame *f;
8561 XImage *ximg;
8562 Pixmap pixmap;
8564 GC gc;
8566 xassert (interrupt_input_blocked);
8567 gc = XCreateGC (NULL, pixmap, 0, NULL);
8568 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
8569 XFreeGC (NULL, gc);
8572 #endif
8575 /***********************************************************************
8576 Searching files
8577 ***********************************************************************/
8579 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
8581 /* Find image file FILE. Look in data-directory, then
8582 x-bitmap-file-path. Value is the full name of the file found, or
8583 nil if not found. */
8585 static Lisp_Object
8586 x_find_image_file (file)
8587 Lisp_Object file;
8589 Lisp_Object file_found, search_path;
8590 struct gcpro gcpro1, gcpro2;
8591 int fd;
8593 file_found = Qnil;
8594 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8595 GCPRO2 (file_found, search_path);
8597 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
8598 fd = openp (search_path, file, "", &file_found, 0);
8600 if (fd == -1)
8601 file_found = Qnil;
8602 else
8603 close (fd);
8605 UNGCPRO;
8606 return file_found;
8611 /***********************************************************************
8612 XBM images
8613 ***********************************************************************/
8615 static int xbm_load P_ ((struct frame *f, struct image *img));
8616 static int xbm_load_image_from_file P_ ((struct frame *f, struct image *img,
8617 Lisp_Object file));
8618 static int xbm_image_p P_ ((Lisp_Object object));
8619 static int xbm_read_bitmap_file_data P_ ((char *, int *, int *,
8620 unsigned char **));
8623 /* Indices of image specification fields in xbm_format, below. */
8625 enum xbm_keyword_index
8627 XBM_TYPE,
8628 XBM_FILE,
8629 XBM_WIDTH,
8630 XBM_HEIGHT,
8631 XBM_DATA,
8632 XBM_FOREGROUND,
8633 XBM_BACKGROUND,
8634 XBM_ASCENT,
8635 XBM_MARGIN,
8636 XBM_RELIEF,
8637 XBM_ALGORITHM,
8638 XBM_HEURISTIC_MASK,
8639 XBM_LAST
8642 /* Vector of image_keyword structures describing the format
8643 of valid XBM image specifications. */
8645 static struct image_keyword xbm_format[XBM_LAST] =
8647 {":type", IMAGE_SYMBOL_VALUE, 1},
8648 {":file", IMAGE_STRING_VALUE, 0},
8649 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8650 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8651 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8652 {":foreground", IMAGE_STRING_VALUE, 0},
8653 {":background", IMAGE_STRING_VALUE, 0},
8654 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8655 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8656 {":relief", IMAGE_INTEGER_VALUE, 0},
8657 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8658 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8661 /* Structure describing the image type XBM. */
8663 static struct image_type xbm_type =
8665 &Qxbm,
8666 xbm_image_p,
8667 xbm_load,
8668 x_clear_image,
8669 NULL
8672 /* Tokens returned from xbm_scan. */
8674 enum xbm_token
8676 XBM_TK_IDENT = 256,
8677 XBM_TK_NUMBER
8681 /* Return non-zero if OBJECT is a valid XBM-type image specification.
8682 A valid specification is a list starting with the symbol `image'
8683 The rest of the list is a property list which must contain an
8684 entry `:type xbm..
8686 If the specification specifies a file to load, it must contain
8687 an entry `:file FILENAME' where FILENAME is a string.
8689 If the specification is for a bitmap loaded from memory it must
8690 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8691 WIDTH and HEIGHT are integers > 0. DATA may be:
8693 1. a string large enough to hold the bitmap data, i.e. it must
8694 have a size >= (WIDTH + 7) / 8 * HEIGHT
8696 2. a bool-vector of size >= WIDTH * HEIGHT
8698 3. a vector of strings or bool-vectors, one for each line of the
8699 bitmap.
8701 Both the file and data forms may contain the additional entries
8702 `:background COLOR' and `:foreground COLOR'. If not present,
8703 foreground and background of the frame on which the image is
8704 displayed, is used. */
8706 static int
8707 xbm_image_p (object)
8708 Lisp_Object object;
8710 struct image_keyword kw[XBM_LAST];
8712 bcopy (xbm_format, kw, sizeof kw);
8713 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8714 return 0;
8716 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8718 if (kw[XBM_FILE].count)
8720 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8721 return 0;
8723 else
8725 Lisp_Object data;
8726 int width, height;
8728 /* Entries for `:width', `:height' and `:data' must be present. */
8729 if (!kw[XBM_WIDTH].count
8730 || !kw[XBM_HEIGHT].count
8731 || !kw[XBM_DATA].count)
8732 return 0;
8734 data = kw[XBM_DATA].value;
8735 width = XFASTINT (kw[XBM_WIDTH].value);
8736 height = XFASTINT (kw[XBM_HEIGHT].value);
8738 /* Check type of data, and width and height against contents of
8739 data. */
8740 if (VECTORP (data))
8742 int i;
8744 /* Number of elements of the vector must be >= height. */
8745 if (XVECTOR (data)->size < height)
8746 return 0;
8748 /* Each string or bool-vector in data must be large enough
8749 for one line of the image. */
8750 for (i = 0; i < height; ++i)
8752 Lisp_Object elt = XVECTOR (data)->contents[i];
8754 if (STRINGP (elt))
8756 if (XSTRING (elt)->size
8757 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8758 return 0;
8760 else if (BOOL_VECTOR_P (elt))
8762 if (XBOOL_VECTOR (elt)->size < width)
8763 return 0;
8765 else
8766 return 0;
8769 else if (STRINGP (data))
8771 if (XSTRING (data)->size
8772 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8773 return 0;
8775 else if (BOOL_VECTOR_P (data))
8777 if (XBOOL_VECTOR (data)->size < width * height)
8778 return 0;
8780 else
8781 return 0;
8784 /* Baseline must be a value between 0 and 100 (a percentage). */
8785 if (kw[XBM_ASCENT].count
8786 && XFASTINT (kw[XBM_ASCENT].value) > 100)
8787 return 0;
8789 return 1;
8793 /* Scan a bitmap file. FP is the stream to read from. Value is
8794 either an enumerator from enum xbm_token, or a character for a
8795 single-character token, or 0 at end of file. If scanning an
8796 identifier, store the lexeme of the identifier in SVAL. If
8797 scanning a number, store its value in *IVAL. */
8799 static int
8800 xbm_scan (fp, sval, ival)
8801 FILE *fp;
8802 char *sval;
8803 int *ival;
8805 int c;
8807 /* Skip white space. */
8808 while ((c = fgetc (fp)) != EOF && isspace (c))
8811 if (c == EOF)
8812 c = 0;
8813 else if (isdigit (c))
8815 int value = 0, digit;
8817 if (c == '0')
8819 c = fgetc (fp);
8820 if (c == 'x' || c == 'X')
8822 while ((c = fgetc (fp)) != EOF)
8824 if (isdigit (c))
8825 digit = c - '0';
8826 else if (c >= 'a' && c <= 'f')
8827 digit = c - 'a' + 10;
8828 else if (c >= 'A' && c <= 'F')
8829 digit = c - 'A' + 10;
8830 else
8831 break;
8832 value = 16 * value + digit;
8835 else if (isdigit (c))
8837 value = c - '0';
8838 while ((c = fgetc (fp)) != EOF
8839 && isdigit (c))
8840 value = 8 * value + c - '0';
8843 else
8845 value = c - '0';
8846 while ((c = fgetc (fp)) != EOF
8847 && isdigit (c))
8848 value = 10 * value + c - '0';
8851 if (c != EOF)
8852 ungetc (c, fp);
8853 *ival = value;
8854 c = XBM_TK_NUMBER;
8856 else if (isalpha (c) || c == '_')
8858 *sval++ = c;
8859 while ((c = fgetc (fp)) != EOF
8860 && (isalnum (c) || c == '_'))
8861 *sval++ = c;
8862 *sval = 0;
8863 if (c != EOF)
8864 ungetc (c, fp);
8865 c = XBM_TK_IDENT;
8868 return c;
8872 /* Replacement for XReadBitmapFileData which isn't available under old
8873 X versions. FILE is the name of the bitmap file to read. Set
8874 *WIDTH and *HEIGHT to the width and height of the image. Return in
8875 *DATA the bitmap data allocated with xmalloc. Value is non-zero if
8876 successful. */
8878 static int
8879 xbm_read_bitmap_file_data (file, width, height, data)
8880 char *file;
8881 int *width, *height;
8882 unsigned char **data;
8884 FILE *fp;
8885 char buffer[BUFSIZ];
8886 int padding_p = 0;
8887 int v10 = 0;
8888 int bytes_per_line, i, nbytes;
8889 unsigned char *p;
8890 int value;
8891 int LA1;
8893 #define match() \
8894 LA1 = xbm_scan (fp, buffer, &value)
8896 #define expect(TOKEN) \
8897 if (LA1 != (TOKEN)) \
8898 goto failure; \
8899 else \
8900 match ()
8902 #define expect_ident(IDENT) \
8903 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8904 match (); \
8905 else \
8906 goto failure
8908 fp = fopen (file, "r");
8909 if (fp == NULL)
8910 return 0;
8912 *width = *height = -1;
8913 *data = NULL;
8914 LA1 = xbm_scan (fp, buffer, &value);
8916 /* Parse defines for width, height and hot-spots. */
8917 while (LA1 == '#')
8919 match ();
8920 expect_ident ("define");
8921 expect (XBM_TK_IDENT);
8923 if (LA1 == XBM_TK_NUMBER);
8925 char *p = strrchr (buffer, '_');
8926 p = p ? p + 1 : buffer;
8927 if (strcmp (p, "width") == 0)
8928 *width = value;
8929 else if (strcmp (p, "height") == 0)
8930 *height = value;
8932 expect (XBM_TK_NUMBER);
8935 if (*width < 0 || *height < 0)
8936 goto failure;
8938 /* Parse bits. Must start with `static'. */
8939 expect_ident ("static");
8940 if (LA1 == XBM_TK_IDENT)
8942 if (strcmp (buffer, "unsigned") == 0)
8944 match ();
8945 expect_ident ("char");
8947 else if (strcmp (buffer, "short") == 0)
8949 match ();
8950 v10 = 1;
8951 if (*width % 16 && *width % 16 < 9)
8952 padding_p = 1;
8954 else if (strcmp (buffer, "char") == 0)
8955 match ();
8956 else
8957 goto failure;
8959 else
8960 goto failure;
8962 expect (XBM_TK_IDENT);
8963 expect ('[');
8964 expect (']');
8965 expect ('=');
8966 expect ('{');
8968 bytes_per_line = (*width + 7) / 8 + padding_p;
8969 nbytes = bytes_per_line * *height;
8970 p = *data = (char *) xmalloc (nbytes);
8972 if (v10)
8975 for (i = 0; i < nbytes; i += 2)
8977 int val = value;
8978 expect (XBM_TK_NUMBER);
8980 *p++ = val;
8981 if (!padding_p || ((i + 2) % bytes_per_line))
8982 *p++ = value >> 8;
8984 if (LA1 == ',' || LA1 == '}')
8985 match ();
8986 else
8987 goto failure;
8990 else
8992 for (i = 0; i < nbytes; ++i)
8994 int val = value;
8995 expect (XBM_TK_NUMBER);
8997 *p++ = val;
8999 if (LA1 == ',' || LA1 == '}')
9000 match ();
9001 else
9002 goto failure;
9006 fclose (fp);
9007 return 1;
9009 failure:
9011 fclose (fp);
9012 if (*data)
9014 xfree (*data);
9015 *data = NULL;
9017 return 0;
9019 #undef match
9020 #undef expect
9021 #undef expect_ident
9025 /* Load XBM image IMG which will be displayed on frame F from file
9026 SPECIFIED_FILE. Value is non-zero if successful. */
9028 static int
9029 xbm_load_image_from_file (f, img, specified_file)
9030 struct frame *f;
9031 struct image *img;
9032 Lisp_Object specified_file;
9034 int rc;
9035 unsigned char *data;
9036 int success_p = 0;
9037 Lisp_Object file;
9038 struct gcpro gcpro1;
9040 xassert (STRINGP (specified_file));
9041 file = Qnil;
9042 GCPRO1 (file);
9044 file = x_find_image_file (specified_file);
9045 if (!STRINGP (file))
9047 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9048 UNGCPRO;
9049 return 0;
9052 rc = xbm_read_bitmap_file_data (XSTRING (file)->data, &img->width,
9053 &img->height, &data);
9054 if (rc)
9056 int depth = one_w32_display_info.n_cbits;
9057 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9058 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9059 Lisp_Object value;
9061 xassert (img->width > 0 && img->height > 0);
9063 /* Get foreground and background colors, maybe allocate colors. */
9064 value = image_spec_value (img->spec, QCforeground, NULL);
9065 if (!NILP (value))
9066 foreground = x_alloc_image_color (f, img, value, foreground);
9068 value = image_spec_value (img->spec, QCbackground, NULL);
9069 if (!NILP (value))
9070 background = x_alloc_image_color (f, img, value, background);
9072 #if 0 /* TODO : Port image display to W32 */
9073 BLOCK_INPUT;
9074 img->pixmap
9075 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
9076 FRAME_W32_WINDOW (f),
9077 data,
9078 img->width, img->height,
9079 foreground, background,
9080 depth);
9081 xfree (data);
9083 if (img->pixmap == 0)
9085 x_clear_image (f, img);
9086 image_error ("Unable to create X pixmap for `%s'", file, Qnil);
9088 else
9089 success_p = 1;
9091 UNBLOCK_INPUT;
9092 #endif
9094 else
9095 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
9097 UNGCPRO;
9098 return success_p;
9102 /* Fill image IMG which is used on frame F with pixmap data. Value is
9103 non-zero if successful. */
9105 static int
9106 xbm_load (f, img)
9107 struct frame *f;
9108 struct image *img;
9110 int success_p = 0;
9111 Lisp_Object file_name;
9113 xassert (xbm_image_p (img->spec));
9115 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9116 file_name = image_spec_value (img->spec, QCfile, NULL);
9117 if (STRINGP (file_name))
9118 success_p = xbm_load_image_from_file (f, img, file_name);
9119 else
9121 struct image_keyword fmt[XBM_LAST];
9122 Lisp_Object data;
9123 int depth;
9124 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9125 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9126 char *bits;
9127 int parsed_p;
9129 /* Parse the list specification. */
9130 bcopy (xbm_format, fmt, sizeof fmt);
9131 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
9132 xassert (parsed_p);
9134 /* Get specified width, and height. */
9135 img->width = XFASTINT (fmt[XBM_WIDTH].value);
9136 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
9137 xassert (img->width > 0 && img->height > 0);
9139 BLOCK_INPUT;
9141 if (fmt[XBM_ASCENT].count)
9142 img->ascent = XFASTINT (fmt[XBM_ASCENT].value);
9144 /* Get foreground and background colors, maybe allocate colors. */
9145 if (fmt[XBM_FOREGROUND].count)
9146 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
9147 foreground);
9148 if (fmt[XBM_BACKGROUND].count)
9149 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
9150 background);
9152 /* Set bits to the bitmap image data. */
9153 data = fmt[XBM_DATA].value;
9154 if (VECTORP (data))
9156 int i;
9157 char *p;
9158 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
9160 p = bits = (char *) alloca (nbytes * img->height);
9161 for (i = 0; i < img->height; ++i, p += nbytes)
9163 Lisp_Object line = XVECTOR (data)->contents[i];
9164 if (STRINGP (line))
9165 bcopy (XSTRING (line)->data, p, nbytes);
9166 else
9167 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
9170 else if (STRINGP (data))
9171 bits = XSTRING (data)->data;
9172 else
9173 bits = XBOOL_VECTOR (data)->data;
9175 #if 0 /* TODO : W32 XPM code */
9176 /* Create the pixmap. */
9177 depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
9178 img->pixmap
9179 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
9180 FRAME_W32_WINDOW (f),
9181 bits,
9182 img->width, img->height,
9183 foreground, background,
9184 depth);
9185 #endif /* TODO */
9187 if (img->pixmap)
9188 success_p = 1;
9189 else
9191 image_error ("Unable to create pixmap for XBM image `%s'",
9192 img->spec, Qnil);
9193 x_clear_image (f, img);
9196 UNBLOCK_INPUT;
9199 return success_p;
9204 /***********************************************************************
9205 XPM images
9206 ***********************************************************************/
9208 #if HAVE_XPM
9210 static int xpm_image_p P_ ((Lisp_Object object));
9211 static int xpm_load P_ ((struct frame *f, struct image *img));
9212 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
9214 #include "X11/xpm.h"
9216 /* The symbol `xpm' identifying XPM-format images. */
9218 Lisp_Object Qxpm;
9220 /* Indices of image specification fields in xpm_format, below. */
9222 enum xpm_keyword_index
9224 XPM_TYPE,
9225 XPM_FILE,
9226 XPM_DATA,
9227 XPM_ASCENT,
9228 XPM_MARGIN,
9229 XPM_RELIEF,
9230 XPM_ALGORITHM,
9231 XPM_HEURISTIC_MASK,
9232 XPM_COLOR_SYMBOLS,
9233 XPM_LAST
9236 /* Vector of image_keyword structures describing the format
9237 of valid XPM image specifications. */
9239 static struct image_keyword xpm_format[XPM_LAST] =
9241 {":type", IMAGE_SYMBOL_VALUE, 1},
9242 {":file", IMAGE_STRING_VALUE, 0},
9243 {":data", IMAGE_STRING_VALUE, 0},
9244 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9245 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9246 {":relief", IMAGE_INTEGER_VALUE, 0},
9247 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9248 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9249 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9252 /* Structure describing the image type XBM. */
9254 static struct image_type xpm_type =
9256 &Qxpm,
9257 xpm_image_p,
9258 xpm_load,
9259 x_clear_image,
9260 NULL
9264 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9265 for XPM images. Such a list must consist of conses whose car and
9266 cdr are strings. */
9268 static int
9269 xpm_valid_color_symbols_p (color_symbols)
9270 Lisp_Object color_symbols;
9272 while (CONSP (color_symbols))
9274 Lisp_Object sym = XCAR (color_symbols);
9275 if (!CONSP (sym)
9276 || !STRINGP (XCAR (sym))
9277 || !STRINGP (XCDR (sym)))
9278 break;
9279 color_symbols = XCDR (color_symbols);
9282 return NILP (color_symbols);
9286 /* Value is non-zero if OBJECT is a valid XPM image specification. */
9288 static int
9289 xpm_image_p (object)
9290 Lisp_Object object;
9292 struct image_keyword fmt[XPM_LAST];
9293 bcopy (xpm_format, fmt, sizeof fmt);
9294 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9295 /* Either `:file' or `:data' must be present. */
9296 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9297 /* Either no `:color-symbols' or it's a list of conses
9298 whose car and cdr are strings. */
9299 && (fmt[XPM_COLOR_SYMBOLS].count == 0
9300 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
9301 && (fmt[XPM_ASCENT].count == 0
9302 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
9306 /* Load image IMG which will be displayed on frame F. Value is
9307 non-zero if successful. */
9309 static int
9310 xpm_load (f, img)
9311 struct frame *f;
9312 struct image *img;
9314 int rc, i;
9315 XpmAttributes attrs;
9316 Lisp_Object specified_file, color_symbols;
9318 /* Configure the XPM lib. Use the visual of frame F. Allocate
9319 close colors. Return colors allocated. */
9320 bzero (&attrs, sizeof attrs);
9321 attrs.visual = FRAME_X_VISUAL (f);
9322 attrs.colormap = FRAME_X_COLORMAP (f);
9323 attrs.valuemask |= XpmVisual;
9324 attrs.valuemask |= XpmColormap;
9325 attrs.valuemask |= XpmReturnAllocPixels;
9326 #ifdef XpmAllocCloseColors
9327 attrs.alloc_close_colors = 1;
9328 attrs.valuemask |= XpmAllocCloseColors;
9329 #else
9330 attrs.closeness = 600;
9331 attrs.valuemask |= XpmCloseness;
9332 #endif
9334 /* If image specification contains symbolic color definitions, add
9335 these to `attrs'. */
9336 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
9337 if (CONSP (color_symbols))
9339 Lisp_Object tail;
9340 XpmColorSymbol *xpm_syms;
9341 int i, size;
9343 attrs.valuemask |= XpmColorSymbols;
9345 /* Count number of symbols. */
9346 attrs.numsymbols = 0;
9347 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
9348 ++attrs.numsymbols;
9350 /* Allocate an XpmColorSymbol array. */
9351 size = attrs.numsymbols * sizeof *xpm_syms;
9352 xpm_syms = (XpmColorSymbol *) alloca (size);
9353 bzero (xpm_syms, size);
9354 attrs.colorsymbols = xpm_syms;
9356 /* Fill the color symbol array. */
9357 for (tail = color_symbols, i = 0;
9358 CONSP (tail);
9359 ++i, tail = XCDR (tail))
9361 Lisp_Object name = XCAR (XCAR (tail));
9362 Lisp_Object color = XCDR (XCAR (tail));
9363 xpm_syms[i].name = (char *) alloca (XSTRING (name)->size + 1);
9364 strcpy (xpm_syms[i].name, XSTRING (name)->data);
9365 xpm_syms[i].value = (char *) alloca (XSTRING (color)->size + 1);
9366 strcpy (xpm_syms[i].value, XSTRING (color)->data);
9370 /* Create a pixmap for the image, either from a file, or from a
9371 string buffer containing data in the same format as an XPM file. */
9372 BLOCK_INPUT;
9373 specified_file = image_spec_value (img->spec, QCfile, NULL);
9374 if (STRINGP (specified_file))
9376 Lisp_Object file = x_find_image_file (specified_file);
9377 if (!STRINGP (file))
9379 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9380 UNBLOCK_INPUT;
9381 return 0;
9384 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
9385 XSTRING (file)->data, &img->pixmap, &img->mask,
9386 &attrs);
9388 else
9390 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
9391 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
9392 XSTRING (buffer)->data,
9393 &img->pixmap, &img->mask,
9394 &attrs);
9396 UNBLOCK_INPUT;
9398 if (rc == XpmSuccess)
9400 /* Remember allocated colors. */
9401 img->ncolors = attrs.nalloc_pixels;
9402 img->colors = (unsigned long *) xmalloc (img->ncolors
9403 * sizeof *img->colors);
9404 for (i = 0; i < attrs.nalloc_pixels; ++i)
9405 img->colors[i] = attrs.alloc_pixels[i];
9407 img->width = attrs.width;
9408 img->height = attrs.height;
9409 xassert (img->width > 0 && img->height > 0);
9411 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
9412 BLOCK_INPUT;
9413 XpmFreeAttributes (&attrs);
9414 UNBLOCK_INPUT;
9416 else
9418 switch (rc)
9420 case XpmOpenFailed:
9421 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9422 break;
9424 case XpmFileInvalid:
9425 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9426 break;
9428 case XpmNoMemory:
9429 image_error ("Out of memory (%s)", img->spec, Qnil);
9430 break;
9432 case XpmColorFailed:
9433 image_error ("Color allocation error (%s)", img->spec, Qnil);
9434 break;
9436 default:
9437 image_error ("Unknown error (%s)", img->spec, Qnil);
9438 break;
9442 return rc == XpmSuccess;
9445 #endif /* HAVE_XPM != 0 */
9448 #if 0 /* TODO : Color tables on W32. */
9449 /***********************************************************************
9450 Color table
9451 ***********************************************************************/
9453 /* An entry in the color table mapping an RGB color to a pixel color. */
9455 struct ct_color
9457 int r, g, b;
9458 unsigned long pixel;
9460 /* Next in color table collision list. */
9461 struct ct_color *next;
9464 /* The bucket vector size to use. Must be prime. */
9466 #define CT_SIZE 101
9468 /* Value is a hash of the RGB color given by R, G, and B. */
9470 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9472 /* The color hash table. */
9474 struct ct_color **ct_table;
9476 /* Number of entries in the color table. */
9478 int ct_colors_allocated;
9480 /* Function prototypes. */
9482 static void init_color_table P_ ((void));
9483 static void free_color_table P_ ((void));
9484 static unsigned long *colors_in_color_table P_ ((int *n));
9485 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9486 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9489 /* Initialize the color table. */
9491 static void
9492 init_color_table ()
9494 int size = CT_SIZE * sizeof (*ct_table);
9495 ct_table = (struct ct_color **) xmalloc (size);
9496 bzero (ct_table, size);
9497 ct_colors_allocated = 0;
9501 /* Free memory associated with the color table. */
9503 static void
9504 free_color_table ()
9506 int i;
9507 struct ct_color *p, *next;
9509 for (i = 0; i < CT_SIZE; ++i)
9510 for (p = ct_table[i]; p; p = next)
9512 next = p->next;
9513 xfree (p);
9516 xfree (ct_table);
9517 ct_table = NULL;
9521 /* Value is a pixel color for RGB color R, G, B on frame F. If an
9522 entry for that color already is in the color table, return the
9523 pixel color of that entry. Otherwise, allocate a new color for R,
9524 G, B, and make an entry in the color table. */
9526 static unsigned long
9527 lookup_rgb_color (f, r, g, b)
9528 struct frame *f;
9529 int r, g, b;
9531 unsigned hash = CT_HASH_RGB (r, g, b);
9532 int i = hash % CT_SIZE;
9533 struct ct_color *p;
9535 for (p = ct_table[i]; p; p = p->next)
9536 if (p->r == r && p->g == g && p->b == b)
9537 break;
9539 if (p == NULL)
9541 COLORREF color;
9542 Colormap cmap;
9543 int rc;
9545 color = PALETTERGB (r, g, b);
9547 ++ct_colors_allocated;
9549 p = (struct ct_color *) xmalloc (sizeof *p);
9550 p->r = r;
9551 p->g = g;
9552 p->b = b;
9553 p->pixel = color;
9554 p->next = ct_table[i];
9555 ct_table[i] = p;
9558 return p->pixel;
9562 /* Look up pixel color PIXEL which is used on frame F in the color
9563 table. If not already present, allocate it. Value is PIXEL. */
9565 static unsigned long
9566 lookup_pixel_color (f, pixel)
9567 struct frame *f;
9568 unsigned long pixel;
9570 int i = pixel % CT_SIZE;
9571 struct ct_color *p;
9573 for (p = ct_table[i]; p; p = p->next)
9574 if (p->pixel == pixel)
9575 break;
9577 if (p == NULL)
9579 XColor color;
9580 Colormap cmap;
9581 int rc;
9583 BLOCK_INPUT;
9585 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9586 color.pixel = pixel;
9587 XQueryColor (NULL, cmap, &color);
9588 rc = x_alloc_nearest_color (f, cmap, &color);
9589 UNBLOCK_INPUT;
9591 if (rc)
9593 ++ct_colors_allocated;
9595 p = (struct ct_color *) xmalloc (sizeof *p);
9596 p->r = color.red;
9597 p->g = color.green;
9598 p->b = color.blue;
9599 p->pixel = pixel;
9600 p->next = ct_table[i];
9601 ct_table[i] = p;
9603 else
9604 return FRAME_FOREGROUND_PIXEL (f);
9606 return p->pixel;
9610 /* Value is a vector of all pixel colors contained in the color table,
9611 allocated via xmalloc. Set *N to the number of colors. */
9613 static unsigned long *
9614 colors_in_color_table (n)
9615 int *n;
9617 int i, j;
9618 struct ct_color *p;
9619 unsigned long *colors;
9621 if (ct_colors_allocated == 0)
9623 *n = 0;
9624 colors = NULL;
9626 else
9628 colors = (unsigned long *) xmalloc (ct_colors_allocated
9629 * sizeof *colors);
9630 *n = ct_colors_allocated;
9632 for (i = j = 0; i < CT_SIZE; ++i)
9633 for (p = ct_table[i]; p; p = p->next)
9634 colors[j++] = p->pixel;
9637 return colors;
9640 #endif /* TODO */
9643 /***********************************************************************
9644 Algorithms
9645 ***********************************************************************/
9647 #if 0 /* TODO : W32 versions of low level algorithms */
9648 static void x_laplace_write_row P_ ((struct frame *, long *,
9649 int, XImage *, int));
9650 static void x_laplace_read_row P_ ((struct frame *, Colormap,
9651 XColor *, int, XImage *, int));
9654 /* Fill COLORS with RGB colors from row Y of image XIMG. F is the
9655 frame we operate on, CMAP is the color-map in effect, and WIDTH is
9656 the width of one row in the image. */
9658 static void
9659 x_laplace_read_row (f, cmap, colors, width, ximg, y)
9660 struct frame *f;
9661 Colormap cmap;
9662 XColor *colors;
9663 int width;
9664 XImage *ximg;
9665 int y;
9667 int x;
9669 for (x = 0; x < width; ++x)
9670 colors[x].pixel = XGetPixel (ximg, x, y);
9672 XQueryColors (NULL, cmap, colors, width);
9676 /* Write row Y of image XIMG. PIXELS is an array of WIDTH longs
9677 containing the pixel colors to write. F is the frame we are
9678 working on. */
9680 static void
9681 x_laplace_write_row (f, pixels, width, ximg, y)
9682 struct frame *f;
9683 long *pixels;
9684 int width;
9685 XImage *ximg;
9686 int y;
9688 int x;
9690 for (x = 0; x < width; ++x)
9691 XPutPixel (ximg, x, y, pixels[x]);
9693 #endif
9695 /* Transform image IMG which is used on frame F with a Laplace
9696 edge-detection algorithm. The result is an image that can be used
9697 to draw disabled buttons, for example. */
9699 static void
9700 x_laplace (f, img)
9701 struct frame *f;
9702 struct image *img;
9704 #if 0 /* TODO : W32 version */
9705 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9706 XImage *ximg, *oimg;
9707 XColor *in[3];
9708 long *out;
9709 Pixmap pixmap;
9710 int x, y, i;
9711 long pixel;
9712 int in_y, out_y, rc;
9713 int mv2 = 45000;
9715 BLOCK_INPUT;
9717 /* Get the X image IMG->pixmap. */
9718 ximg = XGetImage (NULL, img->pixmap,
9719 0, 0, img->width, img->height, ~0, ZPixmap);
9721 /* Allocate 3 input rows, and one output row of colors. */
9722 for (i = 0; i < 3; ++i)
9723 in[i] = (XColor *) alloca (img->width * sizeof (XColor));
9724 out = (long *) alloca (img->width * sizeof (long));
9726 /* Create an X image for output. */
9727 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9728 &oimg, &pixmap);
9730 /* Fill first two rows. */
9731 x_laplace_read_row (f, cmap, in[0], img->width, ximg, 0);
9732 x_laplace_read_row (f, cmap, in[1], img->width, ximg, 1);
9733 in_y = 2;
9735 /* Write first row, all zeros. */
9736 init_color_table ();
9737 pixel = lookup_rgb_color (f, 0, 0, 0);
9738 for (x = 0; x < img->width; ++x)
9739 out[x] = pixel;
9740 x_laplace_write_row (f, out, img->width, oimg, 0);
9741 out_y = 1;
9743 for (y = 2; y < img->height; ++y)
9745 int rowa = y % 3;
9746 int rowb = (y + 2) % 3;
9748 x_laplace_read_row (f, cmap, in[rowa], img->width, ximg, in_y++);
9750 for (x = 0; x < img->width - 2; ++x)
9752 int r = in[rowa][x].red + mv2 - in[rowb][x + 2].red;
9753 int g = in[rowa][x].green + mv2 - in[rowb][x + 2].green;
9754 int b = in[rowa][x].blue + mv2 - in[rowb][x + 2].blue;
9756 out[x + 1] = lookup_rgb_color (f, r & 0xffff, g & 0xffff,
9757 b & 0xffff);
9760 x_laplace_write_row (f, out, img->width, oimg, out_y++);
9763 /* Write last line, all zeros. */
9764 for (x = 0; x < img->width; ++x)
9765 out[x] = pixel;
9766 x_laplace_write_row (f, out, img->width, oimg, out_y);
9768 /* Free the input image, and free resources of IMG. */
9769 XDestroyImage (ximg);
9770 x_clear_image (f, img);
9772 /* Put the output image into pixmap, and destroy it. */
9773 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9774 x_destroy_x_image (oimg);
9776 /* Remember new pixmap and colors in IMG. */
9777 img->pixmap = pixmap;
9778 img->colors = colors_in_color_table (&img->ncolors);
9779 free_color_table ();
9781 UNBLOCK_INPUT;
9782 #endif /* TODO */
9786 /* Build a mask for image IMG which is used on frame F. FILE is the
9787 name of an image file, for error messages. HOW determines how to
9788 determine the background color of IMG. If it is a list '(R G B)',
9789 with R, G, and B being integers >= 0, take that as the color of the
9790 background. Otherwise, determine the background color of IMG
9791 heuristically. Value is non-zero if successful. */
9793 static int
9794 x_build_heuristic_mask (f, img, how)
9795 struct frame *f;
9796 struct image *img;
9797 Lisp_Object how;
9799 #if 0 /* TODO : W32 version */
9800 Display *dpy = FRAME_W32_DISPLAY (f);
9801 XImage *ximg, *mask_img;
9802 int x, y, rc, look_at_corners_p;
9803 unsigned long bg;
9805 BLOCK_INPUT;
9807 /* Create an image and pixmap serving as mask. */
9808 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
9809 &mask_img, &img->mask);
9810 if (!rc)
9812 UNBLOCK_INPUT;
9813 return 0;
9816 /* Get the X image of IMG->pixmap. */
9817 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
9818 ~0, ZPixmap);
9820 /* Determine the background color of ximg. If HOW is `(R G B)'
9821 take that as color. Otherwise, try to determine the color
9822 heuristically. */
9823 look_at_corners_p = 1;
9825 if (CONSP (how))
9827 int rgb[3], i = 0;
9829 while (i < 3
9830 && CONSP (how)
9831 && NATNUMP (XCAR (how)))
9833 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9834 how = XCDR (how);
9837 if (i == 3 && NILP (how))
9839 char color_name[30];
9840 XColor exact, color;
9841 Colormap cmap;
9843 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
9845 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9846 if (XLookupColor (dpy, cmap, color_name, &exact, &color))
9848 bg = color.pixel;
9849 look_at_corners_p = 0;
9854 if (look_at_corners_p)
9856 unsigned long corners[4];
9857 int i, best_count;
9859 /* Get the colors at the corners of ximg. */
9860 corners[0] = XGetPixel (ximg, 0, 0);
9861 corners[1] = XGetPixel (ximg, img->width - 1, 0);
9862 corners[2] = XGetPixel (ximg, img->width - 1, img->height - 1);
9863 corners[3] = XGetPixel (ximg, 0, img->height - 1);
9865 /* Choose the most frequently found color as background. */
9866 for (i = best_count = 0; i < 4; ++i)
9868 int j, n;
9870 for (j = n = 0; j < 4; ++j)
9871 if (corners[i] == corners[j])
9872 ++n;
9874 if (n > best_count)
9875 bg = corners[i], best_count = n;
9879 /* Set all bits in mask_img to 1 whose color in ximg is different
9880 from the background color bg. */
9881 for (y = 0; y < img->height; ++y)
9882 for (x = 0; x < img->width; ++x)
9883 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
9885 /* Put mask_img into img->mask. */
9886 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
9887 x_destroy_x_image (mask_img);
9888 XDestroyImage (ximg);
9890 UNBLOCK_INPUT;
9891 #endif /* TODO */
9893 return 1;
9898 /***********************************************************************
9899 PBM (mono, gray, color)
9900 ***********************************************************************/
9901 #ifdef HAVE_PBM
9903 static int pbm_image_p P_ ((Lisp_Object object));
9904 static int pbm_load P_ ((struct frame *f, struct image *img));
9905 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
9907 /* The symbol `pbm' identifying images of this type. */
9909 Lisp_Object Qpbm;
9911 /* Indices of image specification fields in gs_format, below. */
9913 enum pbm_keyword_index
9915 PBM_TYPE,
9916 PBM_FILE,
9917 PBM_DATA,
9918 PBM_ASCENT,
9919 PBM_MARGIN,
9920 PBM_RELIEF,
9921 PBM_ALGORITHM,
9922 PBM_HEURISTIC_MASK,
9923 PBM_LAST
9926 /* Vector of image_keyword structures describing the format
9927 of valid user-defined image specifications. */
9929 static struct image_keyword pbm_format[PBM_LAST] =
9931 {":type", IMAGE_SYMBOL_VALUE, 1},
9932 {":file", IMAGE_STRING_VALUE, 0},
9933 {":data", IMAGE_STRING_VALUE, 0},
9934 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9935 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9936 {":relief", IMAGE_INTEGER_VALUE, 0},
9937 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9938 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9941 /* Structure describing the image type `pbm'. */
9943 static struct image_type pbm_type =
9945 &Qpbm,
9946 pbm_image_p,
9947 pbm_load,
9948 x_clear_image,
9949 NULL
9953 /* Return non-zero if OBJECT is a valid PBM image specification. */
9955 static int
9956 pbm_image_p (object)
9957 Lisp_Object object;
9959 struct image_keyword fmt[PBM_LAST];
9961 bcopy (pbm_format, fmt, sizeof fmt);
9963 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
9964 || (fmt[PBM_ASCENT].count
9965 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
9966 return 0;
9968 /* Must specify either :data or :file. */
9969 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
9973 /* Scan a decimal number from *S and return it. Advance *S while
9974 reading the number. END is the end of the string. Value is -1 at
9975 end of input. */
9977 static int
9978 pbm_scan_number (s, end)
9979 unsigned char **s, *end;
9981 int c, val = -1;
9983 while (*s < end)
9985 /* Skip white-space. */
9986 while (*s < end && (c = *(*s)++, isspace (c)))
9989 if (c == '#')
9991 /* Skip comment to end of line. */
9992 while (*s < end && (c = *(*s)++, c != '\n'))
9995 else if (isdigit (c))
9997 /* Read decimal number. */
9998 val = c - '0';
9999 while (*s < end && (c = *(*s)++, isdigit (c)))
10000 val = 10 * val + c - '0';
10001 break;
10003 else
10004 break;
10007 return val;
10011 /* Read FILE into memory. Value is a pointer to a buffer allocated
10012 with xmalloc holding FILE's contents. Value is null if an error
10013 occured. *SIZE is set to the size of the file. */
10015 static char *
10016 pbm_read_file (file, size)
10017 Lisp_Object file;
10018 int *size;
10020 FILE *fp = NULL;
10021 char *buf = NULL;
10022 struct stat st;
10024 if (stat (XSTRING (file)->data, &st) == 0
10025 && (fp = fopen (XSTRING (file)->data, "r")) != NULL
10026 && (buf = (char *) xmalloc (st.st_size),
10027 fread (buf, 1, st.st_size, fp) == st.st_size))
10029 *size = st.st_size;
10030 fclose (fp);
10032 else
10034 if (fp)
10035 fclose (fp);
10036 if (buf)
10038 xfree (buf);
10039 buf = NULL;
10043 return buf;
10047 /* Load PBM image IMG for use on frame F. */
10049 static int
10050 pbm_load (f, img)
10051 struct frame *f;
10052 struct image *img;
10054 int raw_p, x, y;
10055 int width, height, max_color_idx = 0;
10056 XImage *ximg;
10057 Lisp_Object file, specified_file;
10058 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
10059 struct gcpro gcpro1;
10060 unsigned char *contents = NULL;
10061 unsigned char *end, *p;
10062 int size;
10064 specified_file = image_spec_value (img->spec, QCfile, NULL);
10065 file = Qnil;
10066 GCPRO1 (file);
10068 if (STRINGP (specified_file))
10070 file = x_find_image_file (specified_file);
10071 if (!STRINGP (file))
10073 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10074 UNGCPRO;
10075 return 0;
10078 contents = pbm_read_file (file, &size);
10079 if (contents == NULL)
10081 image_error ("Error reading `%s'", file, Qnil);
10082 UNGCPRO;
10083 return 0;
10086 p = contents;
10087 end = contents + size;
10089 else
10091 Lisp_Object data;
10092 data = image_spec_value (img->spec, QCdata, NULL);
10093 p = XSTRING (data)->data;
10094 end = p + STRING_BYTES (XSTRING (data));
10097 /* Check magic number. */
10098 if (end - p < 2 || *p++ != 'P')
10100 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10101 error:
10102 xfree (contents);
10103 UNGCPRO;
10104 return 0;
10107 switch (*p++)
10109 case '1':
10110 raw_p = 0, type = PBM_MONO;
10111 break;
10113 case '2':
10114 raw_p = 0, type = PBM_GRAY;
10115 break;
10117 case '3':
10118 raw_p = 0, type = PBM_COLOR;
10119 break;
10121 case '4':
10122 raw_p = 1, type = PBM_MONO;
10123 break;
10125 case '5':
10126 raw_p = 1, type = PBM_GRAY;
10127 break;
10129 case '6':
10130 raw_p = 1, type = PBM_COLOR;
10131 break;
10133 default:
10134 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10135 goto error;
10138 /* Read width, height, maximum color-component. Characters
10139 starting with `#' up to the end of a line are ignored. */
10140 width = pbm_scan_number (&p, end);
10141 height = pbm_scan_number (&p, end);
10143 if (type != PBM_MONO)
10145 max_color_idx = pbm_scan_number (&p, end);
10146 if (raw_p && max_color_idx > 255)
10147 max_color_idx = 255;
10150 if (width < 0
10151 || height < 0
10152 || (type != PBM_MONO && max_color_idx < 0))
10153 goto error;
10155 BLOCK_INPUT;
10156 if (!x_create_x_image_and_pixmap (f, width, height, 0,
10157 &ximg, &img->pixmap))
10159 UNBLOCK_INPUT;
10160 goto error;
10163 /* Initialize the color hash table. */
10164 init_color_table ();
10166 if (type == PBM_MONO)
10168 int c = 0, g;
10170 for (y = 0; y < height; ++y)
10171 for (x = 0; x < width; ++x)
10173 if (raw_p)
10175 if ((x & 7) == 0)
10176 c = *p++;
10177 g = c & 0x80;
10178 c <<= 1;
10180 else
10181 g = pbm_scan_number (&p, end);
10183 XPutPixel (ximg, x, y, (g
10184 ? FRAME_FOREGROUND_PIXEL (f)
10185 : FRAME_BACKGROUND_PIXEL (f)));
10188 else
10190 for (y = 0; y < height; ++y)
10191 for (x = 0; x < width; ++x)
10193 int r, g, b;
10195 if (type == PBM_GRAY)
10196 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
10197 else if (raw_p)
10199 r = *p++;
10200 g = *p++;
10201 b = *p++;
10203 else
10205 r = pbm_scan_number (&p, end);
10206 g = pbm_scan_number (&p, end);
10207 b = pbm_scan_number (&p, end);
10210 if (r < 0 || g < 0 || b < 0)
10212 xfree (ximg->data);
10213 ximg->data = NULL;
10214 XDestroyImage (ximg);
10215 UNBLOCK_INPUT;
10216 image_error ("Invalid pixel value in image `%s'",
10217 img->spec, Qnil);
10218 goto error;
10221 /* RGB values are now in the range 0..max_color_idx.
10222 Scale this to the range 0..0xffff supported by X. */
10223 r = (double) r * 65535 / max_color_idx;
10224 g = (double) g * 65535 / max_color_idx;
10225 b = (double) b * 65535 / max_color_idx;
10226 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10230 /* Store in IMG->colors the colors allocated for the image, and
10231 free the color table. */
10232 img->colors = colors_in_color_table (&img->ncolors);
10233 free_color_table ();
10235 /* Put the image into a pixmap. */
10236 x_put_x_image (f, ximg, img->pixmap, width, height);
10237 x_destroy_x_image (ximg);
10238 UNBLOCK_INPUT;
10240 img->width = width;
10241 img->height = height;
10243 UNGCPRO;
10244 xfree (contents);
10245 return 1;
10247 #endif /* HAVE_PBM */
10250 /***********************************************************************
10252 ***********************************************************************/
10254 #if HAVE_PNG
10256 #include <png.h>
10258 /* Function prototypes. */
10260 static int png_image_p P_ ((Lisp_Object object));
10261 static int png_load P_ ((struct frame *f, struct image *img));
10263 /* The symbol `png' identifying images of this type. */
10265 Lisp_Object Qpng;
10267 /* Indices of image specification fields in png_format, below. */
10269 enum png_keyword_index
10271 PNG_TYPE,
10272 PNG_DATA,
10273 PNG_FILE,
10274 PNG_ASCENT,
10275 PNG_MARGIN,
10276 PNG_RELIEF,
10277 PNG_ALGORITHM,
10278 PNG_HEURISTIC_MASK,
10279 PNG_LAST
10282 /* Vector of image_keyword structures describing the format
10283 of valid user-defined image specifications. */
10285 static struct image_keyword png_format[PNG_LAST] =
10287 {":type", IMAGE_SYMBOL_VALUE, 1},
10288 {":data", IMAGE_STRING_VALUE, 0},
10289 {":file", IMAGE_STRING_VALUE, 0},
10290 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10291 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10292 {":relief", IMAGE_INTEGER_VALUE, 0},
10293 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10294 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10297 /* Structure describing the image type `png'. */
10299 static struct image_type png_type =
10301 &Qpng,
10302 png_image_p,
10303 png_load,
10304 x_clear_image,
10305 NULL
10309 /* Return non-zero if OBJECT is a valid PNG image specification. */
10311 static int
10312 png_image_p (object)
10313 Lisp_Object object;
10315 struct image_keyword fmt[PNG_LAST];
10316 bcopy (png_format, fmt, sizeof fmt);
10318 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
10319 || (fmt[PNG_ASCENT].count
10320 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
10321 return 0;
10323 /* Must specify either the :data or :file keyword. */
10324 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
10328 /* Error and warning handlers installed when the PNG library
10329 is initialized. */
10331 static void
10332 my_png_error (png_ptr, msg)
10333 png_struct *png_ptr;
10334 char *msg;
10336 xassert (png_ptr != NULL);
10337 image_error ("PNG error: %s", build_string (msg), Qnil);
10338 longjmp (png_ptr->jmpbuf, 1);
10342 static void
10343 my_png_warning (png_ptr, msg)
10344 png_struct *png_ptr;
10345 char *msg;
10347 xassert (png_ptr != NULL);
10348 image_error ("PNG warning: %s", build_string (msg), Qnil);
10351 /* Memory source for PNG decoding. */
10353 struct png_memory_storage
10355 unsigned char *bytes; /* The data */
10356 size_t len; /* How big is it? */
10357 int index; /* Where are we? */
10361 /* Function set as reader function when reading PNG image from memory.
10362 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
10363 bytes from the input to DATA. */
10365 static void
10366 png_read_from_memory (png_ptr, data, length)
10367 png_structp png_ptr;
10368 png_bytep data;
10369 png_size_t length;
10371 struct png_memory_storage *tbr
10372 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
10374 if (length > tbr->len - tbr->index)
10375 png_error (png_ptr, "Read error");
10377 bcopy (tbr->bytes + tbr->index, data, length);
10378 tbr->index = tbr->index + length;
10381 /* Load PNG image IMG for use on frame F. Value is non-zero if
10382 successful. */
10384 static int
10385 png_load (f, img)
10386 struct frame *f;
10387 struct image *img;
10389 Lisp_Object file, specified_file;
10390 Lisp_Object specified_data;
10391 int x, y, i;
10392 XImage *ximg, *mask_img = NULL;
10393 struct gcpro gcpro1;
10394 png_struct *png_ptr = NULL;
10395 png_info *info_ptr = NULL, *end_info = NULL;
10396 FILE *fp = NULL;
10397 png_byte sig[8];
10398 png_byte *pixels = NULL;
10399 png_byte **rows = NULL;
10400 png_uint_32 width, height;
10401 int bit_depth, color_type, interlace_type;
10402 png_byte channels;
10403 png_uint_32 row_bytes;
10404 int transparent_p;
10405 char *gamma_str;
10406 double screen_gamma, image_gamma;
10407 int intent;
10408 struct png_memory_storage tbr; /* Data to be read */
10410 /* Find out what file to load. */
10411 specified_file = image_spec_value (img->spec, QCfile, NULL);
10412 specified_data = image_spec_value (img->spec, QCdata, NULL);
10413 file = Qnil;
10414 GCPRO1 (file);
10416 if (NILP (specified_data))
10418 file = x_find_image_file (specified_file);
10419 if (!STRINGP (file))
10421 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10422 UNGCPRO;
10423 return 0;
10426 /* Open the image file. */
10427 fp = fopen (XSTRING (file)->data, "rb");
10428 if (!fp)
10430 image_error ("Cannot open image file `%s'", file, Qnil);
10431 UNGCPRO;
10432 fclose (fp);
10433 return 0;
10436 /* Check PNG signature. */
10437 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
10438 || !png_check_sig (sig, sizeof sig))
10440 image_error ("Not a PNG file:` %s'", file, Qnil);
10441 UNGCPRO;
10442 fclose (fp);
10443 return 0;
10446 else
10448 /* Read from memory. */
10449 tbr.bytes = XSTRING (specified_data)->data;
10450 tbr.len = STRING_BYTES (XSTRING (specified_data));
10451 tbr.index = 0;
10453 /* Check PNG signature. */
10454 if (tbr.len < sizeof sig
10455 || !png_check_sig (tbr.bytes, sizeof sig))
10457 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10458 UNGCPRO;
10459 return 0;
10462 /* Need to skip past the signature. */
10463 tbr.bytes += sizeof (sig);
10466 /* Initialize read and info structs for PNG lib. */
10467 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10468 my_png_error, my_png_warning);
10469 if (!png_ptr)
10471 if (fp) fclose (fp);
10472 UNGCPRO;
10473 return 0;
10476 info_ptr = png_create_info_struct (png_ptr);
10477 if (!info_ptr)
10479 png_destroy_read_struct (&png_ptr, NULL, NULL);
10480 if (fp) fclose (fp);
10481 UNGCPRO;
10482 return 0;
10485 end_info = png_create_info_struct (png_ptr);
10486 if (!end_info)
10488 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
10489 if (fp) fclose (fp);
10490 UNGCPRO;
10491 return 0;
10494 /* Set error jump-back. We come back here when the PNG library
10495 detects an error. */
10496 if (setjmp (png_ptr->jmpbuf))
10498 error:
10499 if (png_ptr)
10500 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10501 xfree (pixels);
10502 xfree (rows);
10503 if (fp) fclose (fp);
10504 UNGCPRO;
10505 return 0;
10508 /* Read image info. */
10509 if (!NILP (specified_data))
10510 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
10511 else
10512 png_init_io (png_ptr, fp);
10514 png_set_sig_bytes (png_ptr, sizeof sig);
10515 png_read_info (png_ptr, info_ptr);
10516 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10517 &interlace_type, NULL, NULL);
10519 /* If image contains simply transparency data, we prefer to
10520 construct a clipping mask. */
10521 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
10522 transparent_p = 1;
10523 else
10524 transparent_p = 0;
10526 /* This function is easier to write if we only have to handle
10527 one data format: RGB or RGBA with 8 bits per channel. Let's
10528 transform other formats into that format. */
10530 /* Strip more than 8 bits per channel. */
10531 if (bit_depth == 16)
10532 png_set_strip_16 (png_ptr);
10534 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10535 if available. */
10536 png_set_expand (png_ptr);
10538 /* Convert grayscale images to RGB. */
10539 if (color_type == PNG_COLOR_TYPE_GRAY
10540 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
10541 png_set_gray_to_rgb (png_ptr);
10543 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
10544 gamma_str = getenv ("SCREEN_GAMMA");
10545 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
10547 /* Tell the PNG lib to handle gamma correction for us. */
10549 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10550 if (png_get_sRGB (png_ptr, info_ptr, &intent))
10551 /* There is a special chunk in the image specifying the gamma. */
10552 png_set_sRGB (png_ptr, info_ptr, intent);
10553 else
10554 #endif
10555 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10556 /* Image contains gamma information. */
10557 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10558 else
10559 /* Use a default of 0.5 for the image gamma. */
10560 png_set_gamma (png_ptr, screen_gamma, 0.5);
10562 /* Handle alpha channel by combining the image with a background
10563 color. Do this only if a real alpha channel is supplied. For
10564 simple transparency, we prefer a clipping mask. */
10565 if (!transparent_p)
10567 png_color_16 *image_background;
10569 if (png_get_bKGD (png_ptr, info_ptr, &image_background))
10570 /* Image contains a background color with which to
10571 combine the image. */
10572 png_set_background (png_ptr, image_background,
10573 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
10574 else
10576 /* Image does not contain a background color with which
10577 to combine the image data via an alpha channel. Use
10578 the frame's background instead. */
10579 XColor color;
10580 Colormap cmap;
10581 png_color_16 frame_background;
10583 BLOCK_INPUT;
10584 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10585 color.pixel = FRAME_BACKGROUND_PIXEL (f);
10586 XQueryColor (FRAME_W32_DISPLAY (f), cmap, &color);
10587 UNBLOCK_INPUT;
10589 bzero (&frame_background, sizeof frame_background);
10590 frame_background.red = color.red;
10591 frame_background.green = color.green;
10592 frame_background.blue = color.blue;
10594 png_set_background (png_ptr, &frame_background,
10595 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10599 /* Update info structure. */
10600 png_read_update_info (png_ptr, info_ptr);
10602 /* Get number of channels. Valid values are 1 for grayscale images
10603 and images with a palette, 2 for grayscale images with transparency
10604 information (alpha channel), 3 for RGB images, and 4 for RGB
10605 images with alpha channel, i.e. RGBA. If conversions above were
10606 sufficient we should only have 3 or 4 channels here. */
10607 channels = png_get_channels (png_ptr, info_ptr);
10608 xassert (channels == 3 || channels == 4);
10610 /* Number of bytes needed for one row of the image. */
10611 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
10613 /* Allocate memory for the image. */
10614 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10615 rows = (png_byte **) xmalloc (height * sizeof *rows);
10616 for (i = 0; i < height; ++i)
10617 rows[i] = pixels + i * row_bytes;
10619 /* Read the entire image. */
10620 png_read_image (png_ptr, rows);
10621 png_read_end (png_ptr, info_ptr);
10622 if (fp)
10624 fclose (fp);
10625 fp = NULL;
10628 BLOCK_INPUT;
10630 /* Create the X image and pixmap. */
10631 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10632 &img->pixmap))
10634 UNBLOCK_INPUT;
10635 goto error;
10638 /* Create an image and pixmap serving as mask if the PNG image
10639 contains an alpha channel. */
10640 if (channels == 4
10641 && !transparent_p
10642 && !x_create_x_image_and_pixmap (f, width, height, 1,
10643 &mask_img, &img->mask))
10645 x_destroy_x_image (ximg);
10646 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
10647 img->pixmap = 0;
10648 UNBLOCK_INPUT;
10649 goto error;
10652 /* Fill the X image and mask from PNG data. */
10653 init_color_table ();
10655 for (y = 0; y < height; ++y)
10657 png_byte *p = rows[y];
10659 for (x = 0; x < width; ++x)
10661 unsigned r, g, b;
10663 r = *p++ << 8;
10664 g = *p++ << 8;
10665 b = *p++ << 8;
10666 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10668 /* An alpha channel, aka mask channel, associates variable
10669 transparency with an image. Where other image formats
10670 support binary transparency---fully transparent or fully
10671 opaque---PNG allows up to 254 levels of partial transparency.
10672 The PNG library implements partial transparency by combining
10673 the image with a specified background color.
10675 I'm not sure how to handle this here nicely: because the
10676 background on which the image is displayed may change, for
10677 real alpha channel support, it would be necessary to create
10678 a new image for each possible background.
10680 What I'm doing now is that a mask is created if we have
10681 boolean transparency information. Otherwise I'm using
10682 the frame's background color to combine the image with. */
10684 if (channels == 4)
10686 if (mask_img)
10687 XPutPixel (mask_img, x, y, *p > 0);
10688 ++p;
10693 /* Remember colors allocated for this image. */
10694 img->colors = colors_in_color_table (&img->ncolors);
10695 free_color_table ();
10697 /* Clean up. */
10698 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10699 xfree (rows);
10700 xfree (pixels);
10702 img->width = width;
10703 img->height = height;
10705 /* Put the image into the pixmap, then free the X image and its buffer. */
10706 x_put_x_image (f, ximg, img->pixmap, width, height);
10707 x_destroy_x_image (ximg);
10709 /* Same for the mask. */
10710 if (mask_img)
10712 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10713 x_destroy_x_image (mask_img);
10716 UNBLOCK_INPUT;
10717 UNGCPRO;
10718 return 1;
10721 #endif /* HAVE_PNG != 0 */
10725 /***********************************************************************
10726 JPEG
10727 ***********************************************************************/
10729 #if HAVE_JPEG
10731 /* Work around a warning about HAVE_STDLIB_H being redefined in
10732 jconfig.h. */
10733 #ifdef HAVE_STDLIB_H
10734 #define HAVE_STDLIB_H_1
10735 #undef HAVE_STDLIB_H
10736 #endif /* HAVE_STLIB_H */
10738 #include <jpeglib.h>
10739 #include <jerror.h>
10740 #include <setjmp.h>
10742 #ifdef HAVE_STLIB_H_1
10743 #define HAVE_STDLIB_H 1
10744 #endif
10746 static int jpeg_image_p P_ ((Lisp_Object object));
10747 static int jpeg_load P_ ((struct frame *f, struct image *img));
10749 /* The symbol `jpeg' identifying images of this type. */
10751 Lisp_Object Qjpeg;
10753 /* Indices of image specification fields in gs_format, below. */
10755 enum jpeg_keyword_index
10757 JPEG_TYPE,
10758 JPEG_DATA,
10759 JPEG_FILE,
10760 JPEG_ASCENT,
10761 JPEG_MARGIN,
10762 JPEG_RELIEF,
10763 JPEG_ALGORITHM,
10764 JPEG_HEURISTIC_MASK,
10765 JPEG_LAST
10768 /* Vector of image_keyword structures describing the format
10769 of valid user-defined image specifications. */
10771 static struct image_keyword jpeg_format[JPEG_LAST] =
10773 {":type", IMAGE_SYMBOL_VALUE, 1},
10774 {":data", IMAGE_STRING_VALUE, 0},
10775 {":file", IMAGE_STRING_VALUE, 0},
10776 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10777 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10778 {":relief", IMAGE_INTEGER_VALUE, 0},
10779 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10780 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10783 /* Structure describing the image type `jpeg'. */
10785 static struct image_type jpeg_type =
10787 &Qjpeg,
10788 jpeg_image_p,
10789 jpeg_load,
10790 x_clear_image,
10791 NULL
10795 /* Return non-zero if OBJECT is a valid JPEG image specification. */
10797 static int
10798 jpeg_image_p (object)
10799 Lisp_Object object;
10801 struct image_keyword fmt[JPEG_LAST];
10803 bcopy (jpeg_format, fmt, sizeof fmt);
10805 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
10806 || (fmt[JPEG_ASCENT].count
10807 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
10808 return 0;
10810 /* Must specify either the :data or :file keyword. */
10811 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
10815 struct my_jpeg_error_mgr
10817 struct jpeg_error_mgr pub;
10818 jmp_buf setjmp_buffer;
10821 static void
10822 my_error_exit (cinfo)
10823 j_common_ptr cinfo;
10825 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
10826 longjmp (mgr->setjmp_buffer, 1);
10829 /* Init source method for JPEG data source manager. Called by
10830 jpeg_read_header() before any data is actually read. See
10831 libjpeg.doc from the JPEG lib distribution. */
10833 static void
10834 our_init_source (cinfo)
10835 j_decompress_ptr cinfo;
10840 /* Fill input buffer method for JPEG data source manager. Called
10841 whenever more data is needed. We read the whole image in one step,
10842 so this only adds a fake end of input marker at the end. */
10844 static boolean
10845 our_fill_input_buffer (cinfo)
10846 j_decompress_ptr cinfo;
10848 /* Insert a fake EOI marker. */
10849 struct jpeg_source_mgr *src = cinfo->src;
10850 static JOCTET buffer[2];
10852 buffer[0] = (JOCTET) 0xFF;
10853 buffer[1] = (JOCTET) JPEG_EOI;
10855 src->next_input_byte = buffer;
10856 src->bytes_in_buffer = 2;
10857 return TRUE;
10861 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
10862 is the JPEG data source manager. */
10864 static void
10865 our_skip_input_data (cinfo, num_bytes)
10866 j_decompress_ptr cinfo;
10867 long num_bytes;
10869 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
10871 if (src)
10873 if (num_bytes > src->bytes_in_buffer)
10874 ERREXIT (cinfo, JERR_INPUT_EOF);
10876 src->bytes_in_buffer -= num_bytes;
10877 src->next_input_byte += num_bytes;
10882 /* Method to terminate data source. Called by
10883 jpeg_finish_decompress() after all data has been processed. */
10885 static void
10886 our_term_source (cinfo)
10887 j_decompress_ptr cinfo;
10892 /* Set up the JPEG lib for reading an image from DATA which contains
10893 LEN bytes. CINFO is the decompression info structure created for
10894 reading the image. */
10896 static void
10897 jpeg_memory_src (cinfo, data, len)
10898 j_decompress_ptr cinfo;
10899 JOCTET *data;
10900 unsigned int len;
10902 struct jpeg_source_mgr *src;
10904 if (cinfo->src == NULL)
10906 /* First time for this JPEG object? */
10907 cinfo->src = (struct jpeg_source_mgr *)
10908 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
10909 sizeof (struct jpeg_source_mgr));
10910 src = (struct jpeg_source_mgr *) cinfo->src;
10911 src->next_input_byte = data;
10914 src = (struct jpeg_source_mgr *) cinfo->src;
10915 src->init_source = our_init_source;
10916 src->fill_input_buffer = our_fill_input_buffer;
10917 src->skip_input_data = our_skip_input_data;
10918 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
10919 src->term_source = our_term_source;
10920 src->bytes_in_buffer = len;
10921 src->next_input_byte = data;
10925 /* Load image IMG for use on frame F. Patterned after example.c
10926 from the JPEG lib. */
10928 static int
10929 jpeg_load (f, img)
10930 struct frame *f;
10931 struct image *img;
10933 struct jpeg_decompress_struct cinfo;
10934 struct my_jpeg_error_mgr mgr;
10935 Lisp_Object file, specified_file;
10936 Lisp_Object specified_data;
10937 FILE *fp = NULL;
10938 JSAMPARRAY buffer;
10939 int row_stride, x, y;
10940 XImage *ximg = NULL;
10941 int rc;
10942 unsigned long *colors;
10943 int width, height;
10944 struct gcpro gcpro1;
10946 /* Open the JPEG file. */
10947 specified_file = image_spec_value (img->spec, QCfile, NULL);
10948 specified_data = image_spec_value (img->spec, QCdata, NULL);
10949 file = Qnil;
10950 GCPRO1 (file);
10952 if (NILP (specified_data))
10954 file = x_find_image_file (specified_file);
10955 if (!STRINGP (file))
10957 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10958 UNGCPRO;
10959 return 0;
10962 fp = fopen (XSTRING (file)->data, "r");
10963 if (fp == NULL)
10965 image_error ("Cannot open `%s'", file, Qnil);
10966 UNGCPRO;
10967 return 0;
10971 /* Customize libjpeg's error handling to call my_error_exit when an
10972 error is detected. This function will perform a longjmp. */
10973 mgr.pub.error_exit = my_error_exit;
10974 cinfo.err = jpeg_std_error (&mgr.pub);
10976 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
10978 if (rc == 1)
10980 /* Called from my_error_exit. Display a JPEG error. */
10981 char buffer[JMSG_LENGTH_MAX];
10982 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
10983 image_error ("Error reading JPEG image `%s': %s", img->spec,
10984 build_string (buffer));
10987 /* Close the input file and destroy the JPEG object. */
10988 if (fp)
10989 fclose (fp);
10990 jpeg_destroy_decompress (&cinfo);
10992 BLOCK_INPUT;
10994 /* If we already have an XImage, free that. */
10995 x_destroy_x_image (ximg);
10997 /* Free pixmap and colors. */
10998 x_clear_image (f, img);
11000 UNBLOCK_INPUT;
11001 UNGCPRO;
11002 return 0;
11005 /* Create the JPEG decompression object. Let it read from fp.
11006 Read the JPEG image header. */
11007 jpeg_create_decompress (&cinfo);
11009 if (NILP (specified_data))
11010 jpeg_stdio_src (&cinfo, fp);
11011 else
11012 jpeg_memory_src (&cinfo, XSTRING (specified_data)->data,
11013 STRING_BYTES (XSTRING (specified_data)));
11015 jpeg_read_header (&cinfo, TRUE);
11017 /* Customize decompression so that color quantization will be used.
11018 Start decompression. */
11019 cinfo.quantize_colors = TRUE;
11020 jpeg_start_decompress (&cinfo);
11021 width = img->width = cinfo.output_width;
11022 height = img->height = cinfo.output_height;
11024 BLOCK_INPUT;
11026 /* Create X image and pixmap. */
11027 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11028 &img->pixmap))
11030 UNBLOCK_INPUT;
11031 longjmp (mgr.setjmp_buffer, 2);
11034 /* Allocate colors. When color quantization is used,
11035 cinfo.actual_number_of_colors has been set with the number of
11036 colors generated, and cinfo.colormap is a two-dimensional array
11037 of color indices in the range 0..cinfo.actual_number_of_colors.
11038 No more than 255 colors will be generated. */
11040 int i, ir, ig, ib;
11042 if (cinfo.out_color_components > 2)
11043 ir = 0, ig = 1, ib = 2;
11044 else if (cinfo.out_color_components > 1)
11045 ir = 0, ig = 1, ib = 0;
11046 else
11047 ir = 0, ig = 0, ib = 0;
11049 /* Use the color table mechanism because it handles colors that
11050 cannot be allocated nicely. Such colors will be replaced with
11051 a default color, and we don't have to care about which colors
11052 can be freed safely, and which can't. */
11053 init_color_table ();
11054 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
11055 * sizeof *colors);
11057 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
11059 /* Multiply RGB values with 255 because X expects RGB values
11060 in the range 0..0xffff. */
11061 int r = cinfo.colormap[ir][i] << 8;
11062 int g = cinfo.colormap[ig][i] << 8;
11063 int b = cinfo.colormap[ib][i] << 8;
11064 colors[i] = lookup_rgb_color (f, r, g, b);
11067 /* Remember those colors actually allocated. */
11068 img->colors = colors_in_color_table (&img->ncolors);
11069 free_color_table ();
11072 /* Read pixels. */
11073 row_stride = width * cinfo.output_components;
11074 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
11075 row_stride, 1);
11076 for (y = 0; y < height; ++y)
11078 jpeg_read_scanlines (&cinfo, buffer, 1);
11079 for (x = 0; x < cinfo.output_width; ++x)
11080 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
11083 /* Clean up. */
11084 jpeg_finish_decompress (&cinfo);
11085 jpeg_destroy_decompress (&cinfo);
11086 if (fp)
11087 fclose (fp);
11089 /* Put the image into the pixmap. */
11090 x_put_x_image (f, ximg, img->pixmap, width, height);
11091 x_destroy_x_image (ximg);
11092 UNBLOCK_INPUT;
11093 UNGCPRO;
11094 return 1;
11097 #endif /* HAVE_JPEG */
11101 /***********************************************************************
11102 TIFF
11103 ***********************************************************************/
11105 #if HAVE_TIFF
11107 #include <tiffio.h>
11109 static int tiff_image_p P_ ((Lisp_Object object));
11110 static int tiff_load P_ ((struct frame *f, struct image *img));
11112 /* The symbol `tiff' identifying images of this type. */
11114 Lisp_Object Qtiff;
11116 /* Indices of image specification fields in tiff_format, below. */
11118 enum tiff_keyword_index
11120 TIFF_TYPE,
11121 TIFF_DATA,
11122 TIFF_FILE,
11123 TIFF_ASCENT,
11124 TIFF_MARGIN,
11125 TIFF_RELIEF,
11126 TIFF_ALGORITHM,
11127 TIFF_HEURISTIC_MASK,
11128 TIFF_LAST
11131 /* Vector of image_keyword structures describing the format
11132 of valid user-defined image specifications. */
11134 static struct image_keyword tiff_format[TIFF_LAST] =
11136 {":type", IMAGE_SYMBOL_VALUE, 1},
11137 {":data", IMAGE_STRING_VALUE, 0},
11138 {":file", IMAGE_STRING_VALUE, 0},
11139 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11140 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11141 {":relief", IMAGE_INTEGER_VALUE, 0},
11142 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11143 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11146 /* Structure describing the image type `tiff'. */
11148 static struct image_type tiff_type =
11150 &Qtiff,
11151 tiff_image_p,
11152 tiff_load,
11153 x_clear_image,
11154 NULL
11158 /* Return non-zero if OBJECT is a valid TIFF image specification. */
11160 static int
11161 tiff_image_p (object)
11162 Lisp_Object object;
11164 struct image_keyword fmt[TIFF_LAST];
11165 bcopy (tiff_format, fmt, sizeof fmt);
11167 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
11168 || (fmt[TIFF_ASCENT].count
11169 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
11170 return 0;
11172 /* Must specify either the :data or :file keyword. */
11173 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
11177 /* Reading from a memory buffer for TIFF images Based on the PNG
11178 memory source, but we have to provide a lot of extra functions.
11179 Blah.
11181 We really only need to implement read and seek, but I am not
11182 convinced that the TIFF library is smart enough not to destroy
11183 itself if we only hand it the function pointers we need to
11184 override. */
11186 typedef struct
11188 unsigned char *bytes;
11189 size_t len;
11190 int index;
11192 tiff_memory_source;
11194 static size_t
11195 tiff_read_from_memory (data, buf, size)
11196 thandle_t data;
11197 tdata_t buf;
11198 tsize_t size;
11200 tiff_memory_source *src = (tiff_memory_source *) data;
11202 if (size > src->len - src->index)
11203 return (size_t) -1;
11204 bcopy (src->bytes + src->index, buf, size);
11205 src->index += size;
11206 return size;
11209 static size_t
11210 tiff_write_from_memory (data, buf, size)
11211 thandle_t data;
11212 tdata_t buf;
11213 tsize_t size;
11215 return (size_t) -1;
11218 static toff_t
11219 tiff_seek_in_memory (data, off, whence)
11220 thandle_t data;
11221 toff_t off;
11222 int whence;
11224 tiff_memory_source *src = (tiff_memory_source *) data;
11225 int idx;
11227 switch (whence)
11229 case SEEK_SET: /* Go from beginning of source. */
11230 idx = off;
11231 break;
11233 case SEEK_END: /* Go from end of source. */
11234 idx = src->len + off;
11235 break;
11237 case SEEK_CUR: /* Go from current position. */
11238 idx = src->index + off;
11239 break;
11241 default: /* Invalid `whence'. */
11242 return -1;
11245 if (idx > src->len || idx < 0)
11246 return -1;
11248 src->index = idx;
11249 return src->index;
11252 static int
11253 tiff_close_memory (data)
11254 thandle_t data;
11256 /* NOOP */
11257 return 0;
11260 static int
11261 tiff_mmap_memory (data, pbase, psize)
11262 thandle_t data;
11263 tdata_t *pbase;
11264 toff_t *psize;
11266 /* It is already _IN_ memory. */
11267 return 0;
11270 static void
11271 tiff_unmap_memory (data, base, size)
11272 thandle_t data;
11273 tdata_t base;
11274 toff_t size;
11276 /* We don't need to do this. */
11279 static toff_t
11280 tiff_size_of_memory (data)
11281 thandle_t data;
11283 return ((tiff_memory_source *) data)->len;
11286 /* Load TIFF image IMG for use on frame F. Value is non-zero if
11287 successful. */
11289 static int
11290 tiff_load (f, img)
11291 struct frame *f;
11292 struct image *img;
11294 Lisp_Object file, specified_file;
11295 Lisp_Object specified_data;
11296 TIFF *tiff;
11297 int width, height, x, y;
11298 uint32 *buf;
11299 int rc;
11300 XImage *ximg;
11301 struct gcpro gcpro1;
11302 tiff_memory_source memsrc;
11304 specified_file = image_spec_value (img->spec, QCfile, NULL);
11305 specified_data = image_spec_value (img->spec, QCdata, NULL);
11306 file = Qnil;
11307 GCPRO1 (file);
11309 if (NILP (specified_data))
11311 /* Read from a file */
11312 file = x_find_image_file (specified_file);
11313 if (!STRINGP (file))
11315 image_error ("Cannot find image file `%s'", file, Qnil);
11316 UNGCPRO;
11317 return 0;
11320 /* Try to open the image file. */
11321 tiff = TIFFOpen (XSTRING (file)->data, "r");
11322 if (tiff == NULL)
11324 image_error ("Cannot open `%s'", file, Qnil);
11325 UNGCPRO;
11326 return 0;
11329 else
11331 /* Memory source! */
11332 memsrc.bytes = XSTRING (specified_data)->data;
11333 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11334 memsrc.index = 0;
11336 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
11337 (TIFFReadWriteProc) tiff_read_from_memory,
11338 (TIFFReadWriteProc) tiff_write_from_memory,
11339 tiff_seek_in_memory,
11340 tiff_close_memory,
11341 tiff_size_of_memory,
11342 tiff_mmap_memory,
11343 tiff_unmap_memory);
11345 if (!tiff)
11347 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
11348 UNGCPRO;
11349 return 0;
11353 /* Get width and height of the image, and allocate a raster buffer
11354 of width x height 32-bit values. */
11355 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
11356 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
11357 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
11359 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
11360 TIFFClose (tiff);
11361 if (!rc)
11363 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
11364 xfree (buf);
11365 UNGCPRO;
11366 return 0;
11369 BLOCK_INPUT;
11371 /* Create the X image and pixmap. */
11372 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11374 UNBLOCK_INPUT;
11375 xfree (buf);
11376 UNGCPRO;
11377 return 0;
11380 /* Initialize the color table. */
11381 init_color_table ();
11383 /* Process the pixel raster. Origin is in the lower-left corner. */
11384 for (y = 0; y < height; ++y)
11386 uint32 *row = buf + y * width;
11388 for (x = 0; x < width; ++x)
11390 uint32 abgr = row[x];
11391 int r = TIFFGetR (abgr) << 8;
11392 int g = TIFFGetG (abgr) << 8;
11393 int b = TIFFGetB (abgr) << 8;
11394 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
11398 /* Remember the colors allocated for the image. Free the color table. */
11399 img->colors = colors_in_color_table (&img->ncolors);
11400 free_color_table ();
11402 /* Put the image into the pixmap, then free the X image and its buffer. */
11403 x_put_x_image (f, ximg, img->pixmap, width, height);
11404 x_destroy_x_image (ximg);
11405 xfree (buf);
11406 UNBLOCK_INPUT;
11408 img->width = width;
11409 img->height = height;
11411 UNGCPRO;
11412 return 1;
11415 #endif /* HAVE_TIFF != 0 */
11419 /***********************************************************************
11421 ***********************************************************************/
11423 #if HAVE_GIF
11425 #include <gif_lib.h>
11427 static int gif_image_p P_ ((Lisp_Object object));
11428 static int gif_load P_ ((struct frame *f, struct image *img));
11430 /* The symbol `gif' identifying images of this type. */
11432 Lisp_Object Qgif;
11434 /* Indices of image specification fields in gif_format, below. */
11436 enum gif_keyword_index
11438 GIF_TYPE,
11439 GIF_DATA,
11440 GIF_FILE,
11441 GIF_ASCENT,
11442 GIF_MARGIN,
11443 GIF_RELIEF,
11444 GIF_ALGORITHM,
11445 GIF_HEURISTIC_MASK,
11446 GIF_IMAGE,
11447 GIF_LAST
11450 /* Vector of image_keyword structures describing the format
11451 of valid user-defined image specifications. */
11453 static struct image_keyword gif_format[GIF_LAST] =
11455 {":type", IMAGE_SYMBOL_VALUE, 1},
11456 {":data", IMAGE_STRING_VALUE, 0},
11457 {":file", IMAGE_STRING_VALUE, 0},
11458 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11459 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11460 {":relief", IMAGE_INTEGER_VALUE, 0},
11461 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11462 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11463 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
11466 /* Structure describing the image type `gif'. */
11468 static struct image_type gif_type =
11470 &Qgif,
11471 gif_image_p,
11472 gif_load,
11473 x_clear_image,
11474 NULL
11477 /* Return non-zero if OBJECT is a valid GIF image specification. */
11479 static int
11480 gif_image_p (object)
11481 Lisp_Object object;
11483 struct image_keyword fmt[GIF_LAST];
11484 bcopy (gif_format, fmt, sizeof fmt);
11486 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
11487 || (fmt[GIF_ASCENT].count
11488 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
11489 return 0;
11491 /* Must specify either the :data or :file keyword. */
11492 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11495 /* Reading a GIF image from memory
11496 Based on the PNG memory stuff to a certain extent. */
11498 typedef struct
11500 unsigned char *bytes;
11501 size_t len;
11502 int index;
11504 gif_memory_source;
11506 /* Make the current memory source available to gif_read_from_memory.
11507 It's done this way because not all versions of libungif support
11508 a UserData field in the GifFileType structure. */
11509 static gif_memory_source *current_gif_memory_src;
11511 static int
11512 gif_read_from_memory (file, buf, len)
11513 GifFileType *file;
11514 GifByteType *buf;
11515 int len;
11517 gif_memory_source *src = current_gif_memory_src;
11519 if (len > src->len - src->index)
11520 return -1;
11522 bcopy (src->bytes + src->index, buf, len);
11523 src->index += len;
11524 return len;
11528 /* Load GIF image IMG for use on frame F. Value is non-zero if
11529 successful. */
11531 static int
11532 gif_load (f, img)
11533 struct frame *f;
11534 struct image *img;
11536 Lisp_Object file, specified_file;
11537 Lisp_Object specified_data;
11538 int rc, width, height, x, y, i;
11539 XImage *ximg;
11540 ColorMapObject *gif_color_map;
11541 unsigned long pixel_colors[256];
11542 GifFileType *gif;
11543 struct gcpro gcpro1;
11544 Lisp_Object image;
11545 int ino, image_left, image_top, image_width, image_height;
11546 gif_memory_source memsrc;
11547 unsigned char *raster;
11549 specified_file = image_spec_value (img->spec, QCfile, NULL);
11550 specified_data = image_spec_value (img->spec, QCdata, NULL);
11551 file = Qnil;
11552 GCPRO1 (file);
11554 if (NILP (specified_data))
11556 file = x_find_image_file (specified_file);
11557 if (!STRINGP (file))
11559 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11560 UNGCPRO;
11561 return 0;
11564 /* Open the GIF file. */
11565 gif = DGifOpenFileName (XSTRING (file)->data);
11566 if (gif == NULL)
11568 image_error ("Cannot open `%s'", file, Qnil);
11569 UNGCPRO;
11570 return 0;
11573 else
11575 /* Read from memory! */
11576 current_gif_memory_src = &memsrc;
11577 memsrc.bytes = XSTRING (specified_data)->data;
11578 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11579 memsrc.index = 0;
11581 gif = DGifOpen(&memsrc, gif_read_from_memory);
11582 if (!gif)
11584 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11585 UNGCPRO;
11586 return 0;
11590 /* Read entire contents. */
11591 rc = DGifSlurp (gif);
11592 if (rc == GIF_ERROR)
11594 image_error ("Error reading `%s'", img->spec, Qnil);
11595 DGifCloseFile (gif);
11596 UNGCPRO;
11597 return 0;
11600 image = image_spec_value (img->spec, QCindex, NULL);
11601 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11602 if (ino >= gif->ImageCount)
11604 image_error ("Invalid image number `%s' in image `%s'",
11605 image, img->spec);
11606 DGifCloseFile (gif);
11607 UNGCPRO;
11608 return 0;
11611 width = img->width = gif->SWidth;
11612 height = img->height = gif->SHeight;
11614 BLOCK_INPUT;
11616 /* Create the X image and pixmap. */
11617 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11619 UNBLOCK_INPUT;
11620 DGifCloseFile (gif);
11621 UNGCPRO;
11622 return 0;
11625 /* Allocate colors. */
11626 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11627 if (!gif_color_map)
11628 gif_color_map = gif->SColorMap;
11629 init_color_table ();
11630 bzero (pixel_colors, sizeof pixel_colors);
11632 for (i = 0; i < gif_color_map->ColorCount; ++i)
11634 int r = gif_color_map->Colors[i].Red << 8;
11635 int g = gif_color_map->Colors[i].Green << 8;
11636 int b = gif_color_map->Colors[i].Blue << 8;
11637 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
11640 img->colors = colors_in_color_table (&img->ncolors);
11641 free_color_table ();
11643 /* Clear the part of the screen image that are not covered by
11644 the image from the GIF file. Full animated GIF support
11645 requires more than can be done here (see the gif89 spec,
11646 disposal methods). Let's simply assume that the part
11647 not covered by a sub-image is in the frame's background color. */
11648 image_top = gif->SavedImages[ino].ImageDesc.Top;
11649 image_left = gif->SavedImages[ino].ImageDesc.Left;
11650 image_width = gif->SavedImages[ino].ImageDesc.Width;
11651 image_height = gif->SavedImages[ino].ImageDesc.Height;
11653 for (y = 0; y < image_top; ++y)
11654 for (x = 0; x < width; ++x)
11655 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11657 for (y = image_top + image_height; y < height; ++y)
11658 for (x = 0; x < width; ++x)
11659 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11661 for (y = image_top; y < image_top + image_height; ++y)
11663 for (x = 0; x < image_left; ++x)
11664 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11665 for (x = image_left + image_width; x < width; ++x)
11666 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11669 /* Read the GIF image into the X image. We use a local variable
11670 `raster' here because RasterBits below is a char *, and invites
11671 problems with bytes >= 0x80. */
11672 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
11674 if (gif->SavedImages[ino].ImageDesc.Interlace)
11676 static int interlace_start[] = {0, 4, 2, 1};
11677 static int interlace_increment[] = {8, 8, 4, 2};
11678 int pass, inc;
11679 int row = interlace_start[0];
11681 pass = 0;
11683 for (y = 0; y < image_height; y++)
11685 if (row >= image_height)
11687 row = interlace_start[++pass];
11688 while (row >= image_height)
11689 row = interlace_start[++pass];
11692 for (x = 0; x < image_width; x++)
11694 int i = raster[(y * image_width) + x];
11695 XPutPixel (ximg, x + image_left, row + image_top,
11696 pixel_colors[i]);
11699 row += interlace_increment[pass];
11702 else
11704 for (y = 0; y < image_height; ++y)
11705 for (x = 0; x < image_width; ++x)
11707 int i = raster[y* image_width + x];
11708 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
11712 DGifCloseFile (gif);
11714 /* Put the image into the pixmap, then free the X image and its buffer. */
11715 x_put_x_image (f, ximg, img->pixmap, width, height);
11716 x_destroy_x_image (ximg);
11717 UNBLOCK_INPUT;
11719 UNGCPRO;
11720 return 1;
11723 #endif /* HAVE_GIF != 0 */
11727 /***********************************************************************
11728 Ghostscript
11729 ***********************************************************************/
11731 #ifdef HAVE_GHOSTSCRIPT
11732 static int gs_image_p P_ ((Lisp_Object object));
11733 static int gs_load P_ ((struct frame *f, struct image *img));
11734 static void gs_clear_image P_ ((struct frame *f, struct image *img));
11736 /* The symbol `postscript' identifying images of this type. */
11738 Lisp_Object Qpostscript;
11740 /* Keyword symbols. */
11742 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
11744 /* Indices of image specification fields in gs_format, below. */
11746 enum gs_keyword_index
11748 GS_TYPE,
11749 GS_PT_WIDTH,
11750 GS_PT_HEIGHT,
11751 GS_FILE,
11752 GS_LOADER,
11753 GS_BOUNDING_BOX,
11754 GS_ASCENT,
11755 GS_MARGIN,
11756 GS_RELIEF,
11757 GS_ALGORITHM,
11758 GS_HEURISTIC_MASK,
11759 GS_LAST
11762 /* Vector of image_keyword structures describing the format
11763 of valid user-defined image specifications. */
11765 static struct image_keyword gs_format[GS_LAST] =
11767 {":type", IMAGE_SYMBOL_VALUE, 1},
11768 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11769 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11770 {":file", IMAGE_STRING_VALUE, 1},
11771 {":loader", IMAGE_FUNCTION_VALUE, 0},
11772 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
11773 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11774 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11775 {":relief", IMAGE_INTEGER_VALUE, 0},
11776 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11777 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11780 /* Structure describing the image type `ghostscript'. */
11782 static struct image_type gs_type =
11784 &Qpostscript,
11785 gs_image_p,
11786 gs_load,
11787 gs_clear_image,
11788 NULL
11792 /* Free X resources of Ghostscript image IMG which is used on frame F. */
11794 static void
11795 gs_clear_image (f, img)
11796 struct frame *f;
11797 struct image *img;
11799 /* IMG->data.ptr_val may contain a recorded colormap. */
11800 xfree (img->data.ptr_val);
11801 x_clear_image (f, img);
11805 /* Return non-zero if OBJECT is a valid Ghostscript image
11806 specification. */
11808 static int
11809 gs_image_p (object)
11810 Lisp_Object object;
11812 struct image_keyword fmt[GS_LAST];
11813 Lisp_Object tem;
11814 int i;
11816 bcopy (gs_format, fmt, sizeof fmt);
11818 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
11819 || (fmt[GS_ASCENT].count
11820 && XFASTINT (fmt[GS_ASCENT].value) > 100))
11821 return 0;
11823 /* Bounding box must be a list or vector containing 4 integers. */
11824 tem = fmt[GS_BOUNDING_BOX].value;
11825 if (CONSP (tem))
11827 for (i = 0; i < 4; ++i, tem = XCDR (tem))
11828 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
11829 return 0;
11830 if (!NILP (tem))
11831 return 0;
11833 else if (VECTORP (tem))
11835 if (XVECTOR (tem)->size != 4)
11836 return 0;
11837 for (i = 0; i < 4; ++i)
11838 if (!INTEGERP (XVECTOR (tem)->contents[i]))
11839 return 0;
11841 else
11842 return 0;
11844 return 1;
11848 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
11849 if successful. */
11851 static int
11852 gs_load (f, img)
11853 struct frame *f;
11854 struct image *img;
11856 char buffer[100];
11857 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
11858 struct gcpro gcpro1, gcpro2;
11859 Lisp_Object frame;
11860 double in_width, in_height;
11861 Lisp_Object pixel_colors = Qnil;
11863 /* Compute pixel size of pixmap needed from the given size in the
11864 image specification. Sizes in the specification are in pt. 1 pt
11865 = 1/72 in, xdpi and ydpi are stored in the frame's X display
11866 info. */
11867 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
11868 in_width = XFASTINT (pt_width) / 72.0;
11869 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
11870 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
11871 in_height = XFASTINT (pt_height) / 72.0;
11872 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
11874 /* Create the pixmap. */
11875 BLOCK_INPUT;
11876 xassert (img->pixmap == 0);
11877 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11878 img->width, img->height,
11879 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
11880 UNBLOCK_INPUT;
11882 if (!img->pixmap)
11884 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
11885 return 0;
11888 /* Call the loader to fill the pixmap. It returns a process object
11889 if successful. We do not record_unwind_protect here because
11890 other places in redisplay like calling window scroll functions
11891 don't either. Let the Lisp loader use `unwind-protect' instead. */
11892 GCPRO2 (window_and_pixmap_id, pixel_colors);
11894 sprintf (buffer, "%lu %lu",
11895 (unsigned long) FRAME_W32_WINDOW (f),
11896 (unsigned long) img->pixmap);
11897 window_and_pixmap_id = build_string (buffer);
11899 sprintf (buffer, "%lu %lu",
11900 FRAME_FOREGROUND_PIXEL (f),
11901 FRAME_BACKGROUND_PIXEL (f));
11902 pixel_colors = build_string (buffer);
11904 XSETFRAME (frame, f);
11905 loader = image_spec_value (img->spec, QCloader, NULL);
11906 if (NILP (loader))
11907 loader = intern ("gs-load-image");
11909 img->data.lisp_val = call6 (loader, frame, img->spec,
11910 make_number (img->width),
11911 make_number (img->height),
11912 window_and_pixmap_id,
11913 pixel_colors);
11914 UNGCPRO;
11915 return PROCESSP (img->data.lisp_val);
11919 /* Kill the Ghostscript process that was started to fill PIXMAP on
11920 frame F. Called from XTread_socket when receiving an event
11921 telling Emacs that Ghostscript has finished drawing. */
11923 void
11924 x_kill_gs_process (pixmap, f)
11925 Pixmap pixmap;
11926 struct frame *f;
11928 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
11929 int class, i;
11930 struct image *img;
11932 /* Find the image containing PIXMAP. */
11933 for (i = 0; i < c->used; ++i)
11934 if (c->images[i]->pixmap == pixmap)
11935 break;
11937 /* Kill the GS process. We should have found PIXMAP in the image
11938 cache and its image should contain a process object. */
11939 xassert (i < c->used);
11940 img = c->images[i];
11941 xassert (PROCESSP (img->data.lisp_val));
11942 Fkill_process (img->data.lisp_val, Qnil);
11943 img->data.lisp_val = Qnil;
11945 /* On displays with a mutable colormap, figure out the colors
11946 allocated for the image by looking at the pixels of an XImage for
11947 img->pixmap. */
11948 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
11949 if (class != StaticColor && class != StaticGray && class != TrueColor)
11951 XImage *ximg;
11953 BLOCK_INPUT;
11955 /* Try to get an XImage for img->pixmep. */
11956 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
11957 0, 0, img->width, img->height, ~0, ZPixmap);
11958 if (ximg)
11960 int x, y;
11962 /* Initialize the color table. */
11963 init_color_table ();
11965 /* For each pixel of the image, look its color up in the
11966 color table. After having done so, the color table will
11967 contain an entry for each color used by the image. */
11968 for (y = 0; y < img->height; ++y)
11969 for (x = 0; x < img->width; ++x)
11971 unsigned long pixel = XGetPixel (ximg, x, y);
11972 lookup_pixel_color (f, pixel);
11975 /* Record colors in the image. Free color table and XImage. */
11976 img->colors = colors_in_color_table (&img->ncolors);
11977 free_color_table ();
11978 XDestroyImage (ximg);
11980 #if 0 /* This doesn't seem to be the case. If we free the colors
11981 here, we get a BadAccess later in x_clear_image when
11982 freeing the colors. */
11983 /* We have allocated colors once, but Ghostscript has also
11984 allocated colors on behalf of us. So, to get the
11985 reference counts right, free them once. */
11986 if (img->ncolors)
11988 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
11989 XFreeColors (FRAME_W32_DISPLAY (f), cmap,
11990 img->colors, img->ncolors, 0);
11992 #endif
11994 else
11995 image_error ("Cannot get X image of `%s'; colors will not be freed",
11996 img->spec, Qnil);
11998 UNBLOCK_INPUT;
12002 #endif /* HAVE_GHOSTSCRIPT */
12005 /***********************************************************************
12006 Window properties
12007 ***********************************************************************/
12009 DEFUN ("x-change-window-property", Fx_change_window_property,
12010 Sx_change_window_property, 2, 3, 0,
12011 "Change window property PROP to VALUE on the X window of FRAME.\n\
12012 PROP and VALUE must be strings. FRAME nil or omitted means use the\n\
12013 selected frame. Value is VALUE.")
12014 (prop, value, frame)
12015 Lisp_Object frame, prop, value;
12017 #if 0 /* TODO : port window properties to W32 */
12018 struct frame *f = check_x_frame (frame);
12019 Atom prop_atom;
12021 CHECK_STRING (prop, 1);
12022 CHECK_STRING (value, 2);
12024 BLOCK_INPUT;
12025 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12026 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12027 prop_atom, XA_STRING, 8, PropModeReplace,
12028 XSTRING (value)->data, XSTRING (value)->size);
12030 /* Make sure the property is set when we return. */
12031 XFlush (FRAME_W32_DISPLAY (f));
12032 UNBLOCK_INPUT;
12034 #endif /* TODO */
12036 return value;
12040 DEFUN ("x-delete-window-property", Fx_delete_window_property,
12041 Sx_delete_window_property, 1, 2, 0,
12042 "Remove window property PROP from X window of FRAME.\n\
12043 FRAME nil or omitted means use the selected frame. Value is PROP.")
12044 (prop, frame)
12045 Lisp_Object prop, frame;
12047 #if 0 /* TODO : port window properties to W32 */
12049 struct frame *f = check_x_frame (frame);
12050 Atom prop_atom;
12052 CHECK_STRING (prop, 1);
12053 BLOCK_INPUT;
12054 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12055 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
12057 /* Make sure the property is removed when we return. */
12058 XFlush (FRAME_W32_DISPLAY (f));
12059 UNBLOCK_INPUT;
12060 #endif /* TODO */
12062 return prop;
12066 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
12067 1, 2, 0,
12068 "Value is the value of window property PROP on FRAME.\n\
12069 If FRAME is nil or omitted, use the selected frame. Value is nil\n\
12070 if FRAME hasn't a property with name PROP or if PROP has no string\n\
12071 value.")
12072 (prop, frame)
12073 Lisp_Object prop, frame;
12075 #if 0 /* TODO : port window properties to W32 */
12077 struct frame *f = check_x_frame (frame);
12078 Atom prop_atom;
12079 int rc;
12080 Lisp_Object prop_value = Qnil;
12081 char *tmp_data = NULL;
12082 Atom actual_type;
12083 int actual_format;
12084 unsigned long actual_size, bytes_remaining;
12086 CHECK_STRING (prop, 1);
12087 BLOCK_INPUT;
12088 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12089 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12090 prop_atom, 0, 0, False, XA_STRING,
12091 &actual_type, &actual_format, &actual_size,
12092 &bytes_remaining, (unsigned char **) &tmp_data);
12093 if (rc == Success)
12095 int size = bytes_remaining;
12097 XFree (tmp_data);
12098 tmp_data = NULL;
12100 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12101 prop_atom, 0, bytes_remaining,
12102 False, XA_STRING,
12103 &actual_type, &actual_format,
12104 &actual_size, &bytes_remaining,
12105 (unsigned char **) &tmp_data);
12106 if (rc == Success)
12107 prop_value = make_string (tmp_data, size);
12109 XFree (tmp_data);
12112 UNBLOCK_INPUT;
12114 return prop_value;
12116 #endif /* TODO */
12117 return Qnil;
12122 /***********************************************************************
12123 Busy cursor
12124 ***********************************************************************/
12126 /* If non-null, an asynchronous timer that, when it expires, displays
12127 a busy cursor on all frames. */
12129 static struct atimer *busy_cursor_atimer;
12131 /* Non-zero means a busy cursor is currently shown. */
12133 static int busy_cursor_shown_p;
12135 /* Number of seconds to wait before displaying a busy cursor. */
12137 static Lisp_Object Vbusy_cursor_delay;
12139 /* Default number of seconds to wait before displaying a busy
12140 cursor. */
12142 #define DEFAULT_BUSY_CURSOR_DELAY 1
12144 /* Function prototypes. */
12146 static void show_busy_cursor P_ ((struct atimer *));
12147 static void hide_busy_cursor P_ ((void));
12150 /* Cancel a currently active busy-cursor timer, and start a new one. */
12152 void
12153 start_busy_cursor ()
12155 #if 0 /* TODO: cursor shape changes. */
12156 EMACS_TIME delay;
12157 int secs, usecs = 0;
12159 cancel_busy_cursor ();
12161 if (INTEGERP (Vbusy_cursor_delay)
12162 && XINT (Vbusy_cursor_delay) > 0)
12163 secs = XFASTINT (Vbusy_cursor_delay);
12164 else if (FLOATP (Vbusy_cursor_delay)
12165 && XFLOAT_DATA (Vbusy_cursor_delay) > 0)
12167 Lisp_Object tem;
12168 tem = Ftruncate (Vbusy_cursor_delay, Qnil);
12169 secs = XFASTINT (tem);
12170 usecs = (XFLOAT_DATA (Vbusy_cursor_delay) - secs) * 1000000;
12172 else
12173 secs = DEFAULT_BUSY_CURSOR_DELAY;
12175 EMACS_SET_SECS_USECS (delay, secs, usecs);
12176 busy_cursor_atimer = start_atimer (ATIMER_RELATIVE, delay,
12177 show_busy_cursor, NULL);
12178 #endif
12182 /* Cancel the busy cursor timer if active, hide a busy cursor if
12183 shown. */
12185 void
12186 cancel_busy_cursor ()
12188 if (busy_cursor_atimer)
12190 cancel_atimer (busy_cursor_atimer);
12191 busy_cursor_atimer = NULL;
12194 if (busy_cursor_shown_p)
12195 hide_busy_cursor ();
12199 /* Timer function of busy_cursor_atimer. TIMER is equal to
12200 busy_cursor_atimer.
12202 Display a busy cursor on all frames by mapping the frames'
12203 busy_window. Set the busy_p flag in the frames' output_data.x
12204 structure to indicate that a busy cursor is shown on the
12205 frames. */
12207 static void
12208 show_busy_cursor (timer)
12209 struct atimer *timer;
12211 #if 0 /* TODO: cursor shape changes. */
12212 /* The timer implementation will cancel this timer automatically
12213 after this function has run. Set busy_cursor_atimer to null
12214 so that we know the timer doesn't have to be canceled. */
12215 busy_cursor_atimer = NULL;
12217 if (!busy_cursor_shown_p)
12219 Lisp_Object rest, frame;
12221 BLOCK_INPUT;
12223 FOR_EACH_FRAME (rest, frame)
12224 if (FRAME_X_P (XFRAME (frame)))
12226 struct frame *f = XFRAME (frame);
12228 f->output_data.w32->busy_p = 1;
12230 if (!f->output_data.w32->busy_window)
12232 unsigned long mask = CWCursor;
12233 XSetWindowAttributes attrs;
12235 attrs.cursor = f->output_data.w32->busy_cursor;
12237 f->output_data.w32->busy_window
12238 = XCreateWindow (FRAME_X_DISPLAY (f),
12239 FRAME_OUTER_WINDOW (f),
12240 0, 0, 32000, 32000, 0, 0,
12241 InputOnly,
12242 CopyFromParent,
12243 mask, &attrs);
12246 XMapRaised (FRAME_X_DISPLAY (f), f->output_data.w32->busy_window);
12247 XFlush (FRAME_X_DISPLAY (f));
12250 busy_cursor_shown_p = 1;
12251 UNBLOCK_INPUT;
12253 #endif
12257 /* Hide the busy cursor on all frames, if it is currently shown. */
12259 static void
12260 hide_busy_cursor ()
12262 #if 0 /* TODO: cursor shape changes. */
12263 if (busy_cursor_shown_p)
12265 Lisp_Object rest, frame;
12267 BLOCK_INPUT;
12268 FOR_EACH_FRAME (rest, frame)
12270 struct frame *f = XFRAME (frame);
12272 if (FRAME_X_P (f)
12273 /* Watch out for newly created frames. */
12274 && f->output_data.x->busy_window)
12276 XUnmapWindow (FRAME_X_DISPLAY (f), f->output_data.x->busy_window);
12277 /* Sync here because XTread_socket looks at the busy_p flag
12278 that is reset to zero below. */
12279 XSync (FRAME_X_DISPLAY (f), False);
12280 f->output_data.x->busy_p = 0;
12284 busy_cursor_shown_p = 0;
12285 UNBLOCK_INPUT;
12287 #endif
12292 /***********************************************************************
12293 Tool tips
12294 ***********************************************************************/
12296 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
12297 Lisp_Object));
12299 /* The frame of a currently visible tooltip, or null. */
12301 Lisp_Object tip_frame;
12303 /* If non-nil, a timer started that hides the last tooltip when it
12304 fires. */
12306 Lisp_Object tip_timer;
12307 Window tip_window;
12309 static Lisp_Object
12310 unwind_create_tip_frame (frame)
12311 Lisp_Object frame;
12313 Lisp_Object deleted;
12315 deleted = unwind_create_frame (frame);
12316 if (EQ (deleted, Qt))
12318 tip_window = NULL;
12319 tip_frame = Qnil;
12322 return deleted;
12326 /* Create a frame for a tooltip on the display described by DPYINFO.
12327 PARMS is a list of frame parameters. Value is the frame.
12329 Note that functions called here, esp. x_default_parameter can
12330 signal errors, for instance when a specified color name is
12331 undefined. We have to make sure that we're in a consistent state
12332 when this happens. */
12334 static Lisp_Object
12335 x_create_tip_frame (dpyinfo, parms)
12336 struct w32_display_info *dpyinfo;
12337 Lisp_Object parms;
12339 #if 0 /* TODO : w32 version */
12340 struct frame *f;
12341 Lisp_Object frame, tem;
12342 Lisp_Object name;
12343 long window_prompting = 0;
12344 int width, height;
12345 int count = specpdl_ptr - specpdl;
12346 struct gcpro gcpro1, gcpro2, gcpro3;
12347 struct kboard *kb;
12349 check_x ();
12351 /* Use this general default value to start with until we know if
12352 this frame has a specified name. */
12353 Vx_resource_name = Vinvocation_name;
12355 #ifdef MULTI_KBOARD
12356 kb = dpyinfo->kboard;
12357 #else
12358 kb = &the_only_kboard;
12359 #endif
12361 /* Get the name of the frame to use for resource lookup. */
12362 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
12363 if (!STRINGP (name)
12364 && !EQ (name, Qunbound)
12365 && !NILP (name))
12366 error ("Invalid frame name--not a string or nil");
12367 Vx_resource_name = name;
12369 frame = Qnil;
12370 GCPRO3 (parms, name, frame);
12371 f = make_frame (1);
12372 XSETFRAME (frame, f);
12373 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
12374 record_unwind_protect (unwind_create_tip_frame, frame);
12376 f->output_method = output_w32;
12377 f->output_data.w32 =
12378 (struct w32_output *) xmalloc (sizeof (struct w32_output));
12379 bzero (f->output_data.w32, sizeof (struct w32_output));
12380 #if 0
12381 f->output_data.w32->icon_bitmap = -1;
12382 #endif
12383 f->output_data.w32->fontset = -1;
12384 f->icon_name = Qnil;
12386 #ifdef GLYPH_DEBUG
12387 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
12388 dpyinfo_refcount = dpyinfo->reference_count;
12389 #endif /* GLYPH_DEBUG */
12390 #ifdef MULTI_KBOARD
12391 FRAME_KBOARD (f) = kb;
12392 #endif
12393 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12394 f->output_data.w32->explicit_parent = 0;
12396 /* Set the name; the functions to which we pass f expect the name to
12397 be set. */
12398 if (EQ (name, Qunbound) || NILP (name))
12400 f->name = build_string (dpyinfo->x_id_name);
12401 f->explicit_name = 0;
12403 else
12405 f->name = name;
12406 f->explicit_name = 1;
12407 /* use the frame's title when getting resources for this frame. */
12408 specbind (Qx_resource_name, name);
12411 /* Extract the window parameters from the supplied values
12412 that are needed to determine window geometry. */
12414 Lisp_Object font;
12416 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12418 BLOCK_INPUT;
12419 /* First, try whatever font the caller has specified. */
12420 if (STRINGP (font))
12422 tem = Fquery_fontset (font, Qnil);
12423 if (STRINGP (tem))
12424 font = x_new_fontset (f, XSTRING (tem)->data);
12425 else
12426 font = x_new_font (f, XSTRING (font)->data);
12429 /* Try out a font which we hope has bold and italic variations. */
12430 if (!STRINGP (font))
12431 font = x_new_font (f, "-*-courier new-normal-r-*-*-*-100-*-*-*-*-iso8859-1");
12432 if (!STRINGP (font))
12433 font = x_new_font (f, "-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12434 if (! STRINGP (font))
12435 font = x_new_font (f, "-*-*-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12436 if (! STRINGP (font))
12437 /* This was formerly the first thing tried, but it finds too many fonts
12438 and takes too long. */
12439 font = x_new_font (f, "-*-*-medium-r-*-*-*-*-*-*-c-*-iso8859-1");
12440 /* If those didn't work, look for something which will at least work. */
12441 if (! STRINGP (font))
12442 font = x_new_font (f, "-*-fixed-*-*-*-*-*-140-*-*-c-*-iso8859-1");
12443 UNBLOCK_INPUT;
12444 if (! STRINGP (font))
12445 font = build_string ("fixed");
12447 x_default_parameter (f, parms, Qfont, font,
12448 "font", "Font", RES_TYPE_STRING);
12451 x_default_parameter (f, parms, Qborder_width, make_number (2),
12452 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
12454 /* This defaults to 2 in order to match xterm. We recognize either
12455 internalBorderWidth or internalBorder (which is what xterm calls
12456 it). */
12457 if (NILP (Fassq (Qinternal_border_width, parms)))
12459 Lisp_Object value;
12461 value = w32_get_arg (parms, Qinternal_border_width,
12462 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12463 if (! EQ (value, Qunbound))
12464 parms = Fcons (Fcons (Qinternal_border_width, value),
12465 parms);
12468 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
12469 "internalBorderWidth", "internalBorderWidth",
12470 RES_TYPE_NUMBER);
12472 /* Also do the stuff which must be set before the window exists. */
12473 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12474 "foreground", "Foreground", RES_TYPE_STRING);
12475 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12476 "background", "Background", RES_TYPE_STRING);
12477 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12478 "pointerColor", "Foreground", RES_TYPE_STRING);
12479 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12480 "cursorColor", "Foreground", RES_TYPE_STRING);
12481 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12482 "borderColor", "BorderColor", RES_TYPE_STRING);
12484 /* Init faces before x_default_parameter is called for scroll-bar
12485 parameters because that function calls x_set_scroll_bar_width,
12486 which calls change_frame_size, which calls Fset_window_buffer,
12487 which runs hooks, which call Fvertical_motion. At the end, we
12488 end up in init_iterator with a null face cache, which should not
12489 happen. */
12490 init_frame_faces (f);
12492 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12493 window_prompting = x_figure_window_size (f, parms);
12495 if (window_prompting & XNegative)
12497 if (window_prompting & YNegative)
12498 f->output_data.w32->win_gravity = SouthEastGravity;
12499 else
12500 f->output_data.w32->win_gravity = NorthEastGravity;
12502 else
12504 if (window_prompting & YNegative)
12505 f->output_data.w32->win_gravity = SouthWestGravity;
12506 else
12507 f->output_data.w32->win_gravity = NorthWestGravity;
12510 f->output_data.w32->size_hint_flags = window_prompting;
12512 XSetWindowAttributes attrs;
12513 unsigned long mask;
12515 BLOCK_INPUT;
12516 mask = CWBackPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask;
12517 /* Window managers looks at the override-redirect flag to
12518 determine whether or net to give windows a decoration (Xlib
12519 3.2.8). */
12520 attrs.override_redirect = True;
12521 attrs.save_under = True;
12522 attrs.background_pixel = FRAME_BACKGROUND_PIXEL (f);
12523 /* Arrange for getting MapNotify and UnmapNotify events. */
12524 attrs.event_mask = StructureNotifyMask;
12525 tip_window
12526 = FRAME_W32_WINDOW (f)
12527 = XCreateWindow (FRAME_W32_DISPLAY (f),
12528 FRAME_W32_DISPLAY_INFO (f)->root_window,
12529 /* x, y, width, height */
12530 0, 0, 1, 1,
12531 /* Border. */
12533 CopyFromParent, InputOutput, CopyFromParent,
12534 mask, &attrs);
12535 UNBLOCK_INPUT;
12538 x_make_gc (f);
12540 x_default_parameter (f, parms, Qauto_raise, Qnil,
12541 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12542 x_default_parameter (f, parms, Qauto_lower, Qnil,
12543 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12544 x_default_parameter (f, parms, Qcursor_type, Qbox,
12545 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12547 /* Dimensions, especially f->height, must be done via change_frame_size.
12548 Change will not be effected unless different from the current
12549 f->height. */
12550 width = f->width;
12551 height = f->height;
12552 f->height = 0;
12553 SET_FRAME_WIDTH (f, 0);
12554 change_frame_size (f, height, width, 1, 0, 0);
12556 f->no_split = 1;
12558 UNGCPRO;
12560 /* It is now ok to make the frame official even if we get an error
12561 below. And the frame needs to be on Vframe_list or making it
12562 visible won't work. */
12563 Vframe_list = Fcons (frame, Vframe_list);
12564 tip_frame = frame;
12566 /* Now that the frame is official, it counts as a reference to
12567 its display. */
12568 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
12570 return unbind_to (count, frame);
12571 #endif /* TODO */
12572 return Qnil;
12575 #ifdef TODO /* Tooltip support not complete. */
12576 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
12577 "Show STRING in a \"tooltip\" window on frame FRAME.\n\
12578 A tooltip window is a small X window displaying a string.\n\
12580 FRAME nil or omitted means use the selected frame.\n\
12582 PARMS is an optional list of frame parameters which can be\n\
12583 used to change the tooltip's appearance.\n\
12585 Automatically hide the tooltip after TIMEOUT seconds.\n\
12586 TIMEOUT nil means use the default timeout of 5 seconds.\n\
12588 If the list of frame parameters PARAMS contains a `left' parameters,\n\
12589 the tooltip is displayed at that x-position. Otherwise it is\n\
12590 displayed at the mouse position, with offset DX added (default is 5 if\n\
12591 DX isn't specified). Likewise for the y-position; if a `top' frame\n\
12592 parameter is specified, it determines the y-position of the tooltip\n\
12593 window, otherwise it is displayed at the mouse position, with offset\n\
12594 DY added (default is -5).")
12595 (string, frame, parms, timeout, dx, dy)
12596 Lisp_Object string, frame, parms, timeout, dx, dy;
12598 struct frame *f;
12599 struct window *w;
12600 Window root, child;
12601 Lisp_Object buffer, top, left;
12602 struct buffer *old_buffer;
12603 struct text_pos pos;
12604 int i, width, height;
12605 int root_x, root_y, win_x, win_y;
12606 unsigned pmask;
12607 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
12608 int old_windows_or_buffers_changed = windows_or_buffers_changed;
12609 int count = specpdl_ptr - specpdl;
12611 specbind (Qinhibit_redisplay, Qt);
12613 GCPRO4 (string, parms, frame, timeout);
12615 CHECK_STRING (string, 0);
12616 f = check_x_frame (frame);
12617 if (NILP (timeout))
12618 timeout = make_number (5);
12619 else
12620 CHECK_NATNUM (timeout, 2);
12622 if (NILP (dx))
12623 dx = make_number (5);
12624 else
12625 CHECK_NUMBER (dx, 5);
12627 if (NILP (dy))
12628 dy = make_number (-5);
12629 else
12630 CHECK_NUMBER (dy, 6);
12632 /* Hide a previous tip, if any. */
12633 Fx_hide_tip ();
12635 /* Add default values to frame parameters. */
12636 if (NILP (Fassq (Qname, parms)))
12637 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
12638 if (NILP (Fassq (Qinternal_border_width, parms)))
12639 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
12640 if (NILP (Fassq (Qborder_width, parms)))
12641 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
12642 if (NILP (Fassq (Qborder_color, parms)))
12643 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
12644 if (NILP (Fassq (Qbackground_color, parms)))
12645 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
12646 parms);
12648 /* Create a frame for the tooltip, and record it in the global
12649 variable tip_frame. */
12650 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms);
12651 f = XFRAME (frame);
12653 /* Set up the frame's root window. Currently we use a size of 80
12654 columns x 40 lines. If someone wants to show a larger tip, he
12655 will loose. I don't think this is a realistic case. */
12656 w = XWINDOW (FRAME_ROOT_WINDOW (f));
12657 w->left = w->top = make_number (0);
12658 w->width = 80;
12659 w->height = 40;
12660 adjust_glyphs (f);
12661 w->pseudo_window_p = 1;
12663 /* Display the tooltip text in a temporary buffer. */
12664 buffer = Fget_buffer_create (build_string (" *tip*"));
12665 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
12666 old_buffer = current_buffer;
12667 set_buffer_internal_1 (XBUFFER (buffer));
12668 Ferase_buffer ();
12669 Finsert (make_number (1), &string);
12670 clear_glyph_matrix (w->desired_matrix);
12671 clear_glyph_matrix (w->current_matrix);
12672 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
12673 try_window (FRAME_ROOT_WINDOW (f), pos);
12675 /* Compute width and height of the tooltip. */
12676 width = height = 0;
12677 for (i = 0; i < w->desired_matrix->nrows; ++i)
12679 struct glyph_row *row = &w->desired_matrix->rows[i];
12680 struct glyph *last;
12681 int row_width;
12683 /* Stop at the first empty row at the end. */
12684 if (!row->enabled_p || !row->displays_text_p)
12685 break;
12687 /* Let the row go over the full width of the frame. */
12688 row->full_width_p = 1;
12690 /* There's a glyph at the end of rows that is use to place
12691 the cursor there. Don't include the width of this glyph. */
12692 if (row->used[TEXT_AREA])
12694 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
12695 row_width = row->pixel_width - last->pixel_width;
12697 else
12698 row_width = row->pixel_width;
12700 height += row->height;
12701 width = max (width, row_width);
12704 /* Add the frame's internal border to the width and height the X
12705 window should have. */
12706 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12707 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12709 /* User-specified position? */
12710 left = Fcdr (Fassq (Qleft, parms));
12711 top = Fcdr (Fassq (Qtop, parms));
12713 /* Move the tooltip window where the mouse pointer is. Resize and
12714 show it. */
12715 #if 0 /* TODO : W32 specifics */
12716 BLOCK_INPUT;
12717 XQueryPointer (FRAME_X_DISPLAY (f), FRAME_X_DISPLAY_INFO (f)->root_window,
12718 &root, &child, &root_x, &root_y, &win_x, &win_y, &pmask);
12719 UNBLOCK_INPUT;
12721 root_x += XINT (dx);
12722 root_y += XINT (dy);
12724 if (INTEGERP (left))
12725 root_x = XINT (left);
12726 if (INTEGERP (top))
12727 root_y = XINT (top);
12729 BLOCK_INPUT;
12730 XMoveResizeWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12731 root_x, root_y - height, width, height);
12732 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12733 UNBLOCK_INPUT;
12734 #endif /* TODO */
12736 /* Draw into the window. */
12737 w->must_be_updated_p = 1;
12738 update_single_window (w, 1);
12740 /* Restore original current buffer. */
12741 set_buffer_internal_1 (old_buffer);
12742 windows_or_buffers_changed = old_windows_or_buffers_changed;
12744 /* Let the tip disappear after timeout seconds. */
12745 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
12746 intern ("x-hide-tip"));
12748 UNGCPRO;
12749 return unbind_to (count, Qnil);
12753 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
12754 "Hide the current tooltip window, if there is any.\n\
12755 Value is t is tooltip was open, nil otherwise.")
12758 int count;
12759 Lisp_Object deleted, frame, timer;
12760 struct gcpro gcpro1, gcpro2;
12762 /* Return quickly if nothing to do. */
12763 if (NILP (tip_timer) && NILP (tip_frame))
12764 return Qnil;
12766 frame = tip_frame;
12767 timer = tip_timer;
12768 GCPRO2 (frame, timer);
12769 tip_frame = tip_timer = deleted = Qnil;
12771 count = BINDING_STACK_SIZE ();
12772 specbind (Qinhibit_redisplay, Qt);
12773 specbind (Qinhibit_quit, Qt);
12775 if (!NILP (timer))
12776 call1 (intern ("cancel-timer"), timer);
12778 if (FRAMEP (frame))
12780 Fdelete_frame (frame, Qnil);
12781 deleted = Qt;
12784 UNGCPRO;
12785 return unbind_to (count, deleted);
12787 #endif
12791 /***********************************************************************
12792 File selection dialog
12793 ***********************************************************************/
12795 extern Lisp_Object Qfile_name_history;
12797 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
12798 "Read file name, prompting with PROMPT in directory DIR.\n\
12799 Use a file selection dialog.\n\
12800 Select DEFAULT-FILENAME in the dialog's file selection box, if\n\
12801 specified. Don't let the user enter a file name in the file\n\
12802 selection dialog's entry field, if MUSTMATCH is non-nil.")
12803 (prompt, dir, default_filename, mustmatch)
12804 Lisp_Object prompt, dir, default_filename, mustmatch;
12806 struct frame *f = SELECTED_FRAME ();
12807 Lisp_Object file = Qnil;
12808 int count = specpdl_ptr - specpdl;
12809 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
12810 char filename[MAX_PATH + 1];
12811 char init_dir[MAX_PATH + 1];
12812 int use_dialog_p = 1;
12814 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
12815 CHECK_STRING (prompt, 0);
12816 CHECK_STRING (dir, 1);
12818 /* Create the dialog with PROMPT as title, using DIR as initial
12819 directory and using "*" as pattern. */
12820 dir = Fexpand_file_name (dir, Qnil);
12821 strncpy (init_dir, XSTRING (dir)->data, MAX_PATH);
12822 init_dir[MAX_PATH] = '\0';
12823 unixtodos_filename (init_dir);
12825 if (STRINGP (default_filename))
12827 char *file_name_only;
12828 char *full_path_name = XSTRING (default_filename)->data;
12830 unixtodos_filename (full_path_name);
12832 file_name_only = strrchr (full_path_name, '\\');
12833 if (!file_name_only)
12834 file_name_only = full_path_name;
12835 else
12837 file_name_only++;
12839 /* If default_file_name is a directory, don't use the open
12840 file dialog, as it does not support selecting
12841 directories. */
12842 if (!(*file_name_only))
12843 use_dialog_p = 0;
12846 strncpy (filename, file_name_only, MAX_PATH);
12847 filename[MAX_PATH] = '\0';
12849 else
12850 filename[0] = '\0';
12852 if (use_dialog_p)
12854 OPENFILENAME file_details;
12856 /* Prevent redisplay. */
12857 specbind (Qinhibit_redisplay, Qt);
12858 BLOCK_INPUT;
12860 bzero (&file_details, sizeof (file_details));
12861 file_details.lStructSize = sizeof (file_details);
12862 file_details.hwndOwner = FRAME_W32_WINDOW (f);
12863 file_details.lpstrFile = filename;
12864 file_details.nMaxFile = sizeof (filename);
12865 file_details.lpstrInitialDir = init_dir;
12866 file_details.lpstrTitle = XSTRING (prompt)->data;
12867 file_details.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
12869 if (!NILP (mustmatch))
12870 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
12872 if (GetOpenFileName (&file_details))
12874 dostounix_filename (filename);
12875 file = build_string (filename);
12877 else
12878 file = Qnil;
12880 UNBLOCK_INPUT;
12881 file = unbind_to (count, file);
12883 /* Open File dialog will not allow folders to be selected, so resort
12884 to minibuffer completing reads for directories. */
12885 else
12886 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
12887 dir, mustmatch, dir, Qfile_name_history,
12888 default_filename, Qnil);
12890 UNGCPRO;
12892 /* Make "Cancel" equivalent to C-g. */
12893 if (NILP (file))
12894 Fsignal (Qquit, Qnil);
12896 return unbind_to (count, file);
12901 /***********************************************************************
12902 Tests
12903 ***********************************************************************/
12905 #if GLYPH_DEBUG
12907 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
12908 "Value is non-nil if SPEC is a valid image specification.")
12909 (spec)
12910 Lisp_Object spec;
12912 return valid_image_p (spec) ? Qt : Qnil;
12916 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
12917 (spec)
12918 Lisp_Object spec;
12920 int id = -1;
12922 if (valid_image_p (spec))
12923 id = lookup_image (SELECTED_FRAME (), spec);
12925 debug_print (spec);
12926 return make_number (id);
12929 #endif /* GLYPH_DEBUG != 0 */
12933 /***********************************************************************
12934 w32 specialized functions
12935 ***********************************************************************/
12937 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 1, 0,
12938 "This will display the W32 font dialog and return an X font string corresponding to the selection.")
12939 (frame)
12940 Lisp_Object frame;
12942 FRAME_PTR f = check_x_frame (frame);
12943 CHOOSEFONT cf;
12944 LOGFONT lf;
12945 TEXTMETRIC tm;
12946 HDC hdc;
12947 HANDLE oldobj;
12948 char buf[100];
12950 bzero (&cf, sizeof (cf));
12951 bzero (&lf, sizeof (lf));
12953 cf.lStructSize = sizeof (cf);
12954 cf.hwndOwner = FRAME_W32_WINDOW (f);
12955 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS;
12956 cf.lpLogFont = &lf;
12958 /* Initialize as much of the font details as we can from the current
12959 default font. */
12960 hdc = GetDC (FRAME_W32_WINDOW (f));
12961 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
12962 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
12963 if (GetTextMetrics (hdc, &tm))
12965 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
12966 lf.lfWeight = tm.tmWeight;
12967 lf.lfItalic = tm.tmItalic;
12968 lf.lfUnderline = tm.tmUnderlined;
12969 lf.lfStrikeOut = tm.tmStruckOut;
12970 lf.lfCharSet = tm.tmCharSet;
12971 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
12973 SelectObject (hdc, oldobj);
12974 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
12976 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
12977 return Qnil;
12979 return build_string (buf);
12982 DEFUN ("w32-send-sys-command", Fw32_send_sys_command, Sw32_send_sys_command, 1, 2, 0,
12983 "Send frame a Windows WM_SYSCOMMAND message of type COMMAND.\n\
12984 Some useful values for command are 0xf030 to maximise frame (0xf020\n\
12985 to minimize), 0xf120 to restore frame to original size, and 0xf100\n\
12986 to activate the menubar for keyboard access. 0xf140 activates the\n\
12987 screen saver if defined.\n\
12989 If optional parameter FRAME is not specified, use selected frame.")
12990 (command, frame)
12991 Lisp_Object command, frame;
12993 FRAME_PTR f = check_x_frame (frame);
12995 CHECK_NUMBER (command, 0);
12997 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
12999 return Qnil;
13002 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
13003 "Get Windows to perform OPERATION on DOCUMENT.\n\
13004 This is a wrapper around the ShellExecute system function, which\n\
13005 invokes the application registered to handle OPERATION for DOCUMENT.\n\
13006 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be\n\
13007 nil for the default action), and DOCUMENT is typically the name of a\n\
13008 document file or URL, but can also be a program executable to run or\n\
13009 a directory to open in the Windows Explorer.\n\
13011 If DOCUMENT is a program executable, PARAMETERS can be a string\n\
13012 containing command line parameters, but otherwise should be nil.\n\
13014 SHOW-FLAG can be used to control whether the invoked application is hidden\n\
13015 or minimized. If SHOW-FLAG is nil, the application is displayed normally,\n\
13016 otherwise it is an integer representing a ShowWindow flag:\n\
13018 0 - start hidden\n\
13019 1 - start normally\n\
13020 3 - start maximized\n\
13021 6 - start minimized")
13022 (operation, document, parameters, show_flag)
13023 Lisp_Object operation, document, parameters, show_flag;
13025 Lisp_Object current_dir;
13027 CHECK_STRING (document, 0);
13029 /* Encode filename and current directory. */
13030 current_dir = ENCODE_FILE (current_buffer->directory);
13031 document = ENCODE_FILE (document);
13032 if ((int) ShellExecute (NULL,
13033 (STRINGP (operation) ?
13034 XSTRING (operation)->data : NULL),
13035 XSTRING (document)->data,
13036 (STRINGP (parameters) ?
13037 XSTRING (parameters)->data : NULL),
13038 XSTRING (current_dir)->data,
13039 (INTEGERP (show_flag) ?
13040 XINT (show_flag) : SW_SHOWDEFAULT))
13041 > 32)
13042 return Qt;
13043 error ("ShellExecute failed: %s", w32_strerror (0));
13046 /* Lookup virtual keycode from string representing the name of a
13047 non-ascii keystroke into the corresponding virtual key, using
13048 lispy_function_keys. */
13049 static int
13050 lookup_vk_code (char *key)
13052 int i;
13054 for (i = 0; i < 256; i++)
13055 if (lispy_function_keys[i] != 0
13056 && strcmp (lispy_function_keys[i], key) == 0)
13057 return i;
13059 return -1;
13062 /* Convert a one-element vector style key sequence to a hot key
13063 definition. */
13064 static int
13065 w32_parse_hot_key (key)
13066 Lisp_Object key;
13068 /* Copied from Fdefine_key and store_in_keymap. */
13069 register Lisp_Object c;
13070 int vk_code;
13071 int lisp_modifiers;
13072 int w32_modifiers;
13073 struct gcpro gcpro1;
13075 CHECK_VECTOR (key, 0);
13077 if (XFASTINT (Flength (key)) != 1)
13078 return Qnil;
13080 GCPRO1 (key);
13082 c = Faref (key, make_number (0));
13084 if (CONSP (c) && lucid_event_type_list_p (c))
13085 c = Fevent_convert_list (c);
13087 UNGCPRO;
13089 if (! INTEGERP (c) && ! SYMBOLP (c))
13090 error ("Key definition is invalid");
13092 /* Work out the base key and the modifiers. */
13093 if (SYMBOLP (c))
13095 c = parse_modifiers (c);
13096 lisp_modifiers = Fcar (Fcdr (c));
13097 c = Fcar (c);
13098 if (!SYMBOLP (c))
13099 abort ();
13100 vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
13102 else if (INTEGERP (c))
13104 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
13105 /* Many ascii characters are their own virtual key code. */
13106 vk_code = XINT (c) & CHARACTERBITS;
13109 if (vk_code < 0 || vk_code > 255)
13110 return Qnil;
13112 if ((lisp_modifiers & meta_modifier) != 0
13113 && !NILP (Vw32_alt_is_meta))
13114 lisp_modifiers |= alt_modifier;
13116 /* Supply defs missing from mingw32. */
13117 #ifndef MOD_ALT
13118 #define MOD_ALT 0x0001
13119 #define MOD_CONTROL 0x0002
13120 #define MOD_SHIFT 0x0004
13121 #define MOD_WIN 0x0008
13122 #endif
13124 /* Convert lisp modifiers to Windows hot-key form. */
13125 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
13126 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
13127 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
13128 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
13130 return HOTKEY (vk_code, w32_modifiers);
13133 DEFUN ("w32-register-hot-key", Fw32_register_hot_key, Sw32_register_hot_key, 1, 1, 0,
13134 "Register KEY as a hot-key combination.\n\
13135 Certain key combinations like Alt-Tab are reserved for system use on\n\
13136 Windows, and therefore are normally intercepted by the system. However,\n\
13137 most of these key combinations can be received by registering them as\n\
13138 hot-keys, overriding their special meaning.\n\
13140 KEY must be a one element key definition in vector form that would be\n\
13141 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta\n\
13142 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper\n\
13143 is always interpreted as the Windows modifier keys.\n\
13145 The return value is the hotkey-id if registered, otherwise nil.")
13146 (key)
13147 Lisp_Object key;
13149 key = w32_parse_hot_key (key);
13151 if (NILP (Fmemq (key, w32_grabbed_keys)))
13153 /* Reuse an empty slot if possible. */
13154 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
13156 /* Safe to add new key to list, even if we have focus. */
13157 if (NILP (item))
13158 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
13159 else
13160 XCAR (item) = key;
13162 /* Notify input thread about new hot-key definition, so that it
13163 takes effect without needing to switch focus. */
13164 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
13165 (WPARAM) key, 0);
13168 return key;
13171 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key, Sw32_unregister_hot_key, 1, 1, 0,
13172 "Unregister HOTKEY as a hot-key combination.")
13173 (key)
13174 Lisp_Object key;
13176 Lisp_Object item;
13178 if (!INTEGERP (key))
13179 key = w32_parse_hot_key (key);
13181 item = Fmemq (key, w32_grabbed_keys);
13183 if (!NILP (item))
13185 /* Notify input thread about hot-key definition being removed, so
13186 that it takes effect without needing focus switch. */
13187 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
13188 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
13190 MSG msg;
13191 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13193 return Qt;
13195 return Qnil;
13198 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys, Sw32_registered_hot_keys, 0, 0, 0,
13199 "Return list of registered hot-key IDs.")
13202 return Fcopy_sequence (w32_grabbed_keys);
13205 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key, Sw32_reconstruct_hot_key, 1, 1, 0,
13206 "Convert hot-key ID to a lisp key combination.")
13207 (hotkeyid)
13208 Lisp_Object hotkeyid;
13210 int vk_code, w32_modifiers;
13211 Lisp_Object key;
13213 CHECK_NUMBER (hotkeyid, 0);
13215 vk_code = HOTKEY_VK_CODE (hotkeyid);
13216 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
13218 if (lispy_function_keys[vk_code])
13219 key = intern (lispy_function_keys[vk_code]);
13220 else
13221 key = make_number (vk_code);
13223 key = Fcons (key, Qnil);
13224 if (w32_modifiers & MOD_SHIFT)
13225 key = Fcons (Qshift, key);
13226 if (w32_modifiers & MOD_CONTROL)
13227 key = Fcons (Qctrl, key);
13228 if (w32_modifiers & MOD_ALT)
13229 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
13230 if (w32_modifiers & MOD_WIN)
13231 key = Fcons (Qhyper, key);
13233 return key;
13236 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key, Sw32_toggle_lock_key, 1, 2, 0,
13237 "Toggle the state of the lock key KEY.\n\
13238 KEY can be `capslock', `kp-numlock', or `scroll'.\n\
13239 If the optional parameter NEW-STATE is a number, then the state of KEY\n\
13240 is set to off if the low bit of NEW-STATE is zero, otherwise on.")
13241 (key, new_state)
13242 Lisp_Object key, new_state;
13244 int vk_code;
13246 if (EQ (key, intern ("capslock")))
13247 vk_code = VK_CAPITAL;
13248 else if (EQ (key, intern ("kp-numlock")))
13249 vk_code = VK_NUMLOCK;
13250 else if (EQ (key, intern ("scroll")))
13251 vk_code = VK_SCROLL;
13252 else
13253 return Qnil;
13255 if (!dwWindowsThreadId)
13256 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
13258 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
13259 (WPARAM) vk_code, (LPARAM) new_state))
13261 MSG msg;
13262 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13263 return make_number (msg.wParam);
13265 return Qnil;
13268 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
13269 "Return storage information about the file system FILENAME is on.\n\
13270 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total\n\
13271 storage of the file system, FREE is the free storage, and AVAIL is the\n\
13272 storage available to a non-superuser. All 3 numbers are in bytes.\n\
13273 If the underlying system call fails, value is nil.")
13274 (filename)
13275 Lisp_Object filename;
13277 Lisp_Object encoded, value;
13279 CHECK_STRING (filename, 0);
13280 filename = Fexpand_file_name (filename, Qnil);
13281 encoded = ENCODE_FILE (filename);
13283 value = Qnil;
13285 /* Determining the required information on Windows turns out, sadly,
13286 to be more involved than one would hope. The original Win32 api
13287 call for this will return bogus information on some systems, but we
13288 must dynamically probe for the replacement api, since that was
13289 added rather late on. */
13291 HMODULE hKernel = GetModuleHandle ("kernel32");
13292 BOOL (*pfn_GetDiskFreeSpaceEx)
13293 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
13294 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
13296 /* On Windows, we may need to specify the root directory of the
13297 volume holding FILENAME. */
13298 char rootname[MAX_PATH];
13299 char *name = XSTRING (encoded)->data;
13301 /* find the root name of the volume if given */
13302 if (isalpha (name[0]) && name[1] == ':')
13304 rootname[0] = name[0];
13305 rootname[1] = name[1];
13306 rootname[2] = '\\';
13307 rootname[3] = 0;
13309 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
13311 char *str = rootname;
13312 int slashes = 4;
13315 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
13316 break;
13317 *str++ = *name++;
13319 while ( *name );
13321 *str++ = '\\';
13322 *str = 0;
13325 if (pfn_GetDiskFreeSpaceEx)
13327 LARGE_INTEGER availbytes;
13328 LARGE_INTEGER freebytes;
13329 LARGE_INTEGER totalbytes;
13331 if (pfn_GetDiskFreeSpaceEx(rootname,
13332 &availbytes,
13333 &totalbytes,
13334 &freebytes))
13335 value = list3 (make_float ((double) totalbytes.QuadPart),
13336 make_float ((double) freebytes.QuadPart),
13337 make_float ((double) availbytes.QuadPart));
13339 else
13341 DWORD sectors_per_cluster;
13342 DWORD bytes_per_sector;
13343 DWORD free_clusters;
13344 DWORD total_clusters;
13346 if (GetDiskFreeSpace(rootname,
13347 &sectors_per_cluster,
13348 &bytes_per_sector,
13349 &free_clusters,
13350 &total_clusters))
13351 value = list3 (make_float ((double) total_clusters
13352 * sectors_per_cluster * bytes_per_sector),
13353 make_float ((double) free_clusters
13354 * sectors_per_cluster * bytes_per_sector),
13355 make_float ((double) free_clusters
13356 * sectors_per_cluster * bytes_per_sector));
13360 return value;
13363 syms_of_w32fns ()
13365 /* This is zero if not using MS-Windows. */
13366 w32_in_use = 0;
13368 /* The section below is built by the lisp expression at the top of the file,
13369 just above where these variables are declared. */
13370 /*&&& init symbols here &&&*/
13371 Qauto_raise = intern ("auto-raise");
13372 staticpro (&Qauto_raise);
13373 Qauto_lower = intern ("auto-lower");
13374 staticpro (&Qauto_lower);
13375 Qbar = intern ("bar");
13376 staticpro (&Qbar);
13377 Qborder_color = intern ("border-color");
13378 staticpro (&Qborder_color);
13379 Qborder_width = intern ("border-width");
13380 staticpro (&Qborder_width);
13381 Qbox = intern ("box");
13382 staticpro (&Qbox);
13383 Qcursor_color = intern ("cursor-color");
13384 staticpro (&Qcursor_color);
13385 Qcursor_type = intern ("cursor-type");
13386 staticpro (&Qcursor_type);
13387 Qgeometry = intern ("geometry");
13388 staticpro (&Qgeometry);
13389 Qicon_left = intern ("icon-left");
13390 staticpro (&Qicon_left);
13391 Qicon_top = intern ("icon-top");
13392 staticpro (&Qicon_top);
13393 Qicon_type = intern ("icon-type");
13394 staticpro (&Qicon_type);
13395 Qicon_name = intern ("icon-name");
13396 staticpro (&Qicon_name);
13397 Qinternal_border_width = intern ("internal-border-width");
13398 staticpro (&Qinternal_border_width);
13399 Qleft = intern ("left");
13400 staticpro (&Qleft);
13401 Qright = intern ("right");
13402 staticpro (&Qright);
13403 Qmouse_color = intern ("mouse-color");
13404 staticpro (&Qmouse_color);
13405 Qnone = intern ("none");
13406 staticpro (&Qnone);
13407 Qparent_id = intern ("parent-id");
13408 staticpro (&Qparent_id);
13409 Qscroll_bar_width = intern ("scroll-bar-width");
13410 staticpro (&Qscroll_bar_width);
13411 Qsuppress_icon = intern ("suppress-icon");
13412 staticpro (&Qsuppress_icon);
13413 Qundefined_color = intern ("undefined-color");
13414 staticpro (&Qundefined_color);
13415 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
13416 staticpro (&Qvertical_scroll_bars);
13417 Qvisibility = intern ("visibility");
13418 staticpro (&Qvisibility);
13419 Qwindow_id = intern ("window-id");
13420 staticpro (&Qwindow_id);
13421 Qx_frame_parameter = intern ("x-frame-parameter");
13422 staticpro (&Qx_frame_parameter);
13423 Qx_resource_name = intern ("x-resource-name");
13424 staticpro (&Qx_resource_name);
13425 Quser_position = intern ("user-position");
13426 staticpro (&Quser_position);
13427 Quser_size = intern ("user-size");
13428 staticpro (&Quser_size);
13429 Qscreen_gamma = intern ("screen-gamma");
13430 staticpro (&Qscreen_gamma);
13431 Qline_spacing = intern ("line-spacing");
13432 staticpro (&Qline_spacing);
13433 Qcenter = intern ("center");
13434 staticpro (&Qcenter);
13435 /* This is the end of symbol initialization. */
13437 Qhyper = intern ("hyper");
13438 staticpro (&Qhyper);
13439 Qsuper = intern ("super");
13440 staticpro (&Qsuper);
13441 Qmeta = intern ("meta");
13442 staticpro (&Qmeta);
13443 Qalt = intern ("alt");
13444 staticpro (&Qalt);
13445 Qctrl = intern ("ctrl");
13446 staticpro (&Qctrl);
13447 Qcontrol = intern ("control");
13448 staticpro (&Qcontrol);
13449 Qshift = intern ("shift");
13450 staticpro (&Qshift);
13452 /* Text property `display' should be nonsticky by default. */
13453 Vtext_property_default_nonsticky
13454 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
13457 Qlaplace = intern ("laplace");
13458 staticpro (&Qlaplace);
13460 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
13461 staticpro (&Qface_set_after_frame_default);
13463 Fput (Qundefined_color, Qerror_conditions,
13464 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
13465 Fput (Qundefined_color, Qerror_message,
13466 build_string ("Undefined color"));
13468 staticpro (&w32_grabbed_keys);
13469 w32_grabbed_keys = Qnil;
13471 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
13472 "An array of color name mappings for windows.");
13473 Vw32_color_map = Qnil;
13475 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
13476 "Non-nil if alt key presses are passed on to Windows.\n\
13477 When non-nil, for example, alt pressed and released and then space will\n\
13478 open the System menu. When nil, Emacs silently swallows alt key events.");
13479 Vw32_pass_alt_to_system = Qnil;
13481 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
13482 "Non-nil if the alt key is to be considered the same as the meta key.\n\
13483 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta.");
13484 Vw32_alt_is_meta = Qt;
13486 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
13487 "If non-zero, the virtual key code for an alternative quit key.");
13488 XSETINT (Vw32_quit_key, 0);
13490 DEFVAR_LISP ("w32-pass-lwindow-to-system",
13491 &Vw32_pass_lwindow_to_system,
13492 "Non-nil if the left \"Windows\" key is passed on to Windows.\n\
13493 When non-nil, the Start menu is opened by tapping the key.");
13494 Vw32_pass_lwindow_to_system = Qt;
13496 DEFVAR_LISP ("w32-pass-rwindow-to-system",
13497 &Vw32_pass_rwindow_to_system,
13498 "Non-nil if the right \"Windows\" key is passed on to Windows.\n\
13499 When non-nil, the Start menu is opened by tapping the key.");
13500 Vw32_pass_rwindow_to_system = Qt;
13502 DEFVAR_INT ("w32-phantom-key-code",
13503 &Vw32_phantom_key_code,
13504 "Virtual key code used to generate \"phantom\" key presses.\n\
13505 Value is a number between 0 and 255.\n\
13507 Phantom key presses are generated in order to stop the system from\n\
13508 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or\n\
13509 `w32-pass-rwindow-to-system' is nil.");
13510 /* Although 255 is technically not a valid key code, it works and
13511 means that this hack won't interfere with any real key code. */
13512 Vw32_phantom_key_code = 255;
13514 DEFVAR_LISP ("w32-enable-num-lock",
13515 &Vw32_enable_num_lock,
13516 "Non-nil if Num Lock should act normally.\n\
13517 Set to nil to see Num Lock as the key `kp-numlock'.");
13518 Vw32_enable_num_lock = Qt;
13520 DEFVAR_LISP ("w32-enable-caps-lock",
13521 &Vw32_enable_caps_lock,
13522 "Non-nil if Caps Lock should act normally.\n\
13523 Set to nil to see Caps Lock as the key `capslock'.");
13524 Vw32_enable_caps_lock = Qt;
13526 DEFVAR_LISP ("w32-scroll-lock-modifier",
13527 &Vw32_scroll_lock_modifier,
13528 "Modifier to use for the Scroll Lock on state.\n\
13529 The value can be hyper, super, meta, alt, control or shift for the\n\
13530 respective modifier, or nil to see Scroll Lock as the key `scroll'.\n\
13531 Any other value will cause the key to be ignored.");
13532 Vw32_scroll_lock_modifier = Qt;
13534 DEFVAR_LISP ("w32-lwindow-modifier",
13535 &Vw32_lwindow_modifier,
13536 "Modifier to use for the left \"Windows\" key.\n\
13537 The value can be hyper, super, meta, alt, control or shift for the\n\
13538 respective modifier, or nil to appear as the key `lwindow'.\n\
13539 Any other value will cause the key to be ignored.");
13540 Vw32_lwindow_modifier = Qnil;
13542 DEFVAR_LISP ("w32-rwindow-modifier",
13543 &Vw32_rwindow_modifier,
13544 "Modifier to use for the right \"Windows\" key.\n\
13545 The value can be hyper, super, meta, alt, control or shift for the\n\
13546 respective modifier, or nil to appear as the key `rwindow'.\n\
13547 Any other value will cause the key to be ignored.");
13548 Vw32_rwindow_modifier = Qnil;
13550 DEFVAR_LISP ("w32-apps-modifier",
13551 &Vw32_apps_modifier,
13552 "Modifier to use for the \"Apps\" key.\n\
13553 The value can be hyper, super, meta, alt, control or shift for the\n\
13554 respective modifier, or nil to appear as the key `apps'.\n\
13555 Any other value will cause the key to be ignored.");
13556 Vw32_apps_modifier = Qnil;
13558 DEFVAR_LISP ("w32-enable-synthesized-fonts", &Vw32_enable_synthesized_fonts,
13559 "Non-nil enables selection of artificially italicized and bold fonts.");
13560 Vw32_enable_synthesized_fonts = Qnil;
13562 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
13563 "Non-nil enables Windows palette management to map colors exactly.");
13564 Vw32_enable_palette = Qt;
13566 DEFVAR_INT ("w32-mouse-button-tolerance",
13567 &Vw32_mouse_button_tolerance,
13568 "Analogue of double click interval for faking middle mouse events.\n\
13569 The value is the minimum time in milliseconds that must elapse between\n\
13570 left/right button down events before they are considered distinct events.\n\
13571 If both mouse buttons are depressed within this interval, a middle mouse\n\
13572 button down event is generated instead.");
13573 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
13575 DEFVAR_INT ("w32-mouse-move-interval",
13576 &Vw32_mouse_move_interval,
13577 "Minimum interval between mouse move events.\n\
13578 The value is the minimum time in milliseconds that must elapse between\n\
13579 successive mouse move (or scroll bar drag) events before they are\n\
13580 reported as lisp events.");
13581 XSETINT (Vw32_mouse_move_interval, 0);
13583 init_x_parm_symbols ();
13585 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
13586 "List of directories to search for bitmap files for w32.");
13587 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
13589 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
13590 "The shape of the pointer when over text.\n\
13591 Changing the value does not affect existing frames\n\
13592 unless you set the mouse color.");
13593 Vx_pointer_shape = Qnil;
13595 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
13596 "The name Emacs uses to look up resources; for internal use only.\n\
13597 `x-get-resource' uses this as the first component of the instance name\n\
13598 when requesting resource values.\n\
13599 Emacs initially sets `x-resource-name' to the name under which Emacs\n\
13600 was invoked, or to the value specified with the `-name' or `-rn'\n\
13601 switches, if present.");
13602 Vx_resource_name = Qnil;
13604 Vx_nontext_pointer_shape = Qnil;
13606 Vx_mode_pointer_shape = Qnil;
13608 DEFVAR_LISP ("x-busy-pointer-shape", &Vx_busy_pointer_shape,
13609 "The shape of the pointer when Emacs is busy.\n\
13610 This variable takes effect when you create a new frame\n\
13611 or when you set the mouse color.");
13612 Vx_busy_pointer_shape = Qnil;
13614 DEFVAR_BOOL ("display-busy-cursor", &display_busy_cursor_p,
13615 "Non-zero means Emacs displays a busy cursor on window systems.");
13616 display_busy_cursor_p = 1;
13618 DEFVAR_LISP ("busy-cursor-delay", &Vbusy_cursor_delay,
13619 "*Seconds to wait before displaying a busy-cursor.\n\
13620 Value must be an integer or float.");
13621 Vbusy_cursor_delay = make_number (DEFAULT_BUSY_CURSOR_DELAY);
13623 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
13624 &Vx_sensitive_text_pointer_shape,
13625 "The shape of the pointer when over mouse-sensitive text.\n\
13626 This variable takes effect when you create a new frame\n\
13627 or when you set the mouse color.");
13628 Vx_sensitive_text_pointer_shape = Qnil;
13630 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
13631 &Vx_window_horizontal_drag_shape,
13632 "Pointer shape to use for indicating a window can be dragged horizontally.\n\
13633 This variable takes effect when you create a new frame\n\
13634 or when you set the mouse color.");
13635 Vx_window_horizontal_drag_shape = Qnil;
13637 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
13638 "A string indicating the foreground color of the cursor box.");
13639 Vx_cursor_fore_pixel = Qnil;
13641 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
13642 "Non-nil if no window manager is in use.\n\
13643 Emacs doesn't try to figure this out; this is always nil\n\
13644 unless you set it to something else.");
13645 /* We don't have any way to find this out, so set it to nil
13646 and maybe the user would like to set it to t. */
13647 Vx_no_window_manager = Qnil;
13649 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
13650 &Vx_pixel_size_width_font_regexp,
13651 "Regexp matching a font name whose width is the same as `PIXEL_SIZE'.\n\
13653 Since Emacs gets width of a font matching with this regexp from\n\
13654 PIXEL_SIZE field of the name, font finding mechanism gets faster for\n\
13655 such a font. This is especially effective for such large fonts as\n\
13656 Chinese, Japanese, and Korean.");
13657 Vx_pixel_size_width_font_regexp = Qnil;
13659 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
13660 "Time after which cached images are removed from the cache.\n\
13661 When an image has not been displayed this many seconds, remove it\n\
13662 from the image cache. Value must be an integer or nil with nil\n\
13663 meaning don't clear the cache.");
13664 Vimage_cache_eviction_delay = make_number (30 * 60);
13666 DEFVAR_LISP ("w32-bdf-filename-alist",
13667 &Vw32_bdf_filename_alist,
13668 "List of bdf fonts and their corresponding filenames.");
13669 Vw32_bdf_filename_alist = Qnil;
13671 DEFVAR_BOOL ("w32-strict-fontnames",
13672 &w32_strict_fontnames,
13673 "Non-nil means only use fonts that are exact matches for those requested.\n\
13674 Default is nil, which allows old fontnames that are not XLFD compliant,\n\
13675 and allows third-party CJK display to work by specifying false charset\n\
13676 fields to trick Emacs into translating to Big5, SJIS etc.\n\
13677 Setting this to t will prevent wrong fonts being selected when\n\
13678 fontsets are automatically created.");
13679 w32_strict_fontnames = 0;
13681 DEFVAR_BOOL ("w32-strict-painting",
13682 &w32_strict_painting,
13683 "Non-nil means use strict rules for repainting frames.\n\
13684 Set this to nil to get the old behaviour for repainting; this should\n\
13685 only be necessary if the default setting causes problems.");
13686 w32_strict_painting = 1;
13688 DEFVAR_LISP ("w32-system-coding-system",
13689 &Vw32_system_coding_system,
13690 "Coding system used by Windows system functions, such as for font names.");
13691 Vw32_system_coding_system = Qnil;
13693 DEFVAR_LISP ("w32-charset-info-alist",
13694 &Vw32_charset_info_alist,
13695 "Alist linking Emacs character sets to Windows fonts\n\
13696 and codepages. Each entry should be of the form:\n\
13698 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))\n\
13700 where CHARSET_NAME is a string used in font names to identify the charset,\n\
13701 WINDOWS_CHARSET is a symbol that can be one of:\n\
13702 w32-charset-ansi, w32-charset-default, w32-charset-symbol,\n\
13703 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,\n\
13704 w32-charset-chinesebig5, "
13705 #ifdef JOHAB_CHARSET
13706 "w32-charset-johab, w32-charset-hebrew,\n\
13707 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,\n\
13708 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,\n\
13709 w32-charset-russian, w32-charset-mac, w32-charset-baltic,\n"
13710 #endif
13711 #ifdef UNICODE_CHARSET
13712 "w32-charset-unicode, "
13713 #endif
13714 "or w32-charset-oem.\n\
13715 CODEPAGE should be an integer specifying the codepage that should be used\n\
13716 to display the character set, t to do no translation and output as Unicode,\n\
13717 or nil to do no translation and output as 8 bit (or multibyte on far-east\n\
13718 versions of Windows) characters.");
13719 Vw32_charset_info_alist = Qnil;
13721 staticpro (&Qw32_charset_ansi);
13722 Qw32_charset_ansi = intern ("w32-charset-ansi");
13723 staticpro (&Qw32_charset_symbol);
13724 Qw32_charset_symbol = intern ("w32-charset-symbol");
13725 staticpro (&Qw32_charset_shiftjis);
13726 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
13727 staticpro (&Qw32_charset_hangeul);
13728 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
13729 staticpro (&Qw32_charset_chinesebig5);
13730 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
13731 staticpro (&Qw32_charset_gb2312);
13732 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
13733 staticpro (&Qw32_charset_oem);
13734 Qw32_charset_oem = intern ("w32-charset-oem");
13736 #ifdef JOHAB_CHARSET
13738 static int w32_extra_charsets_defined = 1;
13739 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined, "");
13741 staticpro (&Qw32_charset_johab);
13742 Qw32_charset_johab = intern ("w32-charset-johab");
13743 staticpro (&Qw32_charset_easteurope);
13744 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
13745 staticpro (&Qw32_charset_turkish);
13746 Qw32_charset_turkish = intern ("w32-charset-turkish");
13747 staticpro (&Qw32_charset_baltic);
13748 Qw32_charset_baltic = intern ("w32-charset-baltic");
13749 staticpro (&Qw32_charset_russian);
13750 Qw32_charset_russian = intern ("w32-charset-russian");
13751 staticpro (&Qw32_charset_arabic);
13752 Qw32_charset_arabic = intern ("w32-charset-arabic");
13753 staticpro (&Qw32_charset_greek);
13754 Qw32_charset_greek = intern ("w32-charset-greek");
13755 staticpro (&Qw32_charset_hebrew);
13756 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
13757 staticpro (&Qw32_charset_vietnamese);
13758 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
13759 staticpro (&Qw32_charset_thai);
13760 Qw32_charset_thai = intern ("w32-charset-thai");
13761 staticpro (&Qw32_charset_mac);
13762 Qw32_charset_mac = intern ("w32-charset-mac");
13764 #endif
13766 #ifdef UNICODE_CHARSET
13768 static int w32_unicode_charset_defined = 1;
13769 DEFVAR_BOOL ("w32-unicode-charset-defined",
13770 &w32_unicode_charset_defined, "");
13772 staticpro (&Qw32_charset_unicode);
13773 Qw32_charset_unicode = intern ("w32-charset-unicode");
13774 #endif
13776 defsubr (&Sx_get_resource);
13777 #if 0 /* TODO: Port to W32 */
13778 defsubr (&Sx_change_window_property);
13779 defsubr (&Sx_delete_window_property);
13780 defsubr (&Sx_window_property);
13781 #endif
13782 defsubr (&Sxw_display_color_p);
13783 defsubr (&Sx_display_grayscale_p);
13784 defsubr (&Sxw_color_defined_p);
13785 defsubr (&Sxw_color_values);
13786 defsubr (&Sx_server_max_request_size);
13787 defsubr (&Sx_server_vendor);
13788 defsubr (&Sx_server_version);
13789 defsubr (&Sx_display_pixel_width);
13790 defsubr (&Sx_display_pixel_height);
13791 defsubr (&Sx_display_mm_width);
13792 defsubr (&Sx_display_mm_height);
13793 defsubr (&Sx_display_screens);
13794 defsubr (&Sx_display_planes);
13795 defsubr (&Sx_display_color_cells);
13796 defsubr (&Sx_display_visual_class);
13797 defsubr (&Sx_display_backing_store);
13798 defsubr (&Sx_display_save_under);
13799 defsubr (&Sx_parse_geometry);
13800 defsubr (&Sx_create_frame);
13801 defsubr (&Sx_open_connection);
13802 defsubr (&Sx_close_connection);
13803 defsubr (&Sx_display_list);
13804 defsubr (&Sx_synchronize);
13806 /* W32 specific functions */
13808 defsubr (&Sw32_focus_frame);
13809 defsubr (&Sw32_select_font);
13810 defsubr (&Sw32_define_rgb_color);
13811 defsubr (&Sw32_default_color_map);
13812 defsubr (&Sw32_load_color_file);
13813 defsubr (&Sw32_send_sys_command);
13814 defsubr (&Sw32_shell_execute);
13815 defsubr (&Sw32_register_hot_key);
13816 defsubr (&Sw32_unregister_hot_key);
13817 defsubr (&Sw32_registered_hot_keys);
13818 defsubr (&Sw32_reconstruct_hot_key);
13819 defsubr (&Sw32_toggle_lock_key);
13820 defsubr (&Sw32_find_bdf_fonts);
13822 defsubr (&Sfile_system_info);
13824 /* Setting callback functions for fontset handler. */
13825 get_font_info_func = w32_get_font_info;
13827 #if 0 /* This function pointer doesn't seem to be used anywhere.
13828 And the pointer assigned has the wrong type, anyway. */
13829 list_fonts_func = w32_list_fonts;
13830 #endif
13832 load_font_func = w32_load_font;
13833 find_ccl_program_func = w32_find_ccl_program;
13834 query_font_func = w32_query_font;
13835 set_frame_fontset_func = x_set_font;
13836 check_window_system_func = check_w32;
13838 #if 0 /* TODO Image support for W32 */
13839 /* Images. */
13840 Qxbm = intern ("xbm");
13841 staticpro (&Qxbm);
13842 QCtype = intern (":type");
13843 staticpro (&QCtype);
13844 QCconversion = intern (":conversion");
13845 staticpro (&QCconversion);
13846 QCheuristic_mask = intern (":heuristic-mask");
13847 staticpro (&QCheuristic_mask);
13848 QCcolor_symbols = intern (":color-symbols");
13849 staticpro (&QCcolor_symbols);
13850 QCascent = intern (":ascent");
13851 staticpro (&QCascent);
13852 QCmargin = intern (":margin");
13853 staticpro (&QCmargin);
13854 QCrelief = intern (":relief");
13855 staticpro (&QCrelief);
13856 Qpostscript = intern ("postscript");
13857 staticpro (&Qpostscript);
13858 QCloader = intern (":loader");
13859 staticpro (&QCloader);
13860 QCbounding_box = intern (":bounding-box");
13861 staticpro (&QCbounding_box);
13862 QCpt_width = intern (":pt-width");
13863 staticpro (&QCpt_width);
13864 QCpt_height = intern (":pt-height");
13865 staticpro (&QCpt_height);
13866 QCindex = intern (":index");
13867 staticpro (&QCindex);
13868 Qpbm = intern ("pbm");
13869 staticpro (&Qpbm);
13871 #if HAVE_XPM
13872 Qxpm = intern ("xpm");
13873 staticpro (&Qxpm);
13874 #endif
13876 #if HAVE_JPEG
13877 Qjpeg = intern ("jpeg");
13878 staticpro (&Qjpeg);
13879 #endif
13881 #if HAVE_TIFF
13882 Qtiff = intern ("tiff");
13883 staticpro (&Qtiff);
13884 #endif
13886 #if HAVE_GIF
13887 Qgif = intern ("gif");
13888 staticpro (&Qgif);
13889 #endif
13891 #if HAVE_PNG
13892 Qpng = intern ("png");
13893 staticpro (&Qpng);
13894 #endif
13896 defsubr (&Sclear_image_cache);
13898 #if GLYPH_DEBUG
13899 defsubr (&Simagep);
13900 defsubr (&Slookup_image);
13901 #endif
13902 #endif /* TODO */
13904 busy_cursor_atimer = NULL;
13905 busy_cursor_shown_p = 0;
13906 #ifdef TODO /* Tooltip support not complete. */
13907 defsubr (&Sx_show_tip);
13908 defsubr (&Sx_hide_tip);
13909 #endif
13910 tip_timer = Qnil;
13911 staticpro (&tip_timer);
13912 tip_frame = Qnil;
13913 staticpro (&tip_frame);
13915 defsubr (&Sx_file_dialog);
13919 void
13920 init_xfns ()
13922 image_types = NULL;
13923 Vimage_types = Qnil;
13925 #if 0 /* TODO : Image support for W32 */
13926 define_image_type (&xbm_type);
13927 define_image_type (&gs_type);
13928 define_image_type (&pbm_type);
13930 #if HAVE_XPM
13931 define_image_type (&xpm_type);
13932 #endif
13934 #if HAVE_JPEG
13935 define_image_type (&jpeg_type);
13936 #endif
13938 #if HAVE_TIFF
13939 define_image_type (&tiff_type);
13940 #endif
13942 #if HAVE_GIF
13943 define_image_type (&gif_type);
13944 #endif
13946 #if HAVE_PNG
13947 define_image_type (&png_type);
13948 #endif
13949 #endif /* TODO */
13952 #undef abort
13954 void
13955 w32_abort()
13957 int button;
13958 button = MessageBox (NULL,
13959 "A fatal error has occurred!\n\n"
13960 "Select Abort to exit, Retry to debug, Ignore to continue",
13961 "Emacs Abort Dialog",
13962 MB_ICONEXCLAMATION | MB_TASKMODAL
13963 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
13964 switch (button)
13966 case IDRETRY:
13967 DebugBreak ();
13968 break;
13969 case IDIGNORE:
13970 break;
13971 case IDABORT:
13972 default:
13973 abort ();
13974 break;
13978 /* For convenience when debugging. */
13980 w32_last_error()
13982 return GetLastError ();