Fix var names in doc.
[emacs.git] / src / w32fns.c
blobd394fb3b81a61116361c57e423e5a00787a11b07
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 92, 93, 94, 95, 1996, 1997, 1998, 1999
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;
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_hangul;
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_thai;
296 Lisp_Object Qw32_charset_johab;
297 Lisp_Object Qw32_charset_mac;
298 #endif
300 #ifdef UNICODE_CHARSET
301 Lisp_Object Qw32_charset_unicode;
302 #endif
304 extern Lisp_Object Qtop;
305 extern Lisp_Object Qdisplay;
306 extern Lisp_Object Qtool_bar_lines;
308 /* State variables for emulating a three button mouse. */
309 #define LMOUSE 1
310 #define MMOUSE 2
311 #define RMOUSE 4
313 static int button_state = 0;
314 static W32Msg saved_mouse_button_msg;
315 static unsigned mouse_button_timer; /* non-zero when timer is active */
316 static W32Msg saved_mouse_move_msg;
317 static unsigned mouse_move_timer;
319 /* W95 mousewheel handler */
320 unsigned int msh_mousewheel = 0;
322 #define MOUSE_BUTTON_ID 1
323 #define MOUSE_MOVE_ID 2
325 /* The below are defined in frame.c. */
327 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
328 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
329 extern Lisp_Object Qtool_bar_lines;
331 extern Lisp_Object Vwindow_system_version;
333 Lisp_Object Qface_set_after_frame_default;
335 /* From w32term.c. */
336 extern Lisp_Object Vw32_num_mouse_buttons;
337 extern Lisp_Object Vw32_recognize_altgr;
340 /* Error if we are not connected to MS-Windows. */
341 void
342 check_w32 ()
344 if (! w32_in_use)
345 error ("MS-Windows not in use or not initialized");
348 /* Nonzero if we can use mouse menus.
349 You should not call this unless HAVE_MENUS is defined. */
352 have_menus_p ()
354 return w32_in_use;
357 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
358 and checking validity for W32. */
360 FRAME_PTR
361 check_x_frame (frame)
362 Lisp_Object frame;
364 FRAME_PTR f;
366 if (NILP (frame))
367 frame = selected_frame;
368 CHECK_LIVE_FRAME (frame, 0);
369 f = XFRAME (frame);
370 if (! FRAME_W32_P (f))
371 error ("non-w32 frame used");
372 return f;
375 /* Let the user specify an display with a frame.
376 nil stands for the selected frame--or, if that is not a w32 frame,
377 the first display on the list. */
379 static struct w32_display_info *
380 check_x_display_info (frame)
381 Lisp_Object frame;
383 if (NILP (frame))
385 struct frame *sf = XFRAME (selected_frame);
387 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
388 return FRAME_W32_DISPLAY_INFO (sf);
389 else
390 return &one_w32_display_info;
392 else if (STRINGP (frame))
393 return x_display_info_for_name (frame);
394 else
396 FRAME_PTR f;
398 CHECK_LIVE_FRAME (frame, 0);
399 f = XFRAME (frame);
400 if (! FRAME_W32_P (f))
401 error ("non-w32 frame used");
402 return FRAME_W32_DISPLAY_INFO (f);
406 /* Return the Emacs frame-object corresponding to an w32 window.
407 It could be the frame's main window or an icon window. */
409 /* This function can be called during GC, so use GC_xxx type test macros. */
411 struct frame *
412 x_window_to_frame (dpyinfo, wdesc)
413 struct w32_display_info *dpyinfo;
414 HWND wdesc;
416 Lisp_Object tail, frame;
417 struct frame *f;
419 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
421 frame = XCAR (tail);
422 if (!GC_FRAMEP (frame))
423 continue;
424 f = XFRAME (frame);
425 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
426 continue;
427 if (f->output_data.w32->busy_window == wdesc)
428 return f;
430 /* NTEMACS_TODO: Check tooltips when supported. */
431 if (FRAME_W32_WINDOW (f) == wdesc)
432 return f;
434 return 0;
439 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
440 id, which is just an int that this section returns. Bitmaps are
441 reference counted so they can be shared among frames.
443 Bitmap indices are guaranteed to be > 0, so a negative number can
444 be used to indicate no bitmap.
446 If you use x_create_bitmap_from_data, then you must keep track of
447 the bitmaps yourself. That is, creating a bitmap from the same
448 data more than once will not be caught. */
451 /* Functions to access the contents of a bitmap, given an id. */
454 x_bitmap_height (f, id)
455 FRAME_PTR f;
456 int id;
458 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
462 x_bitmap_width (f, id)
463 FRAME_PTR f;
464 int id;
466 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
470 x_bitmap_pixmap (f, id)
471 FRAME_PTR f;
472 int id;
474 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
478 /* Allocate a new bitmap record. Returns index of new record. */
480 static int
481 x_allocate_bitmap_record (f)
482 FRAME_PTR f;
484 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
485 int i;
487 if (dpyinfo->bitmaps == NULL)
489 dpyinfo->bitmaps_size = 10;
490 dpyinfo->bitmaps
491 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
492 dpyinfo->bitmaps_last = 1;
493 return 1;
496 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
497 return ++dpyinfo->bitmaps_last;
499 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
500 if (dpyinfo->bitmaps[i].refcount == 0)
501 return i + 1;
503 dpyinfo->bitmaps_size *= 2;
504 dpyinfo->bitmaps
505 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
506 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
507 return ++dpyinfo->bitmaps_last;
510 /* Add one reference to the reference count of the bitmap with id ID. */
512 void
513 x_reference_bitmap (f, id)
514 FRAME_PTR f;
515 int id;
517 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
520 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
523 x_create_bitmap_from_data (f, bits, width, height)
524 struct frame *f;
525 char *bits;
526 unsigned int width, height;
528 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
529 Pixmap bitmap;
530 int id;
532 bitmap = CreateBitmap (width, height,
533 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
534 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
535 bits);
537 if (! bitmap)
538 return -1;
540 id = x_allocate_bitmap_record (f);
541 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
542 dpyinfo->bitmaps[id - 1].file = NULL;
543 dpyinfo->bitmaps[id - 1].hinst = NULL;
544 dpyinfo->bitmaps[id - 1].refcount = 1;
545 dpyinfo->bitmaps[id - 1].depth = 1;
546 dpyinfo->bitmaps[id - 1].height = height;
547 dpyinfo->bitmaps[id - 1].width = width;
549 return id;
552 /* Create bitmap from file FILE for frame F. */
555 x_create_bitmap_from_file (f, file)
556 struct frame *f;
557 Lisp_Object file;
559 return -1;
560 #if 0 /* NTEMACS_TODO : bitmap support */
561 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
562 unsigned int width, height;
563 HBITMAP bitmap;
564 int xhot, yhot, result, id;
565 Lisp_Object found;
566 int fd;
567 char *filename;
568 HINSTANCE hinst;
570 /* Look for an existing bitmap with the same name. */
571 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
573 if (dpyinfo->bitmaps[id].refcount
574 && dpyinfo->bitmaps[id].file
575 && !strcmp (dpyinfo->bitmaps[id].file, (char *) XSTRING (file)->data))
577 ++dpyinfo->bitmaps[id].refcount;
578 return id + 1;
582 /* Search bitmap-file-path for the file, if appropriate. */
583 fd = openp (Vx_bitmap_file_path, file, "", &found, 0);
584 if (fd < 0)
585 return -1;
586 /* LoadLibraryEx won't handle special files handled by Emacs handler. */
587 if (fd == 0)
588 return -1;
589 emacs_close (fd);
591 filename = (char *) XSTRING (found)->data;
593 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
595 if (hinst == NULL)
596 return -1;
599 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
600 filename, &width, &height, &bitmap, &xhot, &yhot);
601 if (result != BitmapSuccess)
602 return -1;
604 id = x_allocate_bitmap_record (f);
605 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
606 dpyinfo->bitmaps[id - 1].refcount = 1;
607 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (XSTRING (file)->size + 1);
608 dpyinfo->bitmaps[id - 1].depth = 1;
609 dpyinfo->bitmaps[id - 1].height = height;
610 dpyinfo->bitmaps[id - 1].width = width;
611 strcpy (dpyinfo->bitmaps[id - 1].file, XSTRING (file)->data);
613 return id;
614 #endif /* NTEMACS_TODO */
617 /* Remove reference to bitmap with id number ID. */
619 void
620 x_destroy_bitmap (f, id)
621 FRAME_PTR f;
622 int id;
624 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
626 if (id > 0)
628 --dpyinfo->bitmaps[id - 1].refcount;
629 if (dpyinfo->bitmaps[id - 1].refcount == 0)
631 BLOCK_INPUT;
632 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
633 if (dpyinfo->bitmaps[id - 1].file)
635 xfree (dpyinfo->bitmaps[id - 1].file);
636 dpyinfo->bitmaps[id - 1].file = NULL;
638 UNBLOCK_INPUT;
643 /* Free all the bitmaps for the display specified by DPYINFO. */
645 static void
646 x_destroy_all_bitmaps (dpyinfo)
647 struct w32_display_info *dpyinfo;
649 int i;
650 for (i = 0; i < dpyinfo->bitmaps_last; i++)
651 if (dpyinfo->bitmaps[i].refcount > 0)
653 DeleteObject (dpyinfo->bitmaps[i].pixmap);
654 if (dpyinfo->bitmaps[i].file)
655 xfree (dpyinfo->bitmaps[i].file);
657 dpyinfo->bitmaps_last = 0;
660 /* Connect the frame-parameter names for W32 frames
661 to the ways of passing the parameter values to the window system.
663 The name of a parameter, as a Lisp symbol,
664 has an `x-frame-parameter' property which is an integer in Lisp
665 but can be interpreted as an `enum x_frame_parm' in C. */
667 enum x_frame_parm
669 X_PARM_FOREGROUND_COLOR,
670 X_PARM_BACKGROUND_COLOR,
671 X_PARM_MOUSE_COLOR,
672 X_PARM_CURSOR_COLOR,
673 X_PARM_BORDER_COLOR,
674 X_PARM_ICON_TYPE,
675 X_PARM_FONT,
676 X_PARM_BORDER_WIDTH,
677 X_PARM_INTERNAL_BORDER_WIDTH,
678 X_PARM_NAME,
679 X_PARM_AUTORAISE,
680 X_PARM_AUTOLOWER,
681 X_PARM_VERT_SCROLL_BAR,
682 X_PARM_VISIBILITY,
683 X_PARM_MENU_BAR_LINES
687 struct x_frame_parm_table
689 char *name;
690 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
693 /* NTEMACS_TODO: Native Input Method support; see x_create_im. */
694 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
695 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
696 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
697 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
698 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
699 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
700 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
701 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
702 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
703 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
704 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
705 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
706 Lisp_Object));
707 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
708 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
709 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
710 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
711 Lisp_Object));
712 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
713 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
714 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
715 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
716 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
717 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
718 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
720 static struct x_frame_parm_table x_frame_parms[] =
722 "auto-raise", x_set_autoraise,
723 "auto-lower", x_set_autolower,
724 "background-color", x_set_background_color,
725 "border-color", x_set_border_color,
726 "border-width", x_set_border_width,
727 "cursor-color", x_set_cursor_color,
728 "cursor-type", x_set_cursor_type,
729 "font", x_set_font,
730 "foreground-color", x_set_foreground_color,
731 "icon-name", x_set_icon_name,
732 "icon-type", x_set_icon_type,
733 "internal-border-width", x_set_internal_border_width,
734 "menu-bar-lines", x_set_menu_bar_lines,
735 "mouse-color", x_set_mouse_color,
736 "name", x_explicitly_set_name,
737 "scroll-bar-width", x_set_scroll_bar_width,
738 "title", x_set_title,
739 "unsplittable", x_set_unsplittable,
740 "vertical-scroll-bars", x_set_vertical_scroll_bars,
741 "visibility", x_set_visibility,
742 "tool-bar-lines", x_set_tool_bar_lines,
743 "screen-gamma", x_set_screen_gamma,
744 "line-spacing", x_set_line_spacing
747 /* Attach the `x-frame-parameter' properties to
748 the Lisp symbol names of parameters relevant to W32. */
750 void
751 init_x_parm_symbols ()
753 int i;
755 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
756 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
757 make_number (i));
760 /* Change the parameters of frame F as specified by ALIST.
761 If a parameter is not specially recognized, do nothing;
762 otherwise call the `x_set_...' function for that parameter. */
764 void
765 x_set_frame_parameters (f, alist)
766 FRAME_PTR f;
767 Lisp_Object alist;
769 Lisp_Object tail;
771 /* If both of these parameters are present, it's more efficient to
772 set them both at once. So we wait until we've looked at the
773 entire list before we set them. */
774 int width, height;
776 /* Same here. */
777 Lisp_Object left, top;
779 /* Same with these. */
780 Lisp_Object icon_left, icon_top;
782 /* Record in these vectors all the parms specified. */
783 Lisp_Object *parms;
784 Lisp_Object *values;
785 int i, p;
786 int left_no_change = 0, top_no_change = 0;
787 int icon_left_no_change = 0, icon_top_no_change = 0;
789 struct gcpro gcpro1, gcpro2;
791 i = 0;
792 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
793 i++;
795 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
796 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
798 /* Extract parm names and values into those vectors. */
800 i = 0;
801 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
803 Lisp_Object elt;
805 elt = Fcar (tail);
806 parms[i] = Fcar (elt);
807 values[i] = Fcdr (elt);
808 i++;
810 /* TAIL and ALIST are not used again below here. */
811 alist = tail = Qnil;
813 GCPRO2 (*parms, *values);
814 gcpro1.nvars = i;
815 gcpro2.nvars = i;
817 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
818 because their values appear in VALUES and strings are not valid. */
819 top = left = Qunbound;
820 icon_left = icon_top = Qunbound;
822 /* Provide default values for HEIGHT and WIDTH. */
823 if (FRAME_NEW_WIDTH (f))
824 width = FRAME_NEW_WIDTH (f);
825 else
826 width = FRAME_WIDTH (f);
828 if (FRAME_NEW_HEIGHT (f))
829 height = FRAME_NEW_HEIGHT (f);
830 else
831 height = FRAME_HEIGHT (f);
833 /* Process foreground_color and background_color before anything else.
834 They are independent of other properties, but other properties (e.g.,
835 cursor_color) are dependent upon them. */
836 for (p = 0; p < i; p++)
838 Lisp_Object prop, val;
840 prop = parms[p];
841 val = values[p];
842 if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
844 register Lisp_Object param_index, old_value;
846 param_index = Fget (prop, Qx_frame_parameter);
847 old_value = get_frame_param (f, prop);
848 store_frame_param (f, prop, val);
849 if (NATNUMP (param_index)
850 && (XFASTINT (param_index)
851 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
852 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
856 /* Now process them in reverse of specified order. */
857 for (i--; i >= 0; i--)
859 Lisp_Object prop, val;
861 prop = parms[i];
862 val = values[i];
864 if (EQ (prop, Qwidth) && NUMBERP (val))
865 width = XFASTINT (val);
866 else if (EQ (prop, Qheight) && NUMBERP (val))
867 height = XFASTINT (val);
868 else if (EQ (prop, Qtop))
869 top = val;
870 else if (EQ (prop, Qleft))
871 left = val;
872 else if (EQ (prop, Qicon_top))
873 icon_top = val;
874 else if (EQ (prop, Qicon_left))
875 icon_left = val;
876 else if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
877 /* Processed above. */
878 continue;
879 else
881 register Lisp_Object param_index, old_value;
883 param_index = Fget (prop, Qx_frame_parameter);
884 old_value = get_frame_param (f, prop);
885 store_frame_param (f, prop, val);
886 if (NATNUMP (param_index)
887 && (XFASTINT (param_index)
888 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
889 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
893 /* Don't die if just one of these was set. */
894 if (EQ (left, Qunbound))
896 left_no_change = 1;
897 if (f->output_data.w32->left_pos < 0)
898 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
899 else
900 XSETINT (left, f->output_data.w32->left_pos);
902 if (EQ (top, Qunbound))
904 top_no_change = 1;
905 if (f->output_data.w32->top_pos < 0)
906 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
907 else
908 XSETINT (top, f->output_data.w32->top_pos);
911 /* If one of the icon positions was not set, preserve or default it. */
912 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
914 icon_left_no_change = 1;
915 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
916 if (NILP (icon_left))
917 XSETINT (icon_left, 0);
919 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
921 icon_top_no_change = 1;
922 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
923 if (NILP (icon_top))
924 XSETINT (icon_top, 0);
927 /* Don't set these parameters unless they've been explicitly
928 specified. The window might be mapped or resized while we're in
929 this function, and we don't want to override that unless the lisp
930 code has asked for it.
932 Don't set these parameters unless they actually differ from the
933 window's current parameters; the window may not actually exist
934 yet. */
936 Lisp_Object frame;
938 check_frame_size (f, &height, &width);
940 XSETFRAME (frame, f);
942 if (width != FRAME_WIDTH (f)
943 || height != FRAME_HEIGHT (f)
944 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
945 Fset_frame_size (frame, make_number (width), make_number (height));
947 if ((!NILP (left) || !NILP (top))
948 && ! (left_no_change && top_no_change)
949 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
950 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
952 int leftpos = 0;
953 int toppos = 0;
955 /* Record the signs. */
956 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
957 if (EQ (left, Qminus))
958 f->output_data.w32->size_hint_flags |= XNegative;
959 else if (INTEGERP (left))
961 leftpos = XINT (left);
962 if (leftpos < 0)
963 f->output_data.w32->size_hint_flags |= XNegative;
965 else if (CONSP (left) && EQ (XCAR (left), Qminus)
966 && CONSP (XCDR (left))
967 && INTEGERP (XCAR (XCDR (left))))
969 leftpos = - XINT (XCAR (XCDR (left)));
970 f->output_data.w32->size_hint_flags |= XNegative;
972 else if (CONSP (left) && EQ (XCAR (left), Qplus)
973 && CONSP (XCDR (left))
974 && INTEGERP (XCAR (XCDR (left))))
976 leftpos = XINT (XCAR (XCDR (left)));
979 if (EQ (top, Qminus))
980 f->output_data.w32->size_hint_flags |= YNegative;
981 else if (INTEGERP (top))
983 toppos = XINT (top);
984 if (toppos < 0)
985 f->output_data.w32->size_hint_flags |= YNegative;
987 else if (CONSP (top) && EQ (XCAR (top), Qminus)
988 && CONSP (XCDR (top))
989 && INTEGERP (XCAR (XCDR (top))))
991 toppos = - XINT (XCAR (XCDR (top)));
992 f->output_data.w32->size_hint_flags |= YNegative;
994 else if (CONSP (top) && EQ (XCAR (top), Qplus)
995 && CONSP (XCDR (top))
996 && INTEGERP (XCAR (XCDR (top))))
998 toppos = XINT (XCAR (XCDR (top)));
1002 /* Store the numeric value of the position. */
1003 f->output_data.w32->top_pos = toppos;
1004 f->output_data.w32->left_pos = leftpos;
1006 f->output_data.w32->win_gravity = NorthWestGravity;
1008 /* Actually set that position, and convert to absolute. */
1009 x_set_offset (f, leftpos, toppos, -1);
1012 if ((!NILP (icon_left) || !NILP (icon_top))
1013 && ! (icon_left_no_change && icon_top_no_change))
1014 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1017 UNGCPRO;
1020 /* Store the screen positions of frame F into XPTR and YPTR.
1021 These are the positions of the containing window manager window,
1022 not Emacs's own window. */
1024 void
1025 x_real_positions (f, xptr, yptr)
1026 FRAME_PTR f;
1027 int *xptr, *yptr;
1029 POINT pt;
1032 RECT rect;
1034 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1035 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1037 pt.x = rect.left;
1038 pt.y = rect.top;
1041 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1043 *xptr = pt.x;
1044 *yptr = pt.y;
1047 /* Insert a description of internally-recorded parameters of frame X
1048 into the parameter alist *ALISTPTR that is to be given to the user.
1049 Only parameters that are specific to W32
1050 and whose values are not correctly recorded in the frame's
1051 param_alist need to be considered here. */
1053 void
1054 x_report_frame_params (f, alistptr)
1055 struct frame *f;
1056 Lisp_Object *alistptr;
1058 char buf[16];
1059 Lisp_Object tem;
1061 /* Represent negative positions (off the top or left screen edge)
1062 in a way that Fmodify_frame_parameters will understand correctly. */
1063 XSETINT (tem, f->output_data.w32->left_pos);
1064 if (f->output_data.w32->left_pos >= 0)
1065 store_in_alist (alistptr, Qleft, tem);
1066 else
1067 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1069 XSETINT (tem, f->output_data.w32->top_pos);
1070 if (f->output_data.w32->top_pos >= 0)
1071 store_in_alist (alistptr, Qtop, tem);
1072 else
1073 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1075 store_in_alist (alistptr, Qborder_width,
1076 make_number (f->output_data.w32->border_width));
1077 store_in_alist (alistptr, Qinternal_border_width,
1078 make_number (f->output_data.w32->internal_border_width));
1079 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1080 store_in_alist (alistptr, Qwindow_id,
1081 build_string (buf));
1082 store_in_alist (alistptr, Qicon_name, f->icon_name);
1083 FRAME_SAMPLE_VISIBILITY (f);
1084 store_in_alist (alistptr, Qvisibility,
1085 (FRAME_VISIBLE_P (f) ? Qt
1086 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1087 store_in_alist (alistptr, Qdisplay,
1088 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1092 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color, Sw32_define_rgb_color, 4, 4, 0,
1093 "Convert RGB numbers to a windows color reference and associate with NAME (a string).\n\
1094 This adds or updates a named color to w32-color-map, making it available for use.\n\
1095 The original entry's RGB ref is returned, or nil if the entry is new.")
1096 (red, green, blue, name)
1097 Lisp_Object red, green, blue, name;
1099 Lisp_Object rgb;
1100 Lisp_Object oldrgb = Qnil;
1101 Lisp_Object entry;
1103 CHECK_NUMBER (red, 0);
1104 CHECK_NUMBER (green, 0);
1105 CHECK_NUMBER (blue, 0);
1106 CHECK_STRING (name, 0);
1108 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1110 BLOCK_INPUT;
1112 /* replace existing entry in w32-color-map or add new entry. */
1113 entry = Fassoc (name, Vw32_color_map);
1114 if (NILP (entry))
1116 entry = Fcons (name, rgb);
1117 Vw32_color_map = Fcons (entry, Vw32_color_map);
1119 else
1121 oldrgb = Fcdr (entry);
1122 Fsetcdr (entry, rgb);
1125 UNBLOCK_INPUT;
1127 return (oldrgb);
1130 DEFUN ("w32-load-color-file", Fw32_load_color_file, Sw32_load_color_file, 1, 1, 0,
1131 "Create an alist of color entries from an external file (ie. rgb.txt).\n\
1132 Assign this value to w32-color-map to replace the existing color map.\n\
1134 The file should define one named RGB color per line like so:\
1135 R G B name\n\
1136 where R,G,B are numbers between 0 and 255 and name is an arbitrary string.")
1137 (filename)
1138 Lisp_Object filename;
1140 FILE *fp;
1141 Lisp_Object cmap = Qnil;
1142 Lisp_Object abspath;
1144 CHECK_STRING (filename, 0);
1145 abspath = Fexpand_file_name (filename, Qnil);
1147 fp = fopen (XSTRING (filename)->data, "rt");
1148 if (fp)
1150 char buf[512];
1151 int red, green, blue;
1152 int num;
1154 BLOCK_INPUT;
1156 while (fgets (buf, sizeof (buf), fp) != NULL) {
1157 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1159 char *name = buf + num;
1160 num = strlen (name) - 1;
1161 if (name[num] == '\n')
1162 name[num] = 0;
1163 cmap = Fcons (Fcons (build_string (name),
1164 make_number (RGB (red, green, blue))),
1165 cmap);
1168 fclose (fp);
1170 UNBLOCK_INPUT;
1173 return cmap;
1176 /* The default colors for the w32 color map */
1177 typedef struct colormap_t
1179 char *name;
1180 COLORREF colorref;
1181 } colormap_t;
1183 colormap_t w32_color_map[] =
1185 {"snow" , PALETTERGB (255,250,250)},
1186 {"ghost white" , PALETTERGB (248,248,255)},
1187 {"GhostWhite" , PALETTERGB (248,248,255)},
1188 {"white smoke" , PALETTERGB (245,245,245)},
1189 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1190 {"gainsboro" , PALETTERGB (220,220,220)},
1191 {"floral white" , PALETTERGB (255,250,240)},
1192 {"FloralWhite" , PALETTERGB (255,250,240)},
1193 {"old lace" , PALETTERGB (253,245,230)},
1194 {"OldLace" , PALETTERGB (253,245,230)},
1195 {"linen" , PALETTERGB (250,240,230)},
1196 {"antique white" , PALETTERGB (250,235,215)},
1197 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1198 {"papaya whip" , PALETTERGB (255,239,213)},
1199 {"PapayaWhip" , PALETTERGB (255,239,213)},
1200 {"blanched almond" , PALETTERGB (255,235,205)},
1201 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1202 {"bisque" , PALETTERGB (255,228,196)},
1203 {"peach puff" , PALETTERGB (255,218,185)},
1204 {"PeachPuff" , PALETTERGB (255,218,185)},
1205 {"navajo white" , PALETTERGB (255,222,173)},
1206 {"NavajoWhite" , PALETTERGB (255,222,173)},
1207 {"moccasin" , PALETTERGB (255,228,181)},
1208 {"cornsilk" , PALETTERGB (255,248,220)},
1209 {"ivory" , PALETTERGB (255,255,240)},
1210 {"lemon chiffon" , PALETTERGB (255,250,205)},
1211 {"LemonChiffon" , PALETTERGB (255,250,205)},
1212 {"seashell" , PALETTERGB (255,245,238)},
1213 {"honeydew" , PALETTERGB (240,255,240)},
1214 {"mint cream" , PALETTERGB (245,255,250)},
1215 {"MintCream" , PALETTERGB (245,255,250)},
1216 {"azure" , PALETTERGB (240,255,255)},
1217 {"alice blue" , PALETTERGB (240,248,255)},
1218 {"AliceBlue" , PALETTERGB (240,248,255)},
1219 {"lavender" , PALETTERGB (230,230,250)},
1220 {"lavender blush" , PALETTERGB (255,240,245)},
1221 {"LavenderBlush" , PALETTERGB (255,240,245)},
1222 {"misty rose" , PALETTERGB (255,228,225)},
1223 {"MistyRose" , PALETTERGB (255,228,225)},
1224 {"white" , PALETTERGB (255,255,255)},
1225 {"black" , PALETTERGB ( 0, 0, 0)},
1226 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1227 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1228 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1229 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1230 {"dim gray" , PALETTERGB (105,105,105)},
1231 {"DimGray" , PALETTERGB (105,105,105)},
1232 {"dim grey" , PALETTERGB (105,105,105)},
1233 {"DimGrey" , PALETTERGB (105,105,105)},
1234 {"slate gray" , PALETTERGB (112,128,144)},
1235 {"SlateGray" , PALETTERGB (112,128,144)},
1236 {"slate grey" , PALETTERGB (112,128,144)},
1237 {"SlateGrey" , PALETTERGB (112,128,144)},
1238 {"light slate gray" , PALETTERGB (119,136,153)},
1239 {"LightSlateGray" , PALETTERGB (119,136,153)},
1240 {"light slate grey" , PALETTERGB (119,136,153)},
1241 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1242 {"gray" , PALETTERGB (190,190,190)},
1243 {"grey" , PALETTERGB (190,190,190)},
1244 {"light grey" , PALETTERGB (211,211,211)},
1245 {"LightGrey" , PALETTERGB (211,211,211)},
1246 {"light gray" , PALETTERGB (211,211,211)},
1247 {"LightGray" , PALETTERGB (211,211,211)},
1248 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1249 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1250 {"navy" , PALETTERGB ( 0, 0,128)},
1251 {"navy blue" , PALETTERGB ( 0, 0,128)},
1252 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1253 {"cornflower blue" , PALETTERGB (100,149,237)},
1254 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1255 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1256 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1257 {"slate blue" , PALETTERGB (106, 90,205)},
1258 {"SlateBlue" , PALETTERGB (106, 90,205)},
1259 {"medium slate blue" , PALETTERGB (123,104,238)},
1260 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1261 {"light slate blue" , PALETTERGB (132,112,255)},
1262 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1263 {"medium blue" , PALETTERGB ( 0, 0,205)},
1264 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1265 {"royal blue" , PALETTERGB ( 65,105,225)},
1266 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1267 {"blue" , PALETTERGB ( 0, 0,255)},
1268 {"dodger blue" , PALETTERGB ( 30,144,255)},
1269 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1270 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1271 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1272 {"sky blue" , PALETTERGB (135,206,235)},
1273 {"SkyBlue" , PALETTERGB (135,206,235)},
1274 {"light sky blue" , PALETTERGB (135,206,250)},
1275 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1276 {"steel blue" , PALETTERGB ( 70,130,180)},
1277 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1278 {"light steel blue" , PALETTERGB (176,196,222)},
1279 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1280 {"light blue" , PALETTERGB (173,216,230)},
1281 {"LightBlue" , PALETTERGB (173,216,230)},
1282 {"powder blue" , PALETTERGB (176,224,230)},
1283 {"PowderBlue" , PALETTERGB (176,224,230)},
1284 {"pale turquoise" , PALETTERGB (175,238,238)},
1285 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1286 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1287 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1288 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1289 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1290 {"turquoise" , PALETTERGB ( 64,224,208)},
1291 {"cyan" , PALETTERGB ( 0,255,255)},
1292 {"light cyan" , PALETTERGB (224,255,255)},
1293 {"LightCyan" , PALETTERGB (224,255,255)},
1294 {"cadet blue" , PALETTERGB ( 95,158,160)},
1295 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1296 {"medium aquamarine" , PALETTERGB (102,205,170)},
1297 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1298 {"aquamarine" , PALETTERGB (127,255,212)},
1299 {"dark green" , PALETTERGB ( 0,100, 0)},
1300 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1301 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1302 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1303 {"dark sea green" , PALETTERGB (143,188,143)},
1304 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1305 {"sea green" , PALETTERGB ( 46,139, 87)},
1306 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1307 {"medium sea green" , PALETTERGB ( 60,179,113)},
1308 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1309 {"light sea green" , PALETTERGB ( 32,178,170)},
1310 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1311 {"pale green" , PALETTERGB (152,251,152)},
1312 {"PaleGreen" , PALETTERGB (152,251,152)},
1313 {"spring green" , PALETTERGB ( 0,255,127)},
1314 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1315 {"lawn green" , PALETTERGB (124,252, 0)},
1316 {"LawnGreen" , PALETTERGB (124,252, 0)},
1317 {"green" , PALETTERGB ( 0,255, 0)},
1318 {"chartreuse" , PALETTERGB (127,255, 0)},
1319 {"medium spring green" , PALETTERGB ( 0,250,154)},
1320 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1321 {"green yellow" , PALETTERGB (173,255, 47)},
1322 {"GreenYellow" , PALETTERGB (173,255, 47)},
1323 {"lime green" , PALETTERGB ( 50,205, 50)},
1324 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1325 {"yellow green" , PALETTERGB (154,205, 50)},
1326 {"YellowGreen" , PALETTERGB (154,205, 50)},
1327 {"forest green" , PALETTERGB ( 34,139, 34)},
1328 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1329 {"olive drab" , PALETTERGB (107,142, 35)},
1330 {"OliveDrab" , PALETTERGB (107,142, 35)},
1331 {"dark khaki" , PALETTERGB (189,183,107)},
1332 {"DarkKhaki" , PALETTERGB (189,183,107)},
1333 {"khaki" , PALETTERGB (240,230,140)},
1334 {"pale goldenrod" , PALETTERGB (238,232,170)},
1335 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1336 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1337 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1338 {"light yellow" , PALETTERGB (255,255,224)},
1339 {"LightYellow" , PALETTERGB (255,255,224)},
1340 {"yellow" , PALETTERGB (255,255, 0)},
1341 {"gold" , PALETTERGB (255,215, 0)},
1342 {"light goldenrod" , PALETTERGB (238,221,130)},
1343 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1344 {"goldenrod" , PALETTERGB (218,165, 32)},
1345 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1346 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1347 {"rosy brown" , PALETTERGB (188,143,143)},
1348 {"RosyBrown" , PALETTERGB (188,143,143)},
1349 {"indian red" , PALETTERGB (205, 92, 92)},
1350 {"IndianRed" , PALETTERGB (205, 92, 92)},
1351 {"saddle brown" , PALETTERGB (139, 69, 19)},
1352 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1353 {"sienna" , PALETTERGB (160, 82, 45)},
1354 {"peru" , PALETTERGB (205,133, 63)},
1355 {"burlywood" , PALETTERGB (222,184,135)},
1356 {"beige" , PALETTERGB (245,245,220)},
1357 {"wheat" , PALETTERGB (245,222,179)},
1358 {"sandy brown" , PALETTERGB (244,164, 96)},
1359 {"SandyBrown" , PALETTERGB (244,164, 96)},
1360 {"tan" , PALETTERGB (210,180,140)},
1361 {"chocolate" , PALETTERGB (210,105, 30)},
1362 {"firebrick" , PALETTERGB (178,34, 34)},
1363 {"brown" , PALETTERGB (165,42, 42)},
1364 {"dark salmon" , PALETTERGB (233,150,122)},
1365 {"DarkSalmon" , PALETTERGB (233,150,122)},
1366 {"salmon" , PALETTERGB (250,128,114)},
1367 {"light salmon" , PALETTERGB (255,160,122)},
1368 {"LightSalmon" , PALETTERGB (255,160,122)},
1369 {"orange" , PALETTERGB (255,165, 0)},
1370 {"dark orange" , PALETTERGB (255,140, 0)},
1371 {"DarkOrange" , PALETTERGB (255,140, 0)},
1372 {"coral" , PALETTERGB (255,127, 80)},
1373 {"light coral" , PALETTERGB (240,128,128)},
1374 {"LightCoral" , PALETTERGB (240,128,128)},
1375 {"tomato" , PALETTERGB (255, 99, 71)},
1376 {"orange red" , PALETTERGB (255, 69, 0)},
1377 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1378 {"red" , PALETTERGB (255, 0, 0)},
1379 {"hot pink" , PALETTERGB (255,105,180)},
1380 {"HotPink" , PALETTERGB (255,105,180)},
1381 {"deep pink" , PALETTERGB (255, 20,147)},
1382 {"DeepPink" , PALETTERGB (255, 20,147)},
1383 {"pink" , PALETTERGB (255,192,203)},
1384 {"light pink" , PALETTERGB (255,182,193)},
1385 {"LightPink" , PALETTERGB (255,182,193)},
1386 {"pale violet red" , PALETTERGB (219,112,147)},
1387 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1388 {"maroon" , PALETTERGB (176, 48, 96)},
1389 {"medium violet red" , PALETTERGB (199, 21,133)},
1390 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1391 {"violet red" , PALETTERGB (208, 32,144)},
1392 {"VioletRed" , PALETTERGB (208, 32,144)},
1393 {"magenta" , PALETTERGB (255, 0,255)},
1394 {"violet" , PALETTERGB (238,130,238)},
1395 {"plum" , PALETTERGB (221,160,221)},
1396 {"orchid" , PALETTERGB (218,112,214)},
1397 {"medium orchid" , PALETTERGB (186, 85,211)},
1398 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1399 {"dark orchid" , PALETTERGB (153, 50,204)},
1400 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1401 {"dark violet" , PALETTERGB (148, 0,211)},
1402 {"DarkViolet" , PALETTERGB (148, 0,211)},
1403 {"blue violet" , PALETTERGB (138, 43,226)},
1404 {"BlueViolet" , PALETTERGB (138, 43,226)},
1405 {"purple" , PALETTERGB (160, 32,240)},
1406 {"medium purple" , PALETTERGB (147,112,219)},
1407 {"MediumPurple" , PALETTERGB (147,112,219)},
1408 {"thistle" , PALETTERGB (216,191,216)},
1409 {"gray0" , PALETTERGB ( 0, 0, 0)},
1410 {"grey0" , PALETTERGB ( 0, 0, 0)},
1411 {"dark grey" , PALETTERGB (169,169,169)},
1412 {"DarkGrey" , PALETTERGB (169,169,169)},
1413 {"dark gray" , PALETTERGB (169,169,169)},
1414 {"DarkGray" , PALETTERGB (169,169,169)},
1415 {"dark blue" , PALETTERGB ( 0, 0,139)},
1416 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1417 {"dark cyan" , PALETTERGB ( 0,139,139)},
1418 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1419 {"dark magenta" , PALETTERGB (139, 0,139)},
1420 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1421 {"dark red" , PALETTERGB (139, 0, 0)},
1422 {"DarkRed" , PALETTERGB (139, 0, 0)},
1423 {"light green" , PALETTERGB (144,238,144)},
1424 {"LightGreen" , PALETTERGB (144,238,144)},
1427 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1428 0, 0, 0, "Return the default color map.")
1431 int i;
1432 colormap_t *pc = w32_color_map;
1433 Lisp_Object cmap;
1435 BLOCK_INPUT;
1437 cmap = Qnil;
1439 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1440 pc++, i++)
1441 cmap = Fcons (Fcons (build_string (pc->name),
1442 make_number (pc->colorref)),
1443 cmap);
1445 UNBLOCK_INPUT;
1447 return (cmap);
1450 Lisp_Object
1451 w32_to_x_color (rgb)
1452 Lisp_Object rgb;
1454 Lisp_Object color;
1456 CHECK_NUMBER (rgb, 0);
1458 BLOCK_INPUT;
1460 color = Frassq (rgb, Vw32_color_map);
1462 UNBLOCK_INPUT;
1464 if (!NILP (color))
1465 return (Fcar (color));
1466 else
1467 return Qnil;
1470 COLORREF
1471 w32_color_map_lookup (colorname)
1472 char *colorname;
1474 Lisp_Object tail, ret = Qnil;
1476 BLOCK_INPUT;
1478 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1480 register Lisp_Object elt, tem;
1482 elt = Fcar (tail);
1483 if (!CONSP (elt)) continue;
1485 tem = Fcar (elt);
1487 if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
1489 ret = XUINT (Fcdr (elt));
1490 break;
1493 QUIT;
1497 UNBLOCK_INPUT;
1499 return ret;
1502 COLORREF
1503 x_to_w32_color (colorname)
1504 char * colorname;
1506 register Lisp_Object tail, ret = Qnil;
1508 BLOCK_INPUT;
1510 if (colorname[0] == '#')
1512 /* Could be an old-style RGB Device specification. */
1513 char *color;
1514 int size;
1515 color = colorname + 1;
1517 size = strlen(color);
1518 if (size == 3 || size == 6 || size == 9 || size == 12)
1520 UINT colorval;
1521 int i, pos;
1522 pos = 0;
1523 size /= 3;
1524 colorval = 0;
1526 for (i = 0; i < 3; i++)
1528 char *end;
1529 char t;
1530 unsigned long value;
1532 /* The check for 'x' in the following conditional takes into
1533 account the fact that strtol allows a "0x" in front of
1534 our numbers, and we don't. */
1535 if (!isxdigit(color[0]) || color[1] == 'x')
1536 break;
1537 t = color[size];
1538 color[size] = '\0';
1539 value = strtoul(color, &end, 16);
1540 color[size] = t;
1541 if (errno == ERANGE || end - color != size)
1542 break;
1543 switch (size)
1545 case 1:
1546 value = value * 0x10;
1547 break;
1548 case 2:
1549 break;
1550 case 3:
1551 value /= 0x10;
1552 break;
1553 case 4:
1554 value /= 0x100;
1555 break;
1557 colorval |= (value << pos);
1558 pos += 0x8;
1559 if (i == 2)
1561 UNBLOCK_INPUT;
1562 return (colorval);
1564 color = end;
1568 else if (strnicmp(colorname, "rgb:", 4) == 0)
1570 char *color;
1571 UINT colorval;
1572 int i, pos;
1573 pos = 0;
1575 colorval = 0;
1576 color = colorname + 4;
1577 for (i = 0; i < 3; i++)
1579 char *end;
1580 unsigned long value;
1582 /* The check for 'x' in the following conditional takes into
1583 account the fact that strtol allows a "0x" in front of
1584 our numbers, and we don't. */
1585 if (!isxdigit(color[0]) || color[1] == 'x')
1586 break;
1587 value = strtoul(color, &end, 16);
1588 if (errno == ERANGE)
1589 break;
1590 switch (end - color)
1592 case 1:
1593 value = value * 0x10 + value;
1594 break;
1595 case 2:
1596 break;
1597 case 3:
1598 value /= 0x10;
1599 break;
1600 case 4:
1601 value /= 0x100;
1602 break;
1603 default:
1604 value = ULONG_MAX;
1606 if (value == ULONG_MAX)
1607 break;
1608 colorval |= (value << pos);
1609 pos += 0x8;
1610 if (i == 2)
1612 if (*end != '\0')
1613 break;
1614 UNBLOCK_INPUT;
1615 return (colorval);
1617 if (*end != '/')
1618 break;
1619 color = end + 1;
1622 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1624 /* This is an RGB Intensity specification. */
1625 char *color;
1626 UINT colorval;
1627 int i, pos;
1628 pos = 0;
1630 colorval = 0;
1631 color = colorname + 5;
1632 for (i = 0; i < 3; i++)
1634 char *end;
1635 double value;
1636 UINT val;
1638 value = strtod(color, &end);
1639 if (errno == ERANGE)
1640 break;
1641 if (value < 0.0 || value > 1.0)
1642 break;
1643 val = (UINT)(0x100 * value);
1644 /* We used 0x100 instead of 0xFF to give an continuous
1645 range between 0.0 and 1.0 inclusive. The next statement
1646 fixes the 1.0 case. */
1647 if (val == 0x100)
1648 val = 0xFF;
1649 colorval |= (val << pos);
1650 pos += 0x8;
1651 if (i == 2)
1653 if (*end != '\0')
1654 break;
1655 UNBLOCK_INPUT;
1656 return (colorval);
1658 if (*end != '/')
1659 break;
1660 color = end + 1;
1663 /* I am not going to attempt to handle any of the CIE color schemes
1664 or TekHVC, since I don't know the algorithms for conversion to
1665 RGB. */
1667 /* If we fail to lookup the color name in w32_color_map, then check the
1668 colorname to see if it can be crudely approximated: If the X color
1669 ends in a number (e.g., "darkseagreen2"), strip the number and
1670 return the result of looking up the base color name. */
1671 ret = w32_color_map_lookup (colorname);
1672 if (NILP (ret))
1674 int len = strlen (colorname);
1676 if (isdigit (colorname[len - 1]))
1678 char *ptr, *approx = alloca (len);
1680 strcpy (approx, colorname);
1681 ptr = &approx[len - 1];
1682 while (ptr > approx && isdigit (*ptr))
1683 *ptr-- = '\0';
1685 ret = w32_color_map_lookup (approx);
1689 UNBLOCK_INPUT;
1690 return ret;
1694 void
1695 w32_regenerate_palette (FRAME_PTR f)
1697 struct w32_palette_entry * list;
1698 LOGPALETTE * log_palette;
1699 HPALETTE new_palette;
1700 int i;
1702 /* don't bother trying to create palette if not supported */
1703 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1704 return;
1706 log_palette = (LOGPALETTE *)
1707 alloca (sizeof (LOGPALETTE) +
1708 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1709 log_palette->palVersion = 0x300;
1710 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1712 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1713 for (i = 0;
1714 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1715 i++, list = list->next)
1716 log_palette->palPalEntry[i] = list->entry;
1718 new_palette = CreatePalette (log_palette);
1720 enter_crit ();
1722 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1723 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1724 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1726 /* Realize display palette and garbage all frames. */
1727 release_frame_dc (f, get_frame_dc (f));
1729 leave_crit ();
1732 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1733 #define SET_W32_COLOR(pe, color) \
1734 do \
1736 pe.peRed = GetRValue (color); \
1737 pe.peGreen = GetGValue (color); \
1738 pe.peBlue = GetBValue (color); \
1739 pe.peFlags = 0; \
1740 } while (0)
1742 #if 0
1743 /* Keep these around in case we ever want to track color usage. */
1744 void
1745 w32_map_color (FRAME_PTR f, COLORREF color)
1747 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1749 if (NILP (Vw32_enable_palette))
1750 return;
1752 /* check if color is already mapped */
1753 while (list)
1755 if (W32_COLOR (list->entry) == color)
1757 ++list->refcount;
1758 return;
1760 list = list->next;
1763 /* not already mapped, so add to list and recreate Windows palette */
1764 list = (struct w32_palette_entry *)
1765 xmalloc (sizeof (struct w32_palette_entry));
1766 SET_W32_COLOR (list->entry, color);
1767 list->refcount = 1;
1768 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1769 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1770 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1772 /* set flag that palette must be regenerated */
1773 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1776 void
1777 w32_unmap_color (FRAME_PTR f, COLORREF color)
1779 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1780 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1782 if (NILP (Vw32_enable_palette))
1783 return;
1785 /* check if color is already mapped */
1786 while (list)
1788 if (W32_COLOR (list->entry) == color)
1790 if (--list->refcount == 0)
1792 *prev = list->next;
1793 xfree (list);
1794 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1795 break;
1797 else
1798 return;
1800 prev = &list->next;
1801 list = list->next;
1804 /* set flag that palette must be regenerated */
1805 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1807 #endif
1810 /* Gamma-correct COLOR on frame F. */
1812 void
1813 gamma_correct (f, color)
1814 struct frame *f;
1815 COLORREF *color;
1817 if (f->gamma)
1819 *color = PALETTERGB (
1820 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1821 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1822 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1827 /* Decide if color named COLOR is valid for the display associated with
1828 the selected frame; if so, return the rgb values in COLOR_DEF.
1829 If ALLOC is nonzero, allocate a new colormap cell. */
1832 w32_defined_color (f, color, color_def, alloc)
1833 FRAME_PTR f;
1834 char *color;
1835 XColor *color_def;
1836 int alloc;
1838 register Lisp_Object tem;
1839 COLORREF w32_color_ref;
1841 tem = x_to_w32_color (color);
1843 if (!NILP (tem))
1845 if (f)
1847 /* Apply gamma correction. */
1848 w32_color_ref = XUINT (tem);
1849 gamma_correct (f, &w32_color_ref);
1850 XSETINT (tem, w32_color_ref);
1853 /* Map this color to the palette if it is enabled. */
1854 if (!NILP (Vw32_enable_palette))
1856 struct w32_palette_entry * entry =
1857 one_w32_display_info.color_list;
1858 struct w32_palette_entry ** prev =
1859 &one_w32_display_info.color_list;
1861 /* check if color is already mapped */
1862 while (entry)
1864 if (W32_COLOR (entry->entry) == XUINT (tem))
1865 break;
1866 prev = &entry->next;
1867 entry = entry->next;
1870 if (entry == NULL && alloc)
1872 /* not already mapped, so add to list */
1873 entry = (struct w32_palette_entry *)
1874 xmalloc (sizeof (struct w32_palette_entry));
1875 SET_W32_COLOR (entry->entry, XUINT (tem));
1876 entry->next = NULL;
1877 *prev = entry;
1878 one_w32_display_info.num_colors++;
1880 /* set flag that palette must be regenerated */
1881 one_w32_display_info.regen_palette = TRUE;
1884 /* Ensure COLORREF value is snapped to nearest color in (default)
1885 palette by simulating the PALETTERGB macro. This works whether
1886 or not the display device has a palette. */
1887 w32_color_ref = XUINT (tem) | 0x2000000;
1889 color_def->pixel = w32_color_ref;
1890 color_def->red = GetRValue (w32_color_ref);
1891 color_def->green = GetGValue (w32_color_ref);
1892 color_def->blue = GetBValue (w32_color_ref);
1894 return 1;
1896 else
1898 return 0;
1902 /* Given a string ARG naming a color, compute a pixel value from it
1903 suitable for screen F.
1904 If F is not a color screen, return DEF (default) regardless of what
1905 ARG says. */
1908 x_decode_color (f, arg, def)
1909 FRAME_PTR f;
1910 Lisp_Object arg;
1911 int def;
1913 XColor cdef;
1915 CHECK_STRING (arg, 0);
1917 if (strcmp (XSTRING (arg)->data, "black") == 0)
1918 return BLACK_PIX_DEFAULT (f);
1919 else if (strcmp (XSTRING (arg)->data, "white") == 0)
1920 return WHITE_PIX_DEFAULT (f);
1922 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1923 return def;
1925 /* w32_defined_color is responsible for coping with failures
1926 by looking for a near-miss. */
1927 if (w32_defined_color (f, XSTRING (arg)->data, &cdef, 1))
1928 return cdef.pixel;
1930 /* defined_color failed; return an ultimate default. */
1931 return def;
1934 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
1935 the previous value of that parameter, NEW_VALUE is the new value. */
1937 static void
1938 x_set_line_spacing (f, new_value, old_value)
1939 struct frame *f;
1940 Lisp_Object new_value, old_value;
1942 if (NILP (new_value))
1943 f->extra_line_spacing = 0;
1944 else if (NATNUMP (new_value))
1945 f->extra_line_spacing = XFASTINT (new_value);
1946 else
1947 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
1948 Fcons (new_value, Qnil)));
1949 if (FRAME_VISIBLE_P (f))
1950 redraw_frame (f);
1954 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
1955 the previous value of that parameter, NEW_VALUE is the new value. */
1957 static void
1958 x_set_screen_gamma (f, new_value, old_value)
1959 struct frame *f;
1960 Lisp_Object new_value, old_value;
1962 if (NILP (new_value))
1963 f->gamma = 0;
1964 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
1965 /* The value 0.4545 is the normal viewing gamma. */
1966 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
1967 else
1968 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
1969 Fcons (new_value, Qnil)));
1971 clear_face_cache (0);
1975 /* Functions called only from `x_set_frame_param'
1976 to set individual parameters.
1978 If FRAME_W32_WINDOW (f) is 0,
1979 the frame is being created and its window does not exist yet.
1980 In that case, just record the parameter's new value
1981 in the standard place; do not attempt to change the window. */
1983 void
1984 x_set_foreground_color (f, arg, oldval)
1985 struct frame *f;
1986 Lisp_Object arg, oldval;
1988 FRAME_FOREGROUND_PIXEL (f)
1989 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1991 if (FRAME_W32_WINDOW (f) != 0)
1993 update_face_from_frame_parameter (f, Qforeground_color, arg);
1994 if (FRAME_VISIBLE_P (f))
1995 redraw_frame (f);
1999 void
2000 x_set_background_color (f, arg, oldval)
2001 struct frame *f;
2002 Lisp_Object arg, oldval;
2004 FRAME_BACKGROUND_PIXEL (f)
2005 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2007 if (FRAME_W32_WINDOW (f) != 0)
2009 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2010 FRAME_BACKGROUND_PIXEL (f));
2012 update_face_from_frame_parameter (f, Qbackground_color, arg);
2014 if (FRAME_VISIBLE_P (f))
2015 redraw_frame (f);
2019 void
2020 x_set_mouse_color (f, arg, oldval)
2021 struct frame *f;
2022 Lisp_Object arg, oldval;
2025 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2026 int count;
2027 int mask_color;
2029 if (!EQ (Qnil, arg))
2030 f->output_data.w32->mouse_pixel
2031 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2032 mask_color = FRAME_BACKGROUND_PIXEL (f);
2034 /* Don't let pointers be invisible. */
2035 if (mask_color == f->output_data.w32->mouse_pixel
2036 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2037 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2039 #if 0 /* NTEMACS_TODO : cursor changes */
2040 BLOCK_INPUT;
2042 /* It's not okay to crash if the user selects a screwy cursor. */
2043 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2045 if (!EQ (Qnil, Vx_pointer_shape))
2047 CHECK_NUMBER (Vx_pointer_shape, 0);
2048 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2050 else
2051 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2052 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2054 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2056 CHECK_NUMBER (Vx_nontext_pointer_shape, 0);
2057 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2058 XINT (Vx_nontext_pointer_shape));
2060 else
2061 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2062 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2064 if (!EQ (Qnil, Vx_busy_pointer_shape))
2066 CHECK_NUMBER (Vx_busy_pointer_shape, 0);
2067 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2068 XINT (Vx_busy_pointer_shape));
2070 else
2071 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2072 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2074 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2075 if (!EQ (Qnil, Vx_mode_pointer_shape))
2077 CHECK_NUMBER (Vx_mode_pointer_shape, 0);
2078 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2079 XINT (Vx_mode_pointer_shape));
2081 else
2082 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2083 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2085 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2087 CHECK_NUMBER (Vx_sensitive_text_pointer_shape, 0);
2088 cross_cursor
2089 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2090 XINT (Vx_sensitive_text_pointer_shape));
2092 else
2093 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2095 /* Check and report errors with the above calls. */
2096 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2097 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2100 XColor fore_color, back_color;
2102 fore_color.pixel = f->output_data.w32->mouse_pixel;
2103 back_color.pixel = mask_color;
2104 XQueryColor (FRAME_W32_DISPLAY (f),
2105 DefaultColormap (FRAME_W32_DISPLAY (f),
2106 DefaultScreen (FRAME_W32_DISPLAY (f))),
2107 &fore_color);
2108 XQueryColor (FRAME_W32_DISPLAY (f),
2109 DefaultColormap (FRAME_W32_DISPLAY (f),
2110 DefaultScreen (FRAME_W32_DISPLAY (f))),
2111 &back_color);
2112 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2113 &fore_color, &back_color);
2114 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2115 &fore_color, &back_color);
2116 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2117 &fore_color, &back_color);
2118 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2119 &fore_color, &back_color);
2120 XRecolorCursor (FRAME_W32_DISPLAY (f), busy_cursor,
2121 &fore_color, &back_color);
2124 if (FRAME_W32_WINDOW (f) != 0)
2125 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2127 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2128 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2129 f->output_data.w32->text_cursor = cursor;
2131 if (nontext_cursor != f->output_data.w32->nontext_cursor
2132 && f->output_data.w32->nontext_cursor != 0)
2133 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2134 f->output_data.w32->nontext_cursor = nontext_cursor;
2136 if (busy_cursor != f->output_data.w32->busy_cursor
2137 && f->output_data.w32->busy_cursor != 0)
2138 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->busy_cursor);
2139 f->output_data.w32->busy_cursor = busy_cursor;
2141 if (mode_cursor != f->output_data.w32->modeline_cursor
2142 && f->output_data.w32->modeline_cursor != 0)
2143 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2144 f->output_data.w32->modeline_cursor = mode_cursor;
2146 if (cross_cursor != f->output_data.w32->cross_cursor
2147 && f->output_data.w32->cross_cursor != 0)
2148 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2149 f->output_data.w32->cross_cursor = cross_cursor;
2151 XFlush (FRAME_W32_DISPLAY (f));
2152 UNBLOCK_INPUT;
2154 update_face_from_frame_parameter (f, Qmouse_color, arg);
2155 #endif /* NTEMACS_TODO */
2158 void
2159 x_set_cursor_color (f, arg, oldval)
2160 struct frame *f;
2161 Lisp_Object arg, oldval;
2163 unsigned long fore_pixel;
2165 if (!NILP (Vx_cursor_fore_pixel))
2166 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2167 WHITE_PIX_DEFAULT (f));
2168 else
2169 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2170 f->output_data.w32->cursor_pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2172 /* Make sure that the cursor color differs from the background color. */
2173 if (f->output_data.w32->cursor_pixel == FRAME_BACKGROUND_PIXEL (f))
2175 f->output_data.w32->cursor_pixel = f->output_data.w32->mouse_pixel;
2176 if (f->output_data.w32->cursor_pixel == fore_pixel)
2177 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2179 FRAME_FOREGROUND_PIXEL (f) = fore_pixel;
2181 if (FRAME_W32_WINDOW (f) != 0)
2183 if (FRAME_VISIBLE_P (f))
2185 x_display_cursor (f, 0);
2186 x_display_cursor (f, 1);
2190 update_face_from_frame_parameter (f, Qcursor_color, arg);
2193 /* Set the border-color of frame F to pixel value PIX.
2194 Note that this does not fully take effect if done before
2195 F has an window. */
2196 void
2197 x_set_border_pixel (f, pix)
2198 struct frame *f;
2199 int pix;
2201 f->output_data.w32->border_pixel = pix;
2203 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2205 if (FRAME_VISIBLE_P (f))
2206 redraw_frame (f);
2210 /* Set the border-color of frame F to value described by ARG.
2211 ARG can be a string naming a color.
2212 The border-color is used for the border that is drawn by the server.
2213 Note that this does not fully take effect if done before
2214 F has a window; it must be redone when the window is created. */
2216 void
2217 x_set_border_color (f, arg, oldval)
2218 struct frame *f;
2219 Lisp_Object arg, oldval;
2221 int pix;
2223 CHECK_STRING (arg, 0);
2224 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2225 x_set_border_pixel (f, pix);
2226 update_face_from_frame_parameter (f, Qborder_color, arg);
2229 /* Value is the internal representation of the specified cursor type
2230 ARG. If type is BAR_CURSOR, return in *WIDTH the specified width
2231 of the bar cursor. */
2233 enum text_cursor_kinds
2234 x_specified_cursor_type (arg, width)
2235 Lisp_Object arg;
2236 int *width;
2238 enum text_cursor_kinds type;
2240 if (EQ (arg, Qbar))
2242 type = BAR_CURSOR;
2243 *width = 2;
2245 else if (CONSP (arg)
2246 && EQ (XCAR (arg), Qbar)
2247 && INTEGERP (XCDR (arg))
2248 && XINT (XCDR (arg)) >= 0)
2250 type = BAR_CURSOR;
2251 *width = XINT (XCDR (arg));
2253 else if (NILP (arg))
2254 type = NO_CURSOR;
2255 else
2256 /* Treat anything unknown as "box cursor".
2257 It was bad to signal an error; people have trouble fixing
2258 .Xdefaults with Emacs, when it has something bad in it. */
2259 type = FILLED_BOX_CURSOR;
2261 return type;
2264 void
2265 x_set_cursor_type (f, arg, oldval)
2266 FRAME_PTR f;
2267 Lisp_Object arg, oldval;
2269 int width;
2271 FRAME_DESIRED_CURSOR (f) = x_specified_cursor_type (arg, &width);
2272 f->output_data.w32->cursor_width = width;
2274 /* Make sure the cursor gets redrawn. This is overkill, but how
2275 often do people change cursor types? */
2276 update_mode_lines++;
2279 void
2280 x_set_icon_type (f, arg, oldval)
2281 struct frame *f;
2282 Lisp_Object arg, oldval;
2284 int result;
2286 if (NILP (arg) && NILP (oldval))
2287 return;
2289 if (STRINGP (arg) && STRINGP (oldval)
2290 && EQ (Fstring_equal (oldval, arg), Qt))
2291 return;
2293 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2294 return;
2296 BLOCK_INPUT;
2298 result = x_bitmap_icon (f, arg);
2299 if (result)
2301 UNBLOCK_INPUT;
2302 error ("No icon window available");
2305 UNBLOCK_INPUT;
2308 /* Return non-nil if frame F wants a bitmap icon. */
2310 Lisp_Object
2311 x_icon_type (f)
2312 FRAME_PTR f;
2314 Lisp_Object tem;
2316 tem = assq_no_quit (Qicon_type, f->param_alist);
2317 if (CONSP (tem))
2318 return XCDR (tem);
2319 else
2320 return Qnil;
2323 void
2324 x_set_icon_name (f, arg, oldval)
2325 struct frame *f;
2326 Lisp_Object arg, oldval;
2328 int result;
2330 if (STRINGP (arg))
2332 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2333 return;
2335 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2336 return;
2338 f->icon_name = arg;
2340 #if 0
2341 if (f->output_data.w32->icon_bitmap != 0)
2342 return;
2344 BLOCK_INPUT;
2346 result = x_text_icon (f,
2347 (char *) XSTRING ((!NILP (f->icon_name)
2348 ? f->icon_name
2349 : !NILP (f->title)
2350 ? f->title
2351 : f->name))->data);
2353 if (result)
2355 UNBLOCK_INPUT;
2356 error ("No icon window available");
2359 /* If the window was unmapped (and its icon was mapped),
2360 the new icon is not mapped, so map the window in its stead. */
2361 if (FRAME_VISIBLE_P (f))
2363 #ifdef USE_X_TOOLKIT
2364 XtPopup (f->output_data.w32->widget, XtGrabNone);
2365 #endif
2366 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2369 XFlush (FRAME_W32_DISPLAY (f));
2370 UNBLOCK_INPUT;
2371 #endif
2374 extern Lisp_Object x_new_font ();
2375 extern Lisp_Object x_new_fontset();
2377 void
2378 x_set_font (f, arg, oldval)
2379 struct frame *f;
2380 Lisp_Object arg, oldval;
2382 Lisp_Object result;
2383 Lisp_Object fontset_name;
2384 Lisp_Object frame;
2386 CHECK_STRING (arg, 1);
2388 fontset_name = Fquery_fontset (arg, Qnil);
2390 BLOCK_INPUT;
2391 result = (STRINGP (fontset_name)
2392 ? x_new_fontset (f, XSTRING (fontset_name)->data)
2393 : x_new_font (f, XSTRING (arg)->data));
2394 UNBLOCK_INPUT;
2396 if (EQ (result, Qnil))
2397 error ("Font `%s' is not defined", XSTRING (arg)->data);
2398 else if (EQ (result, Qt))
2399 error ("The characters of the given font have varying widths");
2400 else if (STRINGP (result))
2402 store_frame_param (f, Qfont, result);
2403 recompute_basic_faces (f);
2405 else
2406 abort ();
2408 do_pending_window_change (0);
2410 /* Don't call `face-set-after-frame-default' when faces haven't been
2411 initialized yet. This is the case when called from
2412 Fx_create_frame. In that case, the X widget or window doesn't
2413 exist either, and we can end up in x_report_frame_params with a
2414 null widget which gives a segfault. */
2415 if (FRAME_FACE_CACHE (f))
2417 XSETFRAME (frame, f);
2418 call1 (Qface_set_after_frame_default, frame);
2422 void
2423 x_set_border_width (f, arg, oldval)
2424 struct frame *f;
2425 Lisp_Object arg, oldval;
2427 CHECK_NUMBER (arg, 0);
2429 if (XINT (arg) == f->output_data.w32->border_width)
2430 return;
2432 if (FRAME_W32_WINDOW (f) != 0)
2433 error ("Cannot change the border width of a window");
2435 f->output_data.w32->border_width = XINT (arg);
2438 void
2439 x_set_internal_border_width (f, arg, oldval)
2440 struct frame *f;
2441 Lisp_Object arg, oldval;
2443 int old = f->output_data.w32->internal_border_width;
2445 CHECK_NUMBER (arg, 0);
2446 f->output_data.w32->internal_border_width = XINT (arg);
2447 if (f->output_data.w32->internal_border_width < 0)
2448 f->output_data.w32->internal_border_width = 0;
2450 if (f->output_data.w32->internal_border_width == old)
2451 return;
2453 if (FRAME_W32_WINDOW (f) != 0)
2455 x_set_window_size (f, 0, f->width, f->height);
2456 SET_FRAME_GARBAGED (f);
2457 do_pending_window_change (0);
2461 void
2462 x_set_visibility (f, value, oldval)
2463 struct frame *f;
2464 Lisp_Object value, oldval;
2466 Lisp_Object frame;
2467 XSETFRAME (frame, f);
2469 if (NILP (value))
2470 Fmake_frame_invisible (frame, Qt);
2471 else if (EQ (value, Qicon))
2472 Ficonify_frame (frame);
2473 else
2474 Fmake_frame_visible (frame);
2477 void
2478 x_set_menu_bar_lines (f, value, oldval)
2479 struct frame *f;
2480 Lisp_Object value, oldval;
2482 int nlines;
2483 int olines = FRAME_MENU_BAR_LINES (f);
2485 /* Right now, menu bars don't work properly in minibuf-only frames;
2486 most of the commands try to apply themselves to the minibuffer
2487 frame itself, and get an error because you can't switch buffers
2488 in or split the minibuffer window. */
2489 if (FRAME_MINIBUF_ONLY_P (f))
2490 return;
2492 if (INTEGERP (value))
2493 nlines = XINT (value);
2494 else
2495 nlines = 0;
2497 FRAME_MENU_BAR_LINES (f) = 0;
2498 if (nlines)
2499 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2500 else
2502 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2503 free_frame_menubar (f);
2504 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2506 /* Adjust the frame size so that the client (text) dimensions
2507 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2508 set correctly. */
2509 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2510 do_pending_window_change (0);
2512 adjust_glyphs (f);
2516 /* Set the number of lines used for the tool bar of frame F to VALUE.
2517 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2518 is the old number of tool bar lines. This function changes the
2519 height of all windows on frame F to match the new tool bar height.
2520 The frame's height doesn't change. */
2522 void
2523 x_set_tool_bar_lines (f, value, oldval)
2524 struct frame *f;
2525 Lisp_Object value, oldval;
2527 int delta, nlines;
2529 /* Use VALUE only if an integer >= 0. */
2530 if (INTEGERP (value) && XINT (value) >= 0)
2531 nlines = XFASTINT (value);
2532 else
2533 nlines = 0;
2535 /* Make sure we redisplay all windows in this frame. */
2536 ++windows_or_buffers_changed;
2538 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2539 FRAME_TOOL_BAR_LINES (f) = nlines;
2540 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2541 do_pending_window_change (0);
2542 adjust_glyphs (f);
2546 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2547 w32_id_name.
2549 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2550 name; if NAME is a string, set F's name to NAME and set
2551 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2553 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2554 suggesting a new name, which lisp code should override; if
2555 F->explicit_name is set, ignore the new name; otherwise, set it. */
2557 void
2558 x_set_name (f, name, explicit)
2559 struct frame *f;
2560 Lisp_Object name;
2561 int explicit;
2563 /* Make sure that requests from lisp code override requests from
2564 Emacs redisplay code. */
2565 if (explicit)
2567 /* If we're switching from explicit to implicit, we had better
2568 update the mode lines and thereby update the title. */
2569 if (f->explicit_name && NILP (name))
2570 update_mode_lines = 1;
2572 f->explicit_name = ! NILP (name);
2574 else if (f->explicit_name)
2575 return;
2577 /* If NAME is nil, set the name to the w32_id_name. */
2578 if (NILP (name))
2580 /* Check for no change needed in this very common case
2581 before we do any consing. */
2582 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2583 XSTRING (f->name)->data))
2584 return;
2585 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2587 else
2588 CHECK_STRING (name, 0);
2590 /* Don't change the name if it's already NAME. */
2591 if (! NILP (Fstring_equal (name, f->name)))
2592 return;
2594 f->name = name;
2596 /* For setting the frame title, the title parameter should override
2597 the name parameter. */
2598 if (! NILP (f->title))
2599 name = f->title;
2601 if (FRAME_W32_WINDOW (f))
2603 if (STRING_MULTIBYTE (name))
2604 name = ENCODE_SYSTEM (name);
2606 BLOCK_INPUT;
2607 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2608 UNBLOCK_INPUT;
2612 /* This function should be called when the user's lisp code has
2613 specified a name for the frame; the name will override any set by the
2614 redisplay code. */
2615 void
2616 x_explicitly_set_name (f, arg, oldval)
2617 FRAME_PTR f;
2618 Lisp_Object arg, oldval;
2620 x_set_name (f, arg, 1);
2623 /* This function should be called by Emacs redisplay code to set the
2624 name; names set this way will never override names set by the user's
2625 lisp code. */
2626 void
2627 x_implicitly_set_name (f, arg, oldval)
2628 FRAME_PTR f;
2629 Lisp_Object arg, oldval;
2631 x_set_name (f, arg, 0);
2634 /* Change the title of frame F to NAME.
2635 If NAME is nil, use the frame name as the title.
2637 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2638 name; if NAME is a string, set F's name to NAME and set
2639 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2641 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2642 suggesting a new name, which lisp code should override; if
2643 F->explicit_name is set, ignore the new name; otherwise, set it. */
2645 void
2646 x_set_title (f, name, old_name)
2647 struct frame *f;
2648 Lisp_Object name, old_name;
2650 /* Don't change the title if it's already NAME. */
2651 if (EQ (name, f->title))
2652 return;
2654 update_mode_lines = 1;
2656 f->title = name;
2658 if (NILP (name))
2659 name = f->name;
2661 if (FRAME_W32_WINDOW (f))
2663 if (STRING_MULTIBYTE (name))
2664 name = ENCODE_SYSTEM (name);
2666 BLOCK_INPUT;
2667 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2668 UNBLOCK_INPUT;
2672 void
2673 x_set_autoraise (f, arg, oldval)
2674 struct frame *f;
2675 Lisp_Object arg, oldval;
2677 f->auto_raise = !EQ (Qnil, arg);
2680 void
2681 x_set_autolower (f, arg, oldval)
2682 struct frame *f;
2683 Lisp_Object arg, oldval;
2685 f->auto_lower = !EQ (Qnil, arg);
2688 void
2689 x_set_unsplittable (f, arg, oldval)
2690 struct frame *f;
2691 Lisp_Object arg, oldval;
2693 f->no_split = !NILP (arg);
2696 void
2697 x_set_vertical_scroll_bars (f, arg, oldval)
2698 struct frame *f;
2699 Lisp_Object arg, oldval;
2701 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2702 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2703 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2704 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2706 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2707 vertical_scroll_bar_none :
2708 /* Put scroll bars on the right by default, as is conventional
2709 on MS-Windows. */
2710 EQ (Qleft, arg)
2711 ? vertical_scroll_bar_left
2712 : vertical_scroll_bar_right;
2714 /* We set this parameter before creating the window for the
2715 frame, so we can get the geometry right from the start.
2716 However, if the window hasn't been created yet, we shouldn't
2717 call x_set_window_size. */
2718 if (FRAME_W32_WINDOW (f))
2719 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2720 do_pending_window_change (0);
2724 void
2725 x_set_scroll_bar_width (f, arg, oldval)
2726 struct frame *f;
2727 Lisp_Object arg, oldval;
2729 int wid = FONT_WIDTH (f->output_data.w32->font);
2731 if (NILP (arg))
2733 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2734 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2735 wid - 1) / wid;
2736 if (FRAME_W32_WINDOW (f))
2737 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2738 do_pending_window_change (0);
2740 else if (INTEGERP (arg) && XINT (arg) > 0
2741 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2743 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2744 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2745 + wid-1) / wid;
2746 if (FRAME_W32_WINDOW (f))
2747 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2748 do_pending_window_change (0);
2750 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2751 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2752 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2755 /* Subroutines of creating an frame. */
2757 /* Make sure that Vx_resource_name is set to a reasonable value.
2758 Fix it up, or set it to `emacs' if it is too hopeless. */
2760 static void
2761 validate_x_resource_name ()
2763 int len = 0;
2764 /* Number of valid characters in the resource name. */
2765 int good_count = 0;
2766 /* Number of invalid characters in the resource name. */
2767 int bad_count = 0;
2768 Lisp_Object new;
2769 int i;
2771 if (STRINGP (Vx_resource_name))
2773 unsigned char *p = XSTRING (Vx_resource_name)->data;
2774 int i;
2776 len = STRING_BYTES (XSTRING (Vx_resource_name));
2778 /* Only letters, digits, - and _ are valid in resource names.
2779 Count the valid characters and count the invalid ones. */
2780 for (i = 0; i < len; i++)
2782 int c = p[i];
2783 if (! ((c >= 'a' && c <= 'z')
2784 || (c >= 'A' && c <= 'Z')
2785 || (c >= '0' && c <= '9')
2786 || c == '-' || c == '_'))
2787 bad_count++;
2788 else
2789 good_count++;
2792 else
2793 /* Not a string => completely invalid. */
2794 bad_count = 5, good_count = 0;
2796 /* If name is valid already, return. */
2797 if (bad_count == 0)
2798 return;
2800 /* If name is entirely invalid, or nearly so, use `emacs'. */
2801 if (good_count == 0
2802 || (good_count == 1 && bad_count > 0))
2804 Vx_resource_name = build_string ("emacs");
2805 return;
2808 /* Name is partly valid. Copy it and replace the invalid characters
2809 with underscores. */
2811 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2813 for (i = 0; i < len; i++)
2815 int c = XSTRING (new)->data[i];
2816 if (! ((c >= 'a' && c <= 'z')
2817 || (c >= 'A' && c <= 'Z')
2818 || (c >= '0' && c <= '9')
2819 || c == '-' || c == '_'))
2820 XSTRING (new)->data[i] = '_';
2825 extern char *x_get_string_resource ();
2827 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2828 "Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.\n\
2829 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the\n\
2830 class, where INSTANCE is the name under which Emacs was invoked, or\n\
2831 the name specified by the `-name' or `-rn' command-line arguments.\n\
2833 The optional arguments COMPONENT and SUBCLASS add to the key and the\n\
2834 class, respectively. You must specify both of them or neither.\n\
2835 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'\n\
2836 and the class is `Emacs.CLASS.SUBCLASS'.")
2837 (attribute, class, component, subclass)
2838 Lisp_Object attribute, class, component, subclass;
2840 register char *value;
2841 char *name_key;
2842 char *class_key;
2844 CHECK_STRING (attribute, 0);
2845 CHECK_STRING (class, 0);
2847 if (!NILP (component))
2848 CHECK_STRING (component, 1);
2849 if (!NILP (subclass))
2850 CHECK_STRING (subclass, 2);
2851 if (NILP (component) != NILP (subclass))
2852 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
2854 validate_x_resource_name ();
2856 /* Allocate space for the components, the dots which separate them,
2857 and the final '\0'. Make them big enough for the worst case. */
2858 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vx_resource_name))
2859 + (STRINGP (component)
2860 ? STRING_BYTES (XSTRING (component)) : 0)
2861 + STRING_BYTES (XSTRING (attribute))
2862 + 3);
2864 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2865 + STRING_BYTES (XSTRING (class))
2866 + (STRINGP (subclass)
2867 ? STRING_BYTES (XSTRING (subclass)) : 0)
2868 + 3);
2870 /* Start with emacs.FRAMENAME for the name (the specific one)
2871 and with `Emacs' for the class key (the general one). */
2872 strcpy (name_key, XSTRING (Vx_resource_name)->data);
2873 strcpy (class_key, EMACS_CLASS);
2875 strcat (class_key, ".");
2876 strcat (class_key, XSTRING (class)->data);
2878 if (!NILP (component))
2880 strcat (class_key, ".");
2881 strcat (class_key, XSTRING (subclass)->data);
2883 strcat (name_key, ".");
2884 strcat (name_key, XSTRING (component)->data);
2887 strcat (name_key, ".");
2888 strcat (name_key, XSTRING (attribute)->data);
2890 value = x_get_string_resource (Qnil,
2891 name_key, class_key);
2893 if (value != (char *) 0)
2894 return build_string (value);
2895 else
2896 return Qnil;
2899 /* Used when C code wants a resource value. */
2901 char *
2902 x_get_resource_string (attribute, class)
2903 char *attribute, *class;
2905 char *name_key;
2906 char *class_key;
2907 struct frame *sf = SELECTED_FRAME ();
2909 /* Allocate space for the components, the dots which separate them,
2910 and the final '\0'. */
2911 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vinvocation_name))
2912 + strlen (attribute) + 2);
2913 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2914 + strlen (class) + 2);
2916 sprintf (name_key, "%s.%s",
2917 XSTRING (Vinvocation_name)->data,
2918 attribute);
2919 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
2921 return x_get_string_resource (sf, name_key, class_key);
2924 /* Types we might convert a resource string into. */
2925 enum resource_types
2927 RES_TYPE_NUMBER,
2928 RES_TYPE_FLOAT,
2929 RES_TYPE_BOOLEAN,
2930 RES_TYPE_STRING,
2931 RES_TYPE_SYMBOL
2934 /* Return the value of parameter PARAM.
2936 First search ALIST, then Vdefault_frame_alist, then the X defaults
2937 database, using ATTRIBUTE as the attribute name and CLASS as its class.
2939 Convert the resource to the type specified by desired_type.
2941 If no default is specified, return Qunbound. If you call
2942 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
2943 and don't let it get stored in any Lisp-visible variables! */
2945 static Lisp_Object
2946 w32_get_arg (alist, param, attribute, class, type)
2947 Lisp_Object alist, param;
2948 char *attribute;
2949 char *class;
2950 enum resource_types type;
2952 register Lisp_Object tem;
2954 tem = Fassq (param, alist);
2955 if (EQ (tem, Qnil))
2956 tem = Fassq (param, Vdefault_frame_alist);
2957 if (EQ (tem, Qnil))
2960 if (attribute)
2962 tem = Fx_get_resource (build_string (attribute),
2963 build_string (class),
2964 Qnil, Qnil);
2966 if (NILP (tem))
2967 return Qunbound;
2969 switch (type)
2971 case RES_TYPE_NUMBER:
2972 return make_number (atoi (XSTRING (tem)->data));
2974 case RES_TYPE_FLOAT:
2975 return make_float (atof (XSTRING (tem)->data));
2977 case RES_TYPE_BOOLEAN:
2978 tem = Fdowncase (tem);
2979 if (!strcmp (XSTRING (tem)->data, "on")
2980 || !strcmp (XSTRING (tem)->data, "true"))
2981 return Qt;
2982 else
2983 return Qnil;
2985 case RES_TYPE_STRING:
2986 return tem;
2988 case RES_TYPE_SYMBOL:
2989 /* As a special case, we map the values `true' and `on'
2990 to Qt, and `false' and `off' to Qnil. */
2992 Lisp_Object lower;
2993 lower = Fdowncase (tem);
2994 if (!strcmp (XSTRING (lower)->data, "on")
2995 || !strcmp (XSTRING (lower)->data, "true"))
2996 return Qt;
2997 else if (!strcmp (XSTRING (lower)->data, "off")
2998 || !strcmp (XSTRING (lower)->data, "false"))
2999 return Qnil;
3000 else
3001 return Fintern (tem, Qnil);
3004 default:
3005 abort ();
3008 else
3009 return Qunbound;
3011 return Fcdr (tem);
3014 /* Record in frame F the specified or default value according to ALIST
3015 of the parameter named PROP (a Lisp symbol).
3016 If no value is specified for PROP, look for an X default for XPROP
3017 on the frame named NAME.
3018 If that is not found either, use the value DEFLT. */
3020 static Lisp_Object
3021 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3022 struct frame *f;
3023 Lisp_Object alist;
3024 Lisp_Object prop;
3025 Lisp_Object deflt;
3026 char *xprop;
3027 char *xclass;
3028 enum resource_types type;
3030 Lisp_Object tem;
3032 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3033 if (EQ (tem, Qunbound))
3034 tem = deflt;
3035 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3036 return tem;
3039 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3040 "Parse an X-style geometry string STRING.\n\
3041 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).\n\
3042 The properties returned may include `top', `left', `height', and `width'.\n\
3043 The value of `left' or `top' may be an integer,\n\
3044 or a list (+ N) meaning N pixels relative to top/left corner,\n\
3045 or a list (- N) meaning -N pixels relative to bottom/right corner.")
3046 (string)
3047 Lisp_Object string;
3049 int geometry, x, y;
3050 unsigned int width, height;
3051 Lisp_Object result;
3053 CHECK_STRING (string, 0);
3055 geometry = XParseGeometry ((char *) XSTRING (string)->data,
3056 &x, &y, &width, &height);
3058 result = Qnil;
3059 if (geometry & XValue)
3061 Lisp_Object element;
3063 if (x >= 0 && (geometry & XNegative))
3064 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3065 else if (x < 0 && ! (geometry & XNegative))
3066 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3067 else
3068 element = Fcons (Qleft, make_number (x));
3069 result = Fcons (element, result);
3072 if (geometry & YValue)
3074 Lisp_Object element;
3076 if (y >= 0 && (geometry & YNegative))
3077 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3078 else if (y < 0 && ! (geometry & YNegative))
3079 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3080 else
3081 element = Fcons (Qtop, make_number (y));
3082 result = Fcons (element, result);
3085 if (geometry & WidthValue)
3086 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3087 if (geometry & HeightValue)
3088 result = Fcons (Fcons (Qheight, make_number (height)), result);
3090 return result;
3093 /* Calculate the desired size and position of this window,
3094 and return the flags saying which aspects were specified.
3096 This function does not make the coordinates positive. */
3098 #define DEFAULT_ROWS 40
3099 #define DEFAULT_COLS 80
3101 static int
3102 x_figure_window_size (f, parms)
3103 struct frame *f;
3104 Lisp_Object parms;
3106 register Lisp_Object tem0, tem1, tem2;
3107 long window_prompting = 0;
3109 /* Default values if we fall through.
3110 Actually, if that happens we should get
3111 window manager prompting. */
3112 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3113 f->height = DEFAULT_ROWS;
3114 /* Window managers expect that if program-specified
3115 positions are not (0,0), they're intentional, not defaults. */
3116 f->output_data.w32->top_pos = 0;
3117 f->output_data.w32->left_pos = 0;
3119 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3120 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3121 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3122 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3124 if (!EQ (tem0, Qunbound))
3126 CHECK_NUMBER (tem0, 0);
3127 f->height = XINT (tem0);
3129 if (!EQ (tem1, Qunbound))
3131 CHECK_NUMBER (tem1, 0);
3132 SET_FRAME_WIDTH (f, XINT (tem1));
3134 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3135 window_prompting |= USSize;
3136 else
3137 window_prompting |= PSize;
3140 f->output_data.w32->vertical_scroll_bar_extra
3141 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3143 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3144 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3145 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3146 f->output_data.w32->flags_areas_extra
3147 = FRAME_FLAGS_AREA_WIDTH (f);
3148 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3149 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3151 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3152 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3153 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3154 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3156 if (EQ (tem0, Qminus))
3158 f->output_data.w32->top_pos = 0;
3159 window_prompting |= YNegative;
3161 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3162 && CONSP (XCDR (tem0))
3163 && INTEGERP (XCAR (XCDR (tem0))))
3165 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3166 window_prompting |= YNegative;
3168 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3169 && CONSP (XCDR (tem0))
3170 && INTEGERP (XCAR (XCDR (tem0))))
3172 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3174 else if (EQ (tem0, Qunbound))
3175 f->output_data.w32->top_pos = 0;
3176 else
3178 CHECK_NUMBER (tem0, 0);
3179 f->output_data.w32->top_pos = XINT (tem0);
3180 if (f->output_data.w32->top_pos < 0)
3181 window_prompting |= YNegative;
3184 if (EQ (tem1, Qminus))
3186 f->output_data.w32->left_pos = 0;
3187 window_prompting |= XNegative;
3189 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3190 && CONSP (XCDR (tem1))
3191 && INTEGERP (XCAR (XCDR (tem1))))
3193 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3194 window_prompting |= XNegative;
3196 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3197 && CONSP (XCDR (tem1))
3198 && INTEGERP (XCAR (XCDR (tem1))))
3200 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3202 else if (EQ (tem1, Qunbound))
3203 f->output_data.w32->left_pos = 0;
3204 else
3206 CHECK_NUMBER (tem1, 0);
3207 f->output_data.w32->left_pos = XINT (tem1);
3208 if (f->output_data.w32->left_pos < 0)
3209 window_prompting |= XNegative;
3212 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3213 window_prompting |= USPosition;
3214 else
3215 window_prompting |= PPosition;
3218 return window_prompting;
3223 extern LRESULT CALLBACK w32_wnd_proc ();
3225 BOOL
3226 w32_init_class (hinst)
3227 HINSTANCE hinst;
3229 WNDCLASS wc;
3231 wc.style = CS_HREDRAW | CS_VREDRAW;
3232 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3233 wc.cbClsExtra = 0;
3234 wc.cbWndExtra = WND_EXTRA_BYTES;
3235 wc.hInstance = hinst;
3236 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3237 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3238 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3239 wc.lpszMenuName = NULL;
3240 wc.lpszClassName = EMACS_CLASS;
3242 return (RegisterClass (&wc));
3245 HWND
3246 w32_createscrollbar (f, bar)
3247 struct frame *f;
3248 struct scroll_bar * bar;
3250 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3251 /* Position and size of scroll bar. */
3252 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3253 XINT(bar->top),
3254 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3255 XINT(bar->height),
3256 FRAME_W32_WINDOW (f),
3257 NULL,
3258 hinst,
3259 NULL));
3262 void
3263 w32_createwindow (f)
3264 struct frame *f;
3266 HWND hwnd;
3267 RECT rect;
3269 rect.left = rect.top = 0;
3270 rect.right = PIXEL_WIDTH (f);
3271 rect.bottom = PIXEL_HEIGHT (f);
3273 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3274 FRAME_EXTERNAL_MENU_BAR (f));
3276 /* Do first time app init */
3278 if (!hprevinst)
3280 w32_init_class (hinst);
3283 FRAME_W32_WINDOW (f) = hwnd
3284 = CreateWindow (EMACS_CLASS,
3285 f->namebuf,
3286 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3287 f->output_data.w32->left_pos,
3288 f->output_data.w32->top_pos,
3289 rect.right - rect.left,
3290 rect.bottom - rect.top,
3291 NULL,
3292 NULL,
3293 hinst,
3294 NULL);
3296 if (hwnd)
3298 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3299 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3300 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3301 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3302 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3304 /* Enable drag-n-drop. */
3305 DragAcceptFiles (hwnd, TRUE);
3307 /* Do this to discard the default setting specified by our parent. */
3308 ShowWindow (hwnd, SW_HIDE);
3312 void
3313 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3314 W32Msg * wmsg;
3315 HWND hwnd;
3316 UINT msg;
3317 WPARAM wParam;
3318 LPARAM lParam;
3320 wmsg->msg.hwnd = hwnd;
3321 wmsg->msg.message = msg;
3322 wmsg->msg.wParam = wParam;
3323 wmsg->msg.lParam = lParam;
3324 wmsg->msg.time = GetMessageTime ();
3326 post_msg (wmsg);
3329 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3330 between left and right keys as advertised. We test for this
3331 support dynamically, and set a flag when the support is absent. If
3332 absent, we keep track of the left and right control and alt keys
3333 ourselves. This is particularly necessary on keyboards that rely
3334 upon the AltGr key, which is represented as having the left control
3335 and right alt keys pressed. For these keyboards, we need to know
3336 when the left alt key has been pressed in addition to the AltGr key
3337 so that we can properly support M-AltGr-key sequences (such as M-@
3338 on Swedish keyboards). */
3340 #define EMACS_LCONTROL 0
3341 #define EMACS_RCONTROL 1
3342 #define EMACS_LMENU 2
3343 #define EMACS_RMENU 3
3345 static int modifiers[4];
3346 static int modifiers_recorded;
3347 static int modifier_key_support_tested;
3349 static void
3350 test_modifier_support (unsigned int wparam)
3352 unsigned int l, r;
3354 if (wparam != VK_CONTROL && wparam != VK_MENU)
3355 return;
3356 if (wparam == VK_CONTROL)
3358 l = VK_LCONTROL;
3359 r = VK_RCONTROL;
3361 else
3363 l = VK_LMENU;
3364 r = VK_RMENU;
3366 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3367 modifiers_recorded = 1;
3368 else
3369 modifiers_recorded = 0;
3370 modifier_key_support_tested = 1;
3373 static void
3374 record_keydown (unsigned int wparam, unsigned int lparam)
3376 int i;
3378 if (!modifier_key_support_tested)
3379 test_modifier_support (wparam);
3381 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3382 return;
3384 if (wparam == VK_CONTROL)
3385 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3386 else
3387 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3389 modifiers[i] = 1;
3392 static void
3393 record_keyup (unsigned int wparam, unsigned int lparam)
3395 int i;
3397 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3398 return;
3400 if (wparam == VK_CONTROL)
3401 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3402 else
3403 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3405 modifiers[i] = 0;
3408 /* Emacs can lose focus while a modifier key has been pressed. When
3409 it regains focus, be conservative and clear all modifiers since
3410 we cannot reconstruct the left and right modifier state. */
3411 static void
3412 reset_modifiers ()
3414 SHORT ctrl, alt;
3416 if (GetFocus () == NULL)
3417 /* Emacs doesn't have keyboard focus. Do nothing. */
3418 return;
3420 ctrl = GetAsyncKeyState (VK_CONTROL);
3421 alt = GetAsyncKeyState (VK_MENU);
3423 if (!(ctrl & 0x08000))
3424 /* Clear any recorded control modifier state. */
3425 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3427 if (!(alt & 0x08000))
3428 /* Clear any recorded alt modifier state. */
3429 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3431 /* Update the state of all modifier keys, because modifiers used in
3432 hot-key combinations can get stuck on if Emacs loses focus as a
3433 result of a hot-key being pressed. */
3435 BYTE keystate[256];
3437 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3439 GetKeyboardState (keystate);
3440 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3441 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3442 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3443 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3444 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3445 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3446 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3447 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3448 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3449 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3450 SetKeyboardState (keystate);
3454 /* Synchronize modifier state with what is reported with the current
3455 keystroke. Even if we cannot distinguish between left and right
3456 modifier keys, we know that, if no modifiers are set, then neither
3457 the left or right modifier should be set. */
3458 static void
3459 sync_modifiers ()
3461 if (!modifiers_recorded)
3462 return;
3464 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3465 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3467 if (!(GetKeyState (VK_MENU) & 0x8000))
3468 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3471 static int
3472 modifier_set (int vkey)
3474 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3475 return (GetKeyState (vkey) & 0x1);
3476 if (!modifiers_recorded)
3477 return (GetKeyState (vkey) & 0x8000);
3479 switch (vkey)
3481 case VK_LCONTROL:
3482 return modifiers[EMACS_LCONTROL];
3483 case VK_RCONTROL:
3484 return modifiers[EMACS_RCONTROL];
3485 case VK_LMENU:
3486 return modifiers[EMACS_LMENU];
3487 case VK_RMENU:
3488 return modifiers[EMACS_RMENU];
3490 return (GetKeyState (vkey) & 0x8000);
3493 /* Convert between the modifier bits W32 uses and the modifier bits
3494 Emacs uses. */
3496 unsigned int
3497 w32_key_to_modifier (int key)
3499 Lisp_Object key_mapping;
3501 switch (key)
3503 case VK_LWIN:
3504 key_mapping = Vw32_lwindow_modifier;
3505 break;
3506 case VK_RWIN:
3507 key_mapping = Vw32_rwindow_modifier;
3508 break;
3509 case VK_APPS:
3510 key_mapping = Vw32_apps_modifier;
3511 break;
3512 case VK_SCROLL:
3513 key_mapping = Vw32_scroll_lock_modifier;
3514 break;
3515 default:
3516 key_mapping = Qnil;
3519 /* NB. This code runs in the input thread, asychronously to the lisp
3520 thread, so we must be careful to ensure access to lisp data is
3521 thread-safe. The following code is safe because the modifier
3522 variable values are updated atomically from lisp and symbols are
3523 not relocated by GC. Also, we don't have to worry about seeing GC
3524 markbits here. */
3525 if (EQ (key_mapping, Qhyper))
3526 return hyper_modifier;
3527 if (EQ (key_mapping, Qsuper))
3528 return super_modifier;
3529 if (EQ (key_mapping, Qmeta))
3530 return meta_modifier;
3531 if (EQ (key_mapping, Qalt))
3532 return alt_modifier;
3533 if (EQ (key_mapping, Qctrl))
3534 return ctrl_modifier;
3535 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3536 return ctrl_modifier;
3537 if (EQ (key_mapping, Qshift))
3538 return shift_modifier;
3540 /* Don't generate any modifier if not explicitly requested. */
3541 return 0;
3544 unsigned int
3545 w32_get_modifiers ()
3547 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3548 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3549 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3550 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3551 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3552 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3553 (modifier_set (VK_MENU) ?
3554 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3557 /* We map the VK_* modifiers into console modifier constants
3558 so that we can use the same routines to handle both console
3559 and window input. */
3561 static int
3562 construct_console_modifiers ()
3564 int mods;
3566 mods = 0;
3567 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3568 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3569 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3570 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3571 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3572 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3573 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3574 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3575 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3576 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3577 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3579 return mods;
3582 static int
3583 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3585 int mods;
3587 /* Convert to emacs modifiers. */
3588 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3590 return mods;
3593 unsigned int
3594 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3596 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3597 return virt_key;
3599 if (virt_key == VK_RETURN)
3600 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3602 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3603 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3605 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3606 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3608 if (virt_key == VK_CLEAR)
3609 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3611 return virt_key;
3614 /* List of special key combinations which w32 would normally capture,
3615 but emacs should grab instead. Not directly visible to lisp, to
3616 simplify synchronization. Each item is an integer encoding a virtual
3617 key code and modifier combination to capture. */
3618 Lisp_Object w32_grabbed_keys;
3620 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3621 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3622 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3623 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3625 /* Register hot-keys for reserved key combinations when Emacs has
3626 keyboard focus, since this is the only way Emacs can receive key
3627 combinations like Alt-Tab which are used by the system. */
3629 static void
3630 register_hot_keys (hwnd)
3631 HWND hwnd;
3633 Lisp_Object keylist;
3635 /* Use GC_CONSP, since we are called asynchronously. */
3636 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3638 Lisp_Object key = XCAR (keylist);
3640 /* Deleted entries get set to nil. */
3641 if (!INTEGERP (key))
3642 continue;
3644 RegisterHotKey (hwnd, HOTKEY_ID (key),
3645 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3649 static void
3650 unregister_hot_keys (hwnd)
3651 HWND hwnd;
3653 Lisp_Object keylist;
3655 /* Use GC_CONSP, since we are called asynchronously. */
3656 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3658 Lisp_Object key = XCAR (keylist);
3660 if (!INTEGERP (key))
3661 continue;
3663 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3667 /* Main message dispatch loop. */
3669 static void
3670 w32_msg_pump (deferred_msg * msg_buf)
3672 MSG msg;
3673 int result;
3674 HWND focus_window;
3676 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3678 while (GetMessage (&msg, NULL, 0, 0))
3680 if (msg.hwnd == NULL)
3682 switch (msg.message)
3684 case WM_NULL:
3685 /* Produced by complete_deferred_msg; just ignore. */
3686 break;
3687 case WM_EMACS_CREATEWINDOW:
3688 w32_createwindow ((struct frame *) msg.wParam);
3689 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3690 abort ();
3691 break;
3692 case WM_EMACS_SETLOCALE:
3693 SetThreadLocale (msg.wParam);
3694 /* Reply is not expected. */
3695 break;
3696 case WM_EMACS_SETKEYBOARDLAYOUT:
3697 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3698 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3699 result, 0))
3700 abort ();
3701 break;
3702 case WM_EMACS_REGISTER_HOT_KEY:
3703 focus_window = GetFocus ();
3704 if (focus_window != NULL)
3705 RegisterHotKey (focus_window,
3706 HOTKEY_ID (msg.wParam),
3707 HOTKEY_MODIFIERS (msg.wParam),
3708 HOTKEY_VK_CODE (msg.wParam));
3709 /* Reply is not expected. */
3710 break;
3711 case WM_EMACS_UNREGISTER_HOT_KEY:
3712 focus_window = GetFocus ();
3713 if (focus_window != NULL)
3714 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3715 /* Mark item as erased. NB: this code must be
3716 thread-safe. The next line is okay because the cons
3717 cell is never made into garbage and is not relocated by
3718 GC. */
3719 XCAR ((Lisp_Object) msg.lParam) = Qnil;
3720 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3721 abort ();
3722 break;
3723 case WM_EMACS_TOGGLE_LOCK_KEY:
3725 int vk_code = (int) msg.wParam;
3726 int cur_state = (GetKeyState (vk_code) & 1);
3727 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3729 /* NB: This code must be thread-safe. It is safe to
3730 call NILP because symbols are not relocated by GC,
3731 and pointer here is not touched by GC (so the markbit
3732 can't be set). Numbers are safe because they are
3733 immediate values. */
3734 if (NILP (new_state)
3735 || (NUMBERP (new_state)
3736 && (XUINT (new_state)) & 1 != cur_state))
3738 one_w32_display_info.faked_key = vk_code;
3740 keybd_event ((BYTE) vk_code,
3741 (BYTE) MapVirtualKey (vk_code, 0),
3742 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3743 keybd_event ((BYTE) vk_code,
3744 (BYTE) MapVirtualKey (vk_code, 0),
3745 KEYEVENTF_EXTENDEDKEY | 0, 0);
3746 keybd_event ((BYTE) vk_code,
3747 (BYTE) MapVirtualKey (vk_code, 0),
3748 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3749 cur_state = !cur_state;
3751 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3752 cur_state, 0))
3753 abort ();
3755 break;
3756 default:
3757 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3760 else
3762 DispatchMessage (&msg);
3765 /* Exit nested loop when our deferred message has completed. */
3766 if (msg_buf->completed)
3767 break;
3771 deferred_msg * deferred_msg_head;
3773 static deferred_msg *
3774 find_deferred_msg (HWND hwnd, UINT msg)
3776 deferred_msg * item;
3778 /* Don't actually need synchronization for read access, since
3779 modification of single pointer is always atomic. */
3780 /* enter_crit (); */
3782 for (item = deferred_msg_head; item != NULL; item = item->next)
3783 if (item->w32msg.msg.hwnd == hwnd
3784 && item->w32msg.msg.message == msg)
3785 break;
3787 /* leave_crit (); */
3789 return item;
3792 static LRESULT
3793 send_deferred_msg (deferred_msg * msg_buf,
3794 HWND hwnd,
3795 UINT msg,
3796 WPARAM wParam,
3797 LPARAM lParam)
3799 /* Only input thread can send deferred messages. */
3800 if (GetCurrentThreadId () != dwWindowsThreadId)
3801 abort ();
3803 /* It is an error to send a message that is already deferred. */
3804 if (find_deferred_msg (hwnd, msg) != NULL)
3805 abort ();
3807 /* Enforced synchronization is not needed because this is the only
3808 function that alters deferred_msg_head, and the following critical
3809 section is guaranteed to only be serially reentered (since only the
3810 input thread can call us). */
3812 /* enter_crit (); */
3814 msg_buf->completed = 0;
3815 msg_buf->next = deferred_msg_head;
3816 deferred_msg_head = msg_buf;
3817 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3819 /* leave_crit (); */
3821 /* Start a new nested message loop to process other messages until
3822 this one is completed. */
3823 w32_msg_pump (msg_buf);
3825 deferred_msg_head = msg_buf->next;
3827 return msg_buf->result;
3830 void
3831 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3833 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3835 if (msg_buf == NULL)
3836 /* Message may have been cancelled, so don't abort(). */
3837 return;
3839 msg_buf->result = result;
3840 msg_buf->completed = 1;
3842 /* Ensure input thread is woken so it notices the completion. */
3843 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3846 void
3847 cancel_all_deferred_msgs ()
3849 deferred_msg * item;
3851 /* Don't actually need synchronization for read access, since
3852 modification of single pointer is always atomic. */
3853 /* enter_crit (); */
3855 for (item = deferred_msg_head; item != NULL; item = item->next)
3857 item->result = 0;
3858 item->completed = 1;
3861 /* leave_crit (); */
3863 /* Ensure input thread is woken so it notices the completion. */
3864 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3867 DWORD
3868 w32_msg_worker (dw)
3869 DWORD dw;
3871 MSG msg;
3872 deferred_msg dummy_buf;
3874 /* Ensure our message queue is created */
3876 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3878 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3879 abort ();
3881 memset (&dummy_buf, 0, sizeof (dummy_buf));
3882 dummy_buf.w32msg.msg.hwnd = NULL;
3883 dummy_buf.w32msg.msg.message = WM_NULL;
3885 /* This is the inital message loop which should only exit when the
3886 application quits. */
3887 w32_msg_pump (&dummy_buf);
3889 return 0;
3892 static void
3893 post_character_message (hwnd, msg, wParam, lParam, modifiers)
3894 HWND hwnd;
3895 UINT msg;
3896 WPARAM wParam;
3897 LPARAM lParam;
3898 DWORD modifiers;
3901 W32Msg wmsg;
3903 wmsg.dwModifiers = modifiers;
3905 /* Detect quit_char and set quit-flag directly. Note that we
3906 still need to post a message to ensure the main thread will be
3907 woken up if blocked in sys_select(), but we do NOT want to post
3908 the quit_char message itself (because it will usually be as if
3909 the user had typed quit_char twice). Instead, we post a dummy
3910 message that has no particular effect. */
3912 int c = wParam;
3913 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
3914 c = make_ctrl_char (c) & 0377;
3915 if (c == quit_char
3916 || (wmsg.dwModifiers == 0 &&
3917 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
3919 Vquit_flag = Qt;
3921 /* The choice of message is somewhat arbitrary, as long as
3922 the main thread handler just ignores it. */
3923 msg = WM_NULL;
3925 /* Interrupt any blocking system calls. */
3926 signal_quit ();
3928 /* As a safety precaution, forcibly complete any deferred
3929 messages. This is a kludge, but I don't see any particularly
3930 clean way to handle the situation where a deferred message is
3931 "dropped" in the lisp thread, and will thus never be
3932 completed, eg. by the user trying to activate the menubar
3933 when the lisp thread is busy, and then typing C-g when the
3934 menubar doesn't open promptly (with the result that the
3935 menubar never responds at all because the deferred
3936 WM_INITMENU message is never completed). Another problem
3937 situation is when the lisp thread calls SendMessage (to send
3938 a window manager command) when a message has been deferred;
3939 the lisp thread gets blocked indefinitely waiting for the
3940 deferred message to be completed, which itself is waiting for
3941 the lisp thread to respond.
3943 Note that we don't want to block the input thread waiting for
3944 a reponse from the lisp thread (although that would at least
3945 solve the deadlock problem above), because we want to be able
3946 to receive C-g to interrupt the lisp thread. */
3947 cancel_all_deferred_msgs ();
3951 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3954 /* Main window procedure */
3956 LRESULT CALLBACK
3957 w32_wnd_proc (hwnd, msg, wParam, lParam)
3958 HWND hwnd;
3959 UINT msg;
3960 WPARAM wParam;
3961 LPARAM lParam;
3963 struct frame *f;
3964 struct w32_display_info *dpyinfo = &one_w32_display_info;
3965 W32Msg wmsg;
3966 int windows_translate;
3967 int key;
3969 /* Note that it is okay to call x_window_to_frame, even though we are
3970 not running in the main lisp thread, because frame deletion
3971 requires the lisp thread to synchronize with this thread. Thus, if
3972 a frame struct is returned, it can be used without concern that the
3973 lisp thread might make it disappear while we are using it.
3975 NB. Walking the frame list in this thread is safe (as long as
3976 writes of Lisp_Object slots are atomic, which they are on Windows).
3977 Although delete-frame can destructively modify the frame list while
3978 we are walking it, a garbage collection cannot occur until after
3979 delete-frame has synchronized with this thread.
3981 It is also safe to use functions that make GDI calls, such as
3982 w32_clear_rect, because these functions must obtain a DC handle
3983 from the frame struct using get_frame_dc which is thread-aware. */
3985 switch (msg)
3987 case WM_ERASEBKGND:
3988 f = x_window_to_frame (dpyinfo, hwnd);
3989 if (f)
3991 HDC hdc = get_frame_dc (f);
3992 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
3993 w32_clear_rect (f, hdc, &wmsg.rect);
3994 release_frame_dc (f, hdc);
3996 #if defined (W32_DEBUG_DISPLAY)
3997 DebPrint (("WM_ERASEBKGND: erasing %d,%d-%d,%d\n",
3998 wmsg.rect.left, wmsg.rect.top, wmsg.rect.right,
3999 wmsg.rect.bottom));
4000 #endif /* W32_DEBUG_DISPLAY */
4002 return 1;
4003 case WM_PALETTECHANGED:
4004 /* ignore our own changes */
4005 if ((HWND)wParam != hwnd)
4007 f = x_window_to_frame (dpyinfo, hwnd);
4008 if (f)
4009 /* get_frame_dc will realize our palette and force all
4010 frames to be redrawn if needed. */
4011 release_frame_dc (f, get_frame_dc (f));
4013 return 0;
4014 case WM_PAINT:
4016 PAINTSTRUCT paintStruct;
4017 RECT update_rect;
4019 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4020 fails. Apparently this can happen under some
4021 circumstances. */
4022 if (!w32_strict_painting || GetUpdateRect (hwnd, &update_rect, FALSE))
4024 enter_crit ();
4025 BeginPaint (hwnd, &paintStruct);
4027 if (w32_strict_painting)
4028 /* The rectangles returned by GetUpdateRect and BeginPaint
4029 do not always match. GetUpdateRect seems to be the
4030 more reliable of the two. */
4031 wmsg.rect = update_rect;
4032 else
4033 wmsg.rect = paintStruct.rcPaint;
4035 #if defined (W32_DEBUG_DISPLAY)
4036 DebPrint (("WM_PAINT: painting %d,%d-%d,%d\n", wmsg.rect.left,
4037 wmsg.rect.top, wmsg.rect.right, wmsg.rect.bottom));
4038 DebPrint (("WM_PAINT: update region is %d,%d-%d,%d\n",
4039 update_rect.left, update_rect.top,
4040 update_rect.right, update_rect.bottom));
4041 #endif
4042 EndPaint (hwnd, &paintStruct);
4043 leave_crit ();
4045 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4047 return 0;
4050 /* If GetUpdateRect returns 0 (meaning there is no update
4051 region), assume the whole window needs to be repainted. */
4052 GetClientRect(hwnd, &wmsg.rect);
4053 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4054 return 0;
4057 case WM_INPUTLANGCHANGE:
4058 /* Inform lisp thread of keyboard layout changes. */
4059 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4061 /* Clear dead keys in the keyboard state; for simplicity only
4062 preserve modifier key states. */
4064 int i;
4065 BYTE keystate[256];
4067 GetKeyboardState (keystate);
4068 for (i = 0; i < 256; i++)
4069 if (1
4070 && i != VK_SHIFT
4071 && i != VK_LSHIFT
4072 && i != VK_RSHIFT
4073 && i != VK_CAPITAL
4074 && i != VK_NUMLOCK
4075 && i != VK_SCROLL
4076 && i != VK_CONTROL
4077 && i != VK_LCONTROL
4078 && i != VK_RCONTROL
4079 && i != VK_MENU
4080 && i != VK_LMENU
4081 && i != VK_RMENU
4082 && i != VK_LWIN
4083 && i != VK_RWIN)
4084 keystate[i] = 0;
4085 SetKeyboardState (keystate);
4087 goto dflt;
4089 case WM_HOTKEY:
4090 /* Synchronize hot keys with normal input. */
4091 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4092 return (0);
4094 case WM_KEYUP:
4095 case WM_SYSKEYUP:
4096 record_keyup (wParam, lParam);
4097 goto dflt;
4099 case WM_KEYDOWN:
4100 case WM_SYSKEYDOWN:
4101 /* Ignore keystrokes we fake ourself; see below. */
4102 if (dpyinfo->faked_key == wParam)
4104 dpyinfo->faked_key = 0;
4105 /* Make sure TranslateMessage sees them though (as long as
4106 they don't produce WM_CHAR messages). This ensures that
4107 indicator lights are toggled promptly on Windows 9x, for
4108 example. */
4109 if (lispy_function_keys[wParam] != 0)
4111 windows_translate = 1;
4112 goto translate;
4114 return 0;
4117 /* Synchronize modifiers with current keystroke. */
4118 sync_modifiers ();
4119 record_keydown (wParam, lParam);
4120 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4122 windows_translate = 0;
4124 switch (wParam)
4126 case VK_LWIN:
4127 if (NILP (Vw32_pass_lwindow_to_system))
4129 /* Prevent system from acting on keyup (which opens the
4130 Start menu if no other key was pressed) by simulating a
4131 press of Space which we will ignore. */
4132 if (GetAsyncKeyState (wParam) & 1)
4134 if (NUMBERP (Vw32_phantom_key_code))
4135 key = XUINT (Vw32_phantom_key_code) & 255;
4136 else
4137 key = VK_SPACE;
4138 dpyinfo->faked_key = key;
4139 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4142 if (!NILP (Vw32_lwindow_modifier))
4143 return 0;
4144 break;
4145 case VK_RWIN:
4146 if (NILP (Vw32_pass_rwindow_to_system))
4148 if (GetAsyncKeyState (wParam) & 1)
4150 if (NUMBERP (Vw32_phantom_key_code))
4151 key = XUINT (Vw32_phantom_key_code) & 255;
4152 else
4153 key = VK_SPACE;
4154 dpyinfo->faked_key = key;
4155 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4158 if (!NILP (Vw32_rwindow_modifier))
4159 return 0;
4160 break;
4161 case VK_APPS:
4162 if (!NILP (Vw32_apps_modifier))
4163 return 0;
4164 break;
4165 case VK_MENU:
4166 if (NILP (Vw32_pass_alt_to_system))
4167 /* Prevent DefWindowProc from activating the menu bar if an
4168 Alt key is pressed and released by itself. */
4169 return 0;
4170 windows_translate = 1;
4171 break;
4172 case VK_CAPITAL:
4173 /* Decide whether to treat as modifier or function key. */
4174 if (NILP (Vw32_enable_caps_lock))
4175 goto disable_lock_key;
4176 windows_translate = 1;
4177 break;
4178 case VK_NUMLOCK:
4179 /* Decide whether to treat as modifier or function key. */
4180 if (NILP (Vw32_enable_num_lock))
4181 goto disable_lock_key;
4182 windows_translate = 1;
4183 break;
4184 case VK_SCROLL:
4185 /* Decide whether to treat as modifier or function key. */
4186 if (NILP (Vw32_scroll_lock_modifier))
4187 goto disable_lock_key;
4188 windows_translate = 1;
4189 break;
4190 disable_lock_key:
4191 /* Ensure the appropriate lock key state (and indicator light)
4192 remains in the same state. We do this by faking another
4193 press of the relevant key. Apparently, this really is the
4194 only way to toggle the state of the indicator lights. */
4195 dpyinfo->faked_key = wParam;
4196 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4197 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4198 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4199 KEYEVENTF_EXTENDEDKEY | 0, 0);
4200 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4201 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4202 /* Ensure indicator lights are updated promptly on Windows 9x
4203 (TranslateMessage apparently does this), after forwarding
4204 input event. */
4205 post_character_message (hwnd, msg, wParam, lParam,
4206 w32_get_key_modifiers (wParam, lParam));
4207 windows_translate = 1;
4208 break;
4209 case VK_CONTROL:
4210 case VK_SHIFT:
4211 case VK_PROCESSKEY: /* Generated by IME. */
4212 windows_translate = 1;
4213 break;
4214 case VK_CANCEL:
4215 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4216 which is confusing for purposes of key binding; convert
4217 VK_CANCEL events into VK_PAUSE events. */
4218 wParam = VK_PAUSE;
4219 break;
4220 case VK_PAUSE:
4221 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4222 for purposes of key binding; convert these back into
4223 VK_NUMLOCK events, at least when we want to see NumLock key
4224 presses. (Note that there is never any possibility that
4225 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4226 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4227 wParam = VK_NUMLOCK;
4228 break;
4229 default:
4230 /* If not defined as a function key, change it to a WM_CHAR message. */
4231 if (lispy_function_keys[wParam] == 0)
4233 DWORD modifiers = construct_console_modifiers ();
4235 if (!NILP (Vw32_recognize_altgr)
4236 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4238 /* Always let TranslateMessage handle AltGr key chords;
4239 for some reason, ToAscii doesn't always process AltGr
4240 chords correctly. */
4241 windows_translate = 1;
4243 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4245 /* Handle key chords including any modifiers other
4246 than shift directly, in order to preserve as much
4247 modifier information as possible. */
4248 if ('A' <= wParam && wParam <= 'Z')
4250 /* Don't translate modified alphabetic keystrokes,
4251 so the user doesn't need to constantly switch
4252 layout to type control or meta keystrokes when
4253 the normal layout translates alphabetic
4254 characters to non-ascii characters. */
4255 if (!modifier_set (VK_SHIFT))
4256 wParam += ('a' - 'A');
4257 msg = WM_CHAR;
4259 else
4261 /* Try to handle other keystrokes by determining the
4262 base character (ie. translating the base key plus
4263 shift modifier). */
4264 int add;
4265 int isdead = 0;
4266 KEY_EVENT_RECORD key;
4268 key.bKeyDown = TRUE;
4269 key.wRepeatCount = 1;
4270 key.wVirtualKeyCode = wParam;
4271 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4272 key.uChar.AsciiChar = 0;
4273 key.dwControlKeyState = modifiers;
4275 add = w32_kbd_patch_key (&key);
4276 /* 0 means an unrecognised keycode, negative means
4277 dead key. Ignore both. */
4278 while (--add >= 0)
4280 /* Forward asciified character sequence. */
4281 post_character_message
4282 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4283 w32_get_key_modifiers (wParam, lParam));
4284 w32_kbd_patch_key (&key);
4286 return 0;
4289 else
4291 /* Let TranslateMessage handle everything else. */
4292 windows_translate = 1;
4297 translate:
4298 if (windows_translate)
4300 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4302 windows_msg.time = GetMessageTime ();
4303 TranslateMessage (&windows_msg);
4304 goto dflt;
4307 /* Fall through */
4309 case WM_SYSCHAR:
4310 case WM_CHAR:
4311 post_character_message (hwnd, msg, wParam, lParam,
4312 w32_get_key_modifiers (wParam, lParam));
4313 break;
4315 /* Simulate middle mouse button events when left and right buttons
4316 are used together, but only if user has two button mouse. */
4317 case WM_LBUTTONDOWN:
4318 case WM_RBUTTONDOWN:
4319 if (XINT (Vw32_num_mouse_buttons) > 2)
4320 goto handle_plain_button;
4323 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4324 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4326 if (button_state & this)
4327 return 0;
4329 if (button_state == 0)
4330 SetCapture (hwnd);
4332 button_state |= this;
4334 if (button_state & other)
4336 if (mouse_button_timer)
4338 KillTimer (hwnd, mouse_button_timer);
4339 mouse_button_timer = 0;
4341 /* Generate middle mouse event instead. */
4342 msg = WM_MBUTTONDOWN;
4343 button_state |= MMOUSE;
4345 else if (button_state & MMOUSE)
4347 /* Ignore button event if we've already generated a
4348 middle mouse down event. This happens if the
4349 user releases and press one of the two buttons
4350 after we've faked a middle mouse event. */
4351 return 0;
4353 else
4355 /* Flush out saved message. */
4356 post_msg (&saved_mouse_button_msg);
4358 wmsg.dwModifiers = w32_get_modifiers ();
4359 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4361 /* Clear message buffer. */
4362 saved_mouse_button_msg.msg.hwnd = 0;
4364 else
4366 /* Hold onto message for now. */
4367 mouse_button_timer =
4368 SetTimer (hwnd, MOUSE_BUTTON_ID,
4369 XINT (Vw32_mouse_button_tolerance), NULL);
4370 saved_mouse_button_msg.msg.hwnd = hwnd;
4371 saved_mouse_button_msg.msg.message = msg;
4372 saved_mouse_button_msg.msg.wParam = wParam;
4373 saved_mouse_button_msg.msg.lParam = lParam;
4374 saved_mouse_button_msg.msg.time = GetMessageTime ();
4375 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4378 return 0;
4380 case WM_LBUTTONUP:
4381 case WM_RBUTTONUP:
4382 if (XINT (Vw32_num_mouse_buttons) > 2)
4383 goto handle_plain_button;
4386 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4387 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4389 if ((button_state & this) == 0)
4390 return 0;
4392 button_state &= ~this;
4394 if (button_state & MMOUSE)
4396 /* Only generate event when second button is released. */
4397 if ((button_state & other) == 0)
4399 msg = WM_MBUTTONUP;
4400 button_state &= ~MMOUSE;
4402 if (button_state) abort ();
4404 else
4405 return 0;
4407 else
4409 /* Flush out saved message if necessary. */
4410 if (saved_mouse_button_msg.msg.hwnd)
4412 post_msg (&saved_mouse_button_msg);
4415 wmsg.dwModifiers = w32_get_modifiers ();
4416 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4418 /* Always clear message buffer and cancel timer. */
4419 saved_mouse_button_msg.msg.hwnd = 0;
4420 KillTimer (hwnd, mouse_button_timer);
4421 mouse_button_timer = 0;
4423 if (button_state == 0)
4424 ReleaseCapture ();
4426 return 0;
4428 case WM_MBUTTONDOWN:
4429 case WM_MBUTTONUP:
4430 handle_plain_button:
4432 BOOL up;
4433 int button;
4435 if (parse_button (msg, &button, &up))
4437 if (up) ReleaseCapture ();
4438 else SetCapture (hwnd);
4439 button = (button == 0) ? LMOUSE :
4440 ((button == 1) ? MMOUSE : RMOUSE);
4441 if (up)
4442 button_state &= ~button;
4443 else
4444 button_state |= button;
4448 wmsg.dwModifiers = w32_get_modifiers ();
4449 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4450 return 0;
4452 case WM_VSCROLL:
4453 case WM_MOUSEMOVE:
4454 if (XINT (Vw32_mouse_move_interval) <= 0
4455 || (msg == WM_MOUSEMOVE && button_state == 0))
4457 wmsg.dwModifiers = w32_get_modifiers ();
4458 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4459 return 0;
4462 /* Hang onto mouse move and scroll messages for a bit, to avoid
4463 sending such events to Emacs faster than it can process them.
4464 If we get more events before the timer from the first message
4465 expires, we just replace the first message. */
4467 if (saved_mouse_move_msg.msg.hwnd == 0)
4468 mouse_move_timer =
4469 SetTimer (hwnd, MOUSE_MOVE_ID,
4470 XINT (Vw32_mouse_move_interval), NULL);
4472 /* Hold onto message for now. */
4473 saved_mouse_move_msg.msg.hwnd = hwnd;
4474 saved_mouse_move_msg.msg.message = msg;
4475 saved_mouse_move_msg.msg.wParam = wParam;
4476 saved_mouse_move_msg.msg.lParam = lParam;
4477 saved_mouse_move_msg.msg.time = GetMessageTime ();
4478 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4480 return 0;
4482 case WM_MOUSEWHEEL:
4483 wmsg.dwModifiers = w32_get_modifiers ();
4484 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4485 return 0;
4487 case WM_DROPFILES:
4488 wmsg.dwModifiers = w32_get_modifiers ();
4489 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4490 return 0;
4492 case WM_TIMER:
4493 /* Flush out saved messages if necessary. */
4494 if (wParam == mouse_button_timer)
4496 if (saved_mouse_button_msg.msg.hwnd)
4498 post_msg (&saved_mouse_button_msg);
4499 saved_mouse_button_msg.msg.hwnd = 0;
4501 KillTimer (hwnd, mouse_button_timer);
4502 mouse_button_timer = 0;
4504 else if (wParam == mouse_move_timer)
4506 if (saved_mouse_move_msg.msg.hwnd)
4508 post_msg (&saved_mouse_move_msg);
4509 saved_mouse_move_msg.msg.hwnd = 0;
4511 KillTimer (hwnd, mouse_move_timer);
4512 mouse_move_timer = 0;
4514 return 0;
4516 case WM_NCACTIVATE:
4517 /* Windows doesn't send us focus messages when putting up and
4518 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4519 The only indication we get that something happened is receiving
4520 this message afterwards. So this is a good time to reset our
4521 keyboard modifiers' state. */
4522 reset_modifiers ();
4523 goto dflt;
4525 case WM_INITMENU:
4526 button_state = 0;
4527 ReleaseCapture ();
4528 /* We must ensure menu bar is fully constructed and up to date
4529 before allowing user interaction with it. To achieve this
4530 we send this message to the lisp thread and wait for a
4531 reply (whose value is not actually needed) to indicate that
4532 the menu bar is now ready for use, so we can now return.
4534 To remain responsive in the meantime, we enter a nested message
4535 loop that can process all other messages.
4537 However, we skip all this if the message results from calling
4538 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4539 thread a message because it is blocked on us at this point. We
4540 set menubar_active before calling TrackPopupMenu to indicate
4541 this (there is no possibility of confusion with real menubar
4542 being active). */
4544 f = x_window_to_frame (dpyinfo, hwnd);
4545 if (f
4546 && (f->output_data.w32->menubar_active
4547 /* We can receive this message even in the absence of a
4548 menubar (ie. when the system menu is activated) - in this
4549 case we do NOT want to forward the message, otherwise it
4550 will cause the menubar to suddenly appear when the user
4551 had requested it to be turned off! */
4552 || f->output_data.w32->menubar_widget == NULL))
4553 return 0;
4556 deferred_msg msg_buf;
4558 /* Detect if message has already been deferred; in this case
4559 we cannot return any sensible value to ignore this. */
4560 if (find_deferred_msg (hwnd, msg) != NULL)
4561 abort ();
4563 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4566 case WM_EXITMENULOOP:
4567 f = x_window_to_frame (dpyinfo, hwnd);
4569 /* Indicate that menubar can be modified again. */
4570 if (f)
4571 f->output_data.w32->menubar_active = 0;
4572 goto dflt;
4574 case WM_MENUSELECT:
4575 wmsg.dwModifiers = w32_get_modifiers ();
4576 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4577 return 0;
4579 case WM_MEASUREITEM:
4580 f = x_window_to_frame (dpyinfo, hwnd);
4581 if (f)
4583 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4585 if (pMis->CtlType == ODT_MENU)
4587 /* Work out dimensions for popup menu titles. */
4588 char * title = (char *) pMis->itemData;
4589 HDC hdc = GetDC (hwnd);
4590 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4591 LOGFONT menu_logfont;
4592 HFONT old_font;
4593 SIZE size;
4595 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4596 menu_logfont.lfWeight = FW_BOLD;
4597 menu_font = CreateFontIndirect (&menu_logfont);
4598 old_font = SelectObject (hdc, menu_font);
4600 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4601 if (title)
4603 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4604 pMis->itemWidth = size.cx;
4605 if (pMis->itemHeight < size.cy)
4606 pMis->itemHeight = size.cy;
4608 else
4609 pMis->itemWidth = 0;
4611 SelectObject (hdc, old_font);
4612 DeleteObject (menu_font);
4613 ReleaseDC (hwnd, hdc);
4614 return TRUE;
4617 return 0;
4619 case WM_DRAWITEM:
4620 f = x_window_to_frame (dpyinfo, hwnd);
4621 if (f)
4623 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4625 if (pDis->CtlType == ODT_MENU)
4627 /* Draw popup menu title. */
4628 char * title = (char *) pDis->itemData;
4629 if (title)
4631 HDC hdc = pDis->hDC;
4632 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4633 LOGFONT menu_logfont;
4634 HFONT old_font;
4636 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4637 menu_logfont.lfWeight = FW_BOLD;
4638 menu_font = CreateFontIndirect (&menu_logfont);
4639 old_font = SelectObject (hdc, menu_font);
4641 /* Always draw title as if not selected. */
4642 ExtTextOut (hdc,
4643 pDis->rcItem.left
4644 + GetSystemMetrics (SM_CXMENUCHECK),
4645 pDis->rcItem.top,
4646 ETO_OPAQUE, &pDis->rcItem,
4647 title, strlen (title), NULL);
4649 SelectObject (hdc, old_font);
4650 DeleteObject (menu_font);
4652 return TRUE;
4655 return 0;
4657 #if 0
4658 /* Still not right - can't distinguish between clicks in the
4659 client area of the frame from clicks forwarded from the scroll
4660 bars - may have to hook WM_NCHITTEST to remember the mouse
4661 position and then check if it is in the client area ourselves. */
4662 case WM_MOUSEACTIVATE:
4663 /* Discard the mouse click that activates a frame, allowing the
4664 user to click anywhere without changing point (or worse!).
4665 Don't eat mouse clicks on scrollbars though!! */
4666 if (LOWORD (lParam) == HTCLIENT )
4667 return MA_ACTIVATEANDEAT;
4668 goto dflt;
4669 #endif
4671 case WM_ACTIVATEAPP:
4672 case WM_ACTIVATE:
4673 case WM_WINDOWPOSCHANGED:
4674 case WM_SHOWWINDOW:
4675 /* Inform lisp thread that a frame might have just been obscured
4676 or exposed, so should recheck visibility of all frames. */
4677 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4678 goto dflt;
4680 case WM_SETFOCUS:
4681 dpyinfo->faked_key = 0;
4682 reset_modifiers ();
4683 register_hot_keys (hwnd);
4684 goto command;
4685 case WM_KILLFOCUS:
4686 unregister_hot_keys (hwnd);
4687 button_state = 0;
4688 ReleaseCapture ();
4689 case WM_MOVE:
4690 case WM_SIZE:
4691 case WM_COMMAND:
4692 command:
4693 wmsg.dwModifiers = w32_get_modifiers ();
4694 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4695 goto dflt;
4697 case WM_CLOSE:
4698 wmsg.dwModifiers = w32_get_modifiers ();
4699 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4700 return 0;
4702 case WM_WINDOWPOSCHANGING:
4704 WINDOWPLACEMENT wp;
4705 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4707 wp.length = sizeof (WINDOWPLACEMENT);
4708 GetWindowPlacement (hwnd, &wp);
4710 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4712 RECT rect;
4713 int wdiff;
4714 int hdiff;
4715 DWORD font_width;
4716 DWORD line_height;
4717 DWORD internal_border;
4718 DWORD scrollbar_extra;
4719 RECT wr;
4721 wp.length = sizeof(wp);
4722 GetWindowRect (hwnd, &wr);
4724 enter_crit ();
4726 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4727 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4728 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4729 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
4731 leave_crit ();
4733 memset (&rect, 0, sizeof (rect));
4734 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4735 GetMenu (hwnd) != NULL);
4737 /* Force width and height of client area to be exact
4738 multiples of the character cell dimensions. */
4739 wdiff = (lppos->cx - (rect.right - rect.left)
4740 - 2 * internal_border - scrollbar_extra)
4741 % font_width;
4742 hdiff = (lppos->cy - (rect.bottom - rect.top)
4743 - 2 * internal_border)
4744 % line_height;
4746 if (wdiff || hdiff)
4748 /* For right/bottom sizing we can just fix the sizes.
4749 However for top/left sizing we will need to fix the X
4750 and Y positions as well. */
4752 lppos->cx -= wdiff;
4753 lppos->cy -= hdiff;
4755 if (wp.showCmd != SW_SHOWMAXIMIZED
4756 && (lppos->flags & SWP_NOMOVE) == 0)
4758 if (lppos->x != wr.left || lppos->y != wr.top)
4760 lppos->x += wdiff;
4761 lppos->y += hdiff;
4763 else
4765 lppos->flags |= SWP_NOMOVE;
4769 return 0;
4774 goto dflt;
4776 case WM_GETMINMAXINFO:
4777 /* Hack to correct bug that allows Emacs frames to be resized
4778 below the Minimum Tracking Size. */
4779 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
4780 return 0;
4782 case WM_EMACS_CREATESCROLLBAR:
4783 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
4784 (struct scroll_bar *) lParam);
4786 case WM_EMACS_SHOWWINDOW:
4787 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4789 case WM_EMACS_SETFOREGROUND:
4791 HWND foreground_window;
4792 DWORD foreground_thread, retval;
4794 /* On NT 5.0, and apparently Windows 98, it is necessary to
4795 attach to the thread that currently has focus in order to
4796 pull the focus away from it. */
4797 foreground_window = GetForegroundWindow ();
4798 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4799 if (!foreground_window
4800 || foreground_thread == GetCurrentThreadId ()
4801 || !AttachThreadInput (GetCurrentThreadId (),
4802 foreground_thread, TRUE))
4803 foreground_thread = 0;
4805 retval = SetForegroundWindow ((HWND) wParam);
4807 /* Detach from the previous foreground thread. */
4808 if (foreground_thread)
4809 AttachThreadInput (GetCurrentThreadId (),
4810 foreground_thread, FALSE);
4812 return retval;
4815 case WM_EMACS_SETWINDOWPOS:
4817 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4818 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4819 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4822 case WM_EMACS_DESTROYWINDOW:
4823 DragAcceptFiles ((HWND) wParam, FALSE);
4824 return DestroyWindow ((HWND) wParam);
4826 case WM_EMACS_TRACKPOPUPMENU:
4828 UINT flags;
4829 POINT *pos;
4830 int retval;
4831 pos = (POINT *)lParam;
4832 flags = TPM_CENTERALIGN;
4833 if (button_state & LMOUSE)
4834 flags |= TPM_LEFTBUTTON;
4835 else if (button_state & RMOUSE)
4836 flags |= TPM_RIGHTBUTTON;
4838 /* Remember we did a SetCapture on the initial mouse down event,
4839 so for safety, we make sure the capture is cancelled now. */
4840 ReleaseCapture ();
4841 button_state = 0;
4843 /* Use menubar_active to indicate that WM_INITMENU is from
4844 TrackPopupMenu below, and should be ignored. */
4845 f = x_window_to_frame (dpyinfo, hwnd);
4846 if (f)
4847 f->output_data.w32->menubar_active = 1;
4849 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4850 0, hwnd, NULL))
4852 MSG amsg;
4853 /* Eat any mouse messages during popupmenu */
4854 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4855 PM_REMOVE));
4856 /* Get the menu selection, if any */
4857 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4859 retval = LOWORD (amsg.wParam);
4861 else
4863 retval = 0;
4866 else
4868 retval = -1;
4871 return retval;
4874 default:
4875 /* Check for messages registered at runtime. */
4876 if (msg == msh_mousewheel)
4878 wmsg.dwModifiers = w32_get_modifiers ();
4879 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4880 return 0;
4883 dflt:
4884 return DefWindowProc (hwnd, msg, wParam, lParam);
4888 /* The most common default return code for handled messages is 0. */
4889 return 0;
4892 void
4893 my_create_window (f)
4894 struct frame * f;
4896 MSG msg;
4898 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4899 abort ();
4900 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4903 /* Create and set up the w32 window for frame F. */
4905 static void
4906 w32_window (f, window_prompting, minibuffer_only)
4907 struct frame *f;
4908 long window_prompting;
4909 int minibuffer_only;
4911 BLOCK_INPUT;
4913 /* Use the resource name as the top-level window name
4914 for looking up resources. Make a non-Lisp copy
4915 for the window manager, so GC relocation won't bother it.
4917 Elsewhere we specify the window name for the window manager. */
4920 char *str = (char *) XSTRING (Vx_resource_name)->data;
4921 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4922 strcpy (f->namebuf, str);
4925 my_create_window (f);
4927 validate_x_resource_name ();
4929 /* x_set_name normally ignores requests to set the name if the
4930 requested name is the same as the current name. This is the one
4931 place where that assumption isn't correct; f->name is set, but
4932 the server hasn't been told. */
4934 Lisp_Object name;
4935 int explicit = f->explicit_name;
4937 f->explicit_name = 0;
4938 name = f->name;
4939 f->name = Qnil;
4940 x_set_name (f, name, explicit);
4943 UNBLOCK_INPUT;
4945 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4946 initialize_frame_menubar (f);
4948 if (FRAME_W32_WINDOW (f) == 0)
4949 error ("Unable to create window");
4952 /* Handle the icon stuff for this window. Perhaps later we might
4953 want an x_set_icon_position which can be called interactively as
4954 well. */
4956 static void
4957 x_icon (f, parms)
4958 struct frame *f;
4959 Lisp_Object parms;
4961 Lisp_Object icon_x, icon_y;
4963 /* Set the position of the icon. Note that Windows 95 groups all
4964 icons in the tray. */
4965 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4966 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4967 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4969 CHECK_NUMBER (icon_x, 0);
4970 CHECK_NUMBER (icon_y, 0);
4972 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4973 error ("Both left and top icon corners of icon must be specified");
4975 BLOCK_INPUT;
4977 if (! EQ (icon_x, Qunbound))
4978 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4980 #if 0 /* TODO */
4981 /* Start up iconic or window? */
4982 x_wm_set_window_state
4983 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4984 ? IconicState
4985 : NormalState));
4987 x_text_icon (f, (char *) XSTRING ((!NILP (f->icon_name)
4988 ? f->icon_name
4989 : f->name))->data);
4990 #endif
4992 UNBLOCK_INPUT;
4996 static void
4997 x_make_gc (f)
4998 struct frame *f;
5000 XGCValues gc_values;
5002 BLOCK_INPUT;
5004 /* Create the GC's of this frame.
5005 Note that many default values are used. */
5007 /* Normal video */
5008 gc_values.font = f->output_data.w32->font;
5010 /* Cursor has cursor-color background, background-color foreground. */
5011 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5012 gc_values.background = f->output_data.w32->cursor_pixel;
5013 f->output_data.w32->cursor_gc
5014 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5015 (GCFont | GCForeground | GCBackground),
5016 &gc_values);
5018 /* Reliefs. */
5019 f->output_data.w32->white_relief.gc = 0;
5020 f->output_data.w32->black_relief.gc = 0;
5022 UNBLOCK_INPUT;
5026 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5027 1, 1, 0,
5028 "Make a new window, which is called a \"frame\" in Emacs terms.\n\
5029 Returns an Emacs frame object.\n\
5030 ALIST is an alist of frame parameters.\n\
5031 If the parameters specify that the frame should not have a minibuffer,\n\
5032 and do not specify a specific minibuffer window to use,\n\
5033 then `default-minibuffer-frame' must be a frame whose minibuffer can\n\
5034 be shared by the new frame.\n\
5036 This function is an internal primitive--use `make-frame' instead.")
5037 (parms)
5038 Lisp_Object parms;
5040 struct frame *f;
5041 Lisp_Object frame, tem;
5042 Lisp_Object name;
5043 int minibuffer_only = 0;
5044 long window_prompting = 0;
5045 int width, height;
5046 int count = specpdl_ptr - specpdl;
5047 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5048 Lisp_Object display;
5049 struct w32_display_info *dpyinfo = NULL;
5050 Lisp_Object parent;
5051 struct kboard *kb;
5053 check_w32 ();
5055 /* Use this general default value to start with
5056 until we know if this frame has a specified name. */
5057 Vx_resource_name = Vinvocation_name;
5059 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5060 if (EQ (display, Qunbound))
5061 display = Qnil;
5062 dpyinfo = check_x_display_info (display);
5063 #ifdef MULTI_KBOARD
5064 kb = dpyinfo->kboard;
5065 #else
5066 kb = &the_only_kboard;
5067 #endif
5069 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5070 if (!STRINGP (name)
5071 && ! EQ (name, Qunbound)
5072 && ! NILP (name))
5073 error ("Invalid frame name--not a string or nil");
5075 if (STRINGP (name))
5076 Vx_resource_name = name;
5078 /* See if parent window is specified. */
5079 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5080 if (EQ (parent, Qunbound))
5081 parent = Qnil;
5082 if (! NILP (parent))
5083 CHECK_NUMBER (parent, 0);
5085 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5086 /* No need to protect DISPLAY because that's not used after passing
5087 it to make_frame_without_minibuffer. */
5088 frame = Qnil;
5089 GCPRO4 (parms, parent, name, frame);
5090 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5091 RES_TYPE_SYMBOL);
5092 if (EQ (tem, Qnone) || NILP (tem))
5093 f = make_frame_without_minibuffer (Qnil, kb, display);
5094 else if (EQ (tem, Qonly))
5096 f = make_minibuffer_frame ();
5097 minibuffer_only = 1;
5099 else if (WINDOWP (tem))
5100 f = make_frame_without_minibuffer (tem, kb, display);
5101 else
5102 f = make_frame (1);
5104 XSETFRAME (frame, f);
5106 /* Note that Windows does support scroll bars. */
5107 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5108 /* By default, make scrollbars the system standard width. */
5109 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5111 f->output_method = output_w32;
5112 f->output_data.w32 =
5113 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5114 bzero (f->output_data.w32, sizeof (struct w32_output));
5116 FRAME_FONTSET (f) = -1;
5118 f->icon_name
5119 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5120 if (! STRINGP (f->icon_name))
5121 f->icon_name = Qnil;
5123 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5124 #ifdef MULTI_KBOARD
5125 FRAME_KBOARD (f) = kb;
5126 #endif
5128 /* Specify the parent under which to make this window. */
5130 if (!NILP (parent))
5132 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5133 f->output_data.w32->explicit_parent = 1;
5135 else
5137 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5138 f->output_data.w32->explicit_parent = 0;
5141 /* Set the name; the functions to which we pass f expect the name to
5142 be set. */
5143 if (EQ (name, Qunbound) || NILP (name))
5145 f->name = build_string (dpyinfo->w32_id_name);
5146 f->explicit_name = 0;
5148 else
5150 f->name = name;
5151 f->explicit_name = 1;
5152 /* use the frame's title when getting resources for this frame. */
5153 specbind (Qx_resource_name, name);
5156 /* Extract the window parameters from the supplied values
5157 that are needed to determine window geometry. */
5159 Lisp_Object font;
5161 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5163 BLOCK_INPUT;
5164 /* First, try whatever font the caller has specified. */
5165 if (STRINGP (font))
5167 tem = Fquery_fontset (font, Qnil);
5168 if (STRINGP (tem))
5169 font = x_new_fontset (f, XSTRING (tem)->data);
5170 else
5171 font = x_new_font (f, XSTRING (font)->data);
5173 /* Try out a font which we hope has bold and italic variations. */
5174 if (!STRINGP (font))
5175 font = x_new_font (f, "-*-Courier New-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5176 if (! STRINGP (font))
5177 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5178 /* If those didn't work, look for something which will at least work. */
5179 if (! STRINGP (font))
5180 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5181 UNBLOCK_INPUT;
5182 if (! STRINGP (font))
5183 font = build_string ("Fixedsys");
5185 x_default_parameter (f, parms, Qfont, font,
5186 "font", "Font", RES_TYPE_STRING);
5189 x_default_parameter (f, parms, Qborder_width, make_number (2),
5190 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5191 /* This defaults to 2 in order to match xterm. We recognize either
5192 internalBorderWidth or internalBorder (which is what xterm calls
5193 it). */
5194 if (NILP (Fassq (Qinternal_border_width, parms)))
5196 Lisp_Object value;
5198 value = w32_get_arg (parms, Qinternal_border_width,
5199 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5200 if (! EQ (value, Qunbound))
5201 parms = Fcons (Fcons (Qinternal_border_width, value),
5202 parms);
5204 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5205 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5206 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5207 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5208 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5210 /* Also do the stuff which must be set before the window exists. */
5211 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5212 "foreground", "Foreground", RES_TYPE_STRING);
5213 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5214 "background", "Background", RES_TYPE_STRING);
5215 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5216 "pointerColor", "Foreground", RES_TYPE_STRING);
5217 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5218 "cursorColor", "Foreground", RES_TYPE_STRING);
5219 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5220 "borderColor", "BorderColor", RES_TYPE_STRING);
5221 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5222 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5223 x_default_parameter (f, parms, Qline_spacing, Qnil,
5224 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5227 /* Init faces before x_default_parameter is called for scroll-bar
5228 parameters because that function calls x_set_scroll_bar_width,
5229 which calls change_frame_size, which calls Fset_window_buffer,
5230 which runs hooks, which call Fvertical_motion. At the end, we
5231 end up in init_iterator with a null face cache, which should not
5232 happen. */
5233 init_frame_faces (f);
5235 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5236 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5237 x_default_parameter (f, parms, Qtool_bar_lines, make_number (0),
5238 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5239 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5240 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5241 x_default_parameter (f, parms, Qtitle, Qnil,
5242 "title", "Title", RES_TYPE_STRING);
5244 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5245 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5246 window_prompting = x_figure_window_size (f, parms);
5248 if (window_prompting & XNegative)
5250 if (window_prompting & YNegative)
5251 f->output_data.w32->win_gravity = SouthEastGravity;
5252 else
5253 f->output_data.w32->win_gravity = NorthEastGravity;
5255 else
5257 if (window_prompting & YNegative)
5258 f->output_data.w32->win_gravity = SouthWestGravity;
5259 else
5260 f->output_data.w32->win_gravity = NorthWestGravity;
5263 f->output_data.w32->size_hint_flags = window_prompting;
5265 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5266 f->no_split = minibuffer_only || EQ (tem, Qt);
5268 /* Create the window. Add the tool-bar height to the initial frame
5269 height so that the user gets a text display area of the size he
5270 specified with -g or via the registry. Later changes of the
5271 tool-bar height don't change the frame size. This is done so that
5272 users can create tall Emacs frames without having to guess how
5273 tall the tool-bar will get. */
5274 f->height += FRAME_TOOL_BAR_LINES (f);
5275 w32_window (f, window_prompting, minibuffer_only);
5276 x_icon (f, parms);
5278 x_make_gc (f);
5280 /* Now consider the frame official. */
5281 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5282 Vframe_list = Fcons (frame, Vframe_list);
5284 /* We need to do this after creating the window, so that the
5285 icon-creation functions can say whose icon they're describing. */
5286 x_default_parameter (f, parms, Qicon_type, Qnil,
5287 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5289 x_default_parameter (f, parms, Qauto_raise, Qnil,
5290 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5291 x_default_parameter (f, parms, Qauto_lower, Qnil,
5292 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5293 x_default_parameter (f, parms, Qcursor_type, Qbox,
5294 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5295 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5296 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5298 /* Dimensions, especially f->height, must be done via change_frame_size.
5299 Change will not be effected unless different from the current
5300 f->height. */
5301 width = f->width;
5302 height = f->height;
5303 f->height = 0;
5304 SET_FRAME_WIDTH (f, 0);
5305 change_frame_size (f, height, width, 1, 0, 0);
5307 /* Tell the server what size and position, etc, we want, and how
5308 badly we want them. This should be done after we have the menu
5309 bar so that its size can be taken into account. */
5310 BLOCK_INPUT;
5311 x_wm_set_size_hint (f, window_prompting, 0);
5312 UNBLOCK_INPUT;
5314 /* Make the window appear on the frame and enable display, unless
5315 the caller says not to. However, with explicit parent, Emacs
5316 cannot control visibility, so don't try. */
5317 if (! f->output_data.w32->explicit_parent)
5319 Lisp_Object visibility;
5321 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5322 if (EQ (visibility, Qunbound))
5323 visibility = Qt;
5325 if (EQ (visibility, Qicon))
5326 x_iconify_frame (f);
5327 else if (! NILP (visibility))
5328 x_make_frame_visible (f);
5329 else
5330 /* Must have been Qnil. */
5333 UNGCPRO;
5334 return unbind_to (count, frame);
5337 /* FRAME is used only to get a handle on the X display. We don't pass the
5338 display info directly because we're called from frame.c, which doesn't
5339 know about that structure. */
5340 Lisp_Object
5341 x_get_focus_frame (frame)
5342 struct frame *frame;
5344 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5345 Lisp_Object xfocus;
5346 if (! dpyinfo->w32_focus_frame)
5347 return Qnil;
5349 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5350 return xfocus;
5353 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5354 "Give FRAME input focus, raising to foreground if necessary.")
5355 (frame)
5356 Lisp_Object frame;
5358 x_focus_on_frame (check_x_frame (frame));
5359 return Qnil;
5363 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5364 int size, char* filename);
5366 struct font_info *
5367 w32_load_system_font (f,fontname,size)
5368 struct frame *f;
5369 char * fontname;
5370 int size;
5372 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5373 Lisp_Object font_names;
5375 /* Get a list of all the fonts that match this name. Once we
5376 have a list of matching fonts, we compare them against the fonts
5377 we already have loaded by comparing names. */
5378 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5380 if (!NILP (font_names))
5382 Lisp_Object tail;
5383 int i;
5385 /* First check if any are already loaded, as that is cheaper
5386 than loading another one. */
5387 for (i = 0; i < dpyinfo->n_fonts; i++)
5388 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5389 if (dpyinfo->font_table[i].name
5390 && (!strcmp (dpyinfo->font_table[i].name,
5391 XSTRING (XCAR (tail))->data)
5392 || !strcmp (dpyinfo->font_table[i].full_name,
5393 XSTRING (XCAR (tail))->data)))
5394 return (dpyinfo->font_table + i);
5396 fontname = (char *) XSTRING (XCAR (font_names))->data;
5398 else if (w32_strict_fontnames)
5400 /* If EnumFontFamiliesEx was available, we got a full list of
5401 fonts back so stop now to avoid the possibility of loading a
5402 random font. If we had to fall back to EnumFontFamilies, the
5403 list is incomplete, so continue whether the font we want was
5404 listed or not. */
5405 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5406 FARPROC enum_font_families_ex
5407 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5408 if (enum_font_families_ex)
5409 return NULL;
5412 /* Load the font and add it to the table. */
5414 char *full_name, *encoding;
5415 XFontStruct *font;
5416 struct font_info *fontp;
5417 LOGFONT lf;
5418 BOOL ok;
5419 int i;
5421 if (!fontname || !x_to_w32_font (fontname, &lf))
5422 return (NULL);
5424 if (!*lf.lfFaceName)
5425 /* If no name was specified for the font, we get a random font
5426 from CreateFontIndirect - this is not particularly
5427 desirable, especially since CreateFontIndirect does not
5428 fill out the missing name in lf, so we never know what we
5429 ended up with. */
5430 return NULL;
5432 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5433 bzero (font, sizeof (*font));
5435 /* Set bdf to NULL to indicate that this is a Windows font. */
5436 font->bdf = NULL;
5438 BLOCK_INPUT;
5440 font->hfont = CreateFontIndirect (&lf);
5442 if (font->hfont == NULL)
5444 ok = FALSE;
5446 else
5448 HDC hdc;
5449 HANDLE oldobj;
5451 hdc = GetDC (dpyinfo->root_window);
5452 oldobj = SelectObject (hdc, font->hfont);
5453 ok = GetTextMetrics (hdc, &font->tm);
5454 font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS;
5455 SelectObject (hdc, oldobj);
5456 ReleaseDC (dpyinfo->root_window, hdc);
5457 /* Fill out details in lf according to the font that was
5458 actually loaded. */
5459 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5460 lf.lfWidth = font->tm.tmAveCharWidth;
5461 lf.lfWeight = font->tm.tmWeight;
5462 lf.lfItalic = font->tm.tmItalic;
5463 lf.lfCharSet = font->tm.tmCharSet;
5464 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5465 ? VARIABLE_PITCH : FIXED_PITCH);
5466 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5467 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5469 w32_cache_char_metrics (font);
5472 UNBLOCK_INPUT;
5474 if (!ok)
5476 w32_unload_font (dpyinfo, font);
5477 return (NULL);
5480 /* Find a free slot in the font table. */
5481 for (i = 0; i < dpyinfo->n_fonts; ++i)
5482 if (dpyinfo->font_table[i].name == NULL)
5483 break;
5485 /* If no free slot found, maybe enlarge the font table. */
5486 if (i == dpyinfo->n_fonts
5487 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5489 int sz;
5490 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5491 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5492 dpyinfo->font_table
5493 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5496 fontp = dpyinfo->font_table + i;
5497 if (i == dpyinfo->n_fonts)
5498 ++dpyinfo->n_fonts;
5500 /* Now fill in the slots of *FONTP. */
5501 BLOCK_INPUT;
5502 fontp->font = font;
5503 fontp->font_idx = i;
5504 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5505 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5507 /* Work out the font's full name. */
5508 full_name = (char *)xmalloc (100);
5509 if (full_name && w32_to_x_font (&lf, full_name, 100))
5510 fontp->full_name = full_name;
5511 else
5513 /* If all else fails - just use the name we used to load it. */
5514 xfree (full_name);
5515 fontp->full_name = fontp->name;
5518 fontp->size = FONT_WIDTH (font);
5519 fontp->height = FONT_HEIGHT (font);
5521 /* The slot `encoding' specifies how to map a character
5522 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
5523 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
5524 (0:0x20..0x7F, 1:0xA0..0xFF,
5525 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
5526 2:0xA020..0xFF7F). For the moment, we don't know which charset
5527 uses this font. So, we set information in fontp->encoding[1]
5528 which is never used by any charset. If mapping can't be
5529 decided, set FONT_ENCODING_NOT_DECIDED. */
5531 /* SJIS fonts need to be set to type 4, all others seem to work as
5532 type FONT_ENCODING_NOT_DECIDED. */
5533 encoding = strrchr (fontp->name, '-');
5534 if (encoding && stricmp (encoding+1, "sjis") == 0)
5535 fontp->encoding[1] = 4;
5536 else
5537 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
5539 /* The following three values are set to 0 under W32, which is
5540 what they get set to if XGetFontProperty fails under X. */
5541 fontp->baseline_offset = 0;
5542 fontp->relative_compose = 0;
5543 fontp->default_ascent = 0;
5545 /* Set global flag fonts_changed_p to non-zero if the font loaded
5546 has a character with a smaller width than any other character
5547 before, or if the font loaded has a smalle>r height than any
5548 other font loaded before. If this happens, it will make a
5549 glyph matrix reallocation necessary. */
5550 fonts_changed_p = x_compute_min_glyph_bounds (f);
5551 UNBLOCK_INPUT;
5552 return fontp;
5556 /* Load font named FONTNAME of size SIZE for frame F, and return a
5557 pointer to the structure font_info while allocating it dynamically.
5558 If loading fails, return NULL. */
5559 struct font_info *
5560 w32_load_font (f,fontname,size)
5561 struct frame *f;
5562 char * fontname;
5563 int size;
5565 Lisp_Object bdf_fonts;
5566 struct font_info *retval = NULL;
5568 bdf_fonts = w32_list_bdf_fonts (build_string (fontname));
5570 while (!retval && CONSP (bdf_fonts))
5572 char *bdf_name, *bdf_file;
5573 Lisp_Object bdf_pair;
5575 bdf_name = XSTRING (XCAR (bdf_fonts))->data;
5576 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
5577 bdf_file = XSTRING (XCDR (bdf_pair))->data;
5579 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
5581 bdf_fonts = XCDR (bdf_fonts);
5584 if (retval)
5585 return retval;
5587 return w32_load_system_font(f, fontname, size);
5591 void
5592 w32_unload_font (dpyinfo, font)
5593 struct w32_display_info *dpyinfo;
5594 XFontStruct * font;
5596 if (font)
5598 if (font->per_char) xfree (font->per_char);
5599 if (font->bdf) w32_free_bdf_font (font->bdf);
5601 if (font->hfont) DeleteObject(font->hfont);
5602 xfree (font);
5606 /* The font conversion stuff between x and w32 */
5608 /* X font string is as follows (from faces.el)
5609 * (let ((- "[-?]")
5610 * (foundry "[^-]+")
5611 * (family "[^-]+")
5612 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
5613 * (weight\? "\\([^-]*\\)") ; 1
5614 * (slant "\\([ior]\\)") ; 2
5615 * (slant\? "\\([^-]?\\)") ; 2
5616 * (swidth "\\([^-]*\\)") ; 3
5617 * (adstyle "[^-]*") ; 4
5618 * (pixelsize "[0-9]+")
5619 * (pointsize "[0-9][0-9]+")
5620 * (resx "[0-9][0-9]+")
5621 * (resy "[0-9][0-9]+")
5622 * (spacing "[cmp?*]")
5623 * (avgwidth "[0-9]+")
5624 * (registry "[^-]+")
5625 * (encoding "[^-]+")
5629 LONG
5630 x_to_w32_weight (lpw)
5631 char * lpw;
5633 if (!lpw) return (FW_DONTCARE);
5635 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
5636 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
5637 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
5638 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
5639 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5640 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
5641 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
5642 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
5643 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
5644 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
5645 else
5646 return FW_DONTCARE;
5650 char *
5651 w32_to_x_weight (fnweight)
5652 int fnweight;
5654 if (fnweight >= FW_HEAVY) return "heavy";
5655 if (fnweight >= FW_EXTRABOLD) return "extrabold";
5656 if (fnweight >= FW_BOLD) return "bold";
5657 if (fnweight >= FW_SEMIBOLD) return "demibold";
5658 if (fnweight >= FW_MEDIUM) return "medium";
5659 if (fnweight >= FW_NORMAL) return "normal";
5660 if (fnweight >= FW_LIGHT) return "light";
5661 if (fnweight >= FW_EXTRALIGHT) return "extralight";
5662 if (fnweight >= FW_THIN) return "thin";
5663 else
5664 return "*";
5667 LONG
5668 x_to_w32_charset (lpcs)
5669 char * lpcs;
5671 Lisp_Object rest;
5673 /* Look through w32-charset-info-alist for the character set.
5674 Format of each entry is
5675 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5677 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5679 Lisp_Object this_entry = XCAR (rest);
5680 char * x_charset = XSTRING (XCAR (this_entry))->data;
5682 if (strnicmp (lpcs, x_charset, strlen(x_charset)) == 0)
5684 Lisp_Object w32_charset = XCAR (XCDR (this_entry));
5685 // Translate Lisp symbol to number.
5686 if (w32_charset == Qw32_charset_ansi)
5687 return ANSI_CHARSET;
5688 if (w32_charset == Qw32_charset_symbol)
5689 return SYMBOL_CHARSET;
5690 if (w32_charset == Qw32_charset_shiftjis)
5691 return SHIFTJIS_CHARSET;
5692 if (w32_charset == Qw32_charset_hangul)
5693 return HANGEUL_CHARSET;
5694 if (w32_charset == Qw32_charset_chinesebig5)
5695 return CHINESEBIG5_CHARSET;
5696 if (w32_charset == Qw32_charset_gb2312)
5697 return GB2312_CHARSET;
5698 if (w32_charset == Qw32_charset_oem)
5699 return OEM_CHARSET;
5700 #ifdef JOHAB_CHARSET
5701 if (w32_charset == Qw32_charset_johab)
5702 return JOHAB_CHARSET;
5703 if (w32_charset == Qw32_charset_easteurope)
5704 return EASTEUROPE_CHARSET;
5705 if (w32_charset == Qw32_charset_turkish)
5706 return TURKISH_CHARSET;
5707 if (w32_charset == Qw32_charset_baltic)
5708 return BALTIC_CHARSET;
5709 if (w32_charset == Qw32_charset_russian)
5710 return RUSSIAN_CHARSET;
5711 if (w32_charset == Qw32_charset_arabic)
5712 return ARABIC_CHARSET;
5713 if (w32_charset == Qw32_charset_greek)
5714 return GREEK_CHARSET;
5715 if (w32_charset == Qw32_charset_hebrew)
5716 return HEBREW_CHARSET;
5717 if (w32_charset == Qw32_charset_thai)
5718 return THAI_CHARSET;
5719 if (w32_charset == Qw32_charset_mac)
5720 return MAC_CHARSET;
5721 #endif /* JOHAB_CHARSET */
5722 #ifdef UNICODE_CHARSET
5723 if (w32_charset == Qw32_charset_unicode)
5724 return UNICODE_CHARSET;
5725 #endif
5729 return DEFAULT_CHARSET;
5733 char *
5734 w32_to_x_charset (fncharset)
5735 int fncharset;
5737 static char buf[16];
5739 /* NTEMACS_TODO: use w32-charset-info-alist. Multiple matches
5740 are possible, so this will require more than just a rewrite of
5741 this function. w32_to_x_font is the only user of this function,
5742 and that will require rewriting too, and its users. */
5743 switch (fncharset)
5745 /* ansi is considered iso8859-1, as most modern ansi fonts are. */
5746 case ANSI_CHARSET: return "iso8859-1";
5747 case DEFAULT_CHARSET: return "ascii-*";
5748 case SYMBOL_CHARSET: return "ms-symbol";
5749 case SHIFTJIS_CHARSET: return "jisx0208-sjis";
5750 case HANGEUL_CHARSET: return "ksc5601.1987-*";
5751 case GB2312_CHARSET: return "gb2312-*";
5752 case CHINESEBIG5_CHARSET: return "big5-*";
5753 case OEM_CHARSET: return "ms-oem";
5755 /* More recent versions of Windows (95 and NT4.0) define more
5756 character sets. */
5757 #ifdef EASTEUROPE_CHARSET
5758 case EASTEUROPE_CHARSET: return "iso8859-2";
5759 case TURKISH_CHARSET: return "iso8859-9";
5760 case BALTIC_CHARSET: return "iso8859-4";
5762 /* W95 with international support but not IE4 often has the
5763 KOI8-R codepage but not ISO8859-5. */
5764 case RUSSIAN_CHARSET:
5765 if (!IsValidCodePage(28595) && IsValidCodePage(20886))
5766 return "koi8-r";
5767 else
5768 return "iso8859-5";
5769 case ARABIC_CHARSET: return "iso8859-6";
5770 case GREEK_CHARSET: return "iso8859-7";
5771 case HEBREW_CHARSET: return "iso8859-8";
5772 case VIETNAMESE_CHARSET: return "viscii1.1-*";
5773 case THAI_CHARSET: return "tis620-*";
5774 case MAC_CHARSET: return "mac-*";
5775 case JOHAB_CHARSET: return "ksc5601.1992-*";
5777 #endif
5779 #ifdef UNICODE_CHARSET
5780 case UNICODE_CHARSET: return "iso10646-unicode";
5781 #endif
5783 /* Encode numerical value of unknown charset. */
5784 sprintf (buf, "*-#%u", fncharset);
5785 return buf;
5789 /* Get the Windows codepage corresponding to the specified font. The
5790 charset info in the font name is used to look up
5791 w32-charset-to-codepage-alist. */
5792 int
5793 w32_codepage_for_font (char *fontname)
5795 Lisp_Object codepage;
5796 char charset_str[20], *charset, *end;
5798 /* Extract charset part of font string. */
5799 if (sscanf (fontname,
5800 "-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%19s",
5801 charset_str) == EOF)
5802 return CP_DEFAULT;
5804 /* Remove leading "*-". */
5805 if (strncmp ("*-", charset_str, 2) == 0)
5806 charset = charset_str + 2;
5807 else
5808 charset = charset_str;
5810 /* Stop match at wildcard (including preceding '-'). */
5811 if (end = strchr (charset, '*'))
5813 if (end > charset && *(end-1) == '-')
5814 end--;
5815 *end = '\0';
5818 codepage = Fcdr (Fcdr (Fassoc (build_string(charset),
5819 Vw32_charset_info_alist)));
5820 if (INTEGERP (codepage))
5821 return XINT (codepage);
5822 else
5823 return CP_DEFAULT;
5827 BOOL
5828 w32_to_x_font (lplogfont, lpxstr, len)
5829 LOGFONT * lplogfont;
5830 char * lpxstr;
5831 int len;
5833 char* fonttype;
5834 char *fontname;
5835 char height_pixels[8];
5836 char height_dpi[8];
5837 char width_pixels[8];
5838 char *fontname_dash;
5839 int display_resy = one_w32_display_info.resy;
5840 int display_resx = one_w32_display_info.resx;
5841 int bufsz;
5842 struct coding_system coding;
5844 if (!lpxstr) abort ();
5846 if (!lplogfont)
5847 return FALSE;
5849 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5850 fonttype = "raster";
5851 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5852 fonttype = "outline";
5853 else
5854 fonttype = "unknown";
5856 setup_coding_system (Fcheck_coding_system (Vw32_system_coding_system),
5857 &coding);
5858 coding.src_multibyte = 0;
5859 coding.dst_multibyte = 1;
5860 coding.mode |= CODING_MODE_LAST_BLOCK;
5861 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
5863 fontname = alloca(sizeof(*fontname) * bufsz);
5864 decode_coding (&coding, lplogfont->lfFaceName, fontname,
5865 strlen(lplogfont->lfFaceName), bufsz - 1);
5866 *(fontname + coding.produced) = '\0';
5868 /* Replace dashes with underscores so the dashes are not
5869 misinterpreted. */
5870 fontname_dash = fontname;
5871 while (fontname_dash = strchr (fontname_dash, '-'))
5872 *fontname_dash = '_';
5874 if (lplogfont->lfHeight)
5876 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
5877 sprintf (height_dpi, "%u",
5878 abs (lplogfont->lfHeight) * 720 / display_resy);
5880 else
5882 strcpy (height_pixels, "*");
5883 strcpy (height_dpi, "*");
5885 if (lplogfont->lfWidth)
5886 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5887 else
5888 strcpy (width_pixels, "*");
5890 _snprintf (lpxstr, len - 1,
5891 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5892 fonttype, /* foundry */
5893 fontname, /* family */
5894 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5895 lplogfont->lfItalic?'i':'r', /* slant */
5896 /* setwidth name */
5897 /* add style name */
5898 height_pixels, /* pixel size */
5899 height_dpi, /* point size */
5900 display_resx, /* resx */
5901 display_resy, /* resy */
5902 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5903 ? 'p' : 'c', /* spacing */
5904 width_pixels, /* avg width */
5905 w32_to_x_charset (lplogfont->lfCharSet) /* charset registry
5906 and encoding*/
5909 lpxstr[len - 1] = 0; /* just to be sure */
5910 return (TRUE);
5913 BOOL
5914 x_to_w32_font (lpxstr, lplogfont)
5915 char * lpxstr;
5916 LOGFONT * lplogfont;
5918 struct coding_system coding;
5920 if (!lplogfont) return (FALSE);
5922 memset (lplogfont, 0, sizeof (*lplogfont));
5924 /* Set default value for each field. */
5925 #if 1
5926 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5927 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5928 lplogfont->lfQuality = DEFAULT_QUALITY;
5929 #else
5930 /* go for maximum quality */
5931 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5932 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5933 lplogfont->lfQuality = PROOF_QUALITY;
5934 #endif
5936 lplogfont->lfCharSet = DEFAULT_CHARSET;
5937 lplogfont->lfWeight = FW_DONTCARE;
5938 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5940 if (!lpxstr)
5941 return FALSE;
5943 /* Provide a simple escape mechanism for specifying Windows font names
5944 * directly -- if font spec does not beginning with '-', assume this
5945 * format:
5946 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5949 if (*lpxstr == '-')
5951 int fields, tem;
5952 char name[50], weight[20], slant, pitch, pixels[10], height[10],
5953 width[10], resy[10], remainder[20];
5954 char * encoding;
5955 int dpi = one_w32_display_info.height_in;
5957 fields = sscanf (lpxstr,
5958 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%19s",
5959 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
5960 if (fields == EOF) return (FALSE);
5962 /* If wildcards cover more than one field, we don't know which
5963 field is which, so don't fill any in. */
5965 if (fields < 9)
5966 fields = 0;
5968 if (fields > 0 && name[0] != '*')
5970 int bufsize;
5971 unsigned char *buf;
5973 setup_coding_system
5974 (Fcheck_coding_system (Vw32_system_coding_system), &coding);
5975 coding.src_multibyte = 1;
5976 coding.dst_multibyte = 1;
5977 bufsize = encoding_buffer_size (&coding, strlen (name));
5978 buf = (unsigned char *) alloca (bufsize);
5979 coding.mode |= CODING_MODE_LAST_BLOCK;
5980 encode_coding (&coding, name, buf, strlen (name), bufsize);
5981 if (coding.produced >= LF_FACESIZE)
5982 coding.produced = LF_FACESIZE - 1;
5983 buf[coding.produced] = 0;
5984 strcpy (lplogfont->lfFaceName, buf);
5986 else
5988 lplogfont->lfFaceName[0] = '\0';
5991 fields--;
5993 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5995 fields--;
5997 if (!NILP (Vw32_enable_synthesized_fonts))
5998 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6000 fields--;
6002 if (fields > 0 && pixels[0] != '*')
6003 lplogfont->lfHeight = atoi (pixels);
6005 fields--;
6006 fields--;
6007 if (fields > 0 && resy[0] != '*')
6009 tem = atoi (resy);
6010 if (tem > 0) dpi = tem;
6013 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6014 lplogfont->lfHeight = atoi (height) * dpi / 720;
6016 if (fields > 0)
6017 lplogfont->lfPitchAndFamily =
6018 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6020 fields--;
6022 if (fields > 0 && width[0] != '*')
6023 lplogfont->lfWidth = atoi (width) / 10;
6025 fields--;
6027 /* Strip the trailing '-' if present. (it shouldn't be, as it
6028 fails the test against xlfd-tight-regexp in fontset.el). */
6030 int len = strlen (remainder);
6031 if (len > 0 && remainder[len-1] == '-')
6032 remainder[len-1] = 0;
6034 encoding = remainder;
6035 if (strncmp (encoding, "*-", 2) == 0)
6036 encoding += 2;
6037 lplogfont->lfCharSet = x_to_w32_charset (fields > 0 ? encoding : "");
6039 else
6041 int fields;
6042 char name[100], height[10], width[10], weight[20];
6044 fields = sscanf (lpxstr,
6045 "%99[^:]:%9[^:]:%9[^:]:%19s",
6046 name, height, width, weight);
6048 if (fields == EOF) return (FALSE);
6050 if (fields > 0)
6052 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6053 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6055 else
6057 lplogfont->lfFaceName[0] = 0;
6060 fields--;
6062 if (fields > 0)
6063 lplogfont->lfHeight = atoi (height);
6065 fields--;
6067 if (fields > 0)
6068 lplogfont->lfWidth = atoi (width);
6070 fields--;
6072 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6075 /* This makes TrueType fonts work better. */
6076 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6078 return (TRUE);
6081 /* Strip the pixel height and point height from the given xlfd, and
6082 return the pixel height. If no pixel height is specified, calculate
6083 one from the point height, or if that isn't defined either, return
6084 0 (which usually signifies a scalable font).
6086 int xlfd_strip_height (char *fontname)
6088 int pixel_height, point_height, dpi, field_number;
6089 char *read_from, *write_to;
6091 xassert (fontname);
6093 pixel_height = field_number = 0;
6094 write_to = NULL;
6096 /* Look for height fields. */
6097 for (read_from = fontname; *read_from; read_from++)
6099 if (*read_from == '-')
6101 field_number++;
6102 if (field_number == 7) /* Pixel height. */
6104 read_from++;
6105 write_to = read_from;
6107 /* Find end of field. */
6108 for (;*read_from && *read_from != '-'; read_from++)
6111 /* Split the fontname at end of field. */
6112 if (*read_from)
6114 *read_from = '\0';
6115 read_from++;
6117 pixel_height = atoi (write_to);
6118 /* Blank out field. */
6119 if (read_from > write_to)
6121 *write_to = '-';
6122 write_to++;
6124 /* If the pixel height field is at the end (partial xfld),
6125 return now. */
6126 else
6127 return pixel_height;
6129 /* If we got a pixel height, the point height can be
6130 ignored. Just blank it out and break now. */
6131 if (pixel_height)
6133 /* Find end of point size field. */
6134 for (; *read_from && *read_from != '-'; read_from++)
6137 if (*read_from)
6138 read_from++;
6140 /* Blank out the point size field. */
6141 if (read_from > write_to)
6143 *write_to = '-';
6144 write_to++;
6146 else
6147 return pixel_height;
6149 break;
6151 /* If the point height is already blank, break now. */
6152 if (*read_from == '-')
6154 read_from++;
6155 break;
6158 else if (field_number == 8)
6160 /* If we didn't get a pixel height, try to get the point
6161 height and convert that. */
6162 int point_size;
6163 char *point_size_start = read_from++;
6165 /* Find end of field. */
6166 for (; *read_from && *read_from != '-'; read_from++)
6169 if (*read_from)
6171 *read_from = '\0';
6172 read_from++;
6175 point_size = atoi (point_size_start);
6177 /* Convert to pixel height. */
6178 pixel_height = point_size
6179 * one_w32_display_info.height_in / 720;
6181 /* Blank out this field and break. */
6182 *write_to = '-';
6183 write_to++;
6184 break;
6189 /* Shift the rest of the font spec into place. */
6190 if (write_to && read_from > write_to)
6192 for (; *read_from; read_from++, write_to++)
6193 *write_to = *read_from;
6194 *write_to = '\0';
6197 return pixel_height;
6200 /* Assume parameter 1 is fully qualified, no wildcards. */
6201 BOOL
6202 w32_font_match (fontname, pattern)
6203 char * fontname;
6204 char * pattern;
6206 char *regex = alloca (strlen (pattern) * 2);
6207 char *font_name_copy = alloca (strlen (fontname) + 1);
6208 char *ptr;
6210 /* Copy fontname so we can modify it during comparison. */
6211 strcpy (font_name_copy, fontname);
6213 ptr = regex;
6214 *ptr++ = '^';
6216 /* Turn pattern into a regexp and do a regexp match. */
6217 for (; *pattern; pattern++)
6219 if (*pattern == '?')
6220 *ptr++ = '.';
6221 else if (*pattern == '*')
6223 *ptr++ = '.';
6224 *ptr++ = '*';
6226 else
6227 *ptr++ = *pattern;
6229 *ptr = '$';
6230 *(ptr + 1) = '\0';
6232 /* Strip out font heights and compare them seperately, since
6233 rounding error can cause mismatches. This also allows a
6234 comparison between a font that declares only a pixel height and a
6235 pattern that declares the point height.
6238 int font_height, pattern_height;
6240 font_height = xlfd_strip_height (font_name_copy);
6241 pattern_height = xlfd_strip_height (regex);
6243 /* Compare now, and don't bother doing expensive regexp matching
6244 if the heights differ. */
6245 if (font_height && pattern_height && (font_height != pattern_height))
6246 return FALSE;
6249 return (fast_c_string_match_ignore_case (build_string (regex),
6250 font_name_copy) >= 0);
6253 /* Callback functions, and a structure holding info they need, for
6254 listing system fonts on W32. We need one set of functions to do the
6255 job properly, but these don't work on NT 3.51 and earlier, so we
6256 have a second set which don't handle character sets properly to
6257 fall back on.
6259 In both cases, there are two passes made. The first pass gets one
6260 font from each family, the second pass lists all the fonts from
6261 each family. */
6263 typedef struct enumfont_t
6265 HDC hdc;
6266 int numFonts;
6267 LOGFONT logfont;
6268 XFontStruct *size_ref;
6269 Lisp_Object *pattern;
6270 Lisp_Object *tail;
6271 } enumfont_t;
6273 int CALLBACK
6274 enum_font_cb2 (lplf, lptm, FontType, lpef)
6275 ENUMLOGFONT * lplf;
6276 NEWTEXTMETRIC * lptm;
6277 int FontType;
6278 enumfont_t * lpef;
6280 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
6281 return (1);
6283 /* Check that the character set matches if it was specified */
6284 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
6285 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
6286 return (1);
6289 char buf[100];
6290 Lisp_Object width = Qnil;
6292 /* Truetype fonts do not report their true metrics until loaded */
6293 if (FontType != RASTER_FONTTYPE)
6295 if (!NILP (*(lpef->pattern)))
6297 /* Scalable fonts are as big as you want them to be. */
6298 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
6299 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
6300 width = make_number (lpef->logfont.lfWidth);
6302 else
6304 lplf->elfLogFont.lfHeight = 0;
6305 lplf->elfLogFont.lfWidth = 0;
6309 /* Make sure the height used here is the same as everywhere
6310 else (ie character height, not cell height). */
6311 if (lplf->elfLogFont.lfHeight > 0)
6313 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
6314 if (FontType == RASTER_FONTTYPE)
6315 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
6316 else
6317 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
6320 if (!w32_to_x_font (&(lplf->elfLogFont), buf, 100))
6321 return (0);
6323 if (NILP (*(lpef->pattern))
6324 || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
6326 *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
6327 lpef->tail = &(XCDR (*lpef->tail));
6328 lpef->numFonts++;
6332 return (1);
6335 int CALLBACK
6336 enum_font_cb1 (lplf, lptm, FontType, lpef)
6337 ENUMLOGFONT * lplf;
6338 NEWTEXTMETRIC * lptm;
6339 int FontType;
6340 enumfont_t * lpef;
6342 return EnumFontFamilies (lpef->hdc,
6343 lplf->elfLogFont.lfFaceName,
6344 (FONTENUMPROC) enum_font_cb2,
6345 (LPARAM) lpef);
6349 int CALLBACK
6350 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6351 ENUMLOGFONTEX * lplf;
6352 NEWTEXTMETRICEX * lptm;
6353 int font_type;
6354 enumfont_t * lpef;
6356 /* We are not interested in the extra info we get back from the 'Ex
6357 version - only the fact that we get character set variations
6358 enumerated seperately. */
6359 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6360 font_type, lpef);
6363 int CALLBACK
6364 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6365 ENUMLOGFONTEX * lplf;
6366 NEWTEXTMETRICEX * lptm;
6367 int font_type;
6368 enumfont_t * lpef;
6370 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6371 FARPROC enum_font_families_ex
6372 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6373 /* We don't really expect EnumFontFamiliesEx to disappear once we
6374 get here, so don't bother handling it gracefully. */
6375 if (enum_font_families_ex == NULL)
6376 error ("gdi32.dll has disappeared!");
6377 return enum_font_families_ex (lpef->hdc,
6378 &lplf->elfLogFont,
6379 (FONTENUMPROC) enum_fontex_cb2,
6380 (LPARAM) lpef, 0);
6383 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6384 and xterm.c in Emacs 20.3) */
6386 Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6388 char *fontname, *ptnstr;
6389 Lisp_Object list, tem, newlist = Qnil;
6390 int n_fonts = 0;
6392 list = Vw32_bdf_filename_alist;
6393 ptnstr = XSTRING (pattern)->data;
6395 for ( ; CONSP (list); list = XCDR (list))
6397 tem = XCAR (list);
6398 if (CONSP (tem))
6399 fontname = XSTRING (XCAR (tem))->data;
6400 else if (STRINGP (tem))
6401 fontname = XSTRING (tem)->data;
6402 else
6403 continue;
6405 if (w32_font_match (fontname, ptnstr))
6407 newlist = Fcons (XCAR (tem), newlist);
6408 n_fonts++;
6409 if (n_fonts >= max_names)
6410 break;
6414 return newlist;
6417 Lisp_Object w32_list_synthesized_fonts (FRAME_PTR f, Lisp_Object pattern,
6418 int size, int max_names);
6420 /* Return a list of names of available fonts matching PATTERN on frame
6421 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6422 to be listed. Frame F NULL means we have not yet created any
6423 frame, which means we can't get proper size info, as we don't have
6424 a device context to use for GetTextMetrics.
6425 MAXNAMES sets a limit on how many fonts to match. */
6427 Lisp_Object
6428 w32_list_fonts (FRAME_PTR f, Lisp_Object pattern, int size, int maxnames )
6430 Lisp_Object patterns, key = Qnil, tem, tpat;
6431 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6432 struct w32_display_info *dpyinfo = &one_w32_display_info;
6433 int n_fonts = 0;
6435 patterns = Fassoc (pattern, Valternate_fontname_alist);
6436 if (NILP (patterns))
6437 patterns = Fcons (pattern, Qnil);
6439 for (; CONSP (patterns); patterns = XCDR (patterns))
6441 enumfont_t ef;
6443 tpat = XCAR (patterns);
6445 /* See if we cached the result for this particular query.
6446 The cache is an alist of the form:
6447 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6449 if (tem = XCDR (dpyinfo->name_list_element),
6450 !NILP (list = Fassoc (tpat, tem)))
6452 list = Fcdr_safe (list);
6453 /* We have a cached list. Don't have to get the list again. */
6454 goto label_cached;
6457 BLOCK_INPUT;
6458 /* At first, put PATTERN in the cache. */
6459 list = Qnil;
6460 ef.pattern = &tpat;
6461 ef.tail = &list;
6462 ef.numFonts = 0;
6464 /* Use EnumFontFamiliesEx where it is available, as it knows
6465 about character sets. Fall back to EnumFontFamilies for
6466 older versions of NT that don't support the 'Ex function. */
6467 x_to_w32_font (STRINGP (tpat) ? XSTRING (tpat)->data :
6468 NULL, &ef.logfont);
6470 LOGFONT font_match_pattern;
6471 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6472 FARPROC enum_font_families_ex
6473 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6475 /* We do our own pattern matching so we can handle wildcards. */
6476 font_match_pattern.lfFaceName[0] = 0;
6477 font_match_pattern.lfPitchAndFamily = 0;
6478 /* We can use the charset, because if it is a wildcard it will
6479 be DEFAULT_CHARSET anyway. */
6480 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6482 ef.hdc = GetDC (dpyinfo->root_window);
6484 if (enum_font_families_ex)
6485 enum_font_families_ex (ef.hdc,
6486 &font_match_pattern,
6487 (FONTENUMPROC) enum_fontex_cb1,
6488 (LPARAM) &ef, 0);
6489 else
6490 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6491 (LPARAM)&ef);
6493 ReleaseDC (dpyinfo->root_window, ef.hdc);
6496 UNBLOCK_INPUT;
6498 /* Make a list of the fonts we got back.
6499 Store that in the font cache for the display. */
6500 XCDR (dpyinfo->name_list_element)
6501 = Fcons (Fcons (tpat, list),
6502 XCDR (dpyinfo->name_list_element));
6504 label_cached:
6505 if (NILP (list)) continue; /* Try the remaining alternatives. */
6507 newlist = second_best = Qnil;
6509 /* Make a list of the fonts that have the right width. */
6510 for (; CONSP (list); list = XCDR (list))
6512 int found_size;
6513 tem = XCAR (list);
6515 if (!CONSP (tem))
6516 continue;
6517 if (NILP (XCAR (tem)))
6518 continue;
6519 if (!size)
6521 newlist = Fcons (XCAR (tem), newlist);
6522 n_fonts++;
6523 if (n_fonts >= maxnames)
6524 break;
6525 else
6526 continue;
6528 if (!INTEGERP (XCDR (tem)))
6530 /* Since we don't yet know the size of the font, we must
6531 load it and try GetTextMetrics. */
6532 W32FontStruct thisinfo;
6533 LOGFONT lf;
6534 HDC hdc;
6535 HANDLE oldobj;
6537 if (!x_to_w32_font (XSTRING (XCAR (tem))->data, &lf))
6538 continue;
6540 BLOCK_INPUT;
6541 thisinfo.bdf = NULL;
6542 thisinfo.hfont = CreateFontIndirect (&lf);
6543 if (thisinfo.hfont == NULL)
6544 continue;
6546 hdc = GetDC (dpyinfo->root_window);
6547 oldobj = SelectObject (hdc, thisinfo.hfont);
6548 if (GetTextMetrics (hdc, &thisinfo.tm))
6549 XCDR (tem) = make_number (FONT_WIDTH (&thisinfo));
6550 else
6551 XCDR (tem) = make_number (0);
6552 SelectObject (hdc, oldobj);
6553 ReleaseDC (dpyinfo->root_window, hdc);
6554 DeleteObject(thisinfo.hfont);
6555 UNBLOCK_INPUT;
6557 found_size = XINT (XCDR (tem));
6558 if (found_size == size)
6560 newlist = Fcons (XCAR (tem), newlist);
6561 n_fonts++;
6562 if (n_fonts >= maxnames)
6563 break;
6565 /* keep track of the closest matching size in case
6566 no exact match is found. */
6567 else if (found_size > 0)
6569 if (NILP (second_best))
6570 second_best = tem;
6572 else if (found_size < size)
6574 if (XINT (XCDR (second_best)) > size
6575 || XINT (XCDR (second_best)) < found_size)
6576 second_best = tem;
6578 else
6580 if (XINT (XCDR (second_best)) > size
6581 && XINT (XCDR (second_best)) >
6582 found_size)
6583 second_best = tem;
6588 if (!NILP (newlist))
6589 break;
6590 else if (!NILP (second_best))
6592 newlist = Fcons (XCAR (second_best), Qnil);
6593 break;
6597 /* Include any bdf fonts. */
6598 if (n_fonts < maxnames)
6600 Lisp_Object combined[2];
6601 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6602 combined[1] = newlist;
6603 newlist = Fnconc(2, combined);
6606 /* If we can't find a font that matches, check if Windows would be
6607 able to synthesize it from a different style. */
6608 if (NILP (newlist) && !NILP (Vw32_enable_synthesized_fonts))
6609 newlist = w32_list_synthesized_fonts (f, pattern, size, maxnames);
6611 return newlist;
6614 Lisp_Object
6615 w32_list_synthesized_fonts (f, pattern, size, max_names)
6616 FRAME_PTR f;
6617 Lisp_Object pattern;
6618 int size;
6619 int max_names;
6621 int fields;
6622 char *full_pattn, *new_pattn, foundary[50], family[50], *pattn_part2;
6623 char style[20], slant;
6624 Lisp_Object matches, match, tem, synthed_matches = Qnil;
6626 full_pattn = XSTRING (pattern)->data;
6628 pattn_part2 = alloca (XSTRING (pattern)->size);
6629 /* Allow some space for wildcard expansion. */
6630 new_pattn = alloca (XSTRING (pattern)->size + 100);
6632 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%19[^-]-%c-%s",
6633 foundary, family, style, &slant, pattn_part2);
6634 if (fields == EOF || fields < 5)
6635 return Qnil;
6637 /* If the style and slant are wildcards already there is no point
6638 checking again (and we don't want to keep recursing). */
6639 if (*style == '*' && slant == '*')
6640 return Qnil;
6642 sprintf (new_pattn, "-%s-%s-*-*-%s", foundary, family, pattn_part2);
6644 matches = w32_list_fonts (f, build_string (new_pattn), size, max_names);
6646 for ( ; CONSP (matches); matches = XCDR (matches))
6648 tem = XCAR (matches);
6649 if (!STRINGP (tem))
6650 continue;
6652 full_pattn = XSTRING (tem)->data;
6653 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%*[^-]-%*c-%s",
6654 foundary, family, pattn_part2);
6655 if (fields == EOF || fields < 3)
6656 continue;
6658 sprintf (new_pattn, "-%s-%s-%s-%c-%s", foundary, family, style,
6659 slant, pattn_part2);
6661 synthed_matches = Fcons (build_string (new_pattn),
6662 synthed_matches);
6665 return synthed_matches;
6669 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6670 struct font_info *
6671 w32_get_font_info (f, font_idx)
6672 FRAME_PTR f;
6673 int font_idx;
6675 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6679 struct font_info*
6680 w32_query_font (struct frame *f, char *fontname)
6682 int i;
6683 struct font_info *pfi;
6685 pfi = FRAME_W32_FONT_TABLE (f);
6687 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6689 if (strcmp(pfi->name, fontname) == 0) return pfi;
6692 return NULL;
6695 /* Find a CCL program for a font specified by FONTP, and set the member
6696 `encoder' of the structure. */
6698 void
6699 w32_find_ccl_program (fontp)
6700 struct font_info *fontp;
6702 Lisp_Object list, elt;
6704 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6706 elt = XCAR (list);
6707 if (CONSP (elt)
6708 && STRINGP (XCAR (elt))
6709 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6710 >= 0))
6711 break;
6713 if (! NILP (list))
6715 struct ccl_program *ccl
6716 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6718 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6719 xfree (ccl);
6720 else
6721 fontp->font_encoder = ccl;
6726 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6727 1, 1, 0,
6728 "Return a list of BDF fonts in DIR, suitable for appending to\n\
6729 w32-bdf-filename-alist. Fonts which do not contain an xfld description\n\
6730 will not be included in the list. DIR may be a list of directories.")
6731 (directory)
6732 Lisp_Object directory;
6734 Lisp_Object list = Qnil;
6735 struct gcpro gcpro1, gcpro2;
6737 if (!CONSP (directory))
6738 return w32_find_bdf_fonts_in_dir (directory);
6740 for ( ; CONSP (directory); directory = XCDR (directory))
6742 Lisp_Object pair[2];
6743 pair[0] = list;
6744 pair[1] = Qnil;
6745 GCPRO2 (directory, list);
6746 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
6747 list = Fnconc( 2, pair );
6748 UNGCPRO;
6750 return list;
6753 /* Find BDF files in a specified directory. (use GCPRO when calling,
6754 as this calls lisp to get a directory listing). */
6755 Lisp_Object w32_find_bdf_fonts_in_dir( Lisp_Object directory )
6757 Lisp_Object filelist, list = Qnil;
6758 char fontname[100];
6760 if (!STRINGP(directory))
6761 return Qnil;
6763 filelist = Fdirectory_files (directory, Qt,
6764 build_string (".*\\.[bB][dD][fF]"), Qt);
6766 for ( ; CONSP(filelist); filelist = XCDR (filelist))
6768 Lisp_Object filename = XCAR (filelist);
6769 if (w32_BDF_to_x_font (XSTRING (filename)->data, fontname, 100))
6770 store_in_alist (&list, build_string (fontname), filename);
6772 return list;
6776 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6777 "Internal function called by `color-defined-p', which see.")
6778 (color, frame)
6779 Lisp_Object color, frame;
6781 XColor foo;
6782 FRAME_PTR f = check_x_frame (frame);
6784 CHECK_STRING (color, 1);
6786 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
6787 return Qt;
6788 else
6789 return Qnil;
6792 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6793 "Internal function called by `color-values', which see.")
6794 (color, frame)
6795 Lisp_Object color, frame;
6797 XColor foo;
6798 FRAME_PTR f = check_x_frame (frame);
6800 CHECK_STRING (color, 1);
6802 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
6804 Lisp_Object rgb[3];
6806 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
6807 | GetRValue (foo.pixel));
6808 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
6809 | GetGValue (foo.pixel));
6810 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
6811 | GetBValue (foo.pixel));
6812 return Flist (3, rgb);
6814 else
6815 return Qnil;
6818 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6819 "Internal function called by `display-color-p', which see.")
6820 (display)
6821 Lisp_Object display;
6823 struct w32_display_info *dpyinfo = check_x_display_info (display);
6825 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6826 return Qnil;
6828 return Qt;
6831 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
6832 0, 1, 0,
6833 "Return t if the X display supports shades of gray.\n\
6834 Note that color displays do support shades of gray.\n\
6835 The optional argument DISPLAY specifies which display to ask about.\n\
6836 DISPLAY should be either a frame or a display name (a string).\n\
6837 If omitted or nil, that stands for the selected frame's display.")
6838 (display)
6839 Lisp_Object display;
6841 struct w32_display_info *dpyinfo = check_x_display_info (display);
6843 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6844 return Qnil;
6846 return Qt;
6849 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
6850 0, 1, 0,
6851 "Returns the width in pixels of the X display DISPLAY.\n\
6852 The optional argument DISPLAY specifies which display to ask about.\n\
6853 DISPLAY should be either a frame or a display name (a string).\n\
6854 If omitted or nil, that stands for the selected frame's display.")
6855 (display)
6856 Lisp_Object display;
6858 struct w32_display_info *dpyinfo = check_x_display_info (display);
6860 return make_number (dpyinfo->width);
6863 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6864 Sx_display_pixel_height, 0, 1, 0,
6865 "Returns the height in pixels of the X display DISPLAY.\n\
6866 The optional argument DISPLAY specifies which display to ask about.\n\
6867 DISPLAY should be either a frame or a display name (a string).\n\
6868 If omitted or nil, that stands for the selected frame's display.")
6869 (display)
6870 Lisp_Object display;
6872 struct w32_display_info *dpyinfo = check_x_display_info (display);
6874 return make_number (dpyinfo->height);
6877 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6878 0, 1, 0,
6879 "Returns the number of bitplanes of the display DISPLAY.\n\
6880 The optional argument DISPLAY specifies which display to ask about.\n\
6881 DISPLAY should be either a frame or a display name (a string).\n\
6882 If omitted or nil, that stands for the selected frame's display.")
6883 (display)
6884 Lisp_Object display;
6886 struct w32_display_info *dpyinfo = check_x_display_info (display);
6888 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6891 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6892 0, 1, 0,
6893 "Returns the number of color cells of the display DISPLAY.\n\
6894 The optional argument DISPLAY specifies which display to ask about.\n\
6895 DISPLAY should be either a frame or a display name (a string).\n\
6896 If omitted or nil, that stands for the selected frame's display.")
6897 (display)
6898 Lisp_Object display;
6900 struct w32_display_info *dpyinfo = check_x_display_info (display);
6901 HDC hdc;
6902 int cap;
6904 hdc = GetDC (dpyinfo->root_window);
6905 if (dpyinfo->has_palette)
6906 cap = GetDeviceCaps (hdc,SIZEPALETTE);
6907 else
6908 cap = GetDeviceCaps (hdc,NUMCOLORS);
6910 ReleaseDC (dpyinfo->root_window, hdc);
6912 return make_number (cap);
6915 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6916 Sx_server_max_request_size,
6917 0, 1, 0,
6918 "Returns the maximum request size of the server of display DISPLAY.\n\
6919 The optional argument DISPLAY specifies which display to ask about.\n\
6920 DISPLAY should be either a frame or a display name (a string).\n\
6921 If omitted or nil, that stands for the selected frame's display.")
6922 (display)
6923 Lisp_Object display;
6925 struct w32_display_info *dpyinfo = check_x_display_info (display);
6927 return make_number (1);
6930 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6931 "Returns the vendor ID string of the W32 system (Microsoft).\n\
6932 The optional argument DISPLAY specifies which display to ask about.\n\
6933 DISPLAY should be either a frame or a display name (a string).\n\
6934 If omitted or nil, that stands for the selected frame's display.")
6935 (display)
6936 Lisp_Object display;
6938 return build_string ("Microsoft Corp.");
6941 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6942 "Returns the version numbers of the server of display DISPLAY.\n\
6943 The value is a list of three integers: the major and minor\n\
6944 version numbers, and the vendor-specific release\n\
6945 number. See also the function `x-server-vendor'.\n\n\
6946 The optional argument DISPLAY specifies which display to ask about.\n\
6947 DISPLAY should be either a frame or a display name (a string).\n\
6948 If omitted or nil, that stands for the selected frame's display.")
6949 (display)
6950 Lisp_Object display;
6952 return Fcons (make_number (w32_major_version),
6953 Fcons (make_number (w32_minor_version), Qnil));
6956 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6957 "Returns the number of screens on the server of display DISPLAY.\n\
6958 The optional argument DISPLAY specifies which display to ask about.\n\
6959 DISPLAY should be either a frame or a display name (a string).\n\
6960 If omitted or nil, that stands for the selected frame's display.")
6961 (display)
6962 Lisp_Object display;
6964 return make_number (1);
6967 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
6968 "Returns the height in millimeters of the X display DISPLAY.\n\
6969 The optional argument DISPLAY specifies which display to ask about.\n\
6970 DISPLAY should be either a frame or a display name (a string).\n\
6971 If omitted or nil, that stands for the selected frame's display.")
6972 (display)
6973 Lisp_Object display;
6975 struct w32_display_info *dpyinfo = check_x_display_info (display);
6976 HDC hdc;
6977 int cap;
6979 hdc = GetDC (dpyinfo->root_window);
6981 cap = GetDeviceCaps (hdc, VERTSIZE);
6983 ReleaseDC (dpyinfo->root_window, hdc);
6985 return make_number (cap);
6988 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6989 "Returns the width in millimeters of the X display DISPLAY.\n\
6990 The optional argument DISPLAY specifies which display to ask about.\n\
6991 DISPLAY should be either a frame or a display name (a string).\n\
6992 If omitted or nil, that stands for the selected frame's display.")
6993 (display)
6994 Lisp_Object display;
6996 struct w32_display_info *dpyinfo = check_x_display_info (display);
6998 HDC hdc;
6999 int cap;
7001 hdc = GetDC (dpyinfo->root_window);
7003 cap = GetDeviceCaps (hdc, HORZSIZE);
7005 ReleaseDC (dpyinfo->root_window, hdc);
7007 return make_number (cap);
7010 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7011 Sx_display_backing_store, 0, 1, 0,
7012 "Returns an indication of whether display DISPLAY does backing store.\n\
7013 The value may be `always', `when-mapped', or `not-useful'.\n\
7014 The optional argument DISPLAY specifies which display to ask about.\n\
7015 DISPLAY should be either a frame or a display name (a string).\n\
7016 If omitted or nil, that stands for the selected frame's display.")
7017 (display)
7018 Lisp_Object display;
7020 return intern ("not-useful");
7023 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7024 Sx_display_visual_class, 0, 1, 0,
7025 "Returns the visual class of the display DISPLAY.\n\
7026 The value is one of the symbols `static-gray', `gray-scale',\n\
7027 `static-color', `pseudo-color', `true-color', or `direct-color'.\n\n\
7028 The optional argument DISPLAY specifies which display to ask about.\n\
7029 DISPLAY should be either a frame or a display name (a string).\n\
7030 If omitted or nil, that stands for the selected frame's display.")
7031 (display)
7032 Lisp_Object display;
7034 struct w32_display_info *dpyinfo = check_x_display_info (display);
7036 #if 0
7037 switch (dpyinfo->visual->class)
7039 case StaticGray: return (intern ("static-gray"));
7040 case GrayScale: return (intern ("gray-scale"));
7041 case StaticColor: return (intern ("static-color"));
7042 case PseudoColor: return (intern ("pseudo-color"));
7043 case TrueColor: return (intern ("true-color"));
7044 case DirectColor: return (intern ("direct-color"));
7045 default:
7046 error ("Display has an unknown visual class");
7048 #endif
7050 error ("Display has an unknown visual class");
7053 DEFUN ("x-display-save-under", Fx_display_save_under,
7054 Sx_display_save_under, 0, 1, 0,
7055 "Returns t if the display DISPLAY supports the save-under feature.\n\
7056 The optional argument DISPLAY specifies which display to ask about.\n\
7057 DISPLAY should be either a frame or a display name (a string).\n\
7058 If omitted or nil, that stands for the selected frame's display.")
7059 (display)
7060 Lisp_Object display;
7062 return Qnil;
7066 x_pixel_width (f)
7067 register struct frame *f;
7069 return PIXEL_WIDTH (f);
7073 x_pixel_height (f)
7074 register struct frame *f;
7076 return PIXEL_HEIGHT (f);
7080 x_char_width (f)
7081 register struct frame *f;
7083 return FONT_WIDTH (f->output_data.w32->font);
7087 x_char_height (f)
7088 register struct frame *f;
7090 return f->output_data.w32->line_height;
7094 x_screen_planes (f)
7095 register struct frame *f;
7097 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7100 /* Return the display structure for the display named NAME.
7101 Open a new connection if necessary. */
7103 struct w32_display_info *
7104 x_display_info_for_name (name)
7105 Lisp_Object name;
7107 Lisp_Object names;
7108 struct w32_display_info *dpyinfo;
7110 CHECK_STRING (name, 0);
7112 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7113 dpyinfo;
7114 dpyinfo = dpyinfo->next, names = XCDR (names))
7116 Lisp_Object tem;
7117 tem = Fstring_equal (XCAR (XCAR (names)), name);
7118 if (!NILP (tem))
7119 return dpyinfo;
7122 /* Use this general default value to start with. */
7123 Vx_resource_name = Vinvocation_name;
7125 validate_x_resource_name ();
7127 dpyinfo = w32_term_init (name, (unsigned char *)0,
7128 (char *) XSTRING (Vx_resource_name)->data);
7130 if (dpyinfo == 0)
7131 error ("Cannot connect to server %s", XSTRING (name)->data);
7133 w32_in_use = 1;
7134 XSETFASTINT (Vwindow_system_version, 3);
7136 return dpyinfo;
7139 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7140 1, 3, 0, "Open a connection to a server.\n\
7141 DISPLAY is the name of the display to connect to.\n\
7142 Optional second arg XRM-STRING is a string of resources in xrdb format.\n\
7143 If the optional third arg MUST-SUCCEED is non-nil,\n\
7144 terminate Emacs if we can't open the connection.")
7145 (display, xrm_string, must_succeed)
7146 Lisp_Object display, xrm_string, must_succeed;
7148 unsigned char *xrm_option;
7149 struct w32_display_info *dpyinfo;
7151 CHECK_STRING (display, 0);
7152 if (! NILP (xrm_string))
7153 CHECK_STRING (xrm_string, 1);
7155 if (! EQ (Vwindow_system, intern ("w32")))
7156 error ("Not using Microsoft Windows");
7158 /* Allow color mapping to be defined externally; first look in user's
7159 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
7161 Lisp_Object color_file;
7162 struct gcpro gcpro1;
7164 color_file = build_string("~/rgb.txt");
7166 GCPRO1 (color_file);
7168 if (NILP (Ffile_readable_p (color_file)))
7169 color_file =
7170 Fexpand_file_name (build_string ("rgb.txt"),
7171 Fsymbol_value (intern ("data-directory")));
7173 Vw32_color_map = Fw32_load_color_file (color_file);
7175 UNGCPRO;
7177 if (NILP (Vw32_color_map))
7178 Vw32_color_map = Fw32_default_color_map ();
7180 if (! NILP (xrm_string))
7181 xrm_option = (unsigned char *) XSTRING (xrm_string)->data;
7182 else
7183 xrm_option = (unsigned char *) 0;
7185 /* Use this general default value to start with. */
7186 /* First remove .exe suffix from invocation-name - it looks ugly. */
7188 char basename[ MAX_PATH ], *str;
7190 strcpy (basename, XSTRING (Vinvocation_name)->data);
7191 str = strrchr (basename, '.');
7192 if (str) *str = 0;
7193 Vinvocation_name = build_string (basename);
7195 Vx_resource_name = Vinvocation_name;
7197 validate_x_resource_name ();
7199 /* This is what opens the connection and sets x_current_display.
7200 This also initializes many symbols, such as those used for input. */
7201 dpyinfo = w32_term_init (display, xrm_option,
7202 (char *) XSTRING (Vx_resource_name)->data);
7204 if (dpyinfo == 0)
7206 if (!NILP (must_succeed))
7207 fatal ("Cannot connect to server %s.\n",
7208 XSTRING (display)->data);
7209 else
7210 error ("Cannot connect to server %s", XSTRING (display)->data);
7213 w32_in_use = 1;
7215 XSETFASTINT (Vwindow_system_version, 3);
7216 return Qnil;
7219 DEFUN ("x-close-connection", Fx_close_connection,
7220 Sx_close_connection, 1, 1, 0,
7221 "Close the connection to DISPLAY's server.\n\
7222 For DISPLAY, specify either a frame or a display name (a string).\n\
7223 If DISPLAY is nil, that stands for the selected frame's display.")
7224 (display)
7225 Lisp_Object display;
7227 struct w32_display_info *dpyinfo = check_x_display_info (display);
7228 int i;
7230 if (dpyinfo->reference_count > 0)
7231 error ("Display still has frames on it");
7233 BLOCK_INPUT;
7234 /* Free the fonts in the font table. */
7235 for (i = 0; i < dpyinfo->n_fonts; i++)
7236 if (dpyinfo->font_table[i].name)
7238 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
7239 xfree (dpyinfo->font_table[i].full_name);
7240 xfree (dpyinfo->font_table[i].name);
7241 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
7243 x_destroy_all_bitmaps (dpyinfo);
7245 x_delete_display (dpyinfo);
7246 UNBLOCK_INPUT;
7248 return Qnil;
7251 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
7252 "Return the list of display names that Emacs has connections to.")
7255 Lisp_Object tail, result;
7257 result = Qnil;
7258 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
7259 result = Fcons (XCAR (XCAR (tail)), result);
7261 return result;
7264 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7265 "If ON is non-nil, report errors as soon as the erring request is made.\n\
7266 If ON is nil, allow buffering of requests.\n\
7267 This is a noop on W32 systems.\n\
7268 The optional second argument DISPLAY specifies which display to act on.\n\
7269 DISPLAY should be either a frame or a display name (a string).\n\
7270 If DISPLAY is omitted or nil, that stands for the selected frame's display.")
7271 (on, display)
7272 Lisp_Object display, on;
7274 return Qnil;
7279 /***********************************************************************
7280 Image types
7281 ***********************************************************************/
7283 /* Value is the number of elements of vector VECTOR. */
7285 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
7287 /* List of supported image types. Use define_image_type to add new
7288 types. Use lookup_image_type to find a type for a given symbol. */
7290 static struct image_type *image_types;
7292 /* The symbol `image' which is the car of the lists used to represent
7293 images in Lisp. */
7295 extern Lisp_Object Qimage;
7297 /* The symbol `xbm' which is used as the type symbol for XBM images. */
7299 Lisp_Object Qxbm;
7301 /* Keywords. */
7303 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
7304 extern Lisp_Object QCdata;
7305 Lisp_Object QCtype, QCascent, QCmargin, QCrelief;
7306 Lisp_Object QCalgorithm, QCcolor_symbols, QCheuristic_mask;
7307 Lisp_Object QCindex;
7309 /* Other symbols. */
7311 Lisp_Object Qlaplace;
7313 /* Time in seconds after which images should be removed from the cache
7314 if not displayed. */
7316 Lisp_Object Vimage_cache_eviction_delay;
7318 /* Function prototypes. */
7320 static void define_image_type P_ ((struct image_type *type));
7321 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
7322 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
7323 static void x_laplace P_ ((struct frame *, struct image *));
7324 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
7325 Lisp_Object));
7328 /* Define a new image type from TYPE. This adds a copy of TYPE to
7329 image_types and adds the symbol *TYPE->type to Vimage_types. */
7331 static void
7332 define_image_type (type)
7333 struct image_type *type;
7335 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
7336 The initialized data segment is read-only. */
7337 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
7338 bcopy (type, p, sizeof *p);
7339 p->next = image_types;
7340 image_types = p;
7341 Vimage_types = Fcons (*p->type, Vimage_types);
7345 /* Look up image type SYMBOL, and return a pointer to its image_type
7346 structure. Value is null if SYMBOL is not a known image type. */
7348 static INLINE struct image_type *
7349 lookup_image_type (symbol)
7350 Lisp_Object symbol;
7352 struct image_type *type;
7354 for (type = image_types; type; type = type->next)
7355 if (EQ (symbol, *type->type))
7356 break;
7358 return type;
7362 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
7363 valid image specification is a list whose car is the symbol
7364 `image', and whose rest is a property list. The property list must
7365 contain a value for key `:type'. That value must be the name of a
7366 supported image type. The rest of the property list depends on the
7367 image type. */
7370 valid_image_p (object)
7371 Lisp_Object object;
7373 int valid_p = 0;
7375 if (CONSP (object) && EQ (XCAR (object), Qimage))
7377 Lisp_Object symbol = Fplist_get (XCDR (object), QCtype);
7378 struct image_type *type = lookup_image_type (symbol);
7380 if (type)
7381 valid_p = type->valid_p (object);
7384 return valid_p;
7388 /* Log error message with format string FORMAT and argument ARG.
7389 Signaling an error, e.g. when an image cannot be loaded, is not a
7390 good idea because this would interrupt redisplay, and the error
7391 message display would lead to another redisplay. This function
7392 therefore simply displays a message. */
7394 static void
7395 image_error (format, arg1, arg2)
7396 char *format;
7397 Lisp_Object arg1, arg2;
7399 add_to_log (format, arg1, arg2);
7404 /***********************************************************************
7405 Image specifications
7406 ***********************************************************************/
7408 enum image_value_type
7410 IMAGE_DONT_CHECK_VALUE_TYPE,
7411 IMAGE_STRING_VALUE,
7412 IMAGE_SYMBOL_VALUE,
7413 IMAGE_POSITIVE_INTEGER_VALUE,
7414 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
7415 IMAGE_ASCENT_VALUE,
7416 IMAGE_INTEGER_VALUE,
7417 IMAGE_FUNCTION_VALUE,
7418 IMAGE_NUMBER_VALUE,
7419 IMAGE_BOOL_VALUE
7422 /* Structure used when parsing image specifications. */
7424 struct image_keyword
7426 /* Name of keyword. */
7427 char *name;
7429 /* The type of value allowed. */
7430 enum image_value_type type;
7432 /* Non-zero means key must be present. */
7433 int mandatory_p;
7435 /* Used to recognize duplicate keywords in a property list. */
7436 int count;
7438 /* The value that was found. */
7439 Lisp_Object value;
7443 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7444 int, Lisp_Object));
7445 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7448 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
7449 has the format (image KEYWORD VALUE ...). One of the keyword/
7450 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7451 image_keywords structures of size NKEYWORDS describing other
7452 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7454 static int
7455 parse_image_spec (spec, keywords, nkeywords, type)
7456 Lisp_Object spec;
7457 struct image_keyword *keywords;
7458 int nkeywords;
7459 Lisp_Object type;
7461 int i;
7462 Lisp_Object plist;
7464 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7465 return 0;
7467 plist = XCDR (spec);
7468 while (CONSP (plist))
7470 Lisp_Object key, value;
7472 /* First element of a pair must be a symbol. */
7473 key = XCAR (plist);
7474 plist = XCDR (plist);
7475 if (!SYMBOLP (key))
7476 return 0;
7478 /* There must follow a value. */
7479 if (!CONSP (plist))
7480 return 0;
7481 value = XCAR (plist);
7482 plist = XCDR (plist);
7484 /* Find key in KEYWORDS. Error if not found. */
7485 for (i = 0; i < nkeywords; ++i)
7486 if (strcmp (keywords[i].name, XSYMBOL (key)->name->data) == 0)
7487 break;
7489 if (i == nkeywords)
7490 continue;
7492 /* Record that we recognized the keyword. If a keywords
7493 was found more than once, it's an error. */
7494 keywords[i].value = value;
7495 ++keywords[i].count;
7497 if (keywords[i].count > 1)
7498 return 0;
7500 /* Check type of value against allowed type. */
7501 switch (keywords[i].type)
7503 case IMAGE_STRING_VALUE:
7504 if (!STRINGP (value))
7505 return 0;
7506 break;
7508 case IMAGE_SYMBOL_VALUE:
7509 if (!SYMBOLP (value))
7510 return 0;
7511 break;
7513 case IMAGE_POSITIVE_INTEGER_VALUE:
7514 if (!INTEGERP (value) || XINT (value) <= 0)
7515 return 0;
7516 break;
7518 case IMAGE_ASCENT_VALUE:
7519 if (SYMBOLP (value) && EQ (value, Qcenter))
7520 break;
7521 else if (INTEGERP (value)
7522 && XINT (value) >= 0
7523 && XINT (value) <= 100)
7524 break;
7525 return 0;
7527 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7528 if (!INTEGERP (value) || XINT (value) < 0)
7529 return 0;
7530 break;
7532 case IMAGE_DONT_CHECK_VALUE_TYPE:
7533 break;
7535 case IMAGE_FUNCTION_VALUE:
7536 value = indirect_function (value);
7537 if (SUBRP (value)
7538 || COMPILEDP (value)
7539 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7540 break;
7541 return 0;
7543 case IMAGE_NUMBER_VALUE:
7544 if (!INTEGERP (value) && !FLOATP (value))
7545 return 0;
7546 break;
7548 case IMAGE_INTEGER_VALUE:
7549 if (!INTEGERP (value))
7550 return 0;
7551 break;
7553 case IMAGE_BOOL_VALUE:
7554 if (!NILP (value) && !EQ (value, Qt))
7555 return 0;
7556 break;
7558 default:
7559 abort ();
7560 break;
7563 if (EQ (key, QCtype) && !EQ (type, value))
7564 return 0;
7567 /* Check that all mandatory fields are present. */
7568 for (i = 0; i < nkeywords; ++i)
7569 if (keywords[i].mandatory_p && keywords[i].count == 0)
7570 return 0;
7572 return NILP (plist);
7576 /* Return the value of KEY in image specification SPEC. Value is nil
7577 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7578 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7580 static Lisp_Object
7581 image_spec_value (spec, key, found)
7582 Lisp_Object spec, key;
7583 int *found;
7585 Lisp_Object tail;
7587 xassert (valid_image_p (spec));
7589 for (tail = XCDR (spec);
7590 CONSP (tail) && CONSP (XCDR (tail));
7591 tail = XCDR (XCDR (tail)))
7593 if (EQ (XCAR (tail), key))
7595 if (found)
7596 *found = 1;
7597 return XCAR (XCDR (tail));
7601 if (found)
7602 *found = 0;
7603 return Qnil;
7609 /***********************************************************************
7610 Image type independent image structures
7611 ***********************************************************************/
7613 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7614 static void free_image P_ ((struct frame *f, struct image *img));
7617 /* Allocate and return a new image structure for image specification
7618 SPEC. SPEC has a hash value of HASH. */
7620 static struct image *
7621 make_image (spec, hash)
7622 Lisp_Object spec;
7623 unsigned hash;
7625 struct image *img = (struct image *) xmalloc (sizeof *img);
7627 xassert (valid_image_p (spec));
7628 bzero (img, sizeof *img);
7629 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7630 xassert (img->type != NULL);
7631 img->spec = spec;
7632 img->data.lisp_val = Qnil;
7633 img->ascent = DEFAULT_IMAGE_ASCENT;
7634 img->hash = hash;
7635 return img;
7639 /* Free image IMG which was used on frame F, including its resources. */
7641 static void
7642 free_image (f, img)
7643 struct frame *f;
7644 struct image *img;
7646 if (img)
7648 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7650 /* Remove IMG from the hash table of its cache. */
7651 if (img->prev)
7652 img->prev->next = img->next;
7653 else
7654 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7656 if (img->next)
7657 img->next->prev = img->prev;
7659 c->images[img->id] = NULL;
7661 /* Free resources, then free IMG. */
7662 img->type->free (f, img);
7663 xfree (img);
7668 /* Prepare image IMG for display on frame F. Must be called before
7669 drawing an image. */
7671 void
7672 prepare_image_for_display (f, img)
7673 struct frame *f;
7674 struct image *img;
7676 EMACS_TIME t;
7678 /* We're about to display IMG, so set its timestamp to `now'. */
7679 EMACS_GET_TIME (t);
7680 img->timestamp = EMACS_SECS (t);
7682 /* If IMG doesn't have a pixmap yet, load it now, using the image
7683 type dependent loader function. */
7684 if (img->pixmap == 0 && !img->load_failed_p)
7685 img->load_failed_p = img->type->load (f, img) == 0;
7689 /* Value is the number of pixels for the ascent of image IMG when
7690 drawn in face FACE. */
7693 image_ascent (img, face)
7694 struct image *img;
7695 struct face *face;
7697 int height = img->height + img->margin;
7698 int ascent;
7700 if (img->ascent == CENTERED_IMAGE_ASCENT)
7702 if (face->font)
7703 ascent = height / 2 - (FONT_DESCENT(face->font)
7704 - FONT_BASE(face->font)) / 2;
7705 else
7706 ascent = height / 2;
7708 else
7709 ascent = height * img->ascent / 100.0;
7711 return ascent;
7716 /***********************************************************************
7717 Helper functions for X image types
7718 ***********************************************************************/
7720 static void x_clear_image P_ ((struct frame *f, struct image *img));
7721 static unsigned long x_alloc_image_color P_ ((struct frame *f,
7722 struct image *img,
7723 Lisp_Object color_name,
7724 unsigned long dflt));
7726 /* Free X resources of image IMG which is used on frame F. */
7728 static void
7729 x_clear_image (f, img)
7730 struct frame *f;
7731 struct image *img;
7733 #if 0 /* NTEMACS_TODO: W32 image support */
7735 if (img->pixmap)
7737 BLOCK_INPUT;
7738 XFreePixmap (NULL, img->pixmap);
7739 img->pixmap = 0;
7740 UNBLOCK_INPUT;
7743 if (img->ncolors)
7745 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
7747 /* If display has an immutable color map, freeing colors is not
7748 necessary and some servers don't allow it. So don't do it. */
7749 if (class != StaticColor
7750 && class != StaticGray
7751 && class != TrueColor)
7753 Colormap cmap;
7754 BLOCK_INPUT;
7755 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
7756 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
7757 img->ncolors, 0);
7758 UNBLOCK_INPUT;
7761 xfree (img->colors);
7762 img->colors = NULL;
7763 img->ncolors = 0;
7765 #endif
7769 /* Allocate color COLOR_NAME for image IMG on frame F. If color
7770 cannot be allocated, use DFLT. Add a newly allocated color to
7771 IMG->colors, so that it can be freed again. Value is the pixel
7772 color. */
7774 static unsigned long
7775 x_alloc_image_color (f, img, color_name, dflt)
7776 struct frame *f;
7777 struct image *img;
7778 Lisp_Object color_name;
7779 unsigned long dflt;
7781 #if 0 /* NTEMACS_TODO: allocing colors. */
7782 XColor color;
7783 unsigned long result;
7785 xassert (STRINGP (color_name));
7787 if (w32_defined_color (f, XSTRING (color_name)->data, &color, 1))
7789 /* This isn't called frequently so we get away with simply
7790 reallocating the color vector to the needed size, here. */
7791 ++img->ncolors;
7792 img->colors =
7793 (unsigned long *) xrealloc (img->colors,
7794 img->ncolors * sizeof *img->colors);
7795 img->colors[img->ncolors - 1] = color.pixel;
7796 result = color.pixel;
7798 else
7799 result = dflt;
7800 return result;
7801 #endif
7802 return 0;
7807 /***********************************************************************
7808 Image Cache
7809 ***********************************************************************/
7811 static void cache_image P_ ((struct frame *f, struct image *img));
7814 /* Return a new, initialized image cache that is allocated from the
7815 heap. Call free_image_cache to free an image cache. */
7817 struct image_cache *
7818 make_image_cache ()
7820 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
7821 int size;
7823 bzero (c, sizeof *c);
7824 c->size = 50;
7825 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
7826 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
7827 c->buckets = (struct image **) xmalloc (size);
7828 bzero (c->buckets, size);
7829 return c;
7833 /* Free image cache of frame F. Be aware that X frames share images
7834 caches. */
7836 void
7837 free_image_cache (f)
7838 struct frame *f;
7840 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7841 if (c)
7843 int i;
7845 /* Cache should not be referenced by any frame when freed. */
7846 xassert (c->refcount == 0);
7848 for (i = 0; i < c->used; ++i)
7849 free_image (f, c->images[i]);
7850 xfree (c->images);
7851 xfree (c);
7852 xfree (c->buckets);
7853 FRAME_X_IMAGE_CACHE (f) = NULL;
7858 /* Clear image cache of frame F. FORCE_P non-zero means free all
7859 images. FORCE_P zero means clear only images that haven't been
7860 displayed for some time. Should be called from time to time to
7861 reduce the number of loaded images. If image-eviction-seconds is
7862 non-nil, this frees images in the cache which weren't displayed for
7863 at least that many seconds. */
7865 void
7866 clear_image_cache (f, force_p)
7867 struct frame *f;
7868 int force_p;
7870 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7872 if (c && INTEGERP (Vimage_cache_eviction_delay))
7874 EMACS_TIME t;
7875 unsigned long old;
7876 int i, any_freed_p = 0;
7878 EMACS_GET_TIME (t);
7879 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
7881 for (i = 0; i < c->used; ++i)
7883 struct image *img = c->images[i];
7884 if (img != NULL
7885 && (force_p
7886 || (img->timestamp > old)))
7888 free_image (f, img);
7889 any_freed_p = 1;
7893 /* We may be clearing the image cache because, for example,
7894 Emacs was iconified for a longer period of time. In that
7895 case, current matrices may still contain references to
7896 images freed above. So, clear these matrices. */
7897 if (any_freed_p)
7899 clear_current_matrices (f);
7900 ++windows_or_buffers_changed;
7906 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
7907 0, 1, 0,
7908 "Clear the image cache of FRAME.\n\
7909 FRAME nil or omitted means use the selected frame.\n\
7910 FRAME t means clear the image caches of all frames.")
7911 (frame)
7912 Lisp_Object frame;
7914 if (EQ (frame, Qt))
7916 Lisp_Object tail;
7918 FOR_EACH_FRAME (tail, frame)
7919 if (FRAME_W32_P (XFRAME (frame)))
7920 clear_image_cache (XFRAME (frame), 1);
7922 else
7923 clear_image_cache (check_x_frame (frame), 1);
7925 return Qnil;
7929 /* Return the id of image with Lisp specification SPEC on frame F.
7930 SPEC must be a valid Lisp image specification (see valid_image_p). */
7933 lookup_image (f, spec)
7934 struct frame *f;
7935 Lisp_Object spec;
7937 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7938 struct image *img;
7939 int i;
7940 unsigned hash;
7941 struct gcpro gcpro1;
7942 EMACS_TIME now;
7944 /* F must be a window-system frame, and SPEC must be a valid image
7945 specification. */
7946 xassert (FRAME_WINDOW_P (f));
7947 xassert (valid_image_p (spec));
7949 GCPRO1 (spec);
7951 /* Look up SPEC in the hash table of the image cache. */
7952 hash = sxhash (spec, 0);
7953 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
7955 for (img = c->buckets[i]; img; img = img->next)
7956 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
7957 break;
7959 /* If not found, create a new image and cache it. */
7960 if (img == NULL)
7962 img = make_image (spec, hash);
7963 cache_image (f, img);
7964 img->load_failed_p = img->type->load (f, img) == 0;
7965 xassert (!interrupt_input_blocked);
7967 /* If we can't load the image, and we don't have a width and
7968 height, use some arbitrary width and height so that we can
7969 draw a rectangle for it. */
7970 if (img->load_failed_p)
7972 Lisp_Object value;
7974 value = image_spec_value (spec, QCwidth, NULL);
7975 img->width = (INTEGERP (value)
7976 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
7977 value = image_spec_value (spec, QCheight, NULL);
7978 img->height = (INTEGERP (value)
7979 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
7981 else
7983 /* Handle image type independent image attributes
7984 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF'. */
7985 Lisp_Object ascent, margin, relief, algorithm, heuristic_mask;
7986 Lisp_Object file;
7988 ascent = image_spec_value (spec, QCascent, NULL);
7989 if (INTEGERP (ascent))
7990 img->ascent = XFASTINT (ascent);
7991 else if (EQ (ascent, Qcenter))
7992 img->ascent = CENTERED_IMAGE_ASCENT;
7994 margin = image_spec_value (spec, QCmargin, NULL);
7995 if (INTEGERP (margin) && XINT (margin) >= 0)
7996 img->margin = XFASTINT (margin);
7998 relief = image_spec_value (spec, QCrelief, NULL);
7999 if (INTEGERP (relief))
8001 img->relief = XINT (relief);
8002 img->margin += abs (img->relief);
8005 /* Should we apply a Laplace edge-detection algorithm? */
8006 algorithm = image_spec_value (spec, QCalgorithm, NULL);
8007 if (img->pixmap && EQ (algorithm, Qlaplace))
8008 x_laplace (f, img);
8010 /* Should we built a mask heuristically? */
8011 heuristic_mask = image_spec_value (spec, QCheuristic_mask, NULL);
8012 if (img->pixmap && !img->mask && !NILP (heuristic_mask))
8013 x_build_heuristic_mask (f, img, heuristic_mask);
8017 /* We're using IMG, so set its timestamp to `now'. */
8018 EMACS_GET_TIME (now);
8019 img->timestamp = EMACS_SECS (now);
8021 UNGCPRO;
8023 /* Value is the image id. */
8024 return img->id;
8028 /* Cache image IMG in the image cache of frame F. */
8030 static void
8031 cache_image (f, img)
8032 struct frame *f;
8033 struct image *img;
8035 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8036 int i;
8038 /* Find a free slot in c->images. */
8039 for (i = 0; i < c->used; ++i)
8040 if (c->images[i] == NULL)
8041 break;
8043 /* If no free slot found, maybe enlarge c->images. */
8044 if (i == c->used && c->used == c->size)
8046 c->size *= 2;
8047 c->images = (struct image **) xrealloc (c->images,
8048 c->size * sizeof *c->images);
8051 /* Add IMG to c->images, and assign IMG an id. */
8052 c->images[i] = img;
8053 img->id = i;
8054 if (i == c->used)
8055 ++c->used;
8057 /* Add IMG to the cache's hash table. */
8058 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8059 img->next = c->buckets[i];
8060 if (img->next)
8061 img->next->prev = img;
8062 img->prev = NULL;
8063 c->buckets[i] = img;
8067 /* Call FN on every image in the image cache of frame F. Used to mark
8068 Lisp Objects in the image cache. */
8070 void
8071 forall_images_in_image_cache (f, fn)
8072 struct frame *f;
8073 void (*fn) P_ ((struct image *img));
8075 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8077 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8078 if (c)
8080 int i;
8081 for (i = 0; i < c->used; ++i)
8082 if (c->images[i])
8083 fn (c->images[i]);
8090 /***********************************************************************
8091 W32 support code
8092 ***********************************************************************/
8094 #if 0 /* NTEMACS_TODO: W32 specific image code. */
8096 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8097 XImage **, Pixmap *));
8098 static void x_destroy_x_image P_ ((XImage *));
8099 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8102 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8103 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8104 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
8105 via xmalloc. Print error messages via image_error if an error
8106 occurs. Value is non-zero if successful. */
8108 static int
8109 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8110 struct frame *f;
8111 int width, height, depth;
8112 XImage **ximg;
8113 Pixmap *pixmap;
8115 #if 0 /* NTEMACS_TODO: Image support for W32 */
8116 Display *display = FRAME_W32_DISPLAY (f);
8117 Screen *screen = FRAME_X_SCREEN (f);
8118 Window window = FRAME_W32_WINDOW (f);
8120 xassert (interrupt_input_blocked);
8122 if (depth <= 0)
8123 depth = DefaultDepthOfScreen (screen);
8124 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
8125 depth, ZPixmap, 0, NULL, width, height,
8126 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
8127 if (*ximg == NULL)
8129 image_error ("Unable to allocate X image", Qnil, Qnil);
8130 return 0;
8133 /* Allocate image raster. */
8134 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
8136 /* Allocate a pixmap of the same size. */
8137 *pixmap = XCreatePixmap (display, window, width, height, depth);
8138 if (*pixmap == 0)
8140 x_destroy_x_image (*ximg);
8141 *ximg = NULL;
8142 image_error ("Unable to create X pixmap", Qnil, Qnil);
8143 return 0;
8145 #endif
8146 return 1;
8150 /* Destroy XImage XIMG. Free XIMG->data. */
8152 static void
8153 x_destroy_x_image (ximg)
8154 XImage *ximg;
8156 xassert (interrupt_input_blocked);
8157 if (ximg)
8159 xfree (ximg->data);
8160 ximg->data = NULL;
8161 XDestroyImage (ximg);
8166 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8167 are width and height of both the image and pixmap. */
8169 static void
8170 x_put_x_image (f, ximg, pixmap, width, height)
8171 struct frame *f;
8172 XImage *ximg;
8173 Pixmap pixmap;
8175 GC gc;
8177 xassert (interrupt_input_blocked);
8178 gc = XCreateGC (NULL, pixmap, 0, NULL);
8179 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
8180 XFreeGC (NULL, gc);
8183 #endif
8186 /***********************************************************************
8187 Searching files
8188 ***********************************************************************/
8190 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
8192 /* Find image file FILE. Look in data-directory, then
8193 x-bitmap-file-path. Value is the full name of the file found, or
8194 nil if not found. */
8196 static Lisp_Object
8197 x_find_image_file (file)
8198 Lisp_Object file;
8200 Lisp_Object file_found, search_path;
8201 struct gcpro gcpro1, gcpro2;
8202 int fd;
8204 file_found = Qnil;
8205 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8206 GCPRO2 (file_found, search_path);
8208 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
8209 fd = openp (search_path, file, "", &file_found, 0);
8211 if (fd < 0)
8212 file_found = Qnil;
8213 else
8214 close (fd);
8216 UNGCPRO;
8217 return file_found;
8222 /***********************************************************************
8223 XBM images
8224 ***********************************************************************/
8226 static int xbm_load P_ ((struct frame *f, struct image *img));
8227 static int xbm_load_image_from_file P_ ((struct frame *f, struct image *img,
8228 Lisp_Object file));
8229 static int xbm_image_p P_ ((Lisp_Object object));
8230 static int xbm_read_bitmap_file_data P_ ((char *, int *, int *,
8231 unsigned char **));
8234 /* Indices of image specification fields in xbm_format, below. */
8236 enum xbm_keyword_index
8238 XBM_TYPE,
8239 XBM_FILE,
8240 XBM_WIDTH,
8241 XBM_HEIGHT,
8242 XBM_DATA,
8243 XBM_FOREGROUND,
8244 XBM_BACKGROUND,
8245 XBM_ASCENT,
8246 XBM_MARGIN,
8247 XBM_RELIEF,
8248 XBM_ALGORITHM,
8249 XBM_HEURISTIC_MASK,
8250 XBM_LAST
8253 /* Vector of image_keyword structures describing the format
8254 of valid XBM image specifications. */
8256 static struct image_keyword xbm_format[XBM_LAST] =
8258 {":type", IMAGE_SYMBOL_VALUE, 1},
8259 {":file", IMAGE_STRING_VALUE, 0},
8260 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8261 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8262 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8263 {":foreground", IMAGE_STRING_VALUE, 0},
8264 {":background", IMAGE_STRING_VALUE, 0},
8265 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8266 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8267 {":relief", IMAGE_INTEGER_VALUE, 0},
8268 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8269 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8272 /* Structure describing the image type XBM. */
8274 static struct image_type xbm_type =
8276 &Qxbm,
8277 xbm_image_p,
8278 xbm_load,
8279 x_clear_image,
8280 NULL
8283 /* Tokens returned from xbm_scan. */
8285 enum xbm_token
8287 XBM_TK_IDENT = 256,
8288 XBM_TK_NUMBER
8292 /* Return non-zero if OBJECT is a valid XBM-type image specification.
8293 A valid specification is a list starting with the symbol `image'
8294 The rest of the list is a property list which must contain an
8295 entry `:type xbm..
8297 If the specification specifies a file to load, it must contain
8298 an entry `:file FILENAME' where FILENAME is a string.
8300 If the specification is for a bitmap loaded from memory it must
8301 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8302 WIDTH and HEIGHT are integers > 0. DATA may be:
8304 1. a string large enough to hold the bitmap data, i.e. it must
8305 have a size >= (WIDTH + 7) / 8 * HEIGHT
8307 2. a bool-vector of size >= WIDTH * HEIGHT
8309 3. a vector of strings or bool-vectors, one for each line of the
8310 bitmap.
8312 Both the file and data forms may contain the additional entries
8313 `:background COLOR' and `:foreground COLOR'. If not present,
8314 foreground and background of the frame on which the image is
8315 displayed, is used. */
8317 static int
8318 xbm_image_p (object)
8319 Lisp_Object object;
8321 struct image_keyword kw[XBM_LAST];
8323 bcopy (xbm_format, kw, sizeof kw);
8324 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8325 return 0;
8327 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8329 if (kw[XBM_FILE].count)
8331 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8332 return 0;
8334 else
8336 Lisp_Object data;
8337 int width, height;
8339 /* Entries for `:width', `:height' and `:data' must be present. */
8340 if (!kw[XBM_WIDTH].count
8341 || !kw[XBM_HEIGHT].count
8342 || !kw[XBM_DATA].count)
8343 return 0;
8345 data = kw[XBM_DATA].value;
8346 width = XFASTINT (kw[XBM_WIDTH].value);
8347 height = XFASTINT (kw[XBM_HEIGHT].value);
8349 /* Check type of data, and width and height against contents of
8350 data. */
8351 if (VECTORP (data))
8353 int i;
8355 /* Number of elements of the vector must be >= height. */
8356 if (XVECTOR (data)->size < height)
8357 return 0;
8359 /* Each string or bool-vector in data must be large enough
8360 for one line of the image. */
8361 for (i = 0; i < height; ++i)
8363 Lisp_Object elt = XVECTOR (data)->contents[i];
8365 if (STRINGP (elt))
8367 if (XSTRING (elt)->size
8368 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8369 return 0;
8371 else if (BOOL_VECTOR_P (elt))
8373 if (XBOOL_VECTOR (elt)->size < width)
8374 return 0;
8376 else
8377 return 0;
8380 else if (STRINGP (data))
8382 if (XSTRING (data)->size
8383 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8384 return 0;
8386 else if (BOOL_VECTOR_P (data))
8388 if (XBOOL_VECTOR (data)->size < width * height)
8389 return 0;
8391 else
8392 return 0;
8395 /* Baseline must be a value between 0 and 100 (a percentage). */
8396 if (kw[XBM_ASCENT].count
8397 && XFASTINT (kw[XBM_ASCENT].value) > 100)
8398 return 0;
8400 return 1;
8404 /* Scan a bitmap file. FP is the stream to read from. Value is
8405 either an enumerator from enum xbm_token, or a character for a
8406 single-character token, or 0 at end of file. If scanning an
8407 identifier, store the lexeme of the identifier in SVAL. If
8408 scanning a number, store its value in *IVAL. */
8410 static int
8411 xbm_scan (fp, sval, ival)
8412 FILE *fp;
8413 char *sval;
8414 int *ival;
8416 int c;
8418 /* Skip white space. */
8419 while ((c = fgetc (fp)) != EOF && isspace (c))
8422 if (c == EOF)
8423 c = 0;
8424 else if (isdigit (c))
8426 int value = 0, digit;
8428 if (c == '0')
8430 c = fgetc (fp);
8431 if (c == 'x' || c == 'X')
8433 while ((c = fgetc (fp)) != EOF)
8435 if (isdigit (c))
8436 digit = c - '0';
8437 else if (c >= 'a' && c <= 'f')
8438 digit = c - 'a' + 10;
8439 else if (c >= 'A' && c <= 'F')
8440 digit = c - 'A' + 10;
8441 else
8442 break;
8443 value = 16 * value + digit;
8446 else if (isdigit (c))
8448 value = c - '0';
8449 while ((c = fgetc (fp)) != EOF
8450 && isdigit (c))
8451 value = 8 * value + c - '0';
8454 else
8456 value = c - '0';
8457 while ((c = fgetc (fp)) != EOF
8458 && isdigit (c))
8459 value = 10 * value + c - '0';
8462 if (c != EOF)
8463 ungetc (c, fp);
8464 *ival = value;
8465 c = XBM_TK_NUMBER;
8467 else if (isalpha (c) || c == '_')
8469 *sval++ = c;
8470 while ((c = fgetc (fp)) != EOF
8471 && (isalnum (c) || c == '_'))
8472 *sval++ = c;
8473 *sval = 0;
8474 if (c != EOF)
8475 ungetc (c, fp);
8476 c = XBM_TK_IDENT;
8479 return c;
8483 /* Replacement for XReadBitmapFileData which isn't available under old
8484 X versions. FILE is the name of the bitmap file to read. Set
8485 *WIDTH and *HEIGHT to the width and height of the image. Return in
8486 *DATA the bitmap data allocated with xmalloc. Value is non-zero if
8487 successful. */
8489 static int
8490 xbm_read_bitmap_file_data (file, width, height, data)
8491 char *file;
8492 int *width, *height;
8493 unsigned char **data;
8495 FILE *fp;
8496 char buffer[BUFSIZ];
8497 int padding_p = 0;
8498 int v10 = 0;
8499 int bytes_per_line, i, nbytes;
8500 unsigned char *p;
8501 int value;
8502 int LA1;
8504 #define match() \
8505 LA1 = xbm_scan (fp, buffer, &value)
8507 #define expect(TOKEN) \
8508 if (LA1 != (TOKEN)) \
8509 goto failure; \
8510 else \
8511 match ()
8513 #define expect_ident(IDENT) \
8514 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8515 match (); \
8516 else \
8517 goto failure
8519 fp = fopen (file, "r");
8520 if (fp == NULL)
8521 return 0;
8523 *width = *height = -1;
8524 *data = NULL;
8525 LA1 = xbm_scan (fp, buffer, &value);
8527 /* Parse defines for width, height and hot-spots. */
8528 while (LA1 == '#')
8530 match ();
8531 expect_ident ("define");
8532 expect (XBM_TK_IDENT);
8534 if (LA1 == XBM_TK_NUMBER);
8536 char *p = strrchr (buffer, '_');
8537 p = p ? p + 1 : buffer;
8538 if (strcmp (p, "width") == 0)
8539 *width = value;
8540 else if (strcmp (p, "height") == 0)
8541 *height = value;
8543 expect (XBM_TK_NUMBER);
8546 if (*width < 0 || *height < 0)
8547 goto failure;
8549 /* Parse bits. Must start with `static'. */
8550 expect_ident ("static");
8551 if (LA1 == XBM_TK_IDENT)
8553 if (strcmp (buffer, "unsigned") == 0)
8555 match ();
8556 expect_ident ("char");
8558 else if (strcmp (buffer, "short") == 0)
8560 match ();
8561 v10 = 1;
8562 if (*width % 16 && *width % 16 < 9)
8563 padding_p = 1;
8565 else if (strcmp (buffer, "char") == 0)
8566 match ();
8567 else
8568 goto failure;
8570 else
8571 goto failure;
8573 expect (XBM_TK_IDENT);
8574 expect ('[');
8575 expect (']');
8576 expect ('=');
8577 expect ('{');
8579 bytes_per_line = (*width + 7) / 8 + padding_p;
8580 nbytes = bytes_per_line * *height;
8581 p = *data = (char *) xmalloc (nbytes);
8583 if (v10)
8586 for (i = 0; i < nbytes; i += 2)
8588 int val = value;
8589 expect (XBM_TK_NUMBER);
8591 *p++ = val;
8592 if (!padding_p || ((i + 2) % bytes_per_line))
8593 *p++ = value >> 8;
8595 if (LA1 == ',' || LA1 == '}')
8596 match ();
8597 else
8598 goto failure;
8601 else
8603 for (i = 0; i < nbytes; ++i)
8605 int val = value;
8606 expect (XBM_TK_NUMBER);
8608 *p++ = val;
8610 if (LA1 == ',' || LA1 == '}')
8611 match ();
8612 else
8613 goto failure;
8617 fclose (fp);
8618 return 1;
8620 failure:
8622 fclose (fp);
8623 if (*data)
8625 xfree (*data);
8626 *data = NULL;
8628 return 0;
8630 #undef match
8631 #undef expect
8632 #undef expect_ident
8636 /* Load XBM image IMG which will be displayed on frame F from file
8637 SPECIFIED_FILE. Value is non-zero if successful. */
8639 static int
8640 xbm_load_image_from_file (f, img, specified_file)
8641 struct frame *f;
8642 struct image *img;
8643 Lisp_Object specified_file;
8645 int rc;
8646 unsigned char *data;
8647 int success_p = 0;
8648 Lisp_Object file;
8649 struct gcpro gcpro1;
8651 xassert (STRINGP (specified_file));
8652 file = Qnil;
8653 GCPRO1 (file);
8655 file = x_find_image_file (specified_file);
8656 if (!STRINGP (file))
8658 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8659 UNGCPRO;
8660 return 0;
8663 rc = xbm_read_bitmap_file_data (XSTRING (file)->data, &img->width,
8664 &img->height, &data);
8665 if (rc)
8667 int depth = one_w32_display_info.n_cbits;
8668 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8669 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8670 Lisp_Object value;
8672 xassert (img->width > 0 && img->height > 0);
8674 /* Get foreground and background colors, maybe allocate colors. */
8675 value = image_spec_value (img->spec, QCforeground, NULL);
8676 if (!NILP (value))
8677 foreground = x_alloc_image_color (f, img, value, foreground);
8679 value = image_spec_value (img->spec, QCbackground, NULL);
8680 if (!NILP (value))
8681 background = x_alloc_image_color (f, img, value, background);
8683 #if 0 /* NTEMACS_TODO : Port image display to W32 */
8684 BLOCK_INPUT;
8685 img->pixmap
8686 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
8687 FRAME_W32_WINDOW (f),
8688 data,
8689 img->width, img->height,
8690 foreground, background,
8691 depth);
8692 xfree (data);
8694 if (img->pixmap == 0)
8696 x_clear_image (f, img);
8697 image_error ("Unable to create X pixmap for `%s'", file, Qnil);
8699 else
8700 success_p = 1;
8702 UNBLOCK_INPUT;
8703 #endif
8705 else
8706 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8708 UNGCPRO;
8709 return success_p;
8713 /* Fill image IMG which is used on frame F with pixmap data. Value is
8714 non-zero if successful. */
8716 static int
8717 xbm_load (f, img)
8718 struct frame *f;
8719 struct image *img;
8721 int success_p = 0;
8722 Lisp_Object file_name;
8724 xassert (xbm_image_p (img->spec));
8726 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8727 file_name = image_spec_value (img->spec, QCfile, NULL);
8728 if (STRINGP (file_name))
8729 success_p = xbm_load_image_from_file (f, img, file_name);
8730 else
8732 struct image_keyword fmt[XBM_LAST];
8733 Lisp_Object data;
8734 int depth;
8735 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8736 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8737 char *bits;
8738 int parsed_p;
8740 /* Parse the list specification. */
8741 bcopy (xbm_format, fmt, sizeof fmt);
8742 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
8743 xassert (parsed_p);
8745 /* Get specified width, and height. */
8746 img->width = XFASTINT (fmt[XBM_WIDTH].value);
8747 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
8748 xassert (img->width > 0 && img->height > 0);
8750 BLOCK_INPUT;
8752 if (fmt[XBM_ASCENT].count)
8753 img->ascent = XFASTINT (fmt[XBM_ASCENT].value);
8755 /* Get foreground and background colors, maybe allocate colors. */
8756 if (fmt[XBM_FOREGROUND].count)
8757 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
8758 foreground);
8759 if (fmt[XBM_BACKGROUND].count)
8760 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
8761 background);
8763 /* Set bits to the bitmap image data. */
8764 data = fmt[XBM_DATA].value;
8765 if (VECTORP (data))
8767 int i;
8768 char *p;
8769 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
8771 p = bits = (char *) alloca (nbytes * img->height);
8772 for (i = 0; i < img->height; ++i, p += nbytes)
8774 Lisp_Object line = XVECTOR (data)->contents[i];
8775 if (STRINGP (line))
8776 bcopy (XSTRING (line)->data, p, nbytes);
8777 else
8778 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
8781 else if (STRINGP (data))
8782 bits = XSTRING (data)->data;
8783 else
8784 bits = XBOOL_VECTOR (data)->data;
8786 #if 0 /* NTEMACS_TODO : W32 XPM code */
8787 /* Create the pixmap. */
8788 depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
8789 img->pixmap
8790 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
8791 FRAME_W32_WINDOW (f),
8792 bits,
8793 img->width, img->height,
8794 foreground, background,
8795 depth);
8796 #endif /* NTEMACS_TODO */
8798 if (img->pixmap)
8799 success_p = 1;
8800 else
8802 image_error ("Unable to create pixmap for XBM image `%s'",
8803 img->spec, Qnil);
8804 x_clear_image (f, img);
8807 UNBLOCK_INPUT;
8810 return success_p;
8815 /***********************************************************************
8816 XPM images
8817 ***********************************************************************/
8819 #if HAVE_XPM
8821 static int xpm_image_p P_ ((Lisp_Object object));
8822 static int xpm_load P_ ((struct frame *f, struct image *img));
8823 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
8825 #include "X11/xpm.h"
8827 /* The symbol `xpm' identifying XPM-format images. */
8829 Lisp_Object Qxpm;
8831 /* Indices of image specification fields in xpm_format, below. */
8833 enum xpm_keyword_index
8835 XPM_TYPE,
8836 XPM_FILE,
8837 XPM_DATA,
8838 XPM_ASCENT,
8839 XPM_MARGIN,
8840 XPM_RELIEF,
8841 XPM_ALGORITHM,
8842 XPM_HEURISTIC_MASK,
8843 XPM_COLOR_SYMBOLS,
8844 XPM_LAST
8847 /* Vector of image_keyword structures describing the format
8848 of valid XPM image specifications. */
8850 static struct image_keyword xpm_format[XPM_LAST] =
8852 {":type", IMAGE_SYMBOL_VALUE, 1},
8853 {":file", IMAGE_STRING_VALUE, 0},
8854 {":data", IMAGE_STRING_VALUE, 0},
8855 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8856 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8857 {":relief", IMAGE_INTEGER_VALUE, 0},
8858 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8859 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8860 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8863 /* Structure describing the image type XBM. */
8865 static struct image_type xpm_type =
8867 &Qxpm,
8868 xpm_image_p,
8869 xpm_load,
8870 x_clear_image,
8871 NULL
8875 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
8876 for XPM images. Such a list must consist of conses whose car and
8877 cdr are strings. */
8879 static int
8880 xpm_valid_color_symbols_p (color_symbols)
8881 Lisp_Object color_symbols;
8883 while (CONSP (color_symbols))
8885 Lisp_Object sym = XCAR (color_symbols);
8886 if (!CONSP (sym)
8887 || !STRINGP (XCAR (sym))
8888 || !STRINGP (XCDR (sym)))
8889 break;
8890 color_symbols = XCDR (color_symbols);
8893 return NILP (color_symbols);
8897 /* Value is non-zero if OBJECT is a valid XPM image specification. */
8899 static int
8900 xpm_image_p (object)
8901 Lisp_Object object;
8903 struct image_keyword fmt[XPM_LAST];
8904 bcopy (xpm_format, fmt, sizeof fmt);
8905 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
8906 /* Either `:file' or `:data' must be present. */
8907 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
8908 /* Either no `:color-symbols' or it's a list of conses
8909 whose car and cdr are strings. */
8910 && (fmt[XPM_COLOR_SYMBOLS].count == 0
8911 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
8912 && (fmt[XPM_ASCENT].count == 0
8913 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
8917 /* Load image IMG which will be displayed on frame F. Value is
8918 non-zero if successful. */
8920 static int
8921 xpm_load (f, img)
8922 struct frame *f;
8923 struct image *img;
8925 int rc, i;
8926 XpmAttributes attrs;
8927 Lisp_Object specified_file, color_symbols;
8929 /* Configure the XPM lib. Use the visual of frame F. Allocate
8930 close colors. Return colors allocated. */
8931 bzero (&attrs, sizeof attrs);
8932 attrs.visual = FRAME_X_VISUAL (f);
8933 attrs.colormap = FRAME_X_COLORMAP (f);
8934 attrs.valuemask |= XpmVisual;
8935 attrs.valuemask |= XpmColormap;
8936 attrs.valuemask |= XpmReturnAllocPixels;
8937 #ifdef XpmAllocCloseColors
8938 attrs.alloc_close_colors = 1;
8939 attrs.valuemask |= XpmAllocCloseColors;
8940 #else
8941 attrs.closeness = 600;
8942 attrs.valuemask |= XpmCloseness;
8943 #endif
8945 /* If image specification contains symbolic color definitions, add
8946 these to `attrs'. */
8947 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
8948 if (CONSP (color_symbols))
8950 Lisp_Object tail;
8951 XpmColorSymbol *xpm_syms;
8952 int i, size;
8954 attrs.valuemask |= XpmColorSymbols;
8956 /* Count number of symbols. */
8957 attrs.numsymbols = 0;
8958 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
8959 ++attrs.numsymbols;
8961 /* Allocate an XpmColorSymbol array. */
8962 size = attrs.numsymbols * sizeof *xpm_syms;
8963 xpm_syms = (XpmColorSymbol *) alloca (size);
8964 bzero (xpm_syms, size);
8965 attrs.colorsymbols = xpm_syms;
8967 /* Fill the color symbol array. */
8968 for (tail = color_symbols, i = 0;
8969 CONSP (tail);
8970 ++i, tail = XCDR (tail))
8972 Lisp_Object name = XCAR (XCAR (tail));
8973 Lisp_Object color = XCDR (XCAR (tail));
8974 xpm_syms[i].name = (char *) alloca (XSTRING (name)->size + 1);
8975 strcpy (xpm_syms[i].name, XSTRING (name)->data);
8976 xpm_syms[i].value = (char *) alloca (XSTRING (color)->size + 1);
8977 strcpy (xpm_syms[i].value, XSTRING (color)->data);
8981 /* Create a pixmap for the image, either from a file, or from a
8982 string buffer containing data in the same format as an XPM file. */
8983 BLOCK_INPUT;
8984 specified_file = image_spec_value (img->spec, QCfile, NULL);
8985 if (STRINGP (specified_file))
8987 Lisp_Object file = x_find_image_file (specified_file);
8988 if (!STRINGP (file))
8990 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8991 UNBLOCK_INPUT;
8992 return 0;
8995 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
8996 XSTRING (file)->data, &img->pixmap, &img->mask,
8997 &attrs);
8999 else
9001 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
9002 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
9003 XSTRING (buffer)->data,
9004 &img->pixmap, &img->mask,
9005 &attrs);
9007 UNBLOCK_INPUT;
9009 if (rc == XpmSuccess)
9011 /* Remember allocated colors. */
9012 img->ncolors = attrs.nalloc_pixels;
9013 img->colors = (unsigned long *) xmalloc (img->ncolors
9014 * sizeof *img->colors);
9015 for (i = 0; i < attrs.nalloc_pixels; ++i)
9016 img->colors[i] = attrs.alloc_pixels[i];
9018 img->width = attrs.width;
9019 img->height = attrs.height;
9020 xassert (img->width > 0 && img->height > 0);
9022 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
9023 BLOCK_INPUT;
9024 XpmFreeAttributes (&attrs);
9025 UNBLOCK_INPUT;
9027 else
9029 switch (rc)
9031 case XpmOpenFailed:
9032 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9033 break;
9035 case XpmFileInvalid:
9036 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9037 break;
9039 case XpmNoMemory:
9040 image_error ("Out of memory (%s)", img->spec, Qnil);
9041 break;
9043 case XpmColorFailed:
9044 image_error ("Color allocation error (%s)", img->spec, Qnil);
9045 break;
9047 default:
9048 image_error ("Unknown error (%s)", img->spec, Qnil);
9049 break;
9053 return rc == XpmSuccess;
9056 #endif /* HAVE_XPM != 0 */
9059 #if 0 /* NTEMACS_TODO : Color tables on W32. */
9060 /***********************************************************************
9061 Color table
9062 ***********************************************************************/
9064 /* An entry in the color table mapping an RGB color to a pixel color. */
9066 struct ct_color
9068 int r, g, b;
9069 unsigned long pixel;
9071 /* Next in color table collision list. */
9072 struct ct_color *next;
9075 /* The bucket vector size to use. Must be prime. */
9077 #define CT_SIZE 101
9079 /* Value is a hash of the RGB color given by R, G, and B. */
9081 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9083 /* The color hash table. */
9085 struct ct_color **ct_table;
9087 /* Number of entries in the color table. */
9089 int ct_colors_allocated;
9091 /* Function prototypes. */
9093 static void init_color_table P_ ((void));
9094 static void free_color_table P_ ((void));
9095 static unsigned long *colors_in_color_table P_ ((int *n));
9096 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9097 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9100 /* Initialize the color table. */
9102 static void
9103 init_color_table ()
9105 int size = CT_SIZE * sizeof (*ct_table);
9106 ct_table = (struct ct_color **) xmalloc (size);
9107 bzero (ct_table, size);
9108 ct_colors_allocated = 0;
9112 /* Free memory associated with the color table. */
9114 static void
9115 free_color_table ()
9117 int i;
9118 struct ct_color *p, *next;
9120 for (i = 0; i < CT_SIZE; ++i)
9121 for (p = ct_table[i]; p; p = next)
9123 next = p->next;
9124 xfree (p);
9127 xfree (ct_table);
9128 ct_table = NULL;
9132 /* Value is a pixel color for RGB color R, G, B on frame F. If an
9133 entry for that color already is in the color table, return the
9134 pixel color of that entry. Otherwise, allocate a new color for R,
9135 G, B, and make an entry in the color table. */
9137 static unsigned long
9138 lookup_rgb_color (f, r, g, b)
9139 struct frame *f;
9140 int r, g, b;
9142 unsigned hash = CT_HASH_RGB (r, g, b);
9143 int i = hash % CT_SIZE;
9144 struct ct_color *p;
9146 for (p = ct_table[i]; p; p = p->next)
9147 if (p->r == r && p->g == g && p->b == b)
9148 break;
9150 if (p == NULL)
9152 COLORREF color;
9153 Colormap cmap;
9154 int rc;
9156 color = PALETTERGB (r, g, b);
9158 ++ct_colors_allocated;
9160 p = (struct ct_color *) xmalloc (sizeof *p);
9161 p->r = r;
9162 p->g = g;
9163 p->b = b;
9164 p->pixel = color;
9165 p->next = ct_table[i];
9166 ct_table[i] = p;
9169 return p->pixel;
9173 /* Look up pixel color PIXEL which is used on frame F in the color
9174 table. If not already present, allocate it. Value is PIXEL. */
9176 static unsigned long
9177 lookup_pixel_color (f, pixel)
9178 struct frame *f;
9179 unsigned long pixel;
9181 int i = pixel % CT_SIZE;
9182 struct ct_color *p;
9184 for (p = ct_table[i]; p; p = p->next)
9185 if (p->pixel == pixel)
9186 break;
9188 if (p == NULL)
9190 XColor color;
9191 Colormap cmap;
9192 int rc;
9194 BLOCK_INPUT;
9196 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9197 color.pixel = pixel;
9198 XQueryColor (NULL, cmap, &color);
9199 rc = x_alloc_nearest_color (f, cmap, &color);
9200 UNBLOCK_INPUT;
9202 if (rc)
9204 ++ct_colors_allocated;
9206 p = (struct ct_color *) xmalloc (sizeof *p);
9207 p->r = color.red;
9208 p->g = color.green;
9209 p->b = color.blue;
9210 p->pixel = pixel;
9211 p->next = ct_table[i];
9212 ct_table[i] = p;
9214 else
9215 return FRAME_FOREGROUND_PIXEL (f);
9217 return p->pixel;
9221 /* Value is a vector of all pixel colors contained in the color table,
9222 allocated via xmalloc. Set *N to the number of colors. */
9224 static unsigned long *
9225 colors_in_color_table (n)
9226 int *n;
9228 int i, j;
9229 struct ct_color *p;
9230 unsigned long *colors;
9232 if (ct_colors_allocated == 0)
9234 *n = 0;
9235 colors = NULL;
9237 else
9239 colors = (unsigned long *) xmalloc (ct_colors_allocated
9240 * sizeof *colors);
9241 *n = ct_colors_allocated;
9243 for (i = j = 0; i < CT_SIZE; ++i)
9244 for (p = ct_table[i]; p; p = p->next)
9245 colors[j++] = p->pixel;
9248 return colors;
9251 #endif /* NTEMACS_TODO */
9254 /***********************************************************************
9255 Algorithms
9256 ***********************************************************************/
9258 #if 0 /* NTEMACS_TODO : W32 versions of low level algorithms */
9259 static void x_laplace_write_row P_ ((struct frame *, long *,
9260 int, XImage *, int));
9261 static void x_laplace_read_row P_ ((struct frame *, Colormap,
9262 XColor *, int, XImage *, int));
9265 /* Fill COLORS with RGB colors from row Y of image XIMG. F is the
9266 frame we operate on, CMAP is the color-map in effect, and WIDTH is
9267 the width of one row in the image. */
9269 static void
9270 x_laplace_read_row (f, cmap, colors, width, ximg, y)
9271 struct frame *f;
9272 Colormap cmap;
9273 XColor *colors;
9274 int width;
9275 XImage *ximg;
9276 int y;
9278 int x;
9280 for (x = 0; x < width; ++x)
9281 colors[x].pixel = XGetPixel (ximg, x, y);
9283 XQueryColors (NULL, cmap, colors, width);
9287 /* Write row Y of image XIMG. PIXELS is an array of WIDTH longs
9288 containing the pixel colors to write. F is the frame we are
9289 working on. */
9291 static void
9292 x_laplace_write_row (f, pixels, width, ximg, y)
9293 struct frame *f;
9294 long *pixels;
9295 int width;
9296 XImage *ximg;
9297 int y;
9299 int x;
9301 for (x = 0; x < width; ++x)
9302 XPutPixel (ximg, x, y, pixels[x]);
9304 #endif
9306 /* Transform image IMG which is used on frame F with a Laplace
9307 edge-detection algorithm. The result is an image that can be used
9308 to draw disabled buttons, for example. */
9310 static void
9311 x_laplace (f, img)
9312 struct frame *f;
9313 struct image *img;
9315 #if 0 /* NTEMACS_TODO : W32 version */
9316 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9317 XImage *ximg, *oimg;
9318 XColor *in[3];
9319 long *out;
9320 Pixmap pixmap;
9321 int x, y, i;
9322 long pixel;
9323 int in_y, out_y, rc;
9324 int mv2 = 45000;
9326 BLOCK_INPUT;
9328 /* Get the X image IMG->pixmap. */
9329 ximg = XGetImage (NULL, img->pixmap,
9330 0, 0, img->width, img->height, ~0, ZPixmap);
9332 /* Allocate 3 input rows, and one output row of colors. */
9333 for (i = 0; i < 3; ++i)
9334 in[i] = (XColor *) alloca (img->width * sizeof (XColor));
9335 out = (long *) alloca (img->width * sizeof (long));
9337 /* Create an X image for output. */
9338 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9339 &oimg, &pixmap);
9341 /* Fill first two rows. */
9342 x_laplace_read_row (f, cmap, in[0], img->width, ximg, 0);
9343 x_laplace_read_row (f, cmap, in[1], img->width, ximg, 1);
9344 in_y = 2;
9346 /* Write first row, all zeros. */
9347 init_color_table ();
9348 pixel = lookup_rgb_color (f, 0, 0, 0);
9349 for (x = 0; x < img->width; ++x)
9350 out[x] = pixel;
9351 x_laplace_write_row (f, out, img->width, oimg, 0);
9352 out_y = 1;
9354 for (y = 2; y < img->height; ++y)
9356 int rowa = y % 3;
9357 int rowb = (y + 2) % 3;
9359 x_laplace_read_row (f, cmap, in[rowa], img->width, ximg, in_y++);
9361 for (x = 0; x < img->width - 2; ++x)
9363 int r = in[rowa][x].red + mv2 - in[rowb][x + 2].red;
9364 int g = in[rowa][x].green + mv2 - in[rowb][x + 2].green;
9365 int b = in[rowa][x].blue + mv2 - in[rowb][x + 2].blue;
9367 out[x + 1] = lookup_rgb_color (f, r & 0xffff, g & 0xffff,
9368 b & 0xffff);
9371 x_laplace_write_row (f, out, img->width, oimg, out_y++);
9374 /* Write last line, all zeros. */
9375 for (x = 0; x < img->width; ++x)
9376 out[x] = pixel;
9377 x_laplace_write_row (f, out, img->width, oimg, out_y);
9379 /* Free the input image, and free resources of IMG. */
9380 XDestroyImage (ximg);
9381 x_clear_image (f, img);
9383 /* Put the output image into pixmap, and destroy it. */
9384 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9385 x_destroy_x_image (oimg);
9387 /* Remember new pixmap and colors in IMG. */
9388 img->pixmap = pixmap;
9389 img->colors = colors_in_color_table (&img->ncolors);
9390 free_color_table ();
9392 UNBLOCK_INPUT;
9393 #endif /* NTEMACS_TODO */
9397 /* Build a mask for image IMG which is used on frame F. FILE is the
9398 name of an image file, for error messages. HOW determines how to
9399 determine the background color of IMG. If it is a list '(R G B)',
9400 with R, G, and B being integers >= 0, take that as the color of the
9401 background. Otherwise, determine the background color of IMG
9402 heuristically. Value is non-zero if successful. */
9404 static int
9405 x_build_heuristic_mask (f, img, how)
9406 struct frame *f;
9407 struct image *img;
9408 Lisp_Object how;
9410 #if 0 /* NTEMACS_TODO : W32 version */
9411 Display *dpy = FRAME_W32_DISPLAY (f);
9412 XImage *ximg, *mask_img;
9413 int x, y, rc, look_at_corners_p;
9414 unsigned long bg;
9416 BLOCK_INPUT;
9418 /* Create an image and pixmap serving as mask. */
9419 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
9420 &mask_img, &img->mask);
9421 if (!rc)
9423 UNBLOCK_INPUT;
9424 return 0;
9427 /* Get the X image of IMG->pixmap. */
9428 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
9429 ~0, ZPixmap);
9431 /* Determine the background color of ximg. If HOW is `(R G B)'
9432 take that as color. Otherwise, try to determine the color
9433 heuristically. */
9434 look_at_corners_p = 1;
9436 if (CONSP (how))
9438 int rgb[3], i = 0;
9440 while (i < 3
9441 && CONSP (how)
9442 && NATNUMP (XCAR (how)))
9444 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9445 how = XCDR (how);
9448 if (i == 3 && NILP (how))
9450 char color_name[30];
9451 XColor exact, color;
9452 Colormap cmap;
9454 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
9456 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9457 if (XLookupColor (dpy, cmap, color_name, &exact, &color))
9459 bg = color.pixel;
9460 look_at_corners_p = 0;
9465 if (look_at_corners_p)
9467 unsigned long corners[4];
9468 int i, best_count;
9470 /* Get the colors at the corners of ximg. */
9471 corners[0] = XGetPixel (ximg, 0, 0);
9472 corners[1] = XGetPixel (ximg, img->width - 1, 0);
9473 corners[2] = XGetPixel (ximg, img->width - 1, img->height - 1);
9474 corners[3] = XGetPixel (ximg, 0, img->height - 1);
9476 /* Choose the most frequently found color as background. */
9477 for (i = best_count = 0; i < 4; ++i)
9479 int j, n;
9481 for (j = n = 0; j < 4; ++j)
9482 if (corners[i] == corners[j])
9483 ++n;
9485 if (n > best_count)
9486 bg = corners[i], best_count = n;
9490 /* Set all bits in mask_img to 1 whose color in ximg is different
9491 from the background color bg. */
9492 for (y = 0; y < img->height; ++y)
9493 for (x = 0; x < img->width; ++x)
9494 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
9496 /* Put mask_img into img->mask. */
9497 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
9498 x_destroy_x_image (mask_img);
9499 XDestroyImage (ximg);
9501 UNBLOCK_INPUT;
9502 #endif /* NTEMACS_TODO */
9504 return 1;
9509 /***********************************************************************
9510 PBM (mono, gray, color)
9511 ***********************************************************************/
9512 #ifdef HAVE_PBM
9514 static int pbm_image_p P_ ((Lisp_Object object));
9515 static int pbm_load P_ ((struct frame *f, struct image *img));
9516 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
9518 /* The symbol `pbm' identifying images of this type. */
9520 Lisp_Object Qpbm;
9522 /* Indices of image specification fields in gs_format, below. */
9524 enum pbm_keyword_index
9526 PBM_TYPE,
9527 PBM_FILE,
9528 PBM_DATA,
9529 PBM_ASCENT,
9530 PBM_MARGIN,
9531 PBM_RELIEF,
9532 PBM_ALGORITHM,
9533 PBM_HEURISTIC_MASK,
9534 PBM_LAST
9537 /* Vector of image_keyword structures describing the format
9538 of valid user-defined image specifications. */
9540 static struct image_keyword pbm_format[PBM_LAST] =
9542 {":type", IMAGE_SYMBOL_VALUE, 1},
9543 {":file", IMAGE_STRING_VALUE, 0},
9544 {":data", IMAGE_STRING_VALUE, 0},
9545 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9546 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9547 {":relief", IMAGE_INTEGER_VALUE, 0},
9548 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9549 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9552 /* Structure describing the image type `pbm'. */
9554 static struct image_type pbm_type =
9556 &Qpbm,
9557 pbm_image_p,
9558 pbm_load,
9559 x_clear_image,
9560 NULL
9564 /* Return non-zero if OBJECT is a valid PBM image specification. */
9566 static int
9567 pbm_image_p (object)
9568 Lisp_Object object;
9570 struct image_keyword fmt[PBM_LAST];
9572 bcopy (pbm_format, fmt, sizeof fmt);
9574 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
9575 || (fmt[PBM_ASCENT].count
9576 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
9577 return 0;
9579 /* Must specify either :data or :file. */
9580 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
9584 /* Scan a decimal number from *S and return it. Advance *S while
9585 reading the number. END is the end of the string. Value is -1 at
9586 end of input. */
9588 static int
9589 pbm_scan_number (s, end)
9590 unsigned char **s, *end;
9592 int c, val = -1;
9594 while (*s < end)
9596 /* Skip white-space. */
9597 while (*s < end && (c = *(*s)++, isspace (c)))
9600 if (c == '#')
9602 /* Skip comment to end of line. */
9603 while (*s < end && (c = *(*s)++, c != '\n'))
9606 else if (isdigit (c))
9608 /* Read decimal number. */
9609 val = c - '0';
9610 while (*s < end && (c = *(*s)++, isdigit (c)))
9611 val = 10 * val + c - '0';
9612 break;
9614 else
9615 break;
9618 return val;
9622 /* Read FILE into memory. Value is a pointer to a buffer allocated
9623 with xmalloc holding FILE's contents. Value is null if an error
9624 occured. *SIZE is set to the size of the file. */
9626 static char *
9627 pbm_read_file (file, size)
9628 Lisp_Object file;
9629 int *size;
9631 FILE *fp = NULL;
9632 char *buf = NULL;
9633 struct stat st;
9635 if (stat (XSTRING (file)->data, &st) == 0
9636 && (fp = fopen (XSTRING (file)->data, "r")) != NULL
9637 && (buf = (char *) xmalloc (st.st_size),
9638 fread (buf, 1, st.st_size, fp) == st.st_size))
9640 *size = st.st_size;
9641 fclose (fp);
9643 else
9645 if (fp)
9646 fclose (fp);
9647 if (buf)
9649 xfree (buf);
9650 buf = NULL;
9654 return buf;
9658 /* Load PBM image IMG for use on frame F. */
9660 static int
9661 pbm_load (f, img)
9662 struct frame *f;
9663 struct image *img;
9665 int raw_p, x, y;
9666 int width, height, max_color_idx = 0;
9667 XImage *ximg;
9668 Lisp_Object file, specified_file;
9669 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
9670 struct gcpro gcpro1;
9671 unsigned char *contents = NULL;
9672 unsigned char *end, *p;
9673 int size;
9675 specified_file = image_spec_value (img->spec, QCfile, NULL);
9676 file = Qnil;
9677 GCPRO1 (file);
9679 if (STRINGP (specified_file))
9681 file = x_find_image_file (specified_file);
9682 if (!STRINGP (file))
9684 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9685 UNGCPRO;
9686 return 0;
9689 contents = pbm_read_file (file, &size);
9690 if (contents == NULL)
9692 image_error ("Error reading `%s'", file, Qnil);
9693 UNGCPRO;
9694 return 0;
9697 p = contents;
9698 end = contents + size;
9700 else
9702 Lisp_Object data;
9703 data = image_spec_value (img->spec, QCdata, NULL);
9704 p = XSTRING (data)->data;
9705 end = p + STRING_BYTES (XSTRING (data));
9708 /* Check magic number. */
9709 if (end - p < 2 || *p++ != 'P')
9711 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
9712 error:
9713 xfree (contents);
9714 UNGCPRO;
9715 return 0;
9718 switch (*p++)
9720 case '1':
9721 raw_p = 0, type = PBM_MONO;
9722 break;
9724 case '2':
9725 raw_p = 0, type = PBM_GRAY;
9726 break;
9728 case '3':
9729 raw_p = 0, type = PBM_COLOR;
9730 break;
9732 case '4':
9733 raw_p = 1, type = PBM_MONO;
9734 break;
9736 case '5':
9737 raw_p = 1, type = PBM_GRAY;
9738 break;
9740 case '6':
9741 raw_p = 1, type = PBM_COLOR;
9742 break;
9744 default:
9745 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
9746 goto error;
9749 /* Read width, height, maximum color-component. Characters
9750 starting with `#' up to the end of a line are ignored. */
9751 width = pbm_scan_number (&p, end);
9752 height = pbm_scan_number (&p, end);
9754 if (type != PBM_MONO)
9756 max_color_idx = pbm_scan_number (&p, end);
9757 if (raw_p && max_color_idx > 255)
9758 max_color_idx = 255;
9761 if (width < 0
9762 || height < 0
9763 || (type != PBM_MONO && max_color_idx < 0))
9764 goto error;
9766 BLOCK_INPUT;
9767 if (!x_create_x_image_and_pixmap (f, width, height, 0,
9768 &ximg, &img->pixmap))
9770 UNBLOCK_INPUT;
9771 goto error;
9774 /* Initialize the color hash table. */
9775 init_color_table ();
9777 if (type == PBM_MONO)
9779 int c = 0, g;
9781 for (y = 0; y < height; ++y)
9782 for (x = 0; x < width; ++x)
9784 if (raw_p)
9786 if ((x & 7) == 0)
9787 c = *p++;
9788 g = c & 0x80;
9789 c <<= 1;
9791 else
9792 g = pbm_scan_number (&p, end);
9794 XPutPixel (ximg, x, y, (g
9795 ? FRAME_FOREGROUND_PIXEL (f)
9796 : FRAME_BACKGROUND_PIXEL (f)));
9799 else
9801 for (y = 0; y < height; ++y)
9802 for (x = 0; x < width; ++x)
9804 int r, g, b;
9806 if (type == PBM_GRAY)
9807 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
9808 else if (raw_p)
9810 r = *p++;
9811 g = *p++;
9812 b = *p++;
9814 else
9816 r = pbm_scan_number (&p, end);
9817 g = pbm_scan_number (&p, end);
9818 b = pbm_scan_number (&p, end);
9821 if (r < 0 || g < 0 || b < 0)
9823 xfree (ximg->data);
9824 ximg->data = NULL;
9825 XDestroyImage (ximg);
9826 UNBLOCK_INPUT;
9827 image_error ("Invalid pixel value in image `%s'",
9828 img->spec, Qnil);
9829 goto error;
9832 /* RGB values are now in the range 0..max_color_idx.
9833 Scale this to the range 0..0xffff supported by X. */
9834 r = (double) r * 65535 / max_color_idx;
9835 g = (double) g * 65535 / max_color_idx;
9836 b = (double) b * 65535 / max_color_idx;
9837 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
9841 /* Store in IMG->colors the colors allocated for the image, and
9842 free the color table. */
9843 img->colors = colors_in_color_table (&img->ncolors);
9844 free_color_table ();
9846 /* Put the image into a pixmap. */
9847 x_put_x_image (f, ximg, img->pixmap, width, height);
9848 x_destroy_x_image (ximg);
9849 UNBLOCK_INPUT;
9851 img->width = width;
9852 img->height = height;
9854 UNGCPRO;
9855 xfree (contents);
9856 return 1;
9858 #endif /* HAVE_PBM */
9861 /***********************************************************************
9863 ***********************************************************************/
9865 #if HAVE_PNG
9867 #include <png.h>
9869 /* Function prototypes. */
9871 static int png_image_p P_ ((Lisp_Object object));
9872 static int png_load P_ ((struct frame *f, struct image *img));
9874 /* The symbol `png' identifying images of this type. */
9876 Lisp_Object Qpng;
9878 /* Indices of image specification fields in png_format, below. */
9880 enum png_keyword_index
9882 PNG_TYPE,
9883 PNG_DATA,
9884 PNG_FILE,
9885 PNG_ASCENT,
9886 PNG_MARGIN,
9887 PNG_RELIEF,
9888 PNG_ALGORITHM,
9889 PNG_HEURISTIC_MASK,
9890 PNG_LAST
9893 /* Vector of image_keyword structures describing the format
9894 of valid user-defined image specifications. */
9896 static struct image_keyword png_format[PNG_LAST] =
9898 {":type", IMAGE_SYMBOL_VALUE, 1},
9899 {":data", IMAGE_STRING_VALUE, 0},
9900 {":file", IMAGE_STRING_VALUE, 0},
9901 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9902 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9903 {":relief", IMAGE_INTEGER_VALUE, 0},
9904 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9905 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9908 /* Structure describing the image type `png'. */
9910 static struct image_type png_type =
9912 &Qpng,
9913 png_image_p,
9914 png_load,
9915 x_clear_image,
9916 NULL
9920 /* Return non-zero if OBJECT is a valid PNG image specification. */
9922 static int
9923 png_image_p (object)
9924 Lisp_Object object;
9926 struct image_keyword fmt[PNG_LAST];
9927 bcopy (png_format, fmt, sizeof fmt);
9929 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
9930 || (fmt[PNG_ASCENT].count
9931 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
9932 return 0;
9934 /* Must specify either the :data or :file keyword. */
9935 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
9939 /* Error and warning handlers installed when the PNG library
9940 is initialized. */
9942 static void
9943 my_png_error (png_ptr, msg)
9944 png_struct *png_ptr;
9945 char *msg;
9947 xassert (png_ptr != NULL);
9948 image_error ("PNG error: %s", build_string (msg), Qnil);
9949 longjmp (png_ptr->jmpbuf, 1);
9953 static void
9954 my_png_warning (png_ptr, msg)
9955 png_struct *png_ptr;
9956 char *msg;
9958 xassert (png_ptr != NULL);
9959 image_error ("PNG warning: %s", build_string (msg), Qnil);
9962 /* Memory source for PNG decoding. */
9964 struct png_memory_storage
9966 unsigned char *bytes; /* The data */
9967 size_t len; /* How big is it? */
9968 int index; /* Where are we? */
9972 /* Function set as reader function when reading PNG image from memory.
9973 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
9974 bytes from the input to DATA. */
9976 static void
9977 png_read_from_memory (png_ptr, data, length)
9978 png_structp png_ptr;
9979 png_bytep data;
9980 png_size_t length;
9982 struct png_memory_storage *tbr
9983 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
9985 if (length > tbr->len - tbr->index)
9986 png_error (png_ptr, "Read error");
9988 bcopy (tbr->bytes + tbr->index, data, length);
9989 tbr->index = tbr->index + length;
9992 /* Load PNG image IMG for use on frame F. Value is non-zero if
9993 successful. */
9995 static int
9996 png_load (f, img)
9997 struct frame *f;
9998 struct image *img;
10000 Lisp_Object file, specified_file;
10001 Lisp_Object specified_data;
10002 int x, y, i;
10003 XImage *ximg, *mask_img = NULL;
10004 struct gcpro gcpro1;
10005 png_struct *png_ptr = NULL;
10006 png_info *info_ptr = NULL, *end_info = NULL;
10007 FILE *fp = NULL;
10008 png_byte sig[8];
10009 png_byte *pixels = NULL;
10010 png_byte **rows = NULL;
10011 png_uint_32 width, height;
10012 int bit_depth, color_type, interlace_type;
10013 png_byte channels;
10014 png_uint_32 row_bytes;
10015 int transparent_p;
10016 char *gamma_str;
10017 double screen_gamma, image_gamma;
10018 int intent;
10019 struct png_memory_storage tbr; /* Data to be read */
10021 /* Find out what file to load. */
10022 specified_file = image_spec_value (img->spec, QCfile, NULL);
10023 specified_data = image_spec_value (img->spec, QCdata, NULL);
10024 file = Qnil;
10025 GCPRO1 (file);
10027 if (NILP (specified_data))
10029 file = x_find_image_file (specified_file);
10030 if (!STRINGP (file))
10032 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10033 UNGCPRO;
10034 return 0;
10037 /* Open the image file. */
10038 fp = fopen (XSTRING (file)->data, "rb");
10039 if (!fp)
10041 image_error ("Cannot open image file `%s'", file, Qnil);
10042 UNGCPRO;
10043 fclose (fp);
10044 return 0;
10047 /* Check PNG signature. */
10048 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
10049 || !png_check_sig (sig, sizeof sig))
10051 image_error ("Not a PNG file:` %s'", file, Qnil);
10052 UNGCPRO;
10053 fclose (fp);
10054 return 0;
10057 else
10059 /* Read from memory. */
10060 tbr.bytes = XSTRING (specified_data)->data;
10061 tbr.len = STRING_BYTES (XSTRING (specified_data));
10062 tbr.index = 0;
10064 /* Check PNG signature. */
10065 if (tbr.len < sizeof sig
10066 || !png_check_sig (tbr.bytes, sizeof sig))
10068 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10069 UNGCPRO;
10070 return 0;
10073 /* Need to skip past the signature. */
10074 tbr.bytes += sizeof (sig);
10077 /* Initialize read and info structs for PNG lib. */
10078 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10079 my_png_error, my_png_warning);
10080 if (!png_ptr)
10082 if (fp) fclose (fp);
10083 UNGCPRO;
10084 return 0;
10087 info_ptr = png_create_info_struct (png_ptr);
10088 if (!info_ptr)
10090 png_destroy_read_struct (&png_ptr, NULL, NULL);
10091 if (fp) fclose (fp);
10092 UNGCPRO;
10093 return 0;
10096 end_info = png_create_info_struct (png_ptr);
10097 if (!end_info)
10099 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
10100 if (fp) fclose (fp);
10101 UNGCPRO;
10102 return 0;
10105 /* Set error jump-back. We come back here when the PNG library
10106 detects an error. */
10107 if (setjmp (png_ptr->jmpbuf))
10109 error:
10110 if (png_ptr)
10111 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10112 xfree (pixels);
10113 xfree (rows);
10114 if (fp) fclose (fp);
10115 UNGCPRO;
10116 return 0;
10119 /* Read image info. */
10120 if (!NILP (specified_data))
10121 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
10122 else
10123 png_init_io (png_ptr, fp);
10125 png_set_sig_bytes (png_ptr, sizeof sig);
10126 png_read_info (png_ptr, info_ptr);
10127 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10128 &interlace_type, NULL, NULL);
10130 /* If image contains simply transparency data, we prefer to
10131 construct a clipping mask. */
10132 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
10133 transparent_p = 1;
10134 else
10135 transparent_p = 0;
10137 /* This function is easier to write if we only have to handle
10138 one data format: RGB or RGBA with 8 bits per channel. Let's
10139 transform other formats into that format. */
10141 /* Strip more than 8 bits per channel. */
10142 if (bit_depth == 16)
10143 png_set_strip_16 (png_ptr);
10145 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10146 if available. */
10147 png_set_expand (png_ptr);
10149 /* Convert grayscale images to RGB. */
10150 if (color_type == PNG_COLOR_TYPE_GRAY
10151 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
10152 png_set_gray_to_rgb (png_ptr);
10154 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
10155 gamma_str = getenv ("SCREEN_GAMMA");
10156 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
10158 /* Tell the PNG lib to handle gamma correction for us. */
10160 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10161 if (png_get_sRGB (png_ptr, info_ptr, &intent))
10162 /* There is a special chunk in the image specifying the gamma. */
10163 png_set_sRGB (png_ptr, info_ptr, intent);
10164 else
10165 #endif
10166 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10167 /* Image contains gamma information. */
10168 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10169 else
10170 /* Use a default of 0.5 for the image gamma. */
10171 png_set_gamma (png_ptr, screen_gamma, 0.5);
10173 /* Handle alpha channel by combining the image with a background
10174 color. Do this only if a real alpha channel is supplied. For
10175 simple transparency, we prefer a clipping mask. */
10176 if (!transparent_p)
10178 png_color_16 *image_background;
10180 if (png_get_bKGD (png_ptr, info_ptr, &image_background))
10181 /* Image contains a background color with which to
10182 combine the image. */
10183 png_set_background (png_ptr, image_background,
10184 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
10185 else
10187 /* Image does not contain a background color with which
10188 to combine the image data via an alpha channel. Use
10189 the frame's background instead. */
10190 XColor color;
10191 Colormap cmap;
10192 png_color_16 frame_background;
10194 BLOCK_INPUT;
10195 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10196 color.pixel = FRAME_BACKGROUND_PIXEL (f);
10197 XQueryColor (FRAME_W32_DISPLAY (f), cmap, &color);
10198 UNBLOCK_INPUT;
10200 bzero (&frame_background, sizeof frame_background);
10201 frame_background.red = color.red;
10202 frame_background.green = color.green;
10203 frame_background.blue = color.blue;
10205 png_set_background (png_ptr, &frame_background,
10206 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10210 /* Update info structure. */
10211 png_read_update_info (png_ptr, info_ptr);
10213 /* Get number of channels. Valid values are 1 for grayscale images
10214 and images with a palette, 2 for grayscale images with transparency
10215 information (alpha channel), 3 for RGB images, and 4 for RGB
10216 images with alpha channel, i.e. RGBA. If conversions above were
10217 sufficient we should only have 3 or 4 channels here. */
10218 channels = png_get_channels (png_ptr, info_ptr);
10219 xassert (channels == 3 || channels == 4);
10221 /* Number of bytes needed for one row of the image. */
10222 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
10224 /* Allocate memory for the image. */
10225 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10226 rows = (png_byte **) xmalloc (height * sizeof *rows);
10227 for (i = 0; i < height; ++i)
10228 rows[i] = pixels + i * row_bytes;
10230 /* Read the entire image. */
10231 png_read_image (png_ptr, rows);
10232 png_read_end (png_ptr, info_ptr);
10233 if (fp)
10235 fclose (fp);
10236 fp = NULL;
10239 BLOCK_INPUT;
10241 /* Create the X image and pixmap. */
10242 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10243 &img->pixmap))
10245 UNBLOCK_INPUT;
10246 goto error;
10249 /* Create an image and pixmap serving as mask if the PNG image
10250 contains an alpha channel. */
10251 if (channels == 4
10252 && !transparent_p
10253 && !x_create_x_image_and_pixmap (f, width, height, 1,
10254 &mask_img, &img->mask))
10256 x_destroy_x_image (ximg);
10257 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
10258 img->pixmap = 0;
10259 UNBLOCK_INPUT;
10260 goto error;
10263 /* Fill the X image and mask from PNG data. */
10264 init_color_table ();
10266 for (y = 0; y < height; ++y)
10268 png_byte *p = rows[y];
10270 for (x = 0; x < width; ++x)
10272 unsigned r, g, b;
10274 r = *p++ << 8;
10275 g = *p++ << 8;
10276 b = *p++ << 8;
10277 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10279 /* An alpha channel, aka mask channel, associates variable
10280 transparency with an image. Where other image formats
10281 support binary transparency---fully transparent or fully
10282 opaque---PNG allows up to 254 levels of partial transparency.
10283 The PNG library implements partial transparency by combining
10284 the image with a specified background color.
10286 I'm not sure how to handle this here nicely: because the
10287 background on which the image is displayed may change, for
10288 real alpha channel support, it would be necessary to create
10289 a new image for each possible background.
10291 What I'm doing now is that a mask is created if we have
10292 boolean transparency information. Otherwise I'm using
10293 the frame's background color to combine the image with. */
10295 if (channels == 4)
10297 if (mask_img)
10298 XPutPixel (mask_img, x, y, *p > 0);
10299 ++p;
10304 /* Remember colors allocated for this image. */
10305 img->colors = colors_in_color_table (&img->ncolors);
10306 free_color_table ();
10308 /* Clean up. */
10309 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10310 xfree (rows);
10311 xfree (pixels);
10313 img->width = width;
10314 img->height = height;
10316 /* Put the image into the pixmap, then free the X image and its buffer. */
10317 x_put_x_image (f, ximg, img->pixmap, width, height);
10318 x_destroy_x_image (ximg);
10320 /* Same for the mask. */
10321 if (mask_img)
10323 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10324 x_destroy_x_image (mask_img);
10327 UNBLOCK_INPUT;
10328 UNGCPRO;
10329 return 1;
10332 #endif /* HAVE_PNG != 0 */
10336 /***********************************************************************
10337 JPEG
10338 ***********************************************************************/
10340 #if HAVE_JPEG
10342 /* Work around a warning about HAVE_STDLIB_H being redefined in
10343 jconfig.h. */
10344 #ifdef HAVE_STDLIB_H
10345 #define HAVE_STDLIB_H_1
10346 #undef HAVE_STDLIB_H
10347 #endif /* HAVE_STLIB_H */
10349 #include <jpeglib.h>
10350 #include <jerror.h>
10351 #include <setjmp.h>
10353 #ifdef HAVE_STLIB_H_1
10354 #define HAVE_STDLIB_H 1
10355 #endif
10357 static int jpeg_image_p P_ ((Lisp_Object object));
10358 static int jpeg_load P_ ((struct frame *f, struct image *img));
10360 /* The symbol `jpeg' identifying images of this type. */
10362 Lisp_Object Qjpeg;
10364 /* Indices of image specification fields in gs_format, below. */
10366 enum jpeg_keyword_index
10368 JPEG_TYPE,
10369 JPEG_DATA,
10370 JPEG_FILE,
10371 JPEG_ASCENT,
10372 JPEG_MARGIN,
10373 JPEG_RELIEF,
10374 JPEG_ALGORITHM,
10375 JPEG_HEURISTIC_MASK,
10376 JPEG_LAST
10379 /* Vector of image_keyword structures describing the format
10380 of valid user-defined image specifications. */
10382 static struct image_keyword jpeg_format[JPEG_LAST] =
10384 {":type", IMAGE_SYMBOL_VALUE, 1},
10385 {":data", IMAGE_STRING_VALUE, 0},
10386 {":file", IMAGE_STRING_VALUE, 0},
10387 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10388 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10389 {":relief", IMAGE_INTEGER_VALUE, 0},
10390 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10391 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10394 /* Structure describing the image type `jpeg'. */
10396 static struct image_type jpeg_type =
10398 &Qjpeg,
10399 jpeg_image_p,
10400 jpeg_load,
10401 x_clear_image,
10402 NULL
10406 /* Return non-zero if OBJECT is a valid JPEG image specification. */
10408 static int
10409 jpeg_image_p (object)
10410 Lisp_Object object;
10412 struct image_keyword fmt[JPEG_LAST];
10414 bcopy (jpeg_format, fmt, sizeof fmt);
10416 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
10417 || (fmt[JPEG_ASCENT].count
10418 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
10419 return 0;
10421 /* Must specify either the :data or :file keyword. */
10422 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
10426 struct my_jpeg_error_mgr
10428 struct jpeg_error_mgr pub;
10429 jmp_buf setjmp_buffer;
10432 static void
10433 my_error_exit (cinfo)
10434 j_common_ptr cinfo;
10436 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
10437 longjmp (mgr->setjmp_buffer, 1);
10440 /* Init source method for JPEG data source manager. Called by
10441 jpeg_read_header() before any data is actually read. See
10442 libjpeg.doc from the JPEG lib distribution. */
10444 static void
10445 our_init_source (cinfo)
10446 j_decompress_ptr cinfo;
10451 /* Fill input buffer method for JPEG data source manager. Called
10452 whenever more data is needed. We read the whole image in one step,
10453 so this only adds a fake end of input marker at the end. */
10455 static boolean
10456 our_fill_input_buffer (cinfo)
10457 j_decompress_ptr cinfo;
10459 /* Insert a fake EOI marker. */
10460 struct jpeg_source_mgr *src = cinfo->src;
10461 static JOCTET buffer[2];
10463 buffer[0] = (JOCTET) 0xFF;
10464 buffer[1] = (JOCTET) JPEG_EOI;
10466 src->next_input_byte = buffer;
10467 src->bytes_in_buffer = 2;
10468 return TRUE;
10472 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
10473 is the JPEG data source manager. */
10475 static void
10476 our_skip_input_data (cinfo, num_bytes)
10477 j_decompress_ptr cinfo;
10478 long num_bytes;
10480 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
10482 if (src)
10484 if (num_bytes > src->bytes_in_buffer)
10485 ERREXIT (cinfo, JERR_INPUT_EOF);
10487 src->bytes_in_buffer -= num_bytes;
10488 src->next_input_byte += num_bytes;
10493 /* Method to terminate data source. Called by
10494 jpeg_finish_decompress() after all data has been processed. */
10496 static void
10497 our_term_source (cinfo)
10498 j_decompress_ptr cinfo;
10503 /* Set up the JPEG lib for reading an image from DATA which contains
10504 LEN bytes. CINFO is the decompression info structure created for
10505 reading the image. */
10507 static void
10508 jpeg_memory_src (cinfo, data, len)
10509 j_decompress_ptr cinfo;
10510 JOCTET *data;
10511 unsigned int len;
10513 struct jpeg_source_mgr *src;
10515 if (cinfo->src == NULL)
10517 /* First time for this JPEG object? */
10518 cinfo->src = (struct jpeg_source_mgr *)
10519 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
10520 sizeof (struct jpeg_source_mgr));
10521 src = (struct jpeg_source_mgr *) cinfo->src;
10522 src->next_input_byte = data;
10525 src = (struct jpeg_source_mgr *) cinfo->src;
10526 src->init_source = our_init_source;
10527 src->fill_input_buffer = our_fill_input_buffer;
10528 src->skip_input_data = our_skip_input_data;
10529 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
10530 src->term_source = our_term_source;
10531 src->bytes_in_buffer = len;
10532 src->next_input_byte = data;
10536 /* Load image IMG for use on frame F. Patterned after example.c
10537 from the JPEG lib. */
10539 static int
10540 jpeg_load (f, img)
10541 struct frame *f;
10542 struct image *img;
10544 struct jpeg_decompress_struct cinfo;
10545 struct my_jpeg_error_mgr mgr;
10546 Lisp_Object file, specified_file;
10547 Lisp_Object specified_data;
10548 FILE *fp = NULL;
10549 JSAMPARRAY buffer;
10550 int row_stride, x, y;
10551 XImage *ximg = NULL;
10552 int rc;
10553 unsigned long *colors;
10554 int width, height;
10555 struct gcpro gcpro1;
10557 /* Open the JPEG file. */
10558 specified_file = image_spec_value (img->spec, QCfile, NULL);
10559 specified_data = image_spec_value (img->spec, QCdata, NULL);
10560 file = Qnil;
10561 GCPRO1 (file);
10563 if (NILP (specified_data))
10565 file = x_find_image_file (specified_file);
10566 if (!STRINGP (file))
10568 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10569 UNGCPRO;
10570 return 0;
10573 fp = fopen (XSTRING (file)->data, "r");
10574 if (fp == NULL)
10576 image_error ("Cannot open `%s'", file, Qnil);
10577 UNGCPRO;
10578 return 0;
10582 /* Customize libjpeg's error handling to call my_error_exit when an
10583 error is detected. This function will perform a longjmp. */
10584 mgr.pub.error_exit = my_error_exit;
10585 cinfo.err = jpeg_std_error (&mgr.pub);
10587 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
10589 if (rc == 1)
10591 /* Called from my_error_exit. Display a JPEG error. */
10592 char buffer[JMSG_LENGTH_MAX];
10593 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
10594 image_error ("Error reading JPEG image `%s': %s", img->spec,
10595 build_string (buffer));
10598 /* Close the input file and destroy the JPEG object. */
10599 if (fp)
10600 fclose (fp);
10601 jpeg_destroy_decompress (&cinfo);
10603 BLOCK_INPUT;
10605 /* If we already have an XImage, free that. */
10606 x_destroy_x_image (ximg);
10608 /* Free pixmap and colors. */
10609 x_clear_image (f, img);
10611 UNBLOCK_INPUT;
10612 UNGCPRO;
10613 return 0;
10616 /* Create the JPEG decompression object. Let it read from fp.
10617 Read the JPEG image header. */
10618 jpeg_create_decompress (&cinfo);
10620 if (NILP (specified_data))
10621 jpeg_stdio_src (&cinfo, fp);
10622 else
10623 jpeg_memory_src (&cinfo, XSTRING (specified_data)->data,
10624 STRING_BYTES (XSTRING (specified_data)));
10626 jpeg_read_header (&cinfo, TRUE);
10628 /* Customize decompression so that color quantization will be used.
10629 Start decompression. */
10630 cinfo.quantize_colors = TRUE;
10631 jpeg_start_decompress (&cinfo);
10632 width = img->width = cinfo.output_width;
10633 height = img->height = cinfo.output_height;
10635 BLOCK_INPUT;
10637 /* Create X image and pixmap. */
10638 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10639 &img->pixmap))
10641 UNBLOCK_INPUT;
10642 longjmp (mgr.setjmp_buffer, 2);
10645 /* Allocate colors. When color quantization is used,
10646 cinfo.actual_number_of_colors has been set with the number of
10647 colors generated, and cinfo.colormap is a two-dimensional array
10648 of color indices in the range 0..cinfo.actual_number_of_colors.
10649 No more than 255 colors will be generated. */
10651 int i, ir, ig, ib;
10653 if (cinfo.out_color_components > 2)
10654 ir = 0, ig = 1, ib = 2;
10655 else if (cinfo.out_color_components > 1)
10656 ir = 0, ig = 1, ib = 0;
10657 else
10658 ir = 0, ig = 0, ib = 0;
10660 /* Use the color table mechanism because it handles colors that
10661 cannot be allocated nicely. Such colors will be replaced with
10662 a default color, and we don't have to care about which colors
10663 can be freed safely, and which can't. */
10664 init_color_table ();
10665 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
10666 * sizeof *colors);
10668 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
10670 /* Multiply RGB values with 255 because X expects RGB values
10671 in the range 0..0xffff. */
10672 int r = cinfo.colormap[ir][i] << 8;
10673 int g = cinfo.colormap[ig][i] << 8;
10674 int b = cinfo.colormap[ib][i] << 8;
10675 colors[i] = lookup_rgb_color (f, r, g, b);
10678 /* Remember those colors actually allocated. */
10679 img->colors = colors_in_color_table (&img->ncolors);
10680 free_color_table ();
10683 /* Read pixels. */
10684 row_stride = width * cinfo.output_components;
10685 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
10686 row_stride, 1);
10687 for (y = 0; y < height; ++y)
10689 jpeg_read_scanlines (&cinfo, buffer, 1);
10690 for (x = 0; x < cinfo.output_width; ++x)
10691 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
10694 /* Clean up. */
10695 jpeg_finish_decompress (&cinfo);
10696 jpeg_destroy_decompress (&cinfo);
10697 if (fp)
10698 fclose (fp);
10700 /* Put the image into the pixmap. */
10701 x_put_x_image (f, ximg, img->pixmap, width, height);
10702 x_destroy_x_image (ximg);
10703 UNBLOCK_INPUT;
10704 UNGCPRO;
10705 return 1;
10708 #endif /* HAVE_JPEG */
10712 /***********************************************************************
10713 TIFF
10714 ***********************************************************************/
10716 #if HAVE_TIFF
10718 #include <tiffio.h>
10720 static int tiff_image_p P_ ((Lisp_Object object));
10721 static int tiff_load P_ ((struct frame *f, struct image *img));
10723 /* The symbol `tiff' identifying images of this type. */
10725 Lisp_Object Qtiff;
10727 /* Indices of image specification fields in tiff_format, below. */
10729 enum tiff_keyword_index
10731 TIFF_TYPE,
10732 TIFF_DATA,
10733 TIFF_FILE,
10734 TIFF_ASCENT,
10735 TIFF_MARGIN,
10736 TIFF_RELIEF,
10737 TIFF_ALGORITHM,
10738 TIFF_HEURISTIC_MASK,
10739 TIFF_LAST
10742 /* Vector of image_keyword structures describing the format
10743 of valid user-defined image specifications. */
10745 static struct image_keyword tiff_format[TIFF_LAST] =
10747 {":type", IMAGE_SYMBOL_VALUE, 1},
10748 {":data", IMAGE_STRING_VALUE, 0},
10749 {":file", IMAGE_STRING_VALUE, 0},
10750 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10751 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10752 {":relief", IMAGE_INTEGER_VALUE, 0},
10753 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10754 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10757 /* Structure describing the image type `tiff'. */
10759 static struct image_type tiff_type =
10761 &Qtiff,
10762 tiff_image_p,
10763 tiff_load,
10764 x_clear_image,
10765 NULL
10769 /* Return non-zero if OBJECT is a valid TIFF image specification. */
10771 static int
10772 tiff_image_p (object)
10773 Lisp_Object object;
10775 struct image_keyword fmt[TIFF_LAST];
10776 bcopy (tiff_format, fmt, sizeof fmt);
10778 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
10779 || (fmt[TIFF_ASCENT].count
10780 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
10781 return 0;
10783 /* Must specify either the :data or :file keyword. */
10784 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
10788 /* Reading from a memory buffer for TIFF images Based on the PNG
10789 memory source, but we have to provide a lot of extra functions.
10790 Blah.
10792 We really only need to implement read and seek, but I am not
10793 convinced that the TIFF library is smart enough not to destroy
10794 itself if we only hand it the function pointers we need to
10795 override. */
10797 typedef struct
10799 unsigned char *bytes;
10800 size_t len;
10801 int index;
10803 tiff_memory_source;
10805 static size_t
10806 tiff_read_from_memory (data, buf, size)
10807 thandle_t data;
10808 tdata_t buf;
10809 tsize_t size;
10811 tiff_memory_source *src = (tiff_memory_source *) data;
10813 if (size > src->len - src->index)
10814 return (size_t) -1;
10815 bcopy (src->bytes + src->index, buf, size);
10816 src->index += size;
10817 return size;
10820 static size_t
10821 tiff_write_from_memory (data, buf, size)
10822 thandle_t data;
10823 tdata_t buf;
10824 tsize_t size;
10826 return (size_t) -1;
10829 static toff_t
10830 tiff_seek_in_memory (data, off, whence)
10831 thandle_t data;
10832 toff_t off;
10833 int whence;
10835 tiff_memory_source *src = (tiff_memory_source *) data;
10836 int idx;
10838 switch (whence)
10840 case SEEK_SET: /* Go from beginning of source. */
10841 idx = off;
10842 break;
10844 case SEEK_END: /* Go from end of source. */
10845 idx = src->len + off;
10846 break;
10848 case SEEK_CUR: /* Go from current position. */
10849 idx = src->index + off;
10850 break;
10852 default: /* Invalid `whence'. */
10853 return -1;
10856 if (idx > src->len || idx < 0)
10857 return -1;
10859 src->index = idx;
10860 return src->index;
10863 static int
10864 tiff_close_memory (data)
10865 thandle_t data;
10867 /* NOOP */
10868 return 0;
10871 static int
10872 tiff_mmap_memory (data, pbase, psize)
10873 thandle_t data;
10874 tdata_t *pbase;
10875 toff_t *psize;
10877 /* It is already _IN_ memory. */
10878 return 0;
10881 static void
10882 tiff_unmap_memory (data, base, size)
10883 thandle_t data;
10884 tdata_t base;
10885 toff_t size;
10887 /* We don't need to do this. */
10890 static toff_t
10891 tiff_size_of_memory (data)
10892 thandle_t data;
10894 return ((tiff_memory_source *) data)->len;
10897 /* Load TIFF image IMG for use on frame F. Value is non-zero if
10898 successful. */
10900 static int
10901 tiff_load (f, img)
10902 struct frame *f;
10903 struct image *img;
10905 Lisp_Object file, specified_file;
10906 Lisp_Object specified_data;
10907 TIFF *tiff;
10908 int width, height, x, y;
10909 uint32 *buf;
10910 int rc;
10911 XImage *ximg;
10912 struct gcpro gcpro1;
10913 tiff_memory_source memsrc;
10915 specified_file = image_spec_value (img->spec, QCfile, NULL);
10916 specified_data = image_spec_value (img->spec, QCdata, NULL);
10917 file = Qnil;
10918 GCPRO1 (file);
10920 if (NILP (specified_data))
10922 /* Read from a file */
10923 file = x_find_image_file (specified_file);
10924 if (!STRINGP (file))
10926 image_error ("Cannot find image file `%s'", file, Qnil);
10927 UNGCPRO;
10928 return 0;
10931 /* Try to open the image file. */
10932 tiff = TIFFOpen (XSTRING (file)->data, "r");
10933 if (tiff == NULL)
10935 image_error ("Cannot open `%s'", file, Qnil);
10936 UNGCPRO;
10937 return 0;
10940 else
10942 /* Memory source! */
10943 memsrc.bytes = XSTRING (specified_data)->data;
10944 memsrc.len = STRING_BYTES (XSTRING (specified_data));
10945 memsrc.index = 0;
10947 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
10948 (TIFFReadWriteProc) tiff_read_from_memory,
10949 (TIFFReadWriteProc) tiff_write_from_memory,
10950 tiff_seek_in_memory,
10951 tiff_close_memory,
10952 tiff_size_of_memory,
10953 tiff_mmap_memory,
10954 tiff_unmap_memory);
10956 if (!tiff)
10958 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
10959 UNGCPRO;
10960 return 0;
10964 /* Get width and height of the image, and allocate a raster buffer
10965 of width x height 32-bit values. */
10966 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
10967 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
10968 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
10970 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
10971 TIFFClose (tiff);
10972 if (!rc)
10974 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
10975 xfree (buf);
10976 UNGCPRO;
10977 return 0;
10980 BLOCK_INPUT;
10982 /* Create the X image and pixmap. */
10983 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
10985 UNBLOCK_INPUT;
10986 xfree (buf);
10987 UNGCPRO;
10988 return 0;
10991 /* Initialize the color table. */
10992 init_color_table ();
10994 /* Process the pixel raster. Origin is in the lower-left corner. */
10995 for (y = 0; y < height; ++y)
10997 uint32 *row = buf + y * width;
10999 for (x = 0; x < width; ++x)
11001 uint32 abgr = row[x];
11002 int r = TIFFGetR (abgr) << 8;
11003 int g = TIFFGetG (abgr) << 8;
11004 int b = TIFFGetB (abgr) << 8;
11005 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
11009 /* Remember the colors allocated for the image. Free the color table. */
11010 img->colors = colors_in_color_table (&img->ncolors);
11011 free_color_table ();
11013 /* Put the image into the pixmap, then free the X image and its buffer. */
11014 x_put_x_image (f, ximg, img->pixmap, width, height);
11015 x_destroy_x_image (ximg);
11016 xfree (buf);
11017 UNBLOCK_INPUT;
11019 img->width = width;
11020 img->height = height;
11022 UNGCPRO;
11023 return 1;
11026 #endif /* HAVE_TIFF != 0 */
11030 /***********************************************************************
11032 ***********************************************************************/
11034 #if HAVE_GIF
11036 #include <gif_lib.h>
11038 static int gif_image_p P_ ((Lisp_Object object));
11039 static int gif_load P_ ((struct frame *f, struct image *img));
11041 /* The symbol `gif' identifying images of this type. */
11043 Lisp_Object Qgif;
11045 /* Indices of image specification fields in gif_format, below. */
11047 enum gif_keyword_index
11049 GIF_TYPE,
11050 GIF_DATA,
11051 GIF_FILE,
11052 GIF_ASCENT,
11053 GIF_MARGIN,
11054 GIF_RELIEF,
11055 GIF_ALGORITHM,
11056 GIF_HEURISTIC_MASK,
11057 GIF_IMAGE,
11058 GIF_LAST
11061 /* Vector of image_keyword structures describing the format
11062 of valid user-defined image specifications. */
11064 static struct image_keyword gif_format[GIF_LAST] =
11066 {":type", IMAGE_SYMBOL_VALUE, 1},
11067 {":data", IMAGE_STRING_VALUE, 0},
11068 {":file", IMAGE_STRING_VALUE, 0},
11069 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11070 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11071 {":relief", IMAGE_INTEGER_VALUE, 0},
11072 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11073 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11074 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
11077 /* Structure describing the image type `gif'. */
11079 static struct image_type gif_type =
11081 &Qgif,
11082 gif_image_p,
11083 gif_load,
11084 x_clear_image,
11085 NULL
11088 /* Return non-zero if OBJECT is a valid GIF image specification. */
11090 static int
11091 gif_image_p (object)
11092 Lisp_Object object;
11094 struct image_keyword fmt[GIF_LAST];
11095 bcopy (gif_format, fmt, sizeof fmt);
11097 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
11098 || (fmt[GIF_ASCENT].count
11099 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
11100 return 0;
11102 /* Must specify either the :data or :file keyword. */
11103 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11106 /* Reading a GIF image from memory
11107 Based on the PNG memory stuff to a certain extent. */
11109 typedef struct
11111 unsigned char *bytes;
11112 size_t len;
11113 int index;
11115 gif_memory_source;
11117 /* Make the current memory source available to gif_read_from_memory.
11118 It's done this way because not all versions of libungif support
11119 a UserData field in the GifFileType structure. */
11120 static gif_memory_source *current_gif_memory_src;
11122 static int
11123 gif_read_from_memory (file, buf, len)
11124 GifFileType *file;
11125 GifByteType *buf;
11126 int len;
11128 gif_memory_source *src = current_gif_memory_src;
11130 if (len > src->len - src->index)
11131 return -1;
11133 bcopy (src->bytes + src->index, buf, len);
11134 src->index += len;
11135 return len;
11139 /* Load GIF image IMG for use on frame F. Value is non-zero if
11140 successful. */
11142 static int
11143 gif_load (f, img)
11144 struct frame *f;
11145 struct image *img;
11147 Lisp_Object file, specified_file;
11148 Lisp_Object specified_data;
11149 int rc, width, height, x, y, i;
11150 XImage *ximg;
11151 ColorMapObject *gif_color_map;
11152 unsigned long pixel_colors[256];
11153 GifFileType *gif;
11154 struct gcpro gcpro1;
11155 Lisp_Object image;
11156 int ino, image_left, image_top, image_width, image_height;
11157 gif_memory_source memsrc;
11158 unsigned char *raster;
11160 specified_file = image_spec_value (img->spec, QCfile, NULL);
11161 specified_data = image_spec_value (img->spec, QCdata, NULL);
11162 file = Qnil;
11163 GCPRO1 (file);
11165 if (NILP (specified_data))
11167 file = x_find_image_file (specified_file);
11168 if (!STRINGP (file))
11170 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11171 UNGCPRO;
11172 return 0;
11175 /* Open the GIF file. */
11176 gif = DGifOpenFileName (XSTRING (file)->data);
11177 if (gif == NULL)
11179 image_error ("Cannot open `%s'", file, Qnil);
11180 UNGCPRO;
11181 return 0;
11184 else
11186 /* Read from memory! */
11187 current_gif_memory_src = &memsrc;
11188 memsrc.bytes = XSTRING (specified_data)->data;
11189 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11190 memsrc.index = 0;
11192 gif = DGifOpen(&memsrc, gif_read_from_memory);
11193 if (!gif)
11195 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11196 UNGCPRO;
11197 return 0;
11201 /* Read entire contents. */
11202 rc = DGifSlurp (gif);
11203 if (rc == GIF_ERROR)
11205 image_error ("Error reading `%s'", img->spec, Qnil);
11206 DGifCloseFile (gif);
11207 UNGCPRO;
11208 return 0;
11211 image = image_spec_value (img->spec, QCindex, NULL);
11212 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11213 if (ino >= gif->ImageCount)
11215 image_error ("Invalid image number `%s' in image `%s'",
11216 image, img->spec);
11217 DGifCloseFile (gif);
11218 UNGCPRO;
11219 return 0;
11222 width = img->width = gif->SWidth;
11223 height = img->height = gif->SHeight;
11225 BLOCK_INPUT;
11227 /* Create the X image and pixmap. */
11228 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11230 UNBLOCK_INPUT;
11231 DGifCloseFile (gif);
11232 UNGCPRO;
11233 return 0;
11236 /* Allocate colors. */
11237 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11238 if (!gif_color_map)
11239 gif_color_map = gif->SColorMap;
11240 init_color_table ();
11241 bzero (pixel_colors, sizeof pixel_colors);
11243 for (i = 0; i < gif_color_map->ColorCount; ++i)
11245 int r = gif_color_map->Colors[i].Red << 8;
11246 int g = gif_color_map->Colors[i].Green << 8;
11247 int b = gif_color_map->Colors[i].Blue << 8;
11248 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
11251 img->colors = colors_in_color_table (&img->ncolors);
11252 free_color_table ();
11254 /* Clear the part of the screen image that are not covered by
11255 the image from the GIF file. Full animated GIF support
11256 requires more than can be done here (see the gif89 spec,
11257 disposal methods). Let's simply assume that the part
11258 not covered by a sub-image is in the frame's background color. */
11259 image_top = gif->SavedImages[ino].ImageDesc.Top;
11260 image_left = gif->SavedImages[ino].ImageDesc.Left;
11261 image_width = gif->SavedImages[ino].ImageDesc.Width;
11262 image_height = gif->SavedImages[ino].ImageDesc.Height;
11264 for (y = 0; y < image_top; ++y)
11265 for (x = 0; x < width; ++x)
11266 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11268 for (y = image_top + image_height; y < height; ++y)
11269 for (x = 0; x < width; ++x)
11270 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11272 for (y = image_top; y < image_top + image_height; ++y)
11274 for (x = 0; x < image_left; ++x)
11275 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11276 for (x = image_left + image_width; x < width; ++x)
11277 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11280 /* Read the GIF image into the X image. We use a local variable
11281 `raster' here because RasterBits below is a char *, and invites
11282 problems with bytes >= 0x80. */
11283 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
11285 if (gif->SavedImages[ino].ImageDesc.Interlace)
11287 static int interlace_start[] = {0, 4, 2, 1};
11288 static int interlace_increment[] = {8, 8, 4, 2};
11289 int pass, inc;
11290 int row = interlace_start[0];
11292 pass = 0;
11294 for (y = 0; y < image_height; y++)
11296 if (row >= image_height)
11298 row = interlace_start[++pass];
11299 while (row >= image_height)
11300 row = interlace_start[++pass];
11303 for (x = 0; x < image_width; x++)
11305 int i = raster[(y * image_width) + x];
11306 XPutPixel (ximg, x + image_left, row + image_top,
11307 pixel_colors[i]);
11310 row += interlace_increment[pass];
11313 else
11315 for (y = 0; y < image_height; ++y)
11316 for (x = 0; x < image_width; ++x)
11318 int i = raster[y* image_width + x];
11319 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
11323 DGifCloseFile (gif);
11325 /* Put the image into the pixmap, then free the X image and its buffer. */
11326 x_put_x_image (f, ximg, img->pixmap, width, height);
11327 x_destroy_x_image (ximg);
11328 UNBLOCK_INPUT;
11330 UNGCPRO;
11331 return 1;
11334 #endif /* HAVE_GIF != 0 */
11338 /***********************************************************************
11339 Ghostscript
11340 ***********************************************************************/
11342 #ifdef HAVE_GHOSTSCRIPT
11343 static int gs_image_p P_ ((Lisp_Object object));
11344 static int gs_load P_ ((struct frame *f, struct image *img));
11345 static void gs_clear_image P_ ((struct frame *f, struct image *img));
11347 /* The symbol `postscript' identifying images of this type. */
11349 Lisp_Object Qpostscript;
11351 /* Keyword symbols. */
11353 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
11355 /* Indices of image specification fields in gs_format, below. */
11357 enum gs_keyword_index
11359 GS_TYPE,
11360 GS_PT_WIDTH,
11361 GS_PT_HEIGHT,
11362 GS_FILE,
11363 GS_LOADER,
11364 GS_BOUNDING_BOX,
11365 GS_ASCENT,
11366 GS_MARGIN,
11367 GS_RELIEF,
11368 GS_ALGORITHM,
11369 GS_HEURISTIC_MASK,
11370 GS_LAST
11373 /* Vector of image_keyword structures describing the format
11374 of valid user-defined image specifications. */
11376 static struct image_keyword gs_format[GS_LAST] =
11378 {":type", IMAGE_SYMBOL_VALUE, 1},
11379 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11380 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11381 {":file", IMAGE_STRING_VALUE, 1},
11382 {":loader", IMAGE_FUNCTION_VALUE, 0},
11383 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
11384 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11385 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11386 {":relief", IMAGE_INTEGER_VALUE, 0},
11387 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11388 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11391 /* Structure describing the image type `ghostscript'. */
11393 static struct image_type gs_type =
11395 &Qpostscript,
11396 gs_image_p,
11397 gs_load,
11398 gs_clear_image,
11399 NULL
11403 /* Free X resources of Ghostscript image IMG which is used on frame F. */
11405 static void
11406 gs_clear_image (f, img)
11407 struct frame *f;
11408 struct image *img;
11410 /* IMG->data.ptr_val may contain a recorded colormap. */
11411 xfree (img->data.ptr_val);
11412 x_clear_image (f, img);
11416 /* Return non-zero if OBJECT is a valid Ghostscript image
11417 specification. */
11419 static int
11420 gs_image_p (object)
11421 Lisp_Object object;
11423 struct image_keyword fmt[GS_LAST];
11424 Lisp_Object tem;
11425 int i;
11427 bcopy (gs_format, fmt, sizeof fmt);
11429 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
11430 || (fmt[GS_ASCENT].count
11431 && XFASTINT (fmt[GS_ASCENT].value) > 100))
11432 return 0;
11434 /* Bounding box must be a list or vector containing 4 integers. */
11435 tem = fmt[GS_BOUNDING_BOX].value;
11436 if (CONSP (tem))
11438 for (i = 0; i < 4; ++i, tem = XCDR (tem))
11439 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
11440 return 0;
11441 if (!NILP (tem))
11442 return 0;
11444 else if (VECTORP (tem))
11446 if (XVECTOR (tem)->size != 4)
11447 return 0;
11448 for (i = 0; i < 4; ++i)
11449 if (!INTEGERP (XVECTOR (tem)->contents[i]))
11450 return 0;
11452 else
11453 return 0;
11455 return 1;
11459 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
11460 if successful. */
11462 static int
11463 gs_load (f, img)
11464 struct frame *f;
11465 struct image *img;
11467 char buffer[100];
11468 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
11469 struct gcpro gcpro1, gcpro2;
11470 Lisp_Object frame;
11471 double in_width, in_height;
11472 Lisp_Object pixel_colors = Qnil;
11474 /* Compute pixel size of pixmap needed from the given size in the
11475 image specification. Sizes in the specification are in pt. 1 pt
11476 = 1/72 in, xdpi and ydpi are stored in the frame's X display
11477 info. */
11478 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
11479 in_width = XFASTINT (pt_width) / 72.0;
11480 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
11481 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
11482 in_height = XFASTINT (pt_height) / 72.0;
11483 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
11485 /* Create the pixmap. */
11486 BLOCK_INPUT;
11487 xassert (img->pixmap == 0);
11488 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11489 img->width, img->height,
11490 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
11491 UNBLOCK_INPUT;
11493 if (!img->pixmap)
11495 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
11496 return 0;
11499 /* Call the loader to fill the pixmap. It returns a process object
11500 if successful. We do not record_unwind_protect here because
11501 other places in redisplay like calling window scroll functions
11502 don't either. Let the Lisp loader use `unwind-protect' instead. */
11503 GCPRO2 (window_and_pixmap_id, pixel_colors);
11505 sprintf (buffer, "%lu %lu",
11506 (unsigned long) FRAME_W32_WINDOW (f),
11507 (unsigned long) img->pixmap);
11508 window_and_pixmap_id = build_string (buffer);
11510 sprintf (buffer, "%lu %lu",
11511 FRAME_FOREGROUND_PIXEL (f),
11512 FRAME_BACKGROUND_PIXEL (f));
11513 pixel_colors = build_string (buffer);
11515 XSETFRAME (frame, f);
11516 loader = image_spec_value (img->spec, QCloader, NULL);
11517 if (NILP (loader))
11518 loader = intern ("gs-load-image");
11520 img->data.lisp_val = call6 (loader, frame, img->spec,
11521 make_number (img->width),
11522 make_number (img->height),
11523 window_and_pixmap_id,
11524 pixel_colors);
11525 UNGCPRO;
11526 return PROCESSP (img->data.lisp_val);
11530 /* Kill the Ghostscript process that was started to fill PIXMAP on
11531 frame F. Called from XTread_socket when receiving an event
11532 telling Emacs that Ghostscript has finished drawing. */
11534 void
11535 x_kill_gs_process (pixmap, f)
11536 Pixmap pixmap;
11537 struct frame *f;
11539 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
11540 int class, i;
11541 struct image *img;
11543 /* Find the image containing PIXMAP. */
11544 for (i = 0; i < c->used; ++i)
11545 if (c->images[i]->pixmap == pixmap)
11546 break;
11548 /* Kill the GS process. We should have found PIXMAP in the image
11549 cache and its image should contain a process object. */
11550 xassert (i < c->used);
11551 img = c->images[i];
11552 xassert (PROCESSP (img->data.lisp_val));
11553 Fkill_process (img->data.lisp_val, Qnil);
11554 img->data.lisp_val = Qnil;
11556 /* On displays with a mutable colormap, figure out the colors
11557 allocated for the image by looking at the pixels of an XImage for
11558 img->pixmap. */
11559 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
11560 if (class != StaticColor && class != StaticGray && class != TrueColor)
11562 XImage *ximg;
11564 BLOCK_INPUT;
11566 /* Try to get an XImage for img->pixmep. */
11567 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
11568 0, 0, img->width, img->height, ~0, ZPixmap);
11569 if (ximg)
11571 int x, y;
11573 /* Initialize the color table. */
11574 init_color_table ();
11576 /* For each pixel of the image, look its color up in the
11577 color table. After having done so, the color table will
11578 contain an entry for each color used by the image. */
11579 for (y = 0; y < img->height; ++y)
11580 for (x = 0; x < img->width; ++x)
11582 unsigned long pixel = XGetPixel (ximg, x, y);
11583 lookup_pixel_color (f, pixel);
11586 /* Record colors in the image. Free color table and XImage. */
11587 img->colors = colors_in_color_table (&img->ncolors);
11588 free_color_table ();
11589 XDestroyImage (ximg);
11591 #if 0 /* This doesn't seem to be the case. If we free the colors
11592 here, we get a BadAccess later in x_clear_image when
11593 freeing the colors. */
11594 /* We have allocated colors once, but Ghostscript has also
11595 allocated colors on behalf of us. So, to get the
11596 reference counts right, free them once. */
11597 if (img->ncolors)
11599 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
11600 XFreeColors (FRAME_W32_DISPLAY (f), cmap,
11601 img->colors, img->ncolors, 0);
11603 #endif
11605 else
11606 image_error ("Cannot get X image of `%s'; colors will not be freed",
11607 img->spec, Qnil);
11609 UNBLOCK_INPUT;
11613 #endif /* HAVE_GHOSTSCRIPT */
11616 /***********************************************************************
11617 Window properties
11618 ***********************************************************************/
11620 DEFUN ("x-change-window-property", Fx_change_window_property,
11621 Sx_change_window_property, 2, 3, 0,
11622 "Change window property PROP to VALUE on the X window of FRAME.\n\
11623 PROP and VALUE must be strings. FRAME nil or omitted means use the\n\
11624 selected frame. Value is VALUE.")
11625 (prop, value, frame)
11626 Lisp_Object frame, prop, value;
11628 #if 0 /* NTEMACS_TODO : port window properties to W32 */
11629 struct frame *f = check_x_frame (frame);
11630 Atom prop_atom;
11632 CHECK_STRING (prop, 1);
11633 CHECK_STRING (value, 2);
11635 BLOCK_INPUT;
11636 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11637 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11638 prop_atom, XA_STRING, 8, PropModeReplace,
11639 XSTRING (value)->data, XSTRING (value)->size);
11641 /* Make sure the property is set when we return. */
11642 XFlush (FRAME_W32_DISPLAY (f));
11643 UNBLOCK_INPUT;
11645 #endif /* NTEMACS_TODO */
11647 return value;
11651 DEFUN ("x-delete-window-property", Fx_delete_window_property,
11652 Sx_delete_window_property, 1, 2, 0,
11653 "Remove window property PROP from X window of FRAME.\n\
11654 FRAME nil or omitted means use the selected frame. Value is PROP.")
11655 (prop, frame)
11656 Lisp_Object prop, frame;
11658 #if 0 /* NTEMACS_TODO : port window properties to W32 */
11660 struct frame *f = check_x_frame (frame);
11661 Atom prop_atom;
11663 CHECK_STRING (prop, 1);
11664 BLOCK_INPUT;
11665 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11666 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
11668 /* Make sure the property is removed when we return. */
11669 XFlush (FRAME_W32_DISPLAY (f));
11670 UNBLOCK_INPUT;
11671 #endif /* NTEMACS_TODO */
11673 return prop;
11677 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
11678 1, 2, 0,
11679 "Value is the value of window property PROP on FRAME.\n\
11680 If FRAME is nil or omitted, use the selected frame. Value is nil\n\
11681 if FRAME hasn't a property with name PROP or if PROP has no string\n\
11682 value.")
11683 (prop, frame)
11684 Lisp_Object prop, frame;
11686 #if 0 /* NTEMACS_TODO : port window properties to W32 */
11688 struct frame *f = check_x_frame (frame);
11689 Atom prop_atom;
11690 int rc;
11691 Lisp_Object prop_value = Qnil;
11692 char *tmp_data = NULL;
11693 Atom actual_type;
11694 int actual_format;
11695 unsigned long actual_size, bytes_remaining;
11697 CHECK_STRING (prop, 1);
11698 BLOCK_INPUT;
11699 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11700 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11701 prop_atom, 0, 0, False, XA_STRING,
11702 &actual_type, &actual_format, &actual_size,
11703 &bytes_remaining, (unsigned char **) &tmp_data);
11704 if (rc == Success)
11706 int size = bytes_remaining;
11708 XFree (tmp_data);
11709 tmp_data = NULL;
11711 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11712 prop_atom, 0, bytes_remaining,
11713 False, XA_STRING,
11714 &actual_type, &actual_format,
11715 &actual_size, &bytes_remaining,
11716 (unsigned char **) &tmp_data);
11717 if (rc == Success)
11718 prop_value = make_string (tmp_data, size);
11720 XFree (tmp_data);
11723 UNBLOCK_INPUT;
11725 return prop_value;
11727 #endif /* NTEMACS_TODO */
11728 return Qnil;
11733 /***********************************************************************
11734 Busy cursor
11735 ***********************************************************************/
11737 /* If non-null, an asynchronous timer that, when it expires, displays
11738 a busy cursor on all frames. */
11740 static struct atimer *busy_cursor_atimer;
11742 /* Non-zero means a busy cursor is currently shown. */
11744 static int busy_cursor_shown_p;
11746 /* Number of seconds to wait before displaying a busy cursor. */
11748 static Lisp_Object Vbusy_cursor_delay;
11750 /* Default number of seconds to wait before displaying a busy
11751 cursor. */
11753 #define DEFAULT_BUSY_CURSOR_DELAY 1
11755 /* Function prototypes. */
11757 static void show_busy_cursor P_ ((struct atimer *));
11758 static void hide_busy_cursor P_ ((void));
11761 /* Cancel a currently active busy-cursor timer, and start a new one. */
11763 void
11764 start_busy_cursor ()
11766 #if 0 /* NTEMACS_TODO: cursor shape changes. */
11767 EMACS_TIME delay;
11768 int secs, usecs = 0;
11770 cancel_busy_cursor ();
11772 if (INTEGERP (Vbusy_cursor_delay)
11773 && XINT (Vbusy_cursor_delay) > 0)
11774 secs = XFASTINT (Vbusy_cursor_delay);
11775 else if (FLOATP (Vbusy_cursor_delay)
11776 && XFLOAT_DATA (Vbusy_cursor_delay) > 0)
11778 Lisp_Object tem;
11779 tem = Ftruncate (Vbusy_cursor_delay, Qnil);
11780 secs = XFASTINT (tem);
11781 usecs = (XFLOAT_DATA (Vbusy_cursor_delay) - secs) * 1000000;
11783 else
11784 secs = DEFAULT_BUSY_CURSOR_DELAY;
11786 EMACS_SET_SECS_USECS (delay, secs, usecs);
11787 busy_cursor_atimer = start_atimer (ATIMER_RELATIVE, delay,
11788 show_busy_cursor, NULL);
11789 #endif
11793 /* Cancel the busy cursor timer if active, hide a busy cursor if
11794 shown. */
11796 void
11797 cancel_busy_cursor ()
11799 if (busy_cursor_atimer)
11801 cancel_atimer (busy_cursor_atimer);
11802 busy_cursor_atimer = NULL;
11805 if (busy_cursor_shown_p)
11806 hide_busy_cursor ();
11810 /* Timer function of busy_cursor_atimer. TIMER is equal to
11811 busy_cursor_atimer.
11813 Display a busy cursor on all frames by mapping the frames'
11814 busy_window. Set the busy_p flag in the frames' output_data.x
11815 structure to indicate that a busy cursor is shown on the
11816 frames. */
11818 static void
11819 show_busy_cursor (timer)
11820 struct atimer *timer;
11822 #if 0 /* NTEMACS_TODO: cursor shape changes. */
11823 /* The timer implementation will cancel this timer automatically
11824 after this function has run. Set busy_cursor_atimer to null
11825 so that we know the timer doesn't have to be canceled. */
11826 busy_cursor_atimer = NULL;
11828 if (!busy_cursor_shown_p)
11830 Lisp_Object rest, frame;
11832 BLOCK_INPUT;
11834 FOR_EACH_FRAME (rest, frame)
11835 if (FRAME_X_P (XFRAME (frame)))
11837 struct frame *f = XFRAME (frame);
11839 f->output_data.w32->busy_p = 1;
11841 if (!f->output_data.w32->busy_window)
11843 unsigned long mask = CWCursor;
11844 XSetWindowAttributes attrs;
11846 attrs.cursor = f->output_data.w32->busy_cursor;
11848 f->output_data.w32->busy_window
11849 = XCreateWindow (FRAME_X_DISPLAY (f),
11850 FRAME_OUTER_WINDOW (f),
11851 0, 0, 32000, 32000, 0, 0,
11852 InputOnly,
11853 CopyFromParent,
11854 mask, &attrs);
11857 XMapRaised (FRAME_X_DISPLAY (f), f->output_data.w32->busy_window);
11858 XFlush (FRAME_X_DISPLAY (f));
11861 busy_cursor_shown_p = 1;
11862 UNBLOCK_INPUT;
11864 #endif
11868 /* Hide the busy cursor on all frames, if it is currently shown. */
11870 static void
11871 hide_busy_cursor ()
11873 #if 0 /* NTEMACS_TODO: cursor shape changes. */
11874 if (busy_cursor_shown_p)
11876 Lisp_Object rest, frame;
11878 BLOCK_INPUT;
11879 FOR_EACH_FRAME (rest, frame)
11881 struct frame *f = XFRAME (frame);
11883 if (FRAME_X_P (f)
11884 /* Watch out for newly created frames. */
11885 && f->output_data.x->busy_window)
11887 XUnmapWindow (FRAME_X_DISPLAY (f), f->output_data.x->busy_window);
11888 /* Sync here because XTread_socket looks at the busy_p flag
11889 that is reset to zero below. */
11890 XSync (FRAME_X_DISPLAY (f), False);
11891 f->output_data.x->busy_p = 0;
11895 busy_cursor_shown_p = 0;
11896 UNBLOCK_INPUT;
11898 #endif
11903 /***********************************************************************
11904 Tool tips
11905 ***********************************************************************/
11907 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
11908 Lisp_Object));
11910 /* The frame of a currently visible tooltip, or null. */
11912 struct frame *tip_frame;
11914 /* If non-nil, a timer started that hides the last tooltip when it
11915 fires. */
11917 Lisp_Object tip_timer;
11918 Window tip_window;
11920 /* Create a frame for a tooltip on the display described by DPYINFO.
11921 PARMS is a list of frame parameters. Value is the frame. */
11923 static Lisp_Object
11924 x_create_tip_frame (dpyinfo, parms)
11925 struct w32_display_info *dpyinfo;
11926 Lisp_Object parms;
11928 #if 0 /* NTEMACS_TODO : w32 version */
11929 struct frame *f;
11930 Lisp_Object frame, tem;
11931 Lisp_Object name;
11932 long window_prompting = 0;
11933 int width, height;
11934 int count = specpdl_ptr - specpdl;
11935 struct gcpro gcpro1, gcpro2, gcpro3;
11936 struct kboard *kb;
11938 check_x ();
11940 /* Use this general default value to start with until we know if
11941 this frame has a specified name. */
11942 Vx_resource_name = Vinvocation_name;
11944 #ifdef MULTI_KBOARD
11945 kb = dpyinfo->kboard;
11946 #else
11947 kb = &the_only_kboard;
11948 #endif
11950 /* Get the name of the frame to use for resource lookup. */
11951 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
11952 if (!STRINGP (name)
11953 && !EQ (name, Qunbound)
11954 && !NILP (name))
11955 error ("Invalid frame name--not a string or nil");
11956 Vx_resource_name = name;
11958 frame = Qnil;
11959 GCPRO3 (parms, name, frame);
11960 tip_frame = f = make_frame (1);
11961 XSETFRAME (frame, f);
11962 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
11964 f->output_method = output_w32;
11965 f->output_data.w32 =
11966 (struct w32_output *) xmalloc (sizeof (struct w32_output));
11967 bzero (f->output_data.w32, sizeof (struct w32_output));
11968 #if 0
11969 f->output_data.w32->icon_bitmap = -1;
11970 #endif
11971 f->output_data.w32->fontset = -1;
11972 f->icon_name = Qnil;
11974 #ifdef MULTI_KBOARD
11975 FRAME_KBOARD (f) = kb;
11976 #endif
11977 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
11978 f->output_data.w32->explicit_parent = 0;
11980 /* Set the name; the functions to which we pass f expect the name to
11981 be set. */
11982 if (EQ (name, Qunbound) || NILP (name))
11984 f->name = build_string (dpyinfo->x_id_name);
11985 f->explicit_name = 0;
11987 else
11989 f->name = name;
11990 f->explicit_name = 1;
11991 /* use the frame's title when getting resources for this frame. */
11992 specbind (Qx_resource_name, name);
11995 /* Extract the window parameters from the supplied values
11996 that are needed to determine window geometry. */
11998 Lisp_Object font;
12000 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12002 BLOCK_INPUT;
12003 /* First, try whatever font the caller has specified. */
12004 if (STRINGP (font))
12006 tem = Fquery_fontset (font, Qnil);
12007 if (STRINGP (tem))
12008 font = x_new_fontset (f, XSTRING (tem)->data);
12009 else
12010 font = x_new_font (f, XSTRING (font)->data);
12013 /* Try out a font which we hope has bold and italic variations. */
12014 if (!STRINGP (font))
12015 font = x_new_font (f, "-adobe-courier-medium-r-*-*-*-120-*-*-*-*-iso8859-1");
12016 if (!STRINGP (font))
12017 font = x_new_font (f, "-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12018 if (! STRINGP (font))
12019 font = x_new_font (f, "-*-*-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12020 if (! STRINGP (font))
12021 /* This was formerly the first thing tried, but it finds too many fonts
12022 and takes too long. */
12023 font = x_new_font (f, "-*-*-medium-r-*-*-*-*-*-*-c-*-iso8859-1");
12024 /* If those didn't work, look for something which will at least work. */
12025 if (! STRINGP (font))
12026 font = x_new_font (f, "-*-fixed-*-*-*-*-*-140-*-*-c-*-iso8859-1");
12027 UNBLOCK_INPUT;
12028 if (! STRINGP (font))
12029 font = build_string ("fixed");
12031 x_default_parameter (f, parms, Qfont, font,
12032 "font", "Font", RES_TYPE_STRING);
12035 x_default_parameter (f, parms, Qborder_width, make_number (2),
12036 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
12038 /* This defaults to 2 in order to match xterm. We recognize either
12039 internalBorderWidth or internalBorder (which is what xterm calls
12040 it). */
12041 if (NILP (Fassq (Qinternal_border_width, parms)))
12043 Lisp_Object value;
12045 value = w32_get_arg (parms, Qinternal_border_width,
12046 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12047 if (! EQ (value, Qunbound))
12048 parms = Fcons (Fcons (Qinternal_border_width, value),
12049 parms);
12052 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
12053 "internalBorderWidth", "internalBorderWidth",
12054 RES_TYPE_NUMBER);
12056 /* Also do the stuff which must be set before the window exists. */
12057 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12058 "foreground", "Foreground", RES_TYPE_STRING);
12059 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12060 "background", "Background", RES_TYPE_STRING);
12061 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12062 "pointerColor", "Foreground", RES_TYPE_STRING);
12063 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12064 "cursorColor", "Foreground", RES_TYPE_STRING);
12065 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12066 "borderColor", "BorderColor", RES_TYPE_STRING);
12068 /* Init faces before x_default_parameter is called for scroll-bar
12069 parameters because that function calls x_set_scroll_bar_width,
12070 which calls change_frame_size, which calls Fset_window_buffer,
12071 which runs hooks, which call Fvertical_motion. At the end, we
12072 end up in init_iterator with a null face cache, which should not
12073 happen. */
12074 init_frame_faces (f);
12076 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12077 window_prompting = x_figure_window_size (f, parms);
12079 if (window_prompting & XNegative)
12081 if (window_prompting & YNegative)
12082 f->output_data.w32->win_gravity = SouthEastGravity;
12083 else
12084 f->output_data.w32->win_gravity = NorthEastGravity;
12086 else
12088 if (window_prompting & YNegative)
12089 f->output_data.w32->win_gravity = SouthWestGravity;
12090 else
12091 f->output_data.w32->win_gravity = NorthWestGravity;
12094 f->output_data.w32->size_hint_flags = window_prompting;
12096 XSetWindowAttributes attrs;
12097 unsigned long mask;
12099 BLOCK_INPUT;
12100 mask = CWBackPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask;
12101 /* Window managers looks at the override-redirect flag to
12102 determine whether or net to give windows a decoration (Xlib
12103 3.2.8). */
12104 attrs.override_redirect = True;
12105 attrs.save_under = True;
12106 attrs.background_pixel = FRAME_BACKGROUND_PIXEL (f);
12107 /* Arrange for getting MapNotify and UnmapNotify events. */
12108 attrs.event_mask = StructureNotifyMask;
12109 tip_window
12110 = FRAME_W32_WINDOW (f)
12111 = XCreateWindow (FRAME_W32_DISPLAY (f),
12112 FRAME_W32_DISPLAY_INFO (f)->root_window,
12113 /* x, y, width, height */
12114 0, 0, 1, 1,
12115 /* Border. */
12117 CopyFromParent, InputOutput, CopyFromParent,
12118 mask, &attrs);
12119 UNBLOCK_INPUT;
12122 x_make_gc (f);
12124 x_default_parameter (f, parms, Qauto_raise, Qnil,
12125 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12126 x_default_parameter (f, parms, Qauto_lower, Qnil,
12127 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12128 x_default_parameter (f, parms, Qcursor_type, Qbox,
12129 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12131 /* Dimensions, especially f->height, must be done via change_frame_size.
12132 Change will not be effected unless different from the current
12133 f->height. */
12134 width = f->width;
12135 height = f->height;
12136 f->height = 0;
12137 SET_FRAME_WIDTH (f, 0);
12138 change_frame_size (f, height, width, 1, 0, 0);
12140 f->no_split = 1;
12142 UNGCPRO;
12144 /* It is now ok to make the frame official even if we get an error
12145 below. And the frame needs to be on Vframe_list or making it
12146 visible won't work. */
12147 Vframe_list = Fcons (frame, Vframe_list);
12149 /* Now that the frame is official, it counts as a reference to
12150 its display. */
12151 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
12153 return unbind_to (count, frame);
12154 #endif /* NTEMACS_TODO */
12155 return Qnil;
12159 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
12160 "Show STRING in a \"tooltip\" window on frame FRAME.\n\
12161 A tooltip window is a small X window displaying a string.\n\
12163 FRAME nil or omitted means use the selected frame.\n\
12165 PARMS is an optional list of frame parameters which can be\n\
12166 used to change the tooltip's appearance.\n\
12168 Automatically hide the tooltip after TIMEOUT seconds.\n\
12169 TIMEOUT nil means use the default timeout of 5 seconds.\n\
12171 If the list of frame parameters PARAMS contains a `left' parameters,\n\
12172 the tooltip is displayed at that x-position. Otherwise it is\n\
12173 displayed at the mouse position, with offset DX added (default is 5 if\n\
12174 DX isn't specified). Likewise for the y-position; if a `top' frame\n\
12175 parameter is specified, it determines the y-position of the tooltip\n\
12176 window, otherwise it is displayed at the mouse position, with offset\n\
12177 DY added (default is -5).")
12178 (string, frame, parms, timeout, dx, dy)
12179 Lisp_Object string, frame, parms, timeout, dx, dy;
12181 struct frame *f;
12182 struct window *w;
12183 Window root, child;
12184 Lisp_Object buffer, top, left;
12185 struct buffer *old_buffer;
12186 struct text_pos pos;
12187 int i, width, height;
12188 int root_x, root_y, win_x, win_y;
12189 unsigned pmask;
12190 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
12191 int old_windows_or_buffers_changed = windows_or_buffers_changed;
12192 int count = specpdl_ptr - specpdl;
12194 specbind (Qinhibit_redisplay, Qt);
12196 GCPRO4 (string, parms, frame, timeout);
12198 CHECK_STRING (string, 0);
12199 f = check_x_frame (frame);
12200 if (NILP (timeout))
12201 timeout = make_number (5);
12202 else
12203 CHECK_NATNUM (timeout, 2);
12205 if (NILP (dx))
12206 dx = make_number (5);
12207 else
12208 CHECK_NUMBER (dx, 5);
12210 if (NILP (dy))
12211 dy = make_number (-5);
12212 else
12213 CHECK_NUMBER (dy, 6);
12215 /* Hide a previous tip, if any. */
12216 Fx_hide_tip ();
12218 /* Add default values to frame parameters. */
12219 if (NILP (Fassq (Qname, parms)))
12220 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
12221 if (NILP (Fassq (Qinternal_border_width, parms)))
12222 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
12223 if (NILP (Fassq (Qborder_width, parms)))
12224 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
12225 if (NILP (Fassq (Qborder_color, parms)))
12226 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
12227 if (NILP (Fassq (Qbackground_color, parms)))
12228 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
12229 parms);
12231 /* Create a frame for the tooltip, and record it in the global
12232 variable tip_frame. */
12233 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms);
12234 tip_frame = f = XFRAME (frame);
12236 /* Set up the frame's root window. Currently we use a size of 80
12237 columns x 40 lines. If someone wants to show a larger tip, he
12238 will loose. I don't think this is a realistic case. */
12239 w = XWINDOW (FRAME_ROOT_WINDOW (f));
12240 w->left = w->top = make_number (0);
12241 w->width = 80;
12242 w->height = 40;
12243 adjust_glyphs (f);
12244 w->pseudo_window_p = 1;
12246 /* Display the tooltip text in a temporary buffer. */
12247 buffer = Fget_buffer_create (build_string (" *tip*"));
12248 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
12249 old_buffer = current_buffer;
12250 set_buffer_internal_1 (XBUFFER (buffer));
12251 Ferase_buffer ();
12252 Finsert (make_number (1), &string);
12253 clear_glyph_matrix (w->desired_matrix);
12254 clear_glyph_matrix (w->current_matrix);
12255 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
12256 try_window (FRAME_ROOT_WINDOW (f), pos);
12258 /* Compute width and height of the tooltip. */
12259 width = height = 0;
12260 for (i = 0; i < w->desired_matrix->nrows; ++i)
12262 struct glyph_row *row = &w->desired_matrix->rows[i];
12263 struct glyph *last;
12264 int row_width;
12266 /* Stop at the first empty row at the end. */
12267 if (!row->enabled_p || !row->displays_text_p)
12268 break;
12270 /* Let the row go over the full width of the frame. */
12271 row->full_width_p = 1;
12273 /* There's a glyph at the end of rows that is use to place
12274 the cursor there. Don't include the width of this glyph. */
12275 if (row->used[TEXT_AREA])
12277 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
12278 row_width = row->pixel_width - last->pixel_width;
12280 else
12281 row_width = row->pixel_width;
12283 height += row->height;
12284 width = max (width, row_width);
12287 /* Add the frame's internal border to the width and height the X
12288 window should have. */
12289 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12290 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12292 /* User-specified position? */
12293 left = Fcdr (Fassq (Qleft, parms));
12294 top = Fcdr (Fassq (Qtop, parms));
12296 /* Move the tooltip window where the mouse pointer is. Resize and
12297 show it. */
12298 #if 0 /* NTEMACS_TODO : W32 specifics */
12299 BLOCK_INPUT;
12300 XQueryPointer (FRAME_X_DISPLAY (f), FRAME_X_DISPLAY_INFO (f)->root_window,
12301 &root, &child, &root_x, &root_y, &win_x, &win_y, &pmask);
12302 UNBLOCK_INPUT;
12304 root_x += XINT (dx);
12305 root_y += XINT (dy);
12307 if (INTEGERP (left))
12308 root_x = XINT (left);
12309 if (INTEGERP (top))
12310 root_y = XINT (top);
12312 BLOCK_INPUT;
12313 XMoveResizeWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12314 root_x, root_y - height, width, height);
12315 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12316 UNBLOCK_INPUT;
12317 #endif /* NTEMACS_TODO */
12319 /* Draw into the window. */
12320 w->must_be_updated_p = 1;
12321 update_single_window (w, 1);
12323 /* Restore original current buffer. */
12324 set_buffer_internal_1 (old_buffer);
12325 windows_or_buffers_changed = old_windows_or_buffers_changed;
12327 /* Let the tip disappear after timeout seconds. */
12328 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
12329 intern ("x-hide-tip"));
12331 UNGCPRO;
12332 return unbind_to (count, Qnil);
12336 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
12337 "Hide the current tooltip window, if there is any.\n\
12338 Value is t is tooltip was open, nil otherwise.")
12341 int count = specpdl_ptr - specpdl;
12342 int deleted_p = 0;
12344 specbind (Qinhibit_redisplay, Qt);
12346 if (!NILP (tip_timer))
12348 call1 (intern ("cancel-timer"), tip_timer);
12349 tip_timer = Qnil;
12352 if (tip_frame)
12354 Lisp_Object frame;
12356 XSETFRAME (frame, tip_frame);
12357 Fdelete_frame (frame, Qt);
12358 tip_frame = NULL;
12359 deleted_p = 1;
12362 return unbind_to (count, deleted_p ? Qt : Qnil);
12367 /***********************************************************************
12368 File selection dialog
12369 ***********************************************************************/
12371 extern Lisp_Object Qfile_name_history;
12373 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
12374 "Read file name, prompting with PROMPT in directory DIR.\n\
12375 Use a file selection dialog.\n\
12376 Select DEFAULT-FILENAME in the dialog's file selection box, if\n\
12377 specified. Don't let the user enter a file name in the file\n\
12378 selection dialog's entry field, if MUSTMATCH is non-nil.")
12379 (prompt, dir, default_filename, mustmatch)
12380 Lisp_Object prompt, dir, default_filename, mustmatch;
12382 struct frame *f = SELECTED_FRAME ();
12383 Lisp_Object file = Qnil;
12384 int count = specpdl_ptr - specpdl;
12385 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
12386 char filename[MAX_PATH + 1];
12387 char init_dir[MAX_PATH + 1];
12388 int use_dialog_p = 1;
12390 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
12391 CHECK_STRING (prompt, 0);
12392 CHECK_STRING (dir, 1);
12394 /* Create the dialog with PROMPT as title, using DIR as initial
12395 directory and using "*" as pattern. */
12396 dir = Fexpand_file_name (dir, Qnil);
12397 strncpy (init_dir, XSTRING (dir)->data, MAX_PATH);
12398 init_dir[MAX_PATH] = '\0';
12399 unixtodos_filename (init_dir);
12401 if (STRINGP (default_filename))
12403 char *file_name_only;
12404 char *full_path_name = XSTRING (default_filename)->data;
12406 unixtodos_filename (full_path_name);
12408 file_name_only = strrchr (full_path_name, '\\');
12409 if (!file_name_only)
12410 file_name_only = full_path_name;
12411 else
12413 file_name_only++;
12415 /* If default_file_name is a directory, don't use the open
12416 file dialog, as it does not support selecting
12417 directories. */
12418 if (!(*file_name_only))
12419 use_dialog_p = 0;
12422 strncpy (filename, file_name_only, MAX_PATH);
12423 filename[MAX_PATH] = '\0';
12425 else
12426 filename[0] = '\0';
12428 if (use_dialog_p)
12430 OPENFILENAME file_details;
12431 char *filename_file;
12433 /* Prevent redisplay. */
12434 specbind (Qinhibit_redisplay, Qt);
12435 BLOCK_INPUT;
12437 bzero (&file_details, sizeof (file_details));
12438 file_details.lStructSize = sizeof (file_details);
12439 file_details.hwndOwner = FRAME_W32_WINDOW (f);
12440 file_details.lpstrFile = filename;
12441 file_details.nMaxFile = sizeof (filename);
12442 file_details.lpstrInitialDir = init_dir;
12443 file_details.lpstrTitle = XSTRING (prompt)->data;
12444 file_details.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
12446 if (!NILP (mustmatch))
12447 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
12449 if (GetOpenFileName (&file_details))
12451 dostounix_filename (filename);
12452 file = build_string (filename);
12454 else
12455 file = Qnil;
12457 UNBLOCK_INPUT;
12458 file = unbind_to (count, file);
12460 /* Open File dialog will not allow folders to be selected, so resort
12461 to minibuffer completing reads for directories. */
12462 else
12463 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
12464 dir, mustmatch, dir, Qfile_name_history,
12465 default_filename, Qnil);
12467 UNGCPRO;
12469 /* Make "Cancel" equivalent to C-g. */
12470 if (NILP (file))
12471 Fsignal (Qquit, Qnil);
12473 return unbind_to (count, file);
12478 /***********************************************************************
12479 Tests
12480 ***********************************************************************/
12482 #if GLYPH_DEBUG
12484 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
12485 "Value is non-nil if SPEC is a valid image specification.")
12486 (spec)
12487 Lisp_Object spec;
12489 return valid_image_p (spec) ? Qt : Qnil;
12493 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
12494 (spec)
12495 Lisp_Object spec;
12497 int id = -1;
12499 if (valid_image_p (spec))
12500 id = lookup_image (SELECTED_FRAME (), spec);
12502 debug_print (spec);
12503 return make_number (id);
12506 #endif /* GLYPH_DEBUG != 0 */
12510 /***********************************************************************
12511 w32 specialized functions
12512 ***********************************************************************/
12514 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 1, 0,
12515 "This will display the W32 font dialog and return an X font string corresponding to the selection.")
12516 (frame)
12517 Lisp_Object frame;
12519 FRAME_PTR f = check_x_frame (frame);
12520 CHOOSEFONT cf;
12521 LOGFONT lf;
12522 TEXTMETRIC tm;
12523 HDC hdc;
12524 HANDLE oldobj;
12525 char buf[100];
12527 bzero (&cf, sizeof (cf));
12528 bzero (&lf, sizeof (lf));
12530 cf.lStructSize = sizeof (cf);
12531 cf.hwndOwner = FRAME_W32_WINDOW (f);
12532 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS;
12533 cf.lpLogFont = &lf;
12535 /* Initialize as much of the font details as we can from the current
12536 default font. */
12537 hdc = GetDC (FRAME_W32_WINDOW (f));
12538 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
12539 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
12540 if (GetTextMetrics (hdc, &tm))
12542 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
12543 lf.lfWeight = tm.tmWeight;
12544 lf.lfItalic = tm.tmItalic;
12545 lf.lfUnderline = tm.tmUnderlined;
12546 lf.lfStrikeOut = tm.tmStruckOut;
12547 lf.lfCharSet = tm.tmCharSet;
12548 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
12550 SelectObject (hdc, oldobj);
12551 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
12553 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100))
12554 return Qnil;
12556 return build_string (buf);
12559 DEFUN ("w32-send-sys-command", Fw32_send_sys_command, Sw32_send_sys_command, 1, 2, 0,
12560 "Send frame a Windows WM_SYSCOMMAND message of type COMMAND.\n\
12561 Some useful values for command are 0xf030 to maximise frame (0xf020\n\
12562 to minimize), 0xf120 to restore frame to original size, and 0xf100\n\
12563 to activate the menubar for keyboard access. 0xf140 activates the\n\
12564 screen saver if defined.\n\
12566 If optional parameter FRAME is not specified, use selected frame.")
12567 (command, frame)
12568 Lisp_Object command, frame;
12570 WPARAM code;
12571 FRAME_PTR f = check_x_frame (frame);
12573 CHECK_NUMBER (command, 0);
12575 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
12577 return Qnil;
12580 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
12581 "Get Windows to perform OPERATION on DOCUMENT.\n\
12582 This is a wrapper around the ShellExecute system function, which\n\
12583 invokes the application registered to handle OPERATION for DOCUMENT.\n\
12584 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be\n\
12585 nil for the default action), and DOCUMENT is typically the name of a\n\
12586 document file or URL, but can also be a program executable to run or\n\
12587 a directory to open in the Windows Explorer.\n\
12589 If DOCUMENT is a program executable, PARAMETERS can be a string\n\
12590 containing command line parameters, but otherwise should be nil.\n\
12592 SHOW-FLAG can be used to control whether the invoked application is hidden\n\
12593 or minimized. If SHOW-FLAG is nil, the application is displayed normally,\n\
12594 otherwise it is an integer representing a ShowWindow flag:\n\
12596 0 - start hidden\n\
12597 1 - start normally\n\
12598 3 - start maximized\n\
12599 6 - start minimized")
12600 (operation, document, parameters, show_flag)
12601 Lisp_Object operation, document, parameters, show_flag;
12603 Lisp_Object current_dir;
12605 CHECK_STRING (document, 0);
12607 /* Encode filename and current directory. */
12608 current_dir = ENCODE_FILE (current_buffer->directory);
12609 document = ENCODE_FILE (document);
12610 if ((int) ShellExecute (NULL,
12611 (STRINGP (operation) ?
12612 XSTRING (operation)->data : NULL),
12613 XSTRING (document)->data,
12614 (STRINGP (parameters) ?
12615 XSTRING (parameters)->data : NULL),
12616 XSTRING (current_dir)->data,
12617 (INTEGERP (show_flag) ?
12618 XINT (show_flag) : SW_SHOWDEFAULT))
12619 > 32)
12620 return Qt;
12621 error ("ShellExecute failed");
12624 /* Lookup virtual keycode from string representing the name of a
12625 non-ascii keystroke into the corresponding virtual key, using
12626 lispy_function_keys. */
12627 static int
12628 lookup_vk_code (char *key)
12630 int i;
12632 for (i = 0; i < 256; i++)
12633 if (lispy_function_keys[i] != 0
12634 && strcmp (lispy_function_keys[i], key) == 0)
12635 return i;
12637 return -1;
12640 /* Convert a one-element vector style key sequence to a hot key
12641 definition. */
12642 static int
12643 w32_parse_hot_key (key)
12644 Lisp_Object key;
12646 /* Copied from Fdefine_key and store_in_keymap. */
12647 register Lisp_Object c;
12648 int vk_code;
12649 int lisp_modifiers;
12650 int w32_modifiers;
12651 struct gcpro gcpro1;
12653 CHECK_VECTOR (key, 0);
12655 if (XFASTINT (Flength (key)) != 1)
12656 return Qnil;
12658 GCPRO1 (key);
12660 c = Faref (key, make_number (0));
12662 if (CONSP (c) && lucid_event_type_list_p (c))
12663 c = Fevent_convert_list (c);
12665 UNGCPRO;
12667 if (! INTEGERP (c) && ! SYMBOLP (c))
12668 error ("Key definition is invalid");
12670 /* Work out the base key and the modifiers. */
12671 if (SYMBOLP (c))
12673 c = parse_modifiers (c);
12674 lisp_modifiers = Fcar (Fcdr (c));
12675 c = Fcar (c);
12676 if (!SYMBOLP (c))
12677 abort ();
12678 vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
12680 else if (INTEGERP (c))
12682 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
12683 /* Many ascii characters are their own virtual key code. */
12684 vk_code = XINT (c) & CHARACTERBITS;
12687 if (vk_code < 0 || vk_code > 255)
12688 return Qnil;
12690 if ((lisp_modifiers & meta_modifier) != 0
12691 && !NILP (Vw32_alt_is_meta))
12692 lisp_modifiers |= alt_modifier;
12694 /* Supply defs missing from mingw32. */
12695 #ifndef MOD_ALT
12696 #define MOD_ALT 0x0001
12697 #define MOD_CONTROL 0x0002
12698 #define MOD_SHIFT 0x0004
12699 #define MOD_WIN 0x0008
12700 #endif
12702 /* Convert lisp modifiers to Windows hot-key form. */
12703 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
12704 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
12705 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
12706 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
12708 return HOTKEY (vk_code, w32_modifiers);
12711 DEFUN ("w32-register-hot-key", Fw32_register_hot_key, Sw32_register_hot_key, 1, 1, 0,
12712 "Register KEY as a hot-key combination.\n\
12713 Certain key combinations like Alt-Tab are reserved for system use on\n\
12714 Windows, and therefore are normally intercepted by the system. However,\n\
12715 most of these key combinations can be received by registering them as\n\
12716 hot-keys, overriding their special meaning.\n\
12718 KEY must be a one element key definition in vector form that would be\n\
12719 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta\n\
12720 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper\n\
12721 is always interpreted as the Windows modifier keys.\n\
12723 The return value is the hotkey-id if registered, otherwise nil.")
12724 (key)
12725 Lisp_Object key;
12727 key = w32_parse_hot_key (key);
12729 if (NILP (Fmemq (key, w32_grabbed_keys)))
12731 /* Reuse an empty slot if possible. */
12732 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
12734 /* Safe to add new key to list, even if we have focus. */
12735 if (NILP (item))
12736 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
12737 else
12738 XCAR (item) = key;
12740 /* Notify input thread about new hot-key definition, so that it
12741 takes effect without needing to switch focus. */
12742 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
12743 (WPARAM) key, 0);
12746 return key;
12749 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key, Sw32_unregister_hot_key, 1, 1, 0,
12750 "Unregister HOTKEY as a hot-key combination.")
12751 (key)
12752 Lisp_Object key;
12754 Lisp_Object item;
12756 if (!INTEGERP (key))
12757 key = w32_parse_hot_key (key);
12759 item = Fmemq (key, w32_grabbed_keys);
12761 if (!NILP (item))
12763 /* Notify input thread about hot-key definition being removed, so
12764 that it takes effect without needing focus switch. */
12765 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
12766 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
12768 MSG msg;
12769 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
12771 return Qt;
12773 return Qnil;
12776 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys, Sw32_registered_hot_keys, 0, 0, 0,
12777 "Return list of registered hot-key IDs.")
12780 return Fcopy_sequence (w32_grabbed_keys);
12783 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key, Sw32_reconstruct_hot_key, 1, 1, 0,
12784 "Convert hot-key ID to a lisp key combination.")
12785 (hotkeyid)
12786 Lisp_Object hotkeyid;
12788 int vk_code, w32_modifiers;
12789 Lisp_Object key;
12791 CHECK_NUMBER (hotkeyid, 0);
12793 vk_code = HOTKEY_VK_CODE (hotkeyid);
12794 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
12796 if (lispy_function_keys[vk_code])
12797 key = intern (lispy_function_keys[vk_code]);
12798 else
12799 key = make_number (vk_code);
12801 key = Fcons (key, Qnil);
12802 if (w32_modifiers & MOD_SHIFT)
12803 key = Fcons (Qshift, key);
12804 if (w32_modifiers & MOD_CONTROL)
12805 key = Fcons (Qctrl, key);
12806 if (w32_modifiers & MOD_ALT)
12807 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
12808 if (w32_modifiers & MOD_WIN)
12809 key = Fcons (Qhyper, key);
12811 return key;
12814 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key, Sw32_toggle_lock_key, 1, 2, 0,
12815 "Toggle the state of the lock key KEY.\n\
12816 KEY can be `capslock', `kp-numlock', or `scroll'.\n\
12817 If the optional parameter NEW-STATE is a number, then the state of KEY\n\
12818 is set to off if the low bit of NEW-STATE is zero, otherwise on.")
12819 (key, new_state)
12820 Lisp_Object key, new_state;
12822 int vk_code;
12823 int cur_state;
12825 if (EQ (key, intern ("capslock")))
12826 vk_code = VK_CAPITAL;
12827 else if (EQ (key, intern ("kp-numlock")))
12828 vk_code = VK_NUMLOCK;
12829 else if (EQ (key, intern ("scroll")))
12830 vk_code = VK_SCROLL;
12831 else
12832 return Qnil;
12834 if (!dwWindowsThreadId)
12835 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
12837 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
12838 (WPARAM) vk_code, (LPARAM) new_state))
12840 MSG msg;
12841 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
12842 return make_number (msg.wParam);
12844 return Qnil;
12847 syms_of_w32fns ()
12849 /* This is zero if not using MS-Windows. */
12850 w32_in_use = 0;
12852 /* The section below is built by the lisp expression at the top of the file,
12853 just above where these variables are declared. */
12854 /*&&& init symbols here &&&*/
12855 Qauto_raise = intern ("auto-raise");
12856 staticpro (&Qauto_raise);
12857 Qauto_lower = intern ("auto-lower");
12858 staticpro (&Qauto_lower);
12859 Qbar = intern ("bar");
12860 staticpro (&Qbar);
12861 Qborder_color = intern ("border-color");
12862 staticpro (&Qborder_color);
12863 Qborder_width = intern ("border-width");
12864 staticpro (&Qborder_width);
12865 Qbox = intern ("box");
12866 staticpro (&Qbox);
12867 Qcursor_color = intern ("cursor-color");
12868 staticpro (&Qcursor_color);
12869 Qcursor_type = intern ("cursor-type");
12870 staticpro (&Qcursor_type);
12871 Qgeometry = intern ("geometry");
12872 staticpro (&Qgeometry);
12873 Qicon_left = intern ("icon-left");
12874 staticpro (&Qicon_left);
12875 Qicon_top = intern ("icon-top");
12876 staticpro (&Qicon_top);
12877 Qicon_type = intern ("icon-type");
12878 staticpro (&Qicon_type);
12879 Qicon_name = intern ("icon-name");
12880 staticpro (&Qicon_name);
12881 Qinternal_border_width = intern ("internal-border-width");
12882 staticpro (&Qinternal_border_width);
12883 Qleft = intern ("left");
12884 staticpro (&Qleft);
12885 Qright = intern ("right");
12886 staticpro (&Qright);
12887 Qmouse_color = intern ("mouse-color");
12888 staticpro (&Qmouse_color);
12889 Qnone = intern ("none");
12890 staticpro (&Qnone);
12891 Qparent_id = intern ("parent-id");
12892 staticpro (&Qparent_id);
12893 Qscroll_bar_width = intern ("scroll-bar-width");
12894 staticpro (&Qscroll_bar_width);
12895 Qsuppress_icon = intern ("suppress-icon");
12896 staticpro (&Qsuppress_icon);
12897 Qundefined_color = intern ("undefined-color");
12898 staticpro (&Qundefined_color);
12899 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
12900 staticpro (&Qvertical_scroll_bars);
12901 Qvisibility = intern ("visibility");
12902 staticpro (&Qvisibility);
12903 Qwindow_id = intern ("window-id");
12904 staticpro (&Qwindow_id);
12905 Qx_frame_parameter = intern ("x-frame-parameter");
12906 staticpro (&Qx_frame_parameter);
12907 Qx_resource_name = intern ("x-resource-name");
12908 staticpro (&Qx_resource_name);
12909 Quser_position = intern ("user-position");
12910 staticpro (&Quser_position);
12911 Quser_size = intern ("user-size");
12912 staticpro (&Quser_size);
12913 Qscreen_gamma = intern ("screen-gamma");
12914 staticpro (&Qscreen_gamma);
12915 Qline_spacing = intern ("line-spacing");
12916 staticpro (&Qline_spacing);
12917 Qcenter = intern ("center");
12918 staticpro (&Qcenter);
12919 /* This is the end of symbol initialization. */
12921 Qhyper = intern ("hyper");
12922 staticpro (&Qhyper);
12923 Qsuper = intern ("super");
12924 staticpro (&Qsuper);
12925 Qmeta = intern ("meta");
12926 staticpro (&Qmeta);
12927 Qalt = intern ("alt");
12928 staticpro (&Qalt);
12929 Qctrl = intern ("ctrl");
12930 staticpro (&Qctrl);
12931 Qcontrol = intern ("control");
12932 staticpro (&Qcontrol);
12933 Qshift = intern ("shift");
12934 staticpro (&Qshift);
12936 /* Text property `display' should be nonsticky by default. */
12937 Vtext_property_default_nonsticky
12938 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
12941 Qlaplace = intern ("laplace");
12942 staticpro (&Qlaplace);
12944 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
12945 staticpro (&Qface_set_after_frame_default);
12947 Fput (Qundefined_color, Qerror_conditions,
12948 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
12949 Fput (Qundefined_color, Qerror_message,
12950 build_string ("Undefined color"));
12952 staticpro (&w32_grabbed_keys);
12953 w32_grabbed_keys = Qnil;
12955 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
12956 "An array of color name mappings for windows.");
12957 Vw32_color_map = Qnil;
12959 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
12960 "Non-nil if alt key presses are passed on to Windows.\n\
12961 When non-nil, for example, alt pressed and released and then space will\n\
12962 open the System menu. When nil, Emacs silently swallows alt key events.");
12963 Vw32_pass_alt_to_system = Qnil;
12965 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
12966 "Non-nil if the alt key is to be considered the same as the meta key.\n\
12967 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta.");
12968 Vw32_alt_is_meta = Qt;
12970 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
12971 "If non-zero, the virtual key code for an alternative quit key.");
12972 XSETINT (Vw32_quit_key, 0);
12974 DEFVAR_LISP ("w32-pass-lwindow-to-system",
12975 &Vw32_pass_lwindow_to_system,
12976 "Non-nil if the left \"Windows\" key is passed on to Windows.\n\
12977 When non-nil, the Start menu is opened by tapping the key.");
12978 Vw32_pass_lwindow_to_system = Qt;
12980 DEFVAR_LISP ("w32-pass-rwindow-to-system",
12981 &Vw32_pass_rwindow_to_system,
12982 "Non-nil if the right \"Windows\" key is passed on to Windows.\n\
12983 When non-nil, the Start menu is opened by tapping the key.");
12984 Vw32_pass_rwindow_to_system = Qt;
12986 DEFVAR_INT ("w32-phantom-key-code",
12987 &Vw32_phantom_key_code,
12988 "Virtual key code used to generate \"phantom\" key presses.\n\
12989 Value is a number between 0 and 255.\n\
12991 Phantom key presses are generated in order to stop the system from\n\
12992 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or\n\
12993 `w32-pass-rwindow-to-system' is nil.");
12994 /* Although 255 is technically not a valid key code, it works and
12995 means that this hack won't interfere with any real key code. */
12996 Vw32_phantom_key_code = 255;
12998 DEFVAR_LISP ("w32-enable-num-lock",
12999 &Vw32_enable_num_lock,
13000 "Non-nil if Num Lock should act normally.\n\
13001 Set to nil to see Num Lock as the key `kp-numlock'.");
13002 Vw32_enable_num_lock = Qt;
13004 DEFVAR_LISP ("w32-enable-caps-lock",
13005 &Vw32_enable_caps_lock,
13006 "Non-nil if Caps Lock should act normally.\n\
13007 Set to nil to see Caps Lock as the key `capslock'.");
13008 Vw32_enable_caps_lock = Qt;
13010 DEFVAR_LISP ("w32-scroll-lock-modifier",
13011 &Vw32_scroll_lock_modifier,
13012 "Modifier to use for the Scroll Lock on state.\n\
13013 The value can be hyper, super, meta, alt, control or shift for the\n\
13014 respective modifier, or nil to see Scroll Lock as the key `scroll'.\n\
13015 Any other value will cause the key to be ignored.");
13016 Vw32_scroll_lock_modifier = Qt;
13018 DEFVAR_LISP ("w32-lwindow-modifier",
13019 &Vw32_lwindow_modifier,
13020 "Modifier to use for the left \"Windows\" key.\n\
13021 The value can be hyper, super, meta, alt, control or shift for the\n\
13022 respective modifier, or nil to appear as the key `lwindow'.\n\
13023 Any other value will cause the key to be ignored.");
13024 Vw32_lwindow_modifier = Qnil;
13026 DEFVAR_LISP ("w32-rwindow-modifier",
13027 &Vw32_rwindow_modifier,
13028 "Modifier to use for the right \"Windows\" key.\n\
13029 The value can be hyper, super, meta, alt, control or shift for the\n\
13030 respective modifier, or nil to appear as the key `rwindow'.\n\
13031 Any other value will cause the key to be ignored.");
13032 Vw32_rwindow_modifier = Qnil;
13034 DEFVAR_LISP ("w32-apps-modifier",
13035 &Vw32_apps_modifier,
13036 "Modifier to use for the \"Apps\" key.\n\
13037 The value can be hyper, super, meta, alt, control or shift for the\n\
13038 respective modifier, or nil to appear as the key `apps'.\n\
13039 Any other value will cause the key to be ignored.");
13040 Vw32_apps_modifier = Qnil;
13042 DEFVAR_LISP ("w32-enable-synthesized-fonts", &Vw32_enable_synthesized_fonts,
13043 "Non-nil enables selection of artificially italicized and bold fonts.");
13044 Vw32_enable_synthesized_fonts = Qnil;
13046 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
13047 "Non-nil enables Windows palette management to map colors exactly.");
13048 Vw32_enable_palette = Qt;
13050 DEFVAR_INT ("w32-mouse-button-tolerance",
13051 &Vw32_mouse_button_tolerance,
13052 "Analogue of double click interval for faking middle mouse events.\n\
13053 The value is the minimum time in milliseconds that must elapse between\n\
13054 left/right button down events before they are considered distinct events.\n\
13055 If both mouse buttons are depressed within this interval, a middle mouse\n\
13056 button down event is generated instead.");
13057 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
13059 DEFVAR_INT ("w32-mouse-move-interval",
13060 &Vw32_mouse_move_interval,
13061 "Minimum interval between mouse move events.\n\
13062 The value is the minimum time in milliseconds that must elapse between\n\
13063 successive mouse move (or scroll bar drag) events before they are\n\
13064 reported as lisp events.");
13065 XSETINT (Vw32_mouse_move_interval, 0);
13067 init_x_parm_symbols ();
13069 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
13070 "List of directories to search for bitmap files for w32.");
13071 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
13073 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
13074 "The shape of the pointer when over text.\n\
13075 Changing the value does not affect existing frames\n\
13076 unless you set the mouse color.");
13077 Vx_pointer_shape = Qnil;
13079 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
13080 "The name Emacs uses to look up resources; for internal use only.\n\
13081 `x-get-resource' uses this as the first component of the instance name\n\
13082 when requesting resource values.\n\
13083 Emacs initially sets `x-resource-name' to the name under which Emacs\n\
13084 was invoked, or to the value specified with the `-name' or `-rn'\n\
13085 switches, if present.");
13086 Vx_resource_name = Qnil;
13088 Vx_nontext_pointer_shape = Qnil;
13090 Vx_mode_pointer_shape = Qnil;
13092 DEFVAR_LISP ("x-busy-pointer-shape", &Vx_busy_pointer_shape,
13093 "The shape of the pointer when Emacs is busy.\n\
13094 This variable takes effect when you create a new frame\n\
13095 or when you set the mouse color.");
13096 Vx_busy_pointer_shape = Qnil;
13098 DEFVAR_BOOL ("display-busy-cursor", &display_busy_cursor_p,
13099 "Non-zero means Emacs displays a busy cursor on window systems.");
13100 display_busy_cursor_p = 1;
13102 DEFVAR_LISP ("busy-cursor-delay", &Vbusy_cursor_delay,
13103 "*Seconds to wait before displaying a busy-cursor.\n\
13104 Value must be an integer or float.");
13105 Vbusy_cursor_delay = make_number (DEFAULT_BUSY_CURSOR_DELAY);
13107 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
13108 &Vx_sensitive_text_pointer_shape,
13109 "The shape of the pointer when over mouse-sensitive text.\n\
13110 This variable takes effect when you create a new frame\n\
13111 or when you set the mouse color.");
13112 Vx_sensitive_text_pointer_shape = Qnil;
13114 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
13115 "A string indicating the foreground color of the cursor box.");
13116 Vx_cursor_fore_pixel = Qnil;
13118 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
13119 "Non-nil if no window manager is in use.\n\
13120 Emacs doesn't try to figure this out; this is always nil\n\
13121 unless you set it to something else.");
13122 /* We don't have any way to find this out, so set it to nil
13123 and maybe the user would like to set it to t. */
13124 Vx_no_window_manager = Qnil;
13126 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
13127 &Vx_pixel_size_width_font_regexp,
13128 "Regexp matching a font name whose width is the same as `PIXEL_SIZE'.\n\
13130 Since Emacs gets width of a font matching with this regexp from\n\
13131 PIXEL_SIZE field of the name, font finding mechanism gets faster for\n\
13132 such a font. This is especially effective for such large fonts as\n\
13133 Chinese, Japanese, and Korean.");
13134 Vx_pixel_size_width_font_regexp = Qnil;
13136 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
13137 "Time after which cached images are removed from the cache.\n\
13138 When an image has not been displayed this many seconds, remove it\n\
13139 from the image cache. Value must be an integer or nil with nil\n\
13140 meaning don't clear the cache.");
13141 Vimage_cache_eviction_delay = make_number (30 * 60);
13143 DEFVAR_LISP ("w32-bdf-filename-alist",
13144 &Vw32_bdf_filename_alist,
13145 "List of bdf fonts and their corresponding filenames.");
13146 Vw32_bdf_filename_alist = Qnil;
13148 DEFVAR_BOOL ("w32-strict-fontnames",
13149 &w32_strict_fontnames,
13150 "Non-nil means only use fonts that are exact matches for those requested.\n\
13151 Default is nil, which allows old fontnames that are not XLFD compliant,\n\
13152 and allows third-party CJK display to work by specifying false charset\n\
13153 fields to trick Emacs into translating to Big5, SJIS etc.\n\
13154 Setting this to t will prevent wrong fonts being selected when\n\
13155 fontsets are automatically created.");
13156 w32_strict_fontnames = 0;
13158 DEFVAR_BOOL ("w32-strict-painting",
13159 &w32_strict_painting,
13160 "Non-nil means use strict rules for repainting frames.\n\
13161 Set this to nil to get the old behaviour for repainting; this should\n\
13162 only be necessary if the default setting causes problems.");
13163 w32_strict_painting = 1;
13165 DEFVAR_LISP ("w32-system-coding-system",
13166 &Vw32_system_coding_system,
13167 "Coding system used by Windows system functions, such as for font names.");
13168 Vw32_system_coding_system = Qnil;
13170 DEFVAR_LISP ("w32-charset-info-alist",
13171 &Vw32_charset_info_alist,
13172 "Alist linking Emacs character sets to Windows fonts\n\
13173 and codepages. Each entry should be of the form:\n\
13175 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))\n\
13177 where CHARSET_NAME is a string used in font names to identify the charset,\n\
13178 WINDOWS_CHARSET is a symbol that can be one of:\n\
13179 w32-charset-ansi, w32-charset-default, w32-charset-symbol,\n\
13180 w32-charset-shiftjis, w32-charset-hangul, w32-charset-gb2312,\n\
13181 w32-charset-chinesebig5, "
13182 #ifdef JOHAB_CHARSET
13183 "w32-charset-johab, w32-charset-hebrew,\n\
13184 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,\n\
13185 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,\n\
13186 w32-charset-russian, w32-charset-mac, w32-charset-baltic,\n"
13187 #endif
13188 #ifdef UNICODE_CHARSET
13189 "w32-charset-unicode, "
13190 #endif
13191 "or w32-charset-oem.\n\
13192 CODEPAGE should be an integer specifying the codepage that should be used\n\
13193 to display the character set, t to do no translation and output as Unicode,\n\
13194 or nil to do no translation and output as 8 bit (or multibyte on far-east\n\
13195 versions of Windows) characters.");
13196 Vw32_charset_info_alist = Qnil;
13198 staticpro (&Qw32_charset_ansi);
13199 Qw32_charset_ansi = intern ("w32-charset-ansi");
13200 staticpro (&Qw32_charset_symbol);
13201 Qw32_charset_symbol = intern ("w32-charset-symbol");
13202 staticpro (&Qw32_charset_shiftjis);
13203 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
13204 staticpro (&Qw32_charset_hangul);
13205 Qw32_charset_hangul = intern ("w32-charset-hangul");
13206 staticpro (&Qw32_charset_chinesebig5);
13207 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
13208 staticpro (&Qw32_charset_gb2312);
13209 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
13210 staticpro (&Qw32_charset_oem);
13211 Qw32_charset_oem = intern ("w32-charset-oem");
13213 #ifdef JOHAB_CHARSET
13215 static int w32_extra_charsets_defined = 1;
13216 DEFVAR_BOOL ("w32-extra-charsets-defined", w32_extra_charsets_defined, "");
13218 staticpro (&Qw32_charset_johab);
13219 Qw32_charset_johab = intern ("w32-charset-johab");
13220 staticpro (&Qw32_charset_easteurope);
13221 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
13222 staticpro (&Qw32_charset_turkish);
13223 Qw32_charset_turkish = intern ("w32-charset-turkish");
13224 staticpro (&Qw32_charset_baltic);
13225 Qw32_charset_baltic = intern ("w32-charset-baltic");
13226 staticpro (&Qw32_charset_russian);
13227 Qw32_charset_russian = intern ("w32-charset-russian");
13228 staticpro (&Qw32_charset_arabic);
13229 Qw32_charset_arabic = intern ("w32-charset-arabic");
13230 staticpro (&Qw32_charset_greek);
13231 Qw32_charset_greek = intern ("w32-charset-greek");
13232 staticpro (&Qw32_charset_hebrew);
13233 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
13234 staticpro (&Qw32_charset_thai);
13235 Qw32_charset_thai = intern ("w32-charset-thai");
13236 staticpro (&Qw32_charset_mac);
13237 Qw32_charset_mac = intern ("w32-charset-mac");
13239 #endif
13241 #ifdef UNICODE_CHARSET
13243 static int w32_unicode_charset_defined = 1;
13244 DEFVAR_BOOL ("w32-unicode-charset-defined",
13245 w32_unicode_charset_defined, "");
13247 staticpro (&Qw32_charset_unicode);
13248 Qw32_charset_unicode = intern ("w32-charset-unicode");
13249 #endif
13251 defsubr (&Sx_get_resource);
13252 #if 0 /* NTEMACS_TODO: Port to W32 */
13253 defsubr (&Sx_change_window_property);
13254 defsubr (&Sx_delete_window_property);
13255 defsubr (&Sx_window_property);
13256 #endif
13257 defsubr (&Sxw_display_color_p);
13258 defsubr (&Sx_display_grayscale_p);
13259 defsubr (&Sxw_color_defined_p);
13260 defsubr (&Sxw_color_values);
13261 defsubr (&Sx_server_max_request_size);
13262 defsubr (&Sx_server_vendor);
13263 defsubr (&Sx_server_version);
13264 defsubr (&Sx_display_pixel_width);
13265 defsubr (&Sx_display_pixel_height);
13266 defsubr (&Sx_display_mm_width);
13267 defsubr (&Sx_display_mm_height);
13268 defsubr (&Sx_display_screens);
13269 defsubr (&Sx_display_planes);
13270 defsubr (&Sx_display_color_cells);
13271 defsubr (&Sx_display_visual_class);
13272 defsubr (&Sx_display_backing_store);
13273 defsubr (&Sx_display_save_under);
13274 defsubr (&Sx_parse_geometry);
13275 defsubr (&Sx_create_frame);
13276 defsubr (&Sx_open_connection);
13277 defsubr (&Sx_close_connection);
13278 defsubr (&Sx_display_list);
13279 defsubr (&Sx_synchronize);
13281 /* W32 specific functions */
13283 defsubr (&Sw32_focus_frame);
13284 defsubr (&Sw32_select_font);
13285 defsubr (&Sw32_define_rgb_color);
13286 defsubr (&Sw32_default_color_map);
13287 defsubr (&Sw32_load_color_file);
13288 defsubr (&Sw32_send_sys_command);
13289 defsubr (&Sw32_shell_execute);
13290 defsubr (&Sw32_register_hot_key);
13291 defsubr (&Sw32_unregister_hot_key);
13292 defsubr (&Sw32_registered_hot_keys);
13293 defsubr (&Sw32_reconstruct_hot_key);
13294 defsubr (&Sw32_toggle_lock_key);
13295 defsubr (&Sw32_find_bdf_fonts);
13297 /* Setting callback functions for fontset handler. */
13298 get_font_info_func = w32_get_font_info;
13300 #if 0 /* This function pointer doesn't seem to be used anywhere.
13301 And the pointer assigned has the wrong type, anyway. */
13302 list_fonts_func = w32_list_fonts;
13303 #endif
13305 load_font_func = w32_load_font;
13306 find_ccl_program_func = w32_find_ccl_program;
13307 query_font_func = w32_query_font;
13308 set_frame_fontset_func = x_set_font;
13309 check_window_system_func = check_w32;
13311 #if 0 /* NTEMACS_TODO Image support for W32 */
13312 /* Images. */
13313 Qxbm = intern ("xbm");
13314 staticpro (&Qxbm);
13315 QCtype = intern (":type");
13316 staticpro (&QCtype);
13317 QCalgorithm = intern (":algorithm");
13318 staticpro (&QCalgorithm);
13319 QCheuristic_mask = intern (":heuristic-mask");
13320 staticpro (&QCheuristic_mask);
13321 QCcolor_symbols = intern (":color-symbols");
13322 staticpro (&QCcolor_symbols);
13323 QCascent = intern (":ascent");
13324 staticpro (&QCascent);
13325 QCmargin = intern (":margin");
13326 staticpro (&QCmargin);
13327 QCrelief = intern (":relief");
13328 staticpro (&QCrelief);
13329 Qpostscript = intern ("postscript");
13330 staticpro (&Qpostscript);
13331 QCloader = intern (":loader");
13332 staticpro (&QCloader);
13333 QCbounding_box = intern (":bounding-box");
13334 staticpro (&QCbounding_box);
13335 QCpt_width = intern (":pt-width");
13336 staticpro (&QCpt_width);
13337 QCpt_height = intern (":pt-height");
13338 staticpro (&QCpt_height);
13339 QCindex = intern (":index");
13340 staticpro (&QCindex);
13341 Qpbm = intern ("pbm");
13342 staticpro (&Qpbm);
13344 #if HAVE_XPM
13345 Qxpm = intern ("xpm");
13346 staticpro (&Qxpm);
13347 #endif
13349 #if HAVE_JPEG
13350 Qjpeg = intern ("jpeg");
13351 staticpro (&Qjpeg);
13352 #endif
13354 #if HAVE_TIFF
13355 Qtiff = intern ("tiff");
13356 staticpro (&Qtiff);
13357 #endif
13359 #if HAVE_GIF
13360 Qgif = intern ("gif");
13361 staticpro (&Qgif);
13362 #endif
13364 #if HAVE_PNG
13365 Qpng = intern ("png");
13366 staticpro (&Qpng);
13367 #endif
13369 defsubr (&Sclear_image_cache);
13371 #if GLYPH_DEBUG
13372 defsubr (&Simagep);
13373 defsubr (&Slookup_image);
13374 #endif
13375 #endif /* NTEMACS_TODO */
13377 busy_cursor_atimer = NULL;
13378 busy_cursor_shown_p = 0;
13380 defsubr (&Sx_show_tip);
13381 defsubr (&Sx_hide_tip);
13382 staticpro (&tip_timer);
13383 tip_timer = Qnil;
13385 defsubr (&Sx_file_dialog);
13389 void
13390 init_xfns ()
13392 image_types = NULL;
13393 Vimage_types = Qnil;
13395 #if 0 /* NTEMACS_TODO : Image support for W32 */
13396 define_image_type (&xbm_type);
13397 define_image_type (&gs_type);
13398 define_image_type (&pbm_type);
13400 #if HAVE_XPM
13401 define_image_type (&xpm_type);
13402 #endif
13404 #if HAVE_JPEG
13405 define_image_type (&jpeg_type);
13406 #endif
13408 #if HAVE_TIFF
13409 define_image_type (&tiff_type);
13410 #endif
13412 #if HAVE_GIF
13413 define_image_type (&gif_type);
13414 #endif
13416 #if HAVE_PNG
13417 define_image_type (&png_type);
13418 #endif
13419 #endif /* NTEMACS_TODO */
13422 #undef abort
13424 void
13425 w32_abort()
13427 int button;
13428 button = MessageBox (NULL,
13429 "A fatal error has occurred!\n\n"
13430 "Select Abort to exit, Retry to debug, Ignore to continue",
13431 "Emacs Abort Dialog",
13432 MB_ICONEXCLAMATION | MB_TASKMODAL
13433 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
13434 switch (button)
13436 case IDRETRY:
13437 DebugBreak ();
13438 break;
13439 case IDIGNORE:
13440 break;
13441 case IDABORT:
13442 default:
13443 abort ();
13444 break;
13448 /* For convenience when debugging. */
13450 w32_last_error()
13452 return GetLastError ();