(diary-button-face): Add group and version number.
[emacs.git] / src / w32fns.c
blobe0925869d896f617ed1c06649ecc6327906fc1f3
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 92, 93, 94, 95, 1996, 1997, 1998, 1999, 2000, 2001
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* Added by Kevin Gallo */
24 #include <config.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <limits.h>
29 #include <errno.h>
31 #include "lisp.h"
32 #include "charset.h"
33 #include "dispextern.h"
34 #include "w32term.h"
35 #include "keyboard.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "buffer.h"
39 #include "fontset.h"
40 #include "intervals.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 #include <dlgs.h>
56 #define FILE_NAME_TEXT_FIELD edt1
58 extern void free_frame_menubar ();
59 extern void x_compute_fringe_widths P_ ((struct frame *, int));
60 extern double atof ();
61 extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
62 extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
63 extern void w32_free_menu_strings P_ ((HWND));
65 extern int quit_char;
67 extern char *lispy_function_keys[];
69 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
70 it, and including `bitmaps/gray' more than once is a problem when
71 config.h defines `static' as an empty replacement string. */
73 int gray_bitmap_width = gray_width;
74 int gray_bitmap_height = gray_height;
75 unsigned char *gray_bitmap_bits = gray_bits;
77 /* The colormap for converting color names to RGB values */
78 Lisp_Object Vw32_color_map;
80 /* Non nil if alt key presses are passed on to Windows. */
81 Lisp_Object Vw32_pass_alt_to_system;
83 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
84 to alt_modifier. */
85 Lisp_Object Vw32_alt_is_meta;
87 /* If non-zero, the windows virtual key code for an alternative quit key. */
88 Lisp_Object Vw32_quit_key;
90 /* Non nil if left window key events are passed on to Windows (this only
91 affects whether "tapping" the key opens the Start menu). */
92 Lisp_Object Vw32_pass_lwindow_to_system;
94 /* Non nil if right window key events are passed on to Windows (this
95 only affects whether "tapping" the key opens the Start menu). */
96 Lisp_Object Vw32_pass_rwindow_to_system;
98 /* Virtual key code used to generate "phantom" key presses in order
99 to stop system from acting on Windows key events. */
100 Lisp_Object Vw32_phantom_key_code;
102 /* Modifier associated with the left "Windows" key, or nil to act as a
103 normal key. */
104 Lisp_Object Vw32_lwindow_modifier;
106 /* Modifier associated with the right "Windows" key, or nil to act as a
107 normal key. */
108 Lisp_Object Vw32_rwindow_modifier;
110 /* Modifier associated with the "Apps" key, or nil to act as a normal
111 key. */
112 Lisp_Object Vw32_apps_modifier;
114 /* Value is nil if Num Lock acts as a function key. */
115 Lisp_Object Vw32_enable_num_lock;
117 /* Value is nil if Caps Lock acts as a function key. */
118 Lisp_Object Vw32_enable_caps_lock;
120 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
121 Lisp_Object Vw32_scroll_lock_modifier;
123 /* Switch to control whether we inhibit requests for synthesized bold
124 and italic versions of fonts. */
125 int w32_enable_synthesized_fonts;
127 /* Enable palette management. */
128 Lisp_Object Vw32_enable_palette;
130 /* Control how close left/right button down events must be to
131 be converted to a middle button down event. */
132 Lisp_Object Vw32_mouse_button_tolerance;
134 /* Minimum interval between mouse movement (and scroll bar drag)
135 events that are passed on to the event loop. */
136 Lisp_Object Vw32_mouse_move_interval;
138 /* Flag to indicate if XBUTTON events should be passed on to Windows. */
139 int w32_pass_extra_mouse_buttons_to_system;
141 /* The name we're using in resource queries. */
142 Lisp_Object Vx_resource_name;
144 /* Non nil if no window manager is in use. */
145 Lisp_Object Vx_no_window_manager;
147 /* Non-zero means we're allowed to display a hourglass pointer. */
149 int display_hourglass_p;
151 /* The background and shape of the mouse pointer, and shape when not
152 over text or in the modeline. */
154 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
155 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
157 /* The shape when over mouse-sensitive text. */
159 Lisp_Object Vx_sensitive_text_pointer_shape;
161 /* Color of chars displayed in cursor box. */
163 Lisp_Object Vx_cursor_fore_pixel;
165 /* Nonzero if using Windows. */
167 static int w32_in_use;
169 /* Search path for bitmap files. */
171 Lisp_Object Vx_bitmap_file_path;
173 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
175 Lisp_Object Vx_pixel_size_width_font_regexp;
177 /* Alist of bdf fonts and the files that define them. */
178 Lisp_Object Vw32_bdf_filename_alist;
180 /* A flag to control whether fonts are matched strictly or not. */
181 int w32_strict_fontnames;
183 /* A flag to control whether we should only repaint if GetUpdateRect
184 indicates there is an update region. */
185 int w32_strict_painting;
187 /* Associative list linking character set strings to Windows codepages. */
188 Lisp_Object Vw32_charset_info_alist;
190 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
191 #ifndef VIETNAMESE_CHARSET
192 #define VIETNAMESE_CHARSET 163
193 #endif
195 Lisp_Object Qauto_raise;
196 Lisp_Object Qauto_lower;
197 Lisp_Object Qborder_color;
198 Lisp_Object Qborder_width;
199 extern Lisp_Object Qbox;
200 Lisp_Object Qcursor_color;
201 Lisp_Object Qcursor_type;
202 Lisp_Object Qgeometry;
203 Lisp_Object Qicon_left;
204 Lisp_Object Qicon_top;
205 Lisp_Object Qicon_type;
206 Lisp_Object Qicon_name;
207 Lisp_Object Qinternal_border_width;
208 Lisp_Object Qleft;
209 Lisp_Object Qright;
210 Lisp_Object Qmouse_color;
211 Lisp_Object Qnone;
212 Lisp_Object Qparent_id;
213 Lisp_Object Qscroll_bar_width;
214 Lisp_Object Qsuppress_icon;
215 Lisp_Object Qundefined_color;
216 Lisp_Object Qvertical_scroll_bars;
217 Lisp_Object Qvisibility;
218 Lisp_Object Qwindow_id;
219 Lisp_Object Qx_frame_parameter;
220 Lisp_Object Qx_resource_name;
221 Lisp_Object Quser_position;
222 Lisp_Object Quser_size;
223 Lisp_Object Qscreen_gamma;
224 Lisp_Object Qline_spacing;
225 Lisp_Object Qcenter;
226 Lisp_Object Qcancel_timer;
227 Lisp_Object Qhyper;
228 Lisp_Object Qsuper;
229 Lisp_Object Qmeta;
230 Lisp_Object Qalt;
231 Lisp_Object Qctrl;
232 Lisp_Object Qcontrol;
233 Lisp_Object Qshift;
235 Lisp_Object Qw32_charset_ansi;
236 Lisp_Object Qw32_charset_default;
237 Lisp_Object Qw32_charset_symbol;
238 Lisp_Object Qw32_charset_shiftjis;
239 Lisp_Object Qw32_charset_hangeul;
240 Lisp_Object Qw32_charset_gb2312;
241 Lisp_Object Qw32_charset_chinesebig5;
242 Lisp_Object Qw32_charset_oem;
244 #ifndef JOHAB_CHARSET
245 #define JOHAB_CHARSET 130
246 #endif
247 #ifdef JOHAB_CHARSET
248 Lisp_Object Qw32_charset_easteurope;
249 Lisp_Object Qw32_charset_turkish;
250 Lisp_Object Qw32_charset_baltic;
251 Lisp_Object Qw32_charset_russian;
252 Lisp_Object Qw32_charset_arabic;
253 Lisp_Object Qw32_charset_greek;
254 Lisp_Object Qw32_charset_hebrew;
255 Lisp_Object Qw32_charset_vietnamese;
256 Lisp_Object Qw32_charset_thai;
257 Lisp_Object Qw32_charset_johab;
258 Lisp_Object Qw32_charset_mac;
259 #endif
261 #ifdef UNICODE_CHARSET
262 Lisp_Object Qw32_charset_unicode;
263 #endif
265 Lisp_Object Qfullscreen;
266 Lisp_Object Qfullwidth;
267 Lisp_Object Qfullheight;
268 Lisp_Object Qfullboth;
270 extern Lisp_Object Qtop;
271 extern Lisp_Object Qdisplay;
273 /* State variables for emulating a three button mouse. */
274 #define LMOUSE 1
275 #define MMOUSE 2
276 #define RMOUSE 4
278 static int button_state = 0;
279 static W32Msg saved_mouse_button_msg;
280 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
281 static W32Msg saved_mouse_move_msg;
282 static unsigned mouse_move_timer = 0;
284 /* Window that is tracking the mouse. */
285 static HWND track_mouse_window;
286 FARPROC track_mouse_event_fn;
288 /* W95 mousewheel handler */
289 unsigned int msh_mousewheel = 0;
291 /* Timers */
292 #define MOUSE_BUTTON_ID 1
293 #define MOUSE_MOVE_ID 2
294 #define MENU_FREE_ID 3
295 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
296 is received. */
297 #define MENU_FREE_DELAY 1000
298 static unsigned menu_free_timer = 0;
300 /* The below are defined in frame.c. */
302 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
303 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
304 extern Lisp_Object Qtool_bar_lines;
306 extern Lisp_Object Vwindow_system_version;
308 Lisp_Object Qface_set_after_frame_default;
310 #ifdef GLYPH_DEBUG
311 int image_cache_refcount, dpyinfo_refcount;
312 #endif
315 /* From w32term.c. */
316 extern Lisp_Object Vw32_num_mouse_buttons;
317 extern Lisp_Object Vw32_recognize_altgr;
319 extern HWND w32_system_caret_hwnd;
321 extern int w32_system_caret_height;
322 extern int w32_system_caret_x;
323 extern int w32_system_caret_y;
324 extern int w32_use_visible_system_caret;
326 static HWND w32_visible_system_caret_hwnd;
329 /* Error if we are not connected to MS-Windows. */
330 void
331 check_w32 ()
333 if (! w32_in_use)
334 error ("MS-Windows not in use or not initialized");
337 /* Nonzero if we can use mouse menus.
338 You should not call this unless HAVE_MENUS is defined. */
341 have_menus_p ()
343 return w32_in_use;
346 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
347 and checking validity for W32. */
349 FRAME_PTR
350 check_x_frame (frame)
351 Lisp_Object frame;
353 FRAME_PTR f;
355 if (NILP (frame))
356 frame = selected_frame;
357 CHECK_LIVE_FRAME (frame);
358 f = XFRAME (frame);
359 if (! FRAME_W32_P (f))
360 error ("non-w32 frame used");
361 return f;
364 /* Let the user specify a display with a frame.
365 nil stands for the selected frame--or, if that is not a w32 frame,
366 the first display on the list. */
368 static struct w32_display_info *
369 check_x_display_info (frame)
370 Lisp_Object frame;
372 if (NILP (frame))
374 struct frame *sf = XFRAME (selected_frame);
376 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
377 return FRAME_W32_DISPLAY_INFO (sf);
378 else
379 return &one_w32_display_info;
381 else if (STRINGP (frame))
382 return x_display_info_for_name (frame);
383 else
385 FRAME_PTR f;
387 CHECK_LIVE_FRAME (frame);
388 f = XFRAME (frame);
389 if (! FRAME_W32_P (f))
390 error ("non-w32 frame used");
391 return FRAME_W32_DISPLAY_INFO (f);
395 /* Return the Emacs frame-object corresponding to an w32 window.
396 It could be the frame's main window or an icon window. */
398 /* This function can be called during GC, so use GC_xxx type test macros. */
400 struct frame *
401 x_window_to_frame (dpyinfo, wdesc)
402 struct w32_display_info *dpyinfo;
403 HWND wdesc;
405 Lisp_Object tail, frame;
406 struct frame *f;
408 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
410 frame = XCAR (tail);
411 if (!GC_FRAMEP (frame))
412 continue;
413 f = XFRAME (frame);
414 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
415 continue;
416 if (f->output_data.w32->hourglass_window == wdesc)
417 return f;
419 if (FRAME_W32_WINDOW (f) == wdesc)
420 return f;
422 return 0;
427 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
428 id, which is just an int that this section returns. Bitmaps are
429 reference counted so they can be shared among frames.
431 Bitmap indices are guaranteed to be > 0, so a negative number can
432 be used to indicate no bitmap.
434 If you use x_create_bitmap_from_data, then you must keep track of
435 the bitmaps yourself. That is, creating a bitmap from the same
436 data more than once will not be caught. */
439 /* Functions to access the contents of a bitmap, given an id. */
442 x_bitmap_height (f, id)
443 FRAME_PTR f;
444 int id;
446 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
450 x_bitmap_width (f, id)
451 FRAME_PTR f;
452 int id;
454 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
458 x_bitmap_pixmap (f, id)
459 FRAME_PTR f;
460 int id;
462 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
466 /* Allocate a new bitmap record. Returns index of new record. */
468 static int
469 x_allocate_bitmap_record (f)
470 FRAME_PTR f;
472 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
473 int i;
475 if (dpyinfo->bitmaps == NULL)
477 dpyinfo->bitmaps_size = 10;
478 dpyinfo->bitmaps
479 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
480 dpyinfo->bitmaps_last = 1;
481 return 1;
484 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
485 return ++dpyinfo->bitmaps_last;
487 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
488 if (dpyinfo->bitmaps[i].refcount == 0)
489 return i + 1;
491 dpyinfo->bitmaps_size *= 2;
492 dpyinfo->bitmaps
493 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
494 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
495 return ++dpyinfo->bitmaps_last;
498 /* Add one reference to the reference count of the bitmap with id ID. */
500 void
501 x_reference_bitmap (f, id)
502 FRAME_PTR f;
503 int id;
505 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
508 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
511 x_create_bitmap_from_data (f, bits, width, height)
512 struct frame *f;
513 char *bits;
514 unsigned int width, height;
516 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
517 Pixmap bitmap;
518 int id;
520 bitmap = CreateBitmap (width, height,
521 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
522 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
523 bits);
525 if (! bitmap)
526 return -1;
528 id = x_allocate_bitmap_record (f);
529 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
530 dpyinfo->bitmaps[id - 1].file = NULL;
531 dpyinfo->bitmaps[id - 1].hinst = NULL;
532 dpyinfo->bitmaps[id - 1].refcount = 1;
533 dpyinfo->bitmaps[id - 1].depth = 1;
534 dpyinfo->bitmaps[id - 1].height = height;
535 dpyinfo->bitmaps[id - 1].width = width;
537 return id;
540 /* Create bitmap from file FILE for frame F. */
543 x_create_bitmap_from_file (f, file)
544 struct frame *f;
545 Lisp_Object file;
547 return -1;
548 #if 0 /* TODO : bitmap support */
549 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
550 unsigned int width, height;
551 HBITMAP bitmap;
552 int xhot, yhot, result, id;
553 Lisp_Object found;
554 int fd;
555 char *filename;
556 HINSTANCE hinst;
558 /* Look for an existing bitmap with the same name. */
559 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
561 if (dpyinfo->bitmaps[id].refcount
562 && dpyinfo->bitmaps[id].file
563 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
565 ++dpyinfo->bitmaps[id].refcount;
566 return id + 1;
570 /* Search bitmap-file-path for the file, if appropriate. */
571 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
572 if (fd < 0)
573 return -1;
574 emacs_close (fd);
576 filename = (char *) SDATA (found);
578 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
580 if (hinst == NULL)
581 return -1;
584 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
585 filename, &width, &height, &bitmap, &xhot, &yhot);
586 if (result != BitmapSuccess)
587 return -1;
589 id = x_allocate_bitmap_record (f);
590 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
591 dpyinfo->bitmaps[id - 1].refcount = 1;
592 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SCHARS (file) + 1);
593 dpyinfo->bitmaps[id - 1].depth = 1;
594 dpyinfo->bitmaps[id - 1].height = height;
595 dpyinfo->bitmaps[id - 1].width = width;
596 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
598 return id;
599 #endif /* TODO */
602 /* Remove reference to bitmap with id number ID. */
604 void
605 x_destroy_bitmap (f, id)
606 FRAME_PTR f;
607 int id;
609 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
611 if (id > 0)
613 --dpyinfo->bitmaps[id - 1].refcount;
614 if (dpyinfo->bitmaps[id - 1].refcount == 0)
616 BLOCK_INPUT;
617 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
618 if (dpyinfo->bitmaps[id - 1].file)
620 xfree (dpyinfo->bitmaps[id - 1].file);
621 dpyinfo->bitmaps[id - 1].file = NULL;
623 UNBLOCK_INPUT;
628 /* Free all the bitmaps for the display specified by DPYINFO. */
630 static void
631 x_destroy_all_bitmaps (dpyinfo)
632 struct w32_display_info *dpyinfo;
634 int i;
635 for (i = 0; i < dpyinfo->bitmaps_last; i++)
636 if (dpyinfo->bitmaps[i].refcount > 0)
638 DeleteObject (dpyinfo->bitmaps[i].pixmap);
639 if (dpyinfo->bitmaps[i].file)
640 xfree (dpyinfo->bitmaps[i].file);
642 dpyinfo->bitmaps_last = 0;
645 /* Connect the frame-parameter names for W32 frames
646 to the ways of passing the parameter values to the window system.
648 The name of a parameter, as a Lisp symbol,
649 has an `x-frame-parameter' property which is an integer in Lisp
650 but can be interpreted as an `enum x_frame_parm' in C. */
652 enum x_frame_parm
654 X_PARM_FOREGROUND_COLOR,
655 X_PARM_BACKGROUND_COLOR,
656 X_PARM_MOUSE_COLOR,
657 X_PARM_CURSOR_COLOR,
658 X_PARM_BORDER_COLOR,
659 X_PARM_ICON_TYPE,
660 X_PARM_FONT,
661 X_PARM_BORDER_WIDTH,
662 X_PARM_INTERNAL_BORDER_WIDTH,
663 X_PARM_NAME,
664 X_PARM_AUTORAISE,
665 X_PARM_AUTOLOWER,
666 X_PARM_VERT_SCROLL_BAR,
667 X_PARM_VISIBILITY,
668 X_PARM_MENU_BAR_LINES
672 struct x_frame_parm_table
674 char *name;
675 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
678 BOOL my_show_window P_ ((struct frame *, HWND, int));
679 void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
680 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
681 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
682 static void x_change_window_heights P_ ((Lisp_Object, int));
683 /* TODO: Native Input Method support; see x_create_im. */
684 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
685 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
686 static void x_set_fullscreen P_ ((struct frame *, Lisp_Object, Lisp_Object));
687 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
688 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
689 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
690 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
691 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
692 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
693 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
694 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
695 static void x_set_fringe_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
696 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
697 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
698 Lisp_Object));
699 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
700 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
701 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
702 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
703 Lisp_Object));
704 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
705 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
706 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
707 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
708 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
709 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
710 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
711 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
712 Lisp_Object));
714 static struct x_frame_parm_table x_frame_parms[] =
716 {"auto-raise", x_set_autoraise},
717 {"auto-lower", x_set_autolower},
718 {"background-color", x_set_background_color},
719 {"border-color", x_set_border_color},
720 {"border-width", x_set_border_width},
721 {"cursor-color", x_set_cursor_color},
722 {"cursor-type", x_set_cursor_type},
723 {"font", x_set_font},
724 {"foreground-color", x_set_foreground_color},
725 {"icon-name", x_set_icon_name},
726 {"icon-type", x_set_icon_type},
727 {"internal-border-width", x_set_internal_border_width},
728 {"menu-bar-lines", x_set_menu_bar_lines},
729 {"mouse-color", x_set_mouse_color},
730 {"name", x_explicitly_set_name},
731 {"scroll-bar-width", x_set_scroll_bar_width},
732 {"title", x_set_title},
733 {"unsplittable", x_set_unsplittable},
734 {"vertical-scroll-bars", x_set_vertical_scroll_bars},
735 {"visibility", x_set_visibility},
736 {"tool-bar-lines", x_set_tool_bar_lines},
737 {"screen-gamma", x_set_screen_gamma},
738 {"line-spacing", x_set_line_spacing},
739 {"left-fringe", x_set_fringe_width},
740 {"right-fringe", x_set_fringe_width},
741 {"fullscreen", x_set_fullscreen},
744 /* Attach the `x-frame-parameter' properties to
745 the Lisp symbol names of parameters relevant to W32. */
747 void
748 init_x_parm_symbols ()
750 int i;
752 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
753 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
754 make_number (i));
757 /* Really try to move where we want to be in case of fullscreen. Some WMs
758 moves the window where we tell them. Some (mwm, twm) moves the outer
759 window manager window there instead.
760 Try to compensate for those WM here. */
761 static void
762 x_fullscreen_move (f, new_top, new_left)
763 struct frame *f;
764 int new_top;
765 int new_left;
767 if (new_top != f->output_data.w32->top_pos
768 || new_left != f->output_data.w32->left_pos)
770 int move_x = new_left;
771 int move_y = new_top;
773 f->output_data.w32->want_fullscreen |= FULLSCREEN_MOVE_WAIT;
774 x_set_offset (f, move_x, move_y, 1);
778 /* Change the parameters of frame F as specified by ALIST.
779 If a parameter is not specially recognized, do nothing;
780 otherwise call the `x_set_...' function for that parameter. */
782 void
783 x_set_frame_parameters (f, alist)
784 FRAME_PTR f;
785 Lisp_Object alist;
787 Lisp_Object tail;
789 /* If both of these parameters are present, it's more efficient to
790 set them both at once. So we wait until we've looked at the
791 entire list before we set them. */
792 int width, height;
794 /* Same here. */
795 Lisp_Object left, top;
797 /* Same with these. */
798 Lisp_Object icon_left, icon_top;
800 /* Record in these vectors all the parms specified. */
801 Lisp_Object *parms;
802 Lisp_Object *values;
803 int i, p;
804 int left_no_change = 0, top_no_change = 0;
805 int icon_left_no_change = 0, icon_top_no_change = 0;
806 int fullscreen_is_being_set = 0;
808 struct gcpro gcpro1, gcpro2;
810 i = 0;
811 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
812 i++;
814 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
815 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
817 /* Extract parm names and values into those vectors. */
819 i = 0;
820 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
822 Lisp_Object elt;
824 elt = Fcar (tail);
825 parms[i] = Fcar (elt);
826 values[i] = Fcdr (elt);
827 i++;
829 /* TAIL and ALIST are not used again below here. */
830 alist = tail = Qnil;
832 GCPRO2 (*parms, *values);
833 gcpro1.nvars = i;
834 gcpro2.nvars = i;
836 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
837 because their values appear in VALUES and strings are not valid. */
838 top = left = Qunbound;
839 icon_left = icon_top = Qunbound;
841 /* Provide default values for HEIGHT and WIDTH. */
842 if (FRAME_NEW_WIDTH (f))
843 width = FRAME_NEW_WIDTH (f);
844 else
845 width = FRAME_WIDTH (f);
847 if (FRAME_NEW_HEIGHT (f))
848 height = FRAME_NEW_HEIGHT (f);
849 else
850 height = FRAME_HEIGHT (f);
852 /* Process foreground_color and background_color before anything else.
853 They are independent of other properties, but other properties (e.g.,
854 cursor_color) are dependent upon them. */
855 /* Process default font as well, since fringe widths depends on it. */
856 for (p = 0; p < i; p++)
858 Lisp_Object prop, val;
860 prop = parms[p];
861 val = values[p];
862 if (EQ (prop, Qforeground_color)
863 || EQ (prop, Qbackground_color)
864 || EQ (prop, Qfont)
865 || EQ (prop, Qfullscreen))
867 register Lisp_Object param_index, old_value;
869 old_value = get_frame_param (f, prop);
870 fullscreen_is_being_set |= EQ (prop, Qfullscreen);
872 if (NILP (Fequal (val, old_value)))
874 store_frame_param (f, prop, val);
876 param_index = Fget (prop, Qx_frame_parameter);
877 if (NATNUMP (param_index)
878 && (XFASTINT (param_index)
879 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
880 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
885 /* Now process them in reverse of specified order. */
886 for (i--; i >= 0; i--)
888 Lisp_Object prop, val;
890 prop = parms[i];
891 val = values[i];
893 if (EQ (prop, Qwidth) && NUMBERP (val))
894 width = XFASTINT (val);
895 else if (EQ (prop, Qheight) && NUMBERP (val))
896 height = XFASTINT (val);
897 else if (EQ (prop, Qtop))
898 top = val;
899 else if (EQ (prop, Qleft))
900 left = val;
901 else if (EQ (prop, Qicon_top))
902 icon_top = val;
903 else if (EQ (prop, Qicon_left))
904 icon_left = val;
905 else if (EQ (prop, Qforeground_color)
906 || EQ (prop, Qbackground_color)
907 || EQ (prop, Qfont)
908 || EQ (prop, Qfullscreen))
909 /* Processed above. */
910 continue;
911 else
913 register Lisp_Object param_index, old_value;
915 old_value = get_frame_param (f, prop);
917 store_frame_param (f, prop, val);
919 param_index = Fget (prop, Qx_frame_parameter);
920 if (NATNUMP (param_index)
921 && (XFASTINT (param_index)
922 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
923 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
927 /* Don't die if just one of these was set. */
928 if (EQ (left, Qunbound))
930 left_no_change = 1;
931 if (f->output_data.w32->left_pos < 0)
932 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
933 else
934 XSETINT (left, f->output_data.w32->left_pos);
936 if (EQ (top, Qunbound))
938 top_no_change = 1;
939 if (f->output_data.w32->top_pos < 0)
940 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
941 else
942 XSETINT (top, f->output_data.w32->top_pos);
945 /* If one of the icon positions was not set, preserve or default it. */
946 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
948 icon_left_no_change = 1;
949 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
950 if (NILP (icon_left))
951 XSETINT (icon_left, 0);
953 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
955 icon_top_no_change = 1;
956 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
957 if (NILP (icon_top))
958 XSETINT (icon_top, 0);
961 if (FRAME_VISIBLE_P (f) && fullscreen_is_being_set)
963 /* If the frame is visible already and the fullscreen parameter is
964 being set, it is too late to set WM manager hints to specify
965 size and position.
966 Here we first get the width, height and position that applies to
967 fullscreen. We then move the frame to the appropriate
968 position. Resize of the frame is taken care of in the code after
969 this if-statement. */
970 int new_left, new_top;
972 x_fullscreen_adjust (f, &width, &height, &new_top, &new_left);
973 x_fullscreen_move (f, new_top, new_left);
976 /* Don't set these parameters unless they've been explicitly
977 specified. The window might be mapped or resized while we're in
978 this function, and we don't want to override that unless the lisp
979 code has asked for it.
981 Don't set these parameters unless they actually differ from the
982 window's current parameters; the window may not actually exist
983 yet. */
985 Lisp_Object frame;
987 check_frame_size (f, &height, &width);
989 XSETFRAME (frame, f);
991 if (width != FRAME_WIDTH (f)
992 || height != FRAME_HEIGHT (f)
993 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
994 Fset_frame_size (frame, make_number (width), make_number (height));
996 if ((!NILP (left) || !NILP (top))
997 && ! (left_no_change && top_no_change)
998 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
999 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
1001 int leftpos = 0;
1002 int toppos = 0;
1004 /* Record the signs. */
1005 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
1006 if (EQ (left, Qminus))
1007 f->output_data.w32->size_hint_flags |= XNegative;
1008 else if (INTEGERP (left))
1010 leftpos = XINT (left);
1011 if (leftpos < 0)
1012 f->output_data.w32->size_hint_flags |= XNegative;
1014 else if (CONSP (left) && EQ (XCAR (left), Qminus)
1015 && CONSP (XCDR (left))
1016 && INTEGERP (XCAR (XCDR (left))))
1018 leftpos = - XINT (XCAR (XCDR (left)));
1019 f->output_data.w32->size_hint_flags |= XNegative;
1021 else if (CONSP (left) && EQ (XCAR (left), Qplus)
1022 && CONSP (XCDR (left))
1023 && INTEGERP (XCAR (XCDR (left))))
1025 leftpos = XINT (XCAR (XCDR (left)));
1028 if (EQ (top, Qminus))
1029 f->output_data.w32->size_hint_flags |= YNegative;
1030 else if (INTEGERP (top))
1032 toppos = XINT (top);
1033 if (toppos < 0)
1034 f->output_data.w32->size_hint_flags |= YNegative;
1036 else if (CONSP (top) && EQ (XCAR (top), Qminus)
1037 && CONSP (XCDR (top))
1038 && INTEGERP (XCAR (XCDR (top))))
1040 toppos = - XINT (XCAR (XCDR (top)));
1041 f->output_data.w32->size_hint_flags |= YNegative;
1043 else if (CONSP (top) && EQ (XCAR (top), Qplus)
1044 && CONSP (XCDR (top))
1045 && INTEGERP (XCAR (XCDR (top))))
1047 toppos = XINT (XCAR (XCDR (top)));
1051 /* Store the numeric value of the position. */
1052 f->output_data.w32->top_pos = toppos;
1053 f->output_data.w32->left_pos = leftpos;
1055 f->output_data.w32->win_gravity = NorthWestGravity;
1057 /* Actually set that position, and convert to absolute. */
1058 x_set_offset (f, leftpos, toppos, -1);
1061 if ((!NILP (icon_left) || !NILP (icon_top))
1062 && ! (icon_left_no_change && icon_top_no_change))
1063 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1066 UNGCPRO;
1069 /* Store the screen positions of frame F into XPTR and YPTR.
1070 These are the positions of the containing window manager window,
1071 not Emacs's own window. */
1073 void
1074 x_real_positions (f, xptr, yptr)
1075 FRAME_PTR f;
1076 int *xptr, *yptr;
1078 POINT pt;
1079 RECT rect;
1081 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1082 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1084 pt.x = rect.left;
1085 pt.y = rect.top;
1087 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1089 /* Remember x_pixels_diff and y_pixels_diff. */
1090 f->output_data.w32->x_pixels_diff = pt.x - rect.left;
1091 f->output_data.w32->y_pixels_diff = pt.y - rect.top;
1093 *xptr = pt.x;
1094 *yptr = pt.y;
1097 /* Insert a description of internally-recorded parameters of frame X
1098 into the parameter alist *ALISTPTR that is to be given to the user.
1099 Only parameters that are specific to W32
1100 and whose values are not correctly recorded in the frame's
1101 param_alist need to be considered here. */
1103 void
1104 x_report_frame_params (f, alistptr)
1105 struct frame *f;
1106 Lisp_Object *alistptr;
1108 char buf[16];
1109 Lisp_Object tem;
1111 /* Represent negative positions (off the top or left screen edge)
1112 in a way that Fmodify_frame_parameters will understand correctly. */
1113 XSETINT (tem, f->output_data.w32->left_pos);
1114 if (f->output_data.w32->left_pos >= 0)
1115 store_in_alist (alistptr, Qleft, tem);
1116 else
1117 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1119 XSETINT (tem, f->output_data.w32->top_pos);
1120 if (f->output_data.w32->top_pos >= 0)
1121 store_in_alist (alistptr, Qtop, tem);
1122 else
1123 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1125 store_in_alist (alistptr, Qborder_width,
1126 make_number (f->output_data.w32->border_width));
1127 store_in_alist (alistptr, Qinternal_border_width,
1128 make_number (f->output_data.w32->internal_border_width));
1129 store_in_alist (alistptr, Qleft_fringe,
1130 make_number (f->output_data.w32->left_fringe_width));
1131 store_in_alist (alistptr, Qright_fringe,
1132 make_number (f->output_data.w32->right_fringe_width));
1133 store_in_alist (alistptr, Qscroll_bar_width,
1134 make_number (FRAME_HAS_VERTICAL_SCROLL_BARS (f)
1135 ? FRAME_SCROLL_BAR_PIXEL_WIDTH(f)
1136 : 0));
1137 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1138 store_in_alist (alistptr, Qwindow_id,
1139 build_string (buf));
1140 store_in_alist (alistptr, Qicon_name, f->icon_name);
1141 FRAME_SAMPLE_VISIBILITY (f);
1142 store_in_alist (alistptr, Qvisibility,
1143 (FRAME_VISIBLE_P (f) ? Qt
1144 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1145 store_in_alist (alistptr, Qdisplay,
1146 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1150 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
1151 Sw32_define_rgb_color, 4, 4, 0,
1152 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
1153 This adds or updates a named color to w32-color-map, making it
1154 available for use. The original entry's RGB ref is returned, or nil
1155 if the entry is new. */)
1156 (red, green, blue, name)
1157 Lisp_Object red, green, blue, name;
1159 Lisp_Object rgb;
1160 Lisp_Object oldrgb = Qnil;
1161 Lisp_Object entry;
1163 CHECK_NUMBER (red);
1164 CHECK_NUMBER (green);
1165 CHECK_NUMBER (blue);
1166 CHECK_STRING (name);
1168 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1170 BLOCK_INPUT;
1172 /* replace existing entry in w32-color-map or add new entry. */
1173 entry = Fassoc (name, Vw32_color_map);
1174 if (NILP (entry))
1176 entry = Fcons (name, rgb);
1177 Vw32_color_map = Fcons (entry, Vw32_color_map);
1179 else
1181 oldrgb = Fcdr (entry);
1182 Fsetcdr (entry, rgb);
1185 UNBLOCK_INPUT;
1187 return (oldrgb);
1190 DEFUN ("w32-load-color-file", Fw32_load_color_file,
1191 Sw32_load_color_file, 1, 1, 0,
1192 doc: /* Create an alist of color entries from an external file.
1193 Assign this value to w32-color-map to replace the existing color map.
1195 The file should define one named RGB color per line like so:
1196 R G B name
1197 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
1198 (filename)
1199 Lisp_Object filename;
1201 FILE *fp;
1202 Lisp_Object cmap = Qnil;
1203 Lisp_Object abspath;
1205 CHECK_STRING (filename);
1206 abspath = Fexpand_file_name (filename, Qnil);
1208 fp = fopen (SDATA (filename), "rt");
1209 if (fp)
1211 char buf[512];
1212 int red, green, blue;
1213 int num;
1215 BLOCK_INPUT;
1217 while (fgets (buf, sizeof (buf), fp) != NULL) {
1218 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1220 char *name = buf + num;
1221 num = strlen (name) - 1;
1222 if (name[num] == '\n')
1223 name[num] = 0;
1224 cmap = Fcons (Fcons (build_string (name),
1225 make_number (RGB (red, green, blue))),
1226 cmap);
1229 fclose (fp);
1231 UNBLOCK_INPUT;
1234 return cmap;
1237 /* The default colors for the w32 color map */
1238 typedef struct colormap_t
1240 char *name;
1241 COLORREF colorref;
1242 } colormap_t;
1244 colormap_t w32_color_map[] =
1246 {"snow" , PALETTERGB (255,250,250)},
1247 {"ghost white" , PALETTERGB (248,248,255)},
1248 {"GhostWhite" , PALETTERGB (248,248,255)},
1249 {"white smoke" , PALETTERGB (245,245,245)},
1250 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1251 {"gainsboro" , PALETTERGB (220,220,220)},
1252 {"floral white" , PALETTERGB (255,250,240)},
1253 {"FloralWhite" , PALETTERGB (255,250,240)},
1254 {"old lace" , PALETTERGB (253,245,230)},
1255 {"OldLace" , PALETTERGB (253,245,230)},
1256 {"linen" , PALETTERGB (250,240,230)},
1257 {"antique white" , PALETTERGB (250,235,215)},
1258 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1259 {"papaya whip" , PALETTERGB (255,239,213)},
1260 {"PapayaWhip" , PALETTERGB (255,239,213)},
1261 {"blanched almond" , PALETTERGB (255,235,205)},
1262 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1263 {"bisque" , PALETTERGB (255,228,196)},
1264 {"peach puff" , PALETTERGB (255,218,185)},
1265 {"PeachPuff" , PALETTERGB (255,218,185)},
1266 {"navajo white" , PALETTERGB (255,222,173)},
1267 {"NavajoWhite" , PALETTERGB (255,222,173)},
1268 {"moccasin" , PALETTERGB (255,228,181)},
1269 {"cornsilk" , PALETTERGB (255,248,220)},
1270 {"ivory" , PALETTERGB (255,255,240)},
1271 {"lemon chiffon" , PALETTERGB (255,250,205)},
1272 {"LemonChiffon" , PALETTERGB (255,250,205)},
1273 {"seashell" , PALETTERGB (255,245,238)},
1274 {"honeydew" , PALETTERGB (240,255,240)},
1275 {"mint cream" , PALETTERGB (245,255,250)},
1276 {"MintCream" , PALETTERGB (245,255,250)},
1277 {"azure" , PALETTERGB (240,255,255)},
1278 {"alice blue" , PALETTERGB (240,248,255)},
1279 {"AliceBlue" , PALETTERGB (240,248,255)},
1280 {"lavender" , PALETTERGB (230,230,250)},
1281 {"lavender blush" , PALETTERGB (255,240,245)},
1282 {"LavenderBlush" , PALETTERGB (255,240,245)},
1283 {"misty rose" , PALETTERGB (255,228,225)},
1284 {"MistyRose" , PALETTERGB (255,228,225)},
1285 {"white" , PALETTERGB (255,255,255)},
1286 {"black" , PALETTERGB ( 0, 0, 0)},
1287 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1288 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1289 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1290 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1291 {"dim gray" , PALETTERGB (105,105,105)},
1292 {"DimGray" , PALETTERGB (105,105,105)},
1293 {"dim grey" , PALETTERGB (105,105,105)},
1294 {"DimGrey" , PALETTERGB (105,105,105)},
1295 {"slate gray" , PALETTERGB (112,128,144)},
1296 {"SlateGray" , PALETTERGB (112,128,144)},
1297 {"slate grey" , PALETTERGB (112,128,144)},
1298 {"SlateGrey" , PALETTERGB (112,128,144)},
1299 {"light slate gray" , PALETTERGB (119,136,153)},
1300 {"LightSlateGray" , PALETTERGB (119,136,153)},
1301 {"light slate grey" , PALETTERGB (119,136,153)},
1302 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1303 {"gray" , PALETTERGB (190,190,190)},
1304 {"grey" , PALETTERGB (190,190,190)},
1305 {"light grey" , PALETTERGB (211,211,211)},
1306 {"LightGrey" , PALETTERGB (211,211,211)},
1307 {"light gray" , PALETTERGB (211,211,211)},
1308 {"LightGray" , PALETTERGB (211,211,211)},
1309 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1310 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1311 {"navy" , PALETTERGB ( 0, 0,128)},
1312 {"navy blue" , PALETTERGB ( 0, 0,128)},
1313 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1314 {"cornflower blue" , PALETTERGB (100,149,237)},
1315 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1316 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1317 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1318 {"slate blue" , PALETTERGB (106, 90,205)},
1319 {"SlateBlue" , PALETTERGB (106, 90,205)},
1320 {"medium slate blue" , PALETTERGB (123,104,238)},
1321 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1322 {"light slate blue" , PALETTERGB (132,112,255)},
1323 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1324 {"medium blue" , PALETTERGB ( 0, 0,205)},
1325 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1326 {"royal blue" , PALETTERGB ( 65,105,225)},
1327 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1328 {"blue" , PALETTERGB ( 0, 0,255)},
1329 {"dodger blue" , PALETTERGB ( 30,144,255)},
1330 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1331 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1332 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1333 {"sky blue" , PALETTERGB (135,206,235)},
1334 {"SkyBlue" , PALETTERGB (135,206,235)},
1335 {"light sky blue" , PALETTERGB (135,206,250)},
1336 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1337 {"steel blue" , PALETTERGB ( 70,130,180)},
1338 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1339 {"light steel blue" , PALETTERGB (176,196,222)},
1340 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1341 {"light blue" , PALETTERGB (173,216,230)},
1342 {"LightBlue" , PALETTERGB (173,216,230)},
1343 {"powder blue" , PALETTERGB (176,224,230)},
1344 {"PowderBlue" , PALETTERGB (176,224,230)},
1345 {"pale turquoise" , PALETTERGB (175,238,238)},
1346 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1347 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1348 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1349 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1350 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1351 {"turquoise" , PALETTERGB ( 64,224,208)},
1352 {"cyan" , PALETTERGB ( 0,255,255)},
1353 {"light cyan" , PALETTERGB (224,255,255)},
1354 {"LightCyan" , PALETTERGB (224,255,255)},
1355 {"cadet blue" , PALETTERGB ( 95,158,160)},
1356 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1357 {"medium aquamarine" , PALETTERGB (102,205,170)},
1358 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1359 {"aquamarine" , PALETTERGB (127,255,212)},
1360 {"dark green" , PALETTERGB ( 0,100, 0)},
1361 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1362 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1363 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1364 {"dark sea green" , PALETTERGB (143,188,143)},
1365 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1366 {"sea green" , PALETTERGB ( 46,139, 87)},
1367 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1368 {"medium sea green" , PALETTERGB ( 60,179,113)},
1369 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1370 {"light sea green" , PALETTERGB ( 32,178,170)},
1371 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1372 {"pale green" , PALETTERGB (152,251,152)},
1373 {"PaleGreen" , PALETTERGB (152,251,152)},
1374 {"spring green" , PALETTERGB ( 0,255,127)},
1375 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1376 {"lawn green" , PALETTERGB (124,252, 0)},
1377 {"LawnGreen" , PALETTERGB (124,252, 0)},
1378 {"green" , PALETTERGB ( 0,255, 0)},
1379 {"chartreuse" , PALETTERGB (127,255, 0)},
1380 {"medium spring green" , PALETTERGB ( 0,250,154)},
1381 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1382 {"green yellow" , PALETTERGB (173,255, 47)},
1383 {"GreenYellow" , PALETTERGB (173,255, 47)},
1384 {"lime green" , PALETTERGB ( 50,205, 50)},
1385 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1386 {"yellow green" , PALETTERGB (154,205, 50)},
1387 {"YellowGreen" , PALETTERGB (154,205, 50)},
1388 {"forest green" , PALETTERGB ( 34,139, 34)},
1389 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1390 {"olive drab" , PALETTERGB (107,142, 35)},
1391 {"OliveDrab" , PALETTERGB (107,142, 35)},
1392 {"dark khaki" , PALETTERGB (189,183,107)},
1393 {"DarkKhaki" , PALETTERGB (189,183,107)},
1394 {"khaki" , PALETTERGB (240,230,140)},
1395 {"pale goldenrod" , PALETTERGB (238,232,170)},
1396 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1397 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1398 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1399 {"light yellow" , PALETTERGB (255,255,224)},
1400 {"LightYellow" , PALETTERGB (255,255,224)},
1401 {"yellow" , PALETTERGB (255,255, 0)},
1402 {"gold" , PALETTERGB (255,215, 0)},
1403 {"light goldenrod" , PALETTERGB (238,221,130)},
1404 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1405 {"goldenrod" , PALETTERGB (218,165, 32)},
1406 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1407 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1408 {"rosy brown" , PALETTERGB (188,143,143)},
1409 {"RosyBrown" , PALETTERGB (188,143,143)},
1410 {"indian red" , PALETTERGB (205, 92, 92)},
1411 {"IndianRed" , PALETTERGB (205, 92, 92)},
1412 {"saddle brown" , PALETTERGB (139, 69, 19)},
1413 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1414 {"sienna" , PALETTERGB (160, 82, 45)},
1415 {"peru" , PALETTERGB (205,133, 63)},
1416 {"burlywood" , PALETTERGB (222,184,135)},
1417 {"beige" , PALETTERGB (245,245,220)},
1418 {"wheat" , PALETTERGB (245,222,179)},
1419 {"sandy brown" , PALETTERGB (244,164, 96)},
1420 {"SandyBrown" , PALETTERGB (244,164, 96)},
1421 {"tan" , PALETTERGB (210,180,140)},
1422 {"chocolate" , PALETTERGB (210,105, 30)},
1423 {"firebrick" , PALETTERGB (178,34, 34)},
1424 {"brown" , PALETTERGB (165,42, 42)},
1425 {"dark salmon" , PALETTERGB (233,150,122)},
1426 {"DarkSalmon" , PALETTERGB (233,150,122)},
1427 {"salmon" , PALETTERGB (250,128,114)},
1428 {"light salmon" , PALETTERGB (255,160,122)},
1429 {"LightSalmon" , PALETTERGB (255,160,122)},
1430 {"orange" , PALETTERGB (255,165, 0)},
1431 {"dark orange" , PALETTERGB (255,140, 0)},
1432 {"DarkOrange" , PALETTERGB (255,140, 0)},
1433 {"coral" , PALETTERGB (255,127, 80)},
1434 {"light coral" , PALETTERGB (240,128,128)},
1435 {"LightCoral" , PALETTERGB (240,128,128)},
1436 {"tomato" , PALETTERGB (255, 99, 71)},
1437 {"orange red" , PALETTERGB (255, 69, 0)},
1438 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1439 {"red" , PALETTERGB (255, 0, 0)},
1440 {"hot pink" , PALETTERGB (255,105,180)},
1441 {"HotPink" , PALETTERGB (255,105,180)},
1442 {"deep pink" , PALETTERGB (255, 20,147)},
1443 {"DeepPink" , PALETTERGB (255, 20,147)},
1444 {"pink" , PALETTERGB (255,192,203)},
1445 {"light pink" , PALETTERGB (255,182,193)},
1446 {"LightPink" , PALETTERGB (255,182,193)},
1447 {"pale violet red" , PALETTERGB (219,112,147)},
1448 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1449 {"maroon" , PALETTERGB (176, 48, 96)},
1450 {"medium violet red" , PALETTERGB (199, 21,133)},
1451 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1452 {"violet red" , PALETTERGB (208, 32,144)},
1453 {"VioletRed" , PALETTERGB (208, 32,144)},
1454 {"magenta" , PALETTERGB (255, 0,255)},
1455 {"violet" , PALETTERGB (238,130,238)},
1456 {"plum" , PALETTERGB (221,160,221)},
1457 {"orchid" , PALETTERGB (218,112,214)},
1458 {"medium orchid" , PALETTERGB (186, 85,211)},
1459 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1460 {"dark orchid" , PALETTERGB (153, 50,204)},
1461 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1462 {"dark violet" , PALETTERGB (148, 0,211)},
1463 {"DarkViolet" , PALETTERGB (148, 0,211)},
1464 {"blue violet" , PALETTERGB (138, 43,226)},
1465 {"BlueViolet" , PALETTERGB (138, 43,226)},
1466 {"purple" , PALETTERGB (160, 32,240)},
1467 {"medium purple" , PALETTERGB (147,112,219)},
1468 {"MediumPurple" , PALETTERGB (147,112,219)},
1469 {"thistle" , PALETTERGB (216,191,216)},
1470 {"gray0" , PALETTERGB ( 0, 0, 0)},
1471 {"grey0" , PALETTERGB ( 0, 0, 0)},
1472 {"dark grey" , PALETTERGB (169,169,169)},
1473 {"DarkGrey" , PALETTERGB (169,169,169)},
1474 {"dark gray" , PALETTERGB (169,169,169)},
1475 {"DarkGray" , PALETTERGB (169,169,169)},
1476 {"dark blue" , PALETTERGB ( 0, 0,139)},
1477 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1478 {"dark cyan" , PALETTERGB ( 0,139,139)},
1479 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1480 {"dark magenta" , PALETTERGB (139, 0,139)},
1481 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1482 {"dark red" , PALETTERGB (139, 0, 0)},
1483 {"DarkRed" , PALETTERGB (139, 0, 0)},
1484 {"light green" , PALETTERGB (144,238,144)},
1485 {"LightGreen" , PALETTERGB (144,238,144)},
1488 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1489 0, 0, 0, doc: /* Return the default color map. */)
1492 int i;
1493 colormap_t *pc = w32_color_map;
1494 Lisp_Object cmap;
1496 BLOCK_INPUT;
1498 cmap = Qnil;
1500 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1501 pc++, i++)
1502 cmap = Fcons (Fcons (build_string (pc->name),
1503 make_number (pc->colorref)),
1504 cmap);
1506 UNBLOCK_INPUT;
1508 return (cmap);
1511 Lisp_Object
1512 w32_to_x_color (rgb)
1513 Lisp_Object rgb;
1515 Lisp_Object color;
1517 CHECK_NUMBER (rgb);
1519 BLOCK_INPUT;
1521 color = Frassq (rgb, Vw32_color_map);
1523 UNBLOCK_INPUT;
1525 if (!NILP (color))
1526 return (Fcar (color));
1527 else
1528 return Qnil;
1531 COLORREF
1532 w32_color_map_lookup (colorname)
1533 char *colorname;
1535 Lisp_Object tail, ret = Qnil;
1537 BLOCK_INPUT;
1539 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1541 register Lisp_Object elt, tem;
1543 elt = Fcar (tail);
1544 if (!CONSP (elt)) continue;
1546 tem = Fcar (elt);
1548 if (lstrcmpi (SDATA (tem), colorname) == 0)
1550 ret = XUINT (Fcdr (elt));
1551 break;
1554 QUIT;
1558 UNBLOCK_INPUT;
1560 return ret;
1563 COLORREF
1564 x_to_w32_color (colorname)
1565 char * colorname;
1567 register Lisp_Object ret = Qnil;
1569 BLOCK_INPUT;
1571 if (colorname[0] == '#')
1573 /* Could be an old-style RGB Device specification. */
1574 char *color;
1575 int size;
1576 color = colorname + 1;
1578 size = strlen(color);
1579 if (size == 3 || size == 6 || size == 9 || size == 12)
1581 UINT colorval;
1582 int i, pos;
1583 pos = 0;
1584 size /= 3;
1585 colorval = 0;
1587 for (i = 0; i < 3; i++)
1589 char *end;
1590 char t;
1591 unsigned long value;
1593 /* The check for 'x' in the following conditional takes into
1594 account the fact that strtol allows a "0x" in front of
1595 our numbers, and we don't. */
1596 if (!isxdigit(color[0]) || color[1] == 'x')
1597 break;
1598 t = color[size];
1599 color[size] = '\0';
1600 value = strtoul(color, &end, 16);
1601 color[size] = t;
1602 if (errno == ERANGE || end - color != size)
1603 break;
1604 switch (size)
1606 case 1:
1607 value = value * 0x10;
1608 break;
1609 case 2:
1610 break;
1611 case 3:
1612 value /= 0x10;
1613 break;
1614 case 4:
1615 value /= 0x100;
1616 break;
1618 colorval |= (value << pos);
1619 pos += 0x8;
1620 if (i == 2)
1622 UNBLOCK_INPUT;
1623 return (colorval);
1625 color = end;
1629 else if (strnicmp(colorname, "rgb:", 4) == 0)
1631 char *color;
1632 UINT colorval;
1633 int i, pos;
1634 pos = 0;
1636 colorval = 0;
1637 color = colorname + 4;
1638 for (i = 0; i < 3; i++)
1640 char *end;
1641 unsigned long value;
1643 /* The check for 'x' in the following conditional takes into
1644 account the fact that strtol allows a "0x" in front of
1645 our numbers, and we don't. */
1646 if (!isxdigit(color[0]) || color[1] == 'x')
1647 break;
1648 value = strtoul(color, &end, 16);
1649 if (errno == ERANGE)
1650 break;
1651 switch (end - color)
1653 case 1:
1654 value = value * 0x10 + value;
1655 break;
1656 case 2:
1657 break;
1658 case 3:
1659 value /= 0x10;
1660 break;
1661 case 4:
1662 value /= 0x100;
1663 break;
1664 default:
1665 value = ULONG_MAX;
1667 if (value == ULONG_MAX)
1668 break;
1669 colorval |= (value << pos);
1670 pos += 0x8;
1671 if (i == 2)
1673 if (*end != '\0')
1674 break;
1675 UNBLOCK_INPUT;
1676 return (colorval);
1678 if (*end != '/')
1679 break;
1680 color = end + 1;
1683 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1685 /* This is an RGB Intensity specification. */
1686 char *color;
1687 UINT colorval;
1688 int i, pos;
1689 pos = 0;
1691 colorval = 0;
1692 color = colorname + 5;
1693 for (i = 0; i < 3; i++)
1695 char *end;
1696 double value;
1697 UINT val;
1699 value = strtod(color, &end);
1700 if (errno == ERANGE)
1701 break;
1702 if (value < 0.0 || value > 1.0)
1703 break;
1704 val = (UINT)(0x100 * value);
1705 /* We used 0x100 instead of 0xFF to give a continuous
1706 range between 0.0 and 1.0 inclusive. The next statement
1707 fixes the 1.0 case. */
1708 if (val == 0x100)
1709 val = 0xFF;
1710 colorval |= (val << pos);
1711 pos += 0x8;
1712 if (i == 2)
1714 if (*end != '\0')
1715 break;
1716 UNBLOCK_INPUT;
1717 return (colorval);
1719 if (*end != '/')
1720 break;
1721 color = end + 1;
1724 /* I am not going to attempt to handle any of the CIE color schemes
1725 or TekHVC, since I don't know the algorithms for conversion to
1726 RGB. */
1728 /* If we fail to lookup the color name in w32_color_map, then check the
1729 colorname to see if it can be crudely approximated: If the X color
1730 ends in a number (e.g., "darkseagreen2"), strip the number and
1731 return the result of looking up the base color name. */
1732 ret = w32_color_map_lookup (colorname);
1733 if (NILP (ret))
1735 int len = strlen (colorname);
1737 if (isdigit (colorname[len - 1]))
1739 char *ptr, *approx = alloca (len + 1);
1741 strcpy (approx, colorname);
1742 ptr = &approx[len - 1];
1743 while (ptr > approx && isdigit (*ptr))
1744 *ptr-- = '\0';
1746 ret = w32_color_map_lookup (approx);
1750 UNBLOCK_INPUT;
1751 return ret;
1755 void
1756 w32_regenerate_palette (FRAME_PTR f)
1758 struct w32_palette_entry * list;
1759 LOGPALETTE * log_palette;
1760 HPALETTE new_palette;
1761 int i;
1763 /* don't bother trying to create palette if not supported */
1764 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1765 return;
1767 log_palette = (LOGPALETTE *)
1768 alloca (sizeof (LOGPALETTE) +
1769 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1770 log_palette->palVersion = 0x300;
1771 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1773 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1774 for (i = 0;
1775 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1776 i++, list = list->next)
1777 log_palette->palPalEntry[i] = list->entry;
1779 new_palette = CreatePalette (log_palette);
1781 enter_crit ();
1783 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1784 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1785 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1787 /* Realize display palette and garbage all frames. */
1788 release_frame_dc (f, get_frame_dc (f));
1790 leave_crit ();
1793 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1794 #define SET_W32_COLOR(pe, color) \
1795 do \
1797 pe.peRed = GetRValue (color); \
1798 pe.peGreen = GetGValue (color); \
1799 pe.peBlue = GetBValue (color); \
1800 pe.peFlags = 0; \
1801 } while (0)
1803 #if 0
1804 /* Keep these around in case we ever want to track color usage. */
1805 void
1806 w32_map_color (FRAME_PTR f, COLORREF color)
1808 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1810 if (NILP (Vw32_enable_palette))
1811 return;
1813 /* check if color is already mapped */
1814 while (list)
1816 if (W32_COLOR (list->entry) == color)
1818 ++list->refcount;
1819 return;
1821 list = list->next;
1824 /* not already mapped, so add to list and recreate Windows palette */
1825 list = (struct w32_palette_entry *)
1826 xmalloc (sizeof (struct w32_palette_entry));
1827 SET_W32_COLOR (list->entry, color);
1828 list->refcount = 1;
1829 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1830 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1831 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1833 /* set flag that palette must be regenerated */
1834 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1837 void
1838 w32_unmap_color (FRAME_PTR f, COLORREF color)
1840 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1841 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1843 if (NILP (Vw32_enable_palette))
1844 return;
1846 /* check if color is already mapped */
1847 while (list)
1849 if (W32_COLOR (list->entry) == color)
1851 if (--list->refcount == 0)
1853 *prev = list->next;
1854 xfree (list);
1855 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1856 break;
1858 else
1859 return;
1861 prev = &list->next;
1862 list = list->next;
1865 /* set flag that palette must be regenerated */
1866 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1868 #endif
1871 /* Gamma-correct COLOR on frame F. */
1873 void
1874 gamma_correct (f, color)
1875 struct frame *f;
1876 COLORREF *color;
1878 if (f->gamma)
1880 *color = PALETTERGB (
1881 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1882 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1883 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1888 /* Decide if color named COLOR is valid for the display associated with
1889 the selected frame; if so, return the rgb values in COLOR_DEF.
1890 If ALLOC is nonzero, allocate a new colormap cell. */
1893 w32_defined_color (f, color, color_def, alloc)
1894 FRAME_PTR f;
1895 char *color;
1896 XColor *color_def;
1897 int alloc;
1899 register Lisp_Object tem;
1900 COLORREF w32_color_ref;
1902 tem = x_to_w32_color (color);
1904 if (!NILP (tem))
1906 if (f)
1908 /* Apply gamma correction. */
1909 w32_color_ref = XUINT (tem);
1910 gamma_correct (f, &w32_color_ref);
1911 XSETINT (tem, w32_color_ref);
1914 /* Map this color to the palette if it is enabled. */
1915 if (!NILP (Vw32_enable_palette))
1917 struct w32_palette_entry * entry =
1918 one_w32_display_info.color_list;
1919 struct w32_palette_entry ** prev =
1920 &one_w32_display_info.color_list;
1922 /* check if color is already mapped */
1923 while (entry)
1925 if (W32_COLOR (entry->entry) == XUINT (tem))
1926 break;
1927 prev = &entry->next;
1928 entry = entry->next;
1931 if (entry == NULL && alloc)
1933 /* not already mapped, so add to list */
1934 entry = (struct w32_palette_entry *)
1935 xmalloc (sizeof (struct w32_palette_entry));
1936 SET_W32_COLOR (entry->entry, XUINT (tem));
1937 entry->next = NULL;
1938 *prev = entry;
1939 one_w32_display_info.num_colors++;
1941 /* set flag that palette must be regenerated */
1942 one_w32_display_info.regen_palette = TRUE;
1945 /* Ensure COLORREF value is snapped to nearest color in (default)
1946 palette by simulating the PALETTERGB macro. This works whether
1947 or not the display device has a palette. */
1948 w32_color_ref = XUINT (tem) | 0x2000000;
1950 color_def->pixel = w32_color_ref;
1951 color_def->red = GetRValue (w32_color_ref) * 256;
1952 color_def->green = GetGValue (w32_color_ref) * 256;
1953 color_def->blue = GetBValue (w32_color_ref) * 256;
1955 return 1;
1957 else
1959 return 0;
1963 /* Given a string ARG naming a color, compute a pixel value from it
1964 suitable for screen F.
1965 If F is not a color screen, return DEF (default) regardless of what
1966 ARG says. */
1969 x_decode_color (f, arg, def)
1970 FRAME_PTR f;
1971 Lisp_Object arg;
1972 int def;
1974 XColor cdef;
1976 CHECK_STRING (arg);
1978 if (strcmp (SDATA (arg), "black") == 0)
1979 return BLACK_PIX_DEFAULT (f);
1980 else if (strcmp (SDATA (arg), "white") == 0)
1981 return WHITE_PIX_DEFAULT (f);
1983 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1984 return def;
1986 /* w32_defined_color is responsible for coping with failures
1987 by looking for a near-miss. */
1988 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1989 return cdef.pixel;
1991 /* defined_color failed; return an ultimate default. */
1992 return def;
1995 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
1996 the previous value of that parameter, NEW_VALUE is the new value. */
1998 static void
1999 x_set_line_spacing (f, new_value, old_value)
2000 struct frame *f;
2001 Lisp_Object new_value, old_value;
2003 if (NILP (new_value))
2004 f->extra_line_spacing = 0;
2005 else if (NATNUMP (new_value))
2006 f->extra_line_spacing = XFASTINT (new_value);
2007 else
2008 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
2009 Fcons (new_value, Qnil)));
2010 if (FRAME_VISIBLE_P (f))
2011 redraw_frame (f);
2015 /* Change the `fullscreen' frame parameter of frame F. OLD_VALUE is
2016 the previous value of that parameter, NEW_VALUE is the new value. */
2018 static void
2019 x_set_fullscreen (f, new_value, old_value)
2020 struct frame *f;
2021 Lisp_Object new_value, old_value;
2023 if (NILP (new_value))
2024 f->output_data.w32->want_fullscreen = FULLSCREEN_NONE;
2025 else if (EQ (new_value, Qfullboth))
2026 f->output_data.w32->want_fullscreen = FULLSCREEN_BOTH;
2027 else if (EQ (new_value, Qfullwidth))
2028 f->output_data.w32->want_fullscreen = FULLSCREEN_WIDTH;
2029 else if (EQ (new_value, Qfullheight))
2030 f->output_data.w32->want_fullscreen = FULLSCREEN_HEIGHT;
2034 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
2035 the previous value of that parameter, NEW_VALUE is the new value. */
2037 static void
2038 x_set_screen_gamma (f, new_value, old_value)
2039 struct frame *f;
2040 Lisp_Object new_value, old_value;
2042 if (NILP (new_value))
2043 f->gamma = 0;
2044 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
2045 /* The value 0.4545 is the normal viewing gamma. */
2046 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
2047 else
2048 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
2049 Fcons (new_value, Qnil)));
2051 clear_face_cache (0);
2055 /* Functions called only from `x_set_frame_param'
2056 to set individual parameters.
2058 If FRAME_W32_WINDOW (f) is 0,
2059 the frame is being created and its window does not exist yet.
2060 In that case, just record the parameter's new value
2061 in the standard place; do not attempt to change the window. */
2063 void
2064 x_set_foreground_color (f, arg, oldval)
2065 struct frame *f;
2066 Lisp_Object arg, oldval;
2068 struct w32_output *x = f->output_data.w32;
2069 PIX_TYPE fg, old_fg;
2071 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2072 old_fg = FRAME_FOREGROUND_PIXEL (f);
2073 FRAME_FOREGROUND_PIXEL (f) = fg;
2075 if (FRAME_W32_WINDOW (f) != 0)
2077 if (x->cursor_pixel == old_fg)
2078 x->cursor_pixel = fg;
2080 update_face_from_frame_parameter (f, Qforeground_color, arg);
2081 if (FRAME_VISIBLE_P (f))
2082 redraw_frame (f);
2086 void
2087 x_set_background_color (f, arg, oldval)
2088 struct frame *f;
2089 Lisp_Object arg, oldval;
2091 FRAME_BACKGROUND_PIXEL (f)
2092 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2094 if (FRAME_W32_WINDOW (f) != 0)
2096 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2097 FRAME_BACKGROUND_PIXEL (f));
2099 update_face_from_frame_parameter (f, Qbackground_color, arg);
2101 if (FRAME_VISIBLE_P (f))
2102 redraw_frame (f);
2106 void
2107 x_set_mouse_color (f, arg, oldval)
2108 struct frame *f;
2109 Lisp_Object arg, oldval;
2111 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2112 int count;
2113 int mask_color;
2115 if (!EQ (Qnil, arg))
2116 f->output_data.w32->mouse_pixel
2117 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2118 mask_color = FRAME_BACKGROUND_PIXEL (f);
2120 /* Don't let pointers be invisible. */
2121 if (mask_color == f->output_data.w32->mouse_pixel
2122 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2123 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2125 #if 0 /* TODO : cursor changes */
2126 BLOCK_INPUT;
2128 /* It's not okay to crash if the user selects a screwy cursor. */
2129 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2131 if (!EQ (Qnil, Vx_pointer_shape))
2133 CHECK_NUMBER (Vx_pointer_shape);
2134 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2136 else
2137 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2138 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2140 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2142 CHECK_NUMBER (Vx_nontext_pointer_shape);
2143 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2144 XINT (Vx_nontext_pointer_shape));
2146 else
2147 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2148 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2150 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
2152 CHECK_NUMBER (Vx_hourglass_pointer_shape);
2153 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2154 XINT (Vx_hourglass_pointer_shape));
2156 else
2157 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2158 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2160 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2161 if (!EQ (Qnil, Vx_mode_pointer_shape))
2163 CHECK_NUMBER (Vx_mode_pointer_shape);
2164 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2165 XINT (Vx_mode_pointer_shape));
2167 else
2168 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2169 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2171 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2173 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
2174 cross_cursor
2175 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2176 XINT (Vx_sensitive_text_pointer_shape));
2178 else
2179 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2181 if (!NILP (Vx_window_horizontal_drag_shape))
2183 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
2184 horizontal_drag_cursor
2185 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2186 XINT (Vx_window_horizontal_drag_shape));
2188 else
2189 horizontal_drag_cursor
2190 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2192 /* Check and report errors with the above calls. */
2193 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2194 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2197 XColor fore_color, back_color;
2199 fore_color.pixel = f->output_data.w32->mouse_pixel;
2200 back_color.pixel = mask_color;
2201 XQueryColor (FRAME_W32_DISPLAY (f),
2202 DefaultColormap (FRAME_W32_DISPLAY (f),
2203 DefaultScreen (FRAME_W32_DISPLAY (f))),
2204 &fore_color);
2205 XQueryColor (FRAME_W32_DISPLAY (f),
2206 DefaultColormap (FRAME_W32_DISPLAY (f),
2207 DefaultScreen (FRAME_W32_DISPLAY (f))),
2208 &back_color);
2209 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2210 &fore_color, &back_color);
2211 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2212 &fore_color, &back_color);
2213 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2214 &fore_color, &back_color);
2215 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2216 &fore_color, &back_color);
2217 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
2218 &fore_color, &back_color);
2221 if (FRAME_W32_WINDOW (f) != 0)
2222 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2224 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2225 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2226 f->output_data.w32->text_cursor = cursor;
2228 if (nontext_cursor != f->output_data.w32->nontext_cursor
2229 && f->output_data.w32->nontext_cursor != 0)
2230 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2231 f->output_data.w32->nontext_cursor = nontext_cursor;
2233 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
2234 && f->output_data.w32->hourglass_cursor != 0)
2235 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
2236 f->output_data.w32->hourglass_cursor = hourglass_cursor;
2238 if (mode_cursor != f->output_data.w32->modeline_cursor
2239 && f->output_data.w32->modeline_cursor != 0)
2240 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2241 f->output_data.w32->modeline_cursor = mode_cursor;
2243 if (cross_cursor != f->output_data.w32->cross_cursor
2244 && f->output_data.w32->cross_cursor != 0)
2245 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2246 f->output_data.w32->cross_cursor = cross_cursor;
2248 XFlush (FRAME_W32_DISPLAY (f));
2249 UNBLOCK_INPUT;
2251 update_face_from_frame_parameter (f, Qmouse_color, arg);
2252 #endif /* TODO */
2255 /* Defined in w32term.c. */
2256 void x_update_cursor (struct frame *f, int on_p);
2258 void
2259 x_set_cursor_color (f, arg, oldval)
2260 struct frame *f;
2261 Lisp_Object arg, oldval;
2263 unsigned long fore_pixel, pixel;
2265 if (!NILP (Vx_cursor_fore_pixel))
2266 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2267 WHITE_PIX_DEFAULT (f));
2268 else
2269 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2271 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2273 /* Make sure that the cursor color differs from the background color. */
2274 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2276 pixel = f->output_data.w32->mouse_pixel;
2277 if (pixel == fore_pixel)
2278 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2281 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
2282 f->output_data.w32->cursor_pixel = pixel;
2284 if (FRAME_W32_WINDOW (f) != 0)
2286 BLOCK_INPUT;
2287 /* Update frame's cursor_gc. */
2288 f->output_data.w32->cursor_gc->foreground = fore_pixel;
2289 f->output_data.w32->cursor_gc->background = pixel;
2291 UNBLOCK_INPUT;
2293 if (FRAME_VISIBLE_P (f))
2295 x_update_cursor (f, 0);
2296 x_update_cursor (f, 1);
2300 update_face_from_frame_parameter (f, Qcursor_color, arg);
2303 /* Set the border-color of frame F to pixel value PIX.
2304 Note that this does not fully take effect if done before
2305 F has a window. */
2306 void
2307 x_set_border_pixel (f, pix)
2308 struct frame *f;
2309 int pix;
2311 f->output_data.w32->border_pixel = pix;
2313 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2315 if (FRAME_VISIBLE_P (f))
2316 redraw_frame (f);
2320 /* Set the border-color of frame F to value described by ARG.
2321 ARG can be a string naming a color.
2322 The border-color is used for the border that is drawn by the server.
2323 Note that this does not fully take effect if done before
2324 F has a window; it must be redone when the window is created. */
2326 void
2327 x_set_border_color (f, arg, oldval)
2328 struct frame *f;
2329 Lisp_Object arg, oldval;
2331 int pix;
2333 CHECK_STRING (arg);
2334 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2335 x_set_border_pixel (f, pix);
2336 update_face_from_frame_parameter (f, Qborder_color, arg);
2340 void
2341 x_set_cursor_type (f, arg, oldval)
2342 FRAME_PTR f;
2343 Lisp_Object arg, oldval;
2345 set_frame_cursor_types (f, arg);
2347 /* Make sure the cursor gets redrawn. This is overkill, but how
2348 often do people change cursor types? */
2349 update_mode_lines++;
2352 void
2353 x_set_icon_type (f, arg, oldval)
2354 struct frame *f;
2355 Lisp_Object arg, oldval;
2357 int result;
2359 if (NILP (arg) && NILP (oldval))
2360 return;
2362 if (STRINGP (arg) && STRINGP (oldval)
2363 && EQ (Fstring_equal (oldval, arg), Qt))
2364 return;
2366 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2367 return;
2369 BLOCK_INPUT;
2371 result = x_bitmap_icon (f, arg);
2372 if (result)
2374 UNBLOCK_INPUT;
2375 error ("No icon window available");
2378 UNBLOCK_INPUT;
2381 /* Return non-nil if frame F wants a bitmap icon. */
2383 Lisp_Object
2384 x_icon_type (f)
2385 FRAME_PTR f;
2387 Lisp_Object tem;
2389 tem = assq_no_quit (Qicon_type, f->param_alist);
2390 if (CONSP (tem))
2391 return XCDR (tem);
2392 else
2393 return Qnil;
2396 void
2397 x_set_icon_name (f, arg, oldval)
2398 struct frame *f;
2399 Lisp_Object arg, oldval;
2401 if (STRINGP (arg))
2403 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2404 return;
2406 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2407 return;
2409 f->icon_name = arg;
2411 #if 0
2412 if (f->output_data.w32->icon_bitmap != 0)
2413 return;
2415 BLOCK_INPUT;
2417 result = x_text_icon (f,
2418 (char *) SDATA ((!NILP (f->icon_name)
2419 ? f->icon_name
2420 : !NILP (f->title)
2421 ? f->title
2422 : f->name)));
2424 if (result)
2426 UNBLOCK_INPUT;
2427 error ("No icon window available");
2430 /* If the window was unmapped (and its icon was mapped),
2431 the new icon is not mapped, so map the window in its stead. */
2432 if (FRAME_VISIBLE_P (f))
2434 #ifdef USE_X_TOOLKIT
2435 XtPopup (f->output_data.w32->widget, XtGrabNone);
2436 #endif
2437 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2440 XFlush (FRAME_W32_DISPLAY (f));
2441 UNBLOCK_INPUT;
2442 #endif
2445 extern Lisp_Object x_new_font ();
2446 extern Lisp_Object x_new_fontset();
2448 void
2449 x_set_font (f, arg, oldval)
2450 struct frame *f;
2451 Lisp_Object arg, oldval;
2453 Lisp_Object result;
2454 Lisp_Object fontset_name;
2455 Lisp_Object frame;
2456 int old_fontset = FRAME_FONTSET(f);
2458 CHECK_STRING (arg);
2460 fontset_name = Fquery_fontset (arg, Qnil);
2462 BLOCK_INPUT;
2463 result = (STRINGP (fontset_name)
2464 ? x_new_fontset (f, SDATA (fontset_name))
2465 : x_new_font (f, SDATA (arg)));
2466 UNBLOCK_INPUT;
2468 if (EQ (result, Qnil))
2469 error ("Font `%s' is not defined", SDATA (arg));
2470 else if (EQ (result, Qt))
2471 error ("The characters of the given font have varying widths");
2472 else if (STRINGP (result))
2474 if (STRINGP (fontset_name))
2476 /* Fontset names are built from ASCII font names, so the
2477 names may be equal despite there was a change. */
2478 if (old_fontset == FRAME_FONTSET (f))
2479 return;
2481 else if (!NILP (Fequal (result, oldval)))
2482 return;
2484 store_frame_param (f, Qfont, result);
2485 recompute_basic_faces (f);
2487 else
2488 abort ();
2490 do_pending_window_change (0);
2492 /* Don't call `face-set-after-frame-default' when faces haven't been
2493 initialized yet. This is the case when called from
2494 Fx_create_frame. In that case, the X widget or window doesn't
2495 exist either, and we can end up in x_report_frame_params with a
2496 null widget which gives a segfault. */
2497 if (FRAME_FACE_CACHE (f))
2499 XSETFRAME (frame, f);
2500 call1 (Qface_set_after_frame_default, frame);
2504 static void
2505 x_set_fringe_width (f, new_value, old_value)
2506 struct frame *f;
2507 Lisp_Object new_value, old_value;
2509 x_compute_fringe_widths (f, 1);
2512 void
2513 x_set_border_width (f, arg, oldval)
2514 struct frame *f;
2515 Lisp_Object arg, oldval;
2517 CHECK_NUMBER (arg);
2519 if (XINT (arg) == f->output_data.w32->border_width)
2520 return;
2522 if (FRAME_W32_WINDOW (f) != 0)
2523 error ("Cannot change the border width of a window");
2525 f->output_data.w32->border_width = XINT (arg);
2528 void
2529 x_set_internal_border_width (f, arg, oldval)
2530 struct frame *f;
2531 Lisp_Object arg, oldval;
2533 int old = f->output_data.w32->internal_border_width;
2535 CHECK_NUMBER (arg);
2536 f->output_data.w32->internal_border_width = XINT (arg);
2537 if (f->output_data.w32->internal_border_width < 0)
2538 f->output_data.w32->internal_border_width = 0;
2540 if (f->output_data.w32->internal_border_width == old)
2541 return;
2543 if (FRAME_W32_WINDOW (f) != 0)
2545 x_set_window_size (f, 0, f->width, f->height);
2546 SET_FRAME_GARBAGED (f);
2547 do_pending_window_change (0);
2549 else
2550 SET_FRAME_GARBAGED (f);
2553 void
2554 x_set_visibility (f, value, oldval)
2555 struct frame *f;
2556 Lisp_Object value, oldval;
2558 Lisp_Object frame;
2559 XSETFRAME (frame, f);
2561 if (NILP (value))
2562 Fmake_frame_invisible (frame, Qt);
2563 else if (EQ (value, Qicon))
2564 Ficonify_frame (frame);
2565 else
2566 Fmake_frame_visible (frame);
2570 /* Change window heights in windows rooted in WINDOW by N lines. */
2572 static void
2573 x_change_window_heights (window, n)
2574 Lisp_Object window;
2575 int n;
2577 struct window *w = XWINDOW (window);
2579 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2580 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2582 if (INTEGERP (w->orig_top))
2583 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2584 if (INTEGERP (w->orig_height))
2585 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2587 /* Handle just the top child in a vertical split. */
2588 if (!NILP (w->vchild))
2589 x_change_window_heights (w->vchild, n);
2591 /* Adjust all children in a horizontal split. */
2592 for (window = w->hchild; !NILP (window); window = w->next)
2594 w = XWINDOW (window);
2595 x_change_window_heights (window, n);
2599 void
2600 x_set_menu_bar_lines (f, value, oldval)
2601 struct frame *f;
2602 Lisp_Object value, oldval;
2604 int nlines;
2605 int olines = FRAME_MENU_BAR_LINES (f);
2607 /* Right now, menu bars don't work properly in minibuf-only frames;
2608 most of the commands try to apply themselves to the minibuffer
2609 frame itself, and get an error because you can't switch buffers
2610 in or split the minibuffer window. */
2611 if (FRAME_MINIBUF_ONLY_P (f))
2612 return;
2614 if (INTEGERP (value))
2615 nlines = XINT (value);
2616 else
2617 nlines = 0;
2619 FRAME_MENU_BAR_LINES (f) = 0;
2620 if (nlines)
2621 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2622 else
2624 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2625 free_frame_menubar (f);
2626 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2628 /* Adjust the frame size so that the client (text) dimensions
2629 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2630 set correctly. */
2631 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2632 do_pending_window_change (0);
2634 adjust_glyphs (f);
2638 /* Set the number of lines used for the tool bar of frame F to VALUE.
2639 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2640 is the old number of tool bar lines. This function changes the
2641 height of all windows on frame F to match the new tool bar height.
2642 The frame's height doesn't change. */
2644 void
2645 x_set_tool_bar_lines (f, value, oldval)
2646 struct frame *f;
2647 Lisp_Object value, oldval;
2649 int delta, nlines, root_height;
2650 Lisp_Object root_window;
2652 /* Treat tool bars like menu bars. */
2653 if (FRAME_MINIBUF_ONLY_P (f))
2654 return;
2656 /* Use VALUE only if an integer >= 0. */
2657 if (INTEGERP (value) && XINT (value) >= 0)
2658 nlines = XFASTINT (value);
2659 else
2660 nlines = 0;
2662 /* Make sure we redisplay all windows in this frame. */
2663 ++windows_or_buffers_changed;
2665 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2667 /* Don't resize the tool-bar to more than we have room for. */
2668 root_window = FRAME_ROOT_WINDOW (f);
2669 root_height = XINT (XWINDOW (root_window)->height);
2670 if (root_height - delta < 1)
2672 delta = root_height - 1;
2673 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2676 FRAME_TOOL_BAR_LINES (f) = nlines;
2677 x_change_window_heights (root_window, delta);
2678 adjust_glyphs (f);
2680 /* We also have to make sure that the internal border at the top of
2681 the frame, below the menu bar or tool bar, is redrawn when the
2682 tool bar disappears. This is so because the internal border is
2683 below the tool bar if one is displayed, but is below the menu bar
2684 if there isn't a tool bar. The tool bar draws into the area
2685 below the menu bar. */
2686 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2688 updating_frame = f;
2689 clear_frame ();
2690 clear_current_matrices (f);
2691 updating_frame = NULL;
2694 /* If the tool bar gets smaller, the internal border below it
2695 has to be cleared. It was formerly part of the display
2696 of the larger tool bar, and updating windows won't clear it. */
2697 if (delta < 0)
2699 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2700 int width = PIXEL_WIDTH (f);
2701 int y = nlines * CANON_Y_UNIT (f);
2703 BLOCK_INPUT;
2705 HDC hdc = get_frame_dc (f);
2706 w32_clear_area (f, hdc, 0, y, width, height);
2707 release_frame_dc (f, hdc);
2709 UNBLOCK_INPUT;
2711 if (WINDOWP (f->tool_bar_window))
2712 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
2717 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2718 w32_id_name.
2720 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2721 name; if NAME is a string, set F's name to NAME and set
2722 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2724 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2725 suggesting a new name, which lisp code should override; if
2726 F->explicit_name is set, ignore the new name; otherwise, set it. */
2728 void
2729 x_set_name (f, name, explicit)
2730 struct frame *f;
2731 Lisp_Object name;
2732 int explicit;
2734 /* Make sure that requests from lisp code override requests from
2735 Emacs redisplay code. */
2736 if (explicit)
2738 /* If we're switching from explicit to implicit, we had better
2739 update the mode lines and thereby update the title. */
2740 if (f->explicit_name && NILP (name))
2741 update_mode_lines = 1;
2743 f->explicit_name = ! NILP (name);
2745 else if (f->explicit_name)
2746 return;
2748 /* If NAME is nil, set the name to the w32_id_name. */
2749 if (NILP (name))
2751 /* Check for no change needed in this very common case
2752 before we do any consing. */
2753 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2754 SDATA (f->name)))
2755 return;
2756 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2758 else
2759 CHECK_STRING (name);
2761 /* Don't change the name if it's already NAME. */
2762 if (! NILP (Fstring_equal (name, f->name)))
2763 return;
2765 f->name = name;
2767 /* For setting the frame title, the title parameter should override
2768 the name parameter. */
2769 if (! NILP (f->title))
2770 name = f->title;
2772 if (FRAME_W32_WINDOW (f))
2774 if (STRING_MULTIBYTE (name))
2775 name = ENCODE_SYSTEM (name);
2777 BLOCK_INPUT;
2778 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2779 UNBLOCK_INPUT;
2783 /* This function should be called when the user's lisp code has
2784 specified a name for the frame; the name will override any set by the
2785 redisplay code. */
2786 void
2787 x_explicitly_set_name (f, arg, oldval)
2788 FRAME_PTR f;
2789 Lisp_Object arg, oldval;
2791 x_set_name (f, arg, 1);
2794 /* This function should be called by Emacs redisplay code to set the
2795 name; names set this way will never override names set by the user's
2796 lisp code. */
2797 void
2798 x_implicitly_set_name (f, arg, oldval)
2799 FRAME_PTR f;
2800 Lisp_Object arg, oldval;
2802 x_set_name (f, arg, 0);
2805 /* Change the title of frame F to NAME.
2806 If NAME is nil, use the frame name as the title.
2808 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2809 name; if NAME is a string, set F's name to NAME and set
2810 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2812 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2813 suggesting a new name, which lisp code should override; if
2814 F->explicit_name is set, ignore the new name; otherwise, set it. */
2816 void
2817 x_set_title (f, name, old_name)
2818 struct frame *f;
2819 Lisp_Object name, old_name;
2821 /* Don't change the title if it's already NAME. */
2822 if (EQ (name, f->title))
2823 return;
2825 update_mode_lines = 1;
2827 f->title = name;
2829 if (NILP (name))
2830 name = f->name;
2832 if (FRAME_W32_WINDOW (f))
2834 if (STRING_MULTIBYTE (name))
2835 name = ENCODE_SYSTEM (name);
2837 BLOCK_INPUT;
2838 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2839 UNBLOCK_INPUT;
2843 void
2844 x_set_autoraise (f, arg, oldval)
2845 struct frame *f;
2846 Lisp_Object arg, oldval;
2848 f->auto_raise = !EQ (Qnil, arg);
2851 void
2852 x_set_autolower (f, arg, oldval)
2853 struct frame *f;
2854 Lisp_Object arg, oldval;
2856 f->auto_lower = !EQ (Qnil, arg);
2859 void
2860 x_set_unsplittable (f, arg, oldval)
2861 struct frame *f;
2862 Lisp_Object arg, oldval;
2864 f->no_split = !NILP (arg);
2867 void
2868 x_set_vertical_scroll_bars (f, arg, oldval)
2869 struct frame *f;
2870 Lisp_Object arg, oldval;
2872 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2873 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2874 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2875 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2877 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2878 vertical_scroll_bar_none :
2879 /* Put scroll bars on the right by default, as is conventional
2880 on MS-Windows. */
2881 EQ (Qleft, arg)
2882 ? vertical_scroll_bar_left
2883 : vertical_scroll_bar_right;
2885 /* We set this parameter before creating the window for the
2886 frame, so we can get the geometry right from the start.
2887 However, if the window hasn't been created yet, we shouldn't
2888 call x_set_window_size. */
2889 if (FRAME_W32_WINDOW (f))
2890 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2891 do_pending_window_change (0);
2895 void
2896 x_set_scroll_bar_width (f, arg, oldval)
2897 struct frame *f;
2898 Lisp_Object arg, oldval;
2900 int wid = FONT_WIDTH (f->output_data.w32->font);
2902 if (NILP (arg))
2904 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2905 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2906 wid - 1) / wid;
2907 if (FRAME_W32_WINDOW (f))
2908 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2909 do_pending_window_change (0);
2911 else if (INTEGERP (arg) && XINT (arg) > 0
2912 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2914 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2915 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2916 + wid-1) / wid;
2917 if (FRAME_W32_WINDOW (f))
2918 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2919 do_pending_window_change (0);
2921 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2922 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2923 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2926 /* Subroutines of creating a frame. */
2928 /* Make sure that Vx_resource_name is set to a reasonable value.
2929 Fix it up, or set it to `emacs' if it is too hopeless. */
2931 static void
2932 validate_x_resource_name ()
2934 int len = 0;
2935 /* Number of valid characters in the resource name. */
2936 int good_count = 0;
2937 /* Number of invalid characters in the resource name. */
2938 int bad_count = 0;
2939 Lisp_Object new;
2940 int i;
2942 if (STRINGP (Vx_resource_name))
2944 unsigned char *p = SDATA (Vx_resource_name);
2945 int i;
2947 len = SBYTES (Vx_resource_name);
2949 /* Only letters, digits, - and _ are valid in resource names.
2950 Count the valid characters and count the invalid ones. */
2951 for (i = 0; i < len; i++)
2953 int c = p[i];
2954 if (! ((c >= 'a' && c <= 'z')
2955 || (c >= 'A' && c <= 'Z')
2956 || (c >= '0' && c <= '9')
2957 || c == '-' || c == '_'))
2958 bad_count++;
2959 else
2960 good_count++;
2963 else
2964 /* Not a string => completely invalid. */
2965 bad_count = 5, good_count = 0;
2967 /* If name is valid already, return. */
2968 if (bad_count == 0)
2969 return;
2971 /* If name is entirely invalid, or nearly so, use `emacs'. */
2972 if (good_count == 0
2973 || (good_count == 1 && bad_count > 0))
2975 Vx_resource_name = build_string ("emacs");
2976 return;
2979 /* Name is partly valid. Copy it and replace the invalid characters
2980 with underscores. */
2982 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2984 for (i = 0; i < len; i++)
2986 int c = SREF (new, i);
2987 if (! ((c >= 'a' && c <= 'z')
2988 || (c >= 'A' && c <= 'Z')
2989 || (c >= '0' && c <= '9')
2990 || c == '-' || c == '_'))
2991 SSET (new, i, '_');
2996 extern char *x_get_string_resource ();
2998 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2999 doc: /* Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.
3000 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the
3001 class, where INSTANCE is the name under which Emacs was invoked, or
3002 the name specified by the `-name' or `-rn' command-line arguments.
3004 The optional arguments COMPONENT and SUBCLASS add to the key and the
3005 class, respectively. You must specify both of them or neither.
3006 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'
3007 and the class is `Emacs.CLASS.SUBCLASS'. */)
3008 (attribute, class, component, subclass)
3009 Lisp_Object attribute, class, component, subclass;
3011 register char *value;
3012 char *name_key;
3013 char *class_key;
3015 CHECK_STRING (attribute);
3016 CHECK_STRING (class);
3018 if (!NILP (component))
3019 CHECK_STRING (component);
3020 if (!NILP (subclass))
3021 CHECK_STRING (subclass);
3022 if (NILP (component) != NILP (subclass))
3023 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
3025 validate_x_resource_name ();
3027 /* Allocate space for the components, the dots which separate them,
3028 and the final '\0'. Make them big enough for the worst case. */
3029 name_key = (char *) alloca (SBYTES (Vx_resource_name)
3030 + (STRINGP (component)
3031 ? SBYTES (component) : 0)
3032 + SBYTES (attribute)
3033 + 3);
3035 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3036 + SBYTES (class)
3037 + (STRINGP (subclass)
3038 ? SBYTES (subclass) : 0)
3039 + 3);
3041 /* Start with emacs.FRAMENAME for the name (the specific one)
3042 and with `Emacs' for the class key (the general one). */
3043 strcpy (name_key, SDATA (Vx_resource_name));
3044 strcpy (class_key, EMACS_CLASS);
3046 strcat (class_key, ".");
3047 strcat (class_key, SDATA (class));
3049 if (!NILP (component))
3051 strcat (class_key, ".");
3052 strcat (class_key, SDATA (subclass));
3054 strcat (name_key, ".");
3055 strcat (name_key, SDATA (component));
3058 strcat (name_key, ".");
3059 strcat (name_key, SDATA (attribute));
3061 value = x_get_string_resource (Qnil,
3062 name_key, class_key);
3064 if (value != (char *) 0)
3065 return build_string (value);
3066 else
3067 return Qnil;
3070 /* Used when C code wants a resource value. */
3072 char *
3073 x_get_resource_string (attribute, class)
3074 char *attribute, *class;
3076 char *name_key;
3077 char *class_key;
3078 struct frame *sf = SELECTED_FRAME ();
3080 /* Allocate space for the components, the dots which separate them,
3081 and the final '\0'. */
3082 name_key = (char *) alloca (SBYTES (Vinvocation_name)
3083 + strlen (attribute) + 2);
3084 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3085 + strlen (class) + 2);
3087 sprintf (name_key, "%s.%s",
3088 SDATA (Vinvocation_name),
3089 attribute);
3090 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
3092 return x_get_string_resource (sf, name_key, class_key);
3095 /* Types we might convert a resource string into. */
3096 enum resource_types
3098 RES_TYPE_NUMBER,
3099 RES_TYPE_FLOAT,
3100 RES_TYPE_BOOLEAN,
3101 RES_TYPE_STRING,
3102 RES_TYPE_SYMBOL
3105 /* Return the value of parameter PARAM.
3107 First search ALIST, then Vdefault_frame_alist, then the X defaults
3108 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3110 Convert the resource to the type specified by desired_type.
3112 If no default is specified, return Qunbound. If you call
3113 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3114 and don't let it get stored in any Lisp-visible variables! */
3116 static Lisp_Object
3117 w32_get_arg (alist, param, attribute, class, type)
3118 Lisp_Object alist, param;
3119 char *attribute;
3120 char *class;
3121 enum resource_types type;
3123 register Lisp_Object tem;
3125 tem = Fassq (param, alist);
3126 if (EQ (tem, Qnil))
3127 tem = Fassq (param, Vdefault_frame_alist);
3128 if (EQ (tem, Qnil))
3131 if (attribute)
3133 tem = Fx_get_resource (build_string (attribute),
3134 build_string (class),
3135 Qnil, Qnil);
3137 if (NILP (tem))
3138 return Qunbound;
3140 switch (type)
3142 case RES_TYPE_NUMBER:
3143 return make_number (atoi (SDATA (tem)));
3145 case RES_TYPE_FLOAT:
3146 return make_float (atof (SDATA (tem)));
3148 case RES_TYPE_BOOLEAN:
3149 tem = Fdowncase (tem);
3150 if (!strcmp (SDATA (tem), "on")
3151 || !strcmp (SDATA (tem), "true"))
3152 return Qt;
3153 else
3154 return Qnil;
3156 case RES_TYPE_STRING:
3157 return tem;
3159 case RES_TYPE_SYMBOL:
3160 /* As a special case, we map the values `true' and `on'
3161 to Qt, and `false' and `off' to Qnil. */
3163 Lisp_Object lower;
3164 lower = Fdowncase (tem);
3165 if (!strcmp (SDATA (lower), "on")
3166 || !strcmp (SDATA (lower), "true"))
3167 return Qt;
3168 else if (!strcmp (SDATA (lower), "off")
3169 || !strcmp (SDATA (lower), "false"))
3170 return Qnil;
3171 else
3172 return Fintern (tem, Qnil);
3175 default:
3176 abort ();
3179 else
3180 return Qunbound;
3182 return Fcdr (tem);
3185 /* Record in frame F the specified or default value according to ALIST
3186 of the parameter named PROP (a Lisp symbol).
3187 If no value is specified for PROP, look for an X default for XPROP
3188 on the frame named NAME.
3189 If that is not found either, use the value DEFLT. */
3191 static Lisp_Object
3192 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3193 struct frame *f;
3194 Lisp_Object alist;
3195 Lisp_Object prop;
3196 Lisp_Object deflt;
3197 char *xprop;
3198 char *xclass;
3199 enum resource_types type;
3201 Lisp_Object tem;
3203 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3204 if (EQ (tem, Qunbound))
3205 tem = deflt;
3206 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3207 return tem;
3210 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3211 doc: /* Parse an X-style geometry string STRING.
3212 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).
3213 The properties returned may include `top', `left', `height', and `width'.
3214 The value of `left' or `top' may be an integer,
3215 or a list (+ N) meaning N pixels relative to top/left corner,
3216 or a list (- N) meaning -N pixels relative to bottom/right corner. */)
3217 (string)
3218 Lisp_Object string;
3220 int geometry, x, y;
3221 unsigned int width, height;
3222 Lisp_Object result;
3224 CHECK_STRING (string);
3226 geometry = XParseGeometry ((char *) SDATA (string),
3227 &x, &y, &width, &height);
3229 result = Qnil;
3230 if (geometry & XValue)
3232 Lisp_Object element;
3234 if (x >= 0 && (geometry & XNegative))
3235 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3236 else if (x < 0 && ! (geometry & XNegative))
3237 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3238 else
3239 element = Fcons (Qleft, make_number (x));
3240 result = Fcons (element, result);
3243 if (geometry & YValue)
3245 Lisp_Object element;
3247 if (y >= 0 && (geometry & YNegative))
3248 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3249 else if (y < 0 && ! (geometry & YNegative))
3250 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3251 else
3252 element = Fcons (Qtop, make_number (y));
3253 result = Fcons (element, result);
3256 if (geometry & WidthValue)
3257 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3258 if (geometry & HeightValue)
3259 result = Fcons (Fcons (Qheight, make_number (height)), result);
3261 return result;
3264 /* Calculate the desired size and position of this window,
3265 and return the flags saying which aspects were specified.
3267 This function does not make the coordinates positive. */
3269 #define DEFAULT_ROWS 40
3270 #define DEFAULT_COLS 80
3272 static int
3273 x_figure_window_size (f, parms)
3274 struct frame *f;
3275 Lisp_Object parms;
3277 register Lisp_Object tem0, tem1, tem2;
3278 long window_prompting = 0;
3280 /* Default values if we fall through.
3281 Actually, if that happens we should get
3282 window manager prompting. */
3283 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3284 f->height = DEFAULT_ROWS;
3285 /* Window managers expect that if program-specified
3286 positions are not (0,0), they're intentional, not defaults. */
3287 f->output_data.w32->top_pos = 0;
3288 f->output_data.w32->left_pos = 0;
3290 /* Ensure that old new_width and new_height will not override the
3291 values set here. */
3292 FRAME_NEW_WIDTH (f) = 0;
3293 FRAME_NEW_HEIGHT (f) = 0;
3295 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3296 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3297 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3298 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3300 if (!EQ (tem0, Qunbound))
3302 CHECK_NUMBER (tem0);
3303 f->height = XINT (tem0);
3305 if (!EQ (tem1, Qunbound))
3307 CHECK_NUMBER (tem1);
3308 SET_FRAME_WIDTH (f, XINT (tem1));
3310 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3311 window_prompting |= USSize;
3312 else
3313 window_prompting |= PSize;
3316 f->output_data.w32->vertical_scroll_bar_extra
3317 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3319 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3320 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3321 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3323 x_compute_fringe_widths (f, 0);
3325 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3326 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3328 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3329 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3330 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3331 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3333 if (EQ (tem0, Qminus))
3335 f->output_data.w32->top_pos = 0;
3336 window_prompting |= YNegative;
3338 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3339 && CONSP (XCDR (tem0))
3340 && INTEGERP (XCAR (XCDR (tem0))))
3342 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3343 window_prompting |= YNegative;
3345 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3346 && CONSP (XCDR (tem0))
3347 && INTEGERP (XCAR (XCDR (tem0))))
3349 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3351 else if (EQ (tem0, Qunbound))
3352 f->output_data.w32->top_pos = 0;
3353 else
3355 CHECK_NUMBER (tem0);
3356 f->output_data.w32->top_pos = XINT (tem0);
3357 if (f->output_data.w32->top_pos < 0)
3358 window_prompting |= YNegative;
3361 if (EQ (tem1, Qminus))
3363 f->output_data.w32->left_pos = 0;
3364 window_prompting |= XNegative;
3366 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3367 && CONSP (XCDR (tem1))
3368 && INTEGERP (XCAR (XCDR (tem1))))
3370 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3371 window_prompting |= XNegative;
3373 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3374 && CONSP (XCDR (tem1))
3375 && INTEGERP (XCAR (XCDR (tem1))))
3377 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3379 else if (EQ (tem1, Qunbound))
3380 f->output_data.w32->left_pos = 0;
3381 else
3383 CHECK_NUMBER (tem1);
3384 f->output_data.w32->left_pos = XINT (tem1);
3385 if (f->output_data.w32->left_pos < 0)
3386 window_prompting |= XNegative;
3389 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3390 window_prompting |= USPosition;
3391 else
3392 window_prompting |= PPosition;
3395 if (f->output_data.w32->want_fullscreen != FULLSCREEN_NONE)
3397 int left, top;
3398 int width, height;
3400 /* It takes both for some WM:s to place it where we want */
3401 window_prompting = USPosition | PPosition;
3402 x_fullscreen_adjust (f, &width, &height, &top, &left);
3403 f->width = width;
3404 f->height = height;
3405 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3406 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3407 f->output_data.w32->left_pos = left;
3408 f->output_data.w32->top_pos = top;
3411 return window_prompting;
3416 extern LRESULT CALLBACK w32_wnd_proc ();
3418 BOOL
3419 w32_init_class (hinst)
3420 HINSTANCE hinst;
3422 WNDCLASS wc;
3424 wc.style = CS_HREDRAW | CS_VREDRAW;
3425 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3426 wc.cbClsExtra = 0;
3427 wc.cbWndExtra = WND_EXTRA_BYTES;
3428 wc.hInstance = hinst;
3429 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3430 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3431 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3432 wc.lpszMenuName = NULL;
3433 wc.lpszClassName = EMACS_CLASS;
3435 return (RegisterClass (&wc));
3438 HWND
3439 w32_createscrollbar (f, bar)
3440 struct frame *f;
3441 struct scroll_bar * bar;
3443 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3444 /* Position and size of scroll bar. */
3445 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3446 XINT(bar->top),
3447 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3448 XINT(bar->height),
3449 FRAME_W32_WINDOW (f),
3450 NULL,
3451 hinst,
3452 NULL));
3455 void
3456 w32_createwindow (f)
3457 struct frame *f;
3459 HWND hwnd;
3460 RECT rect;
3462 rect.left = rect.top = 0;
3463 rect.right = PIXEL_WIDTH (f);
3464 rect.bottom = PIXEL_HEIGHT (f);
3466 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3467 FRAME_EXTERNAL_MENU_BAR (f));
3469 /* Do first time app init */
3471 if (!hprevinst)
3473 w32_init_class (hinst);
3476 FRAME_W32_WINDOW (f) = hwnd
3477 = CreateWindow (EMACS_CLASS,
3478 f->namebuf,
3479 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3480 f->output_data.w32->left_pos,
3481 f->output_data.w32->top_pos,
3482 rect.right - rect.left,
3483 rect.bottom - rect.top,
3484 NULL,
3485 NULL,
3486 hinst,
3487 NULL);
3489 if (hwnd)
3491 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3492 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3493 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3494 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3495 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3497 /* Enable drag-n-drop. */
3498 DragAcceptFiles (hwnd, TRUE);
3500 /* Do this to discard the default setting specified by our parent. */
3501 ShowWindow (hwnd, SW_HIDE);
3505 void
3506 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3507 W32Msg * wmsg;
3508 HWND hwnd;
3509 UINT msg;
3510 WPARAM wParam;
3511 LPARAM lParam;
3513 wmsg->msg.hwnd = hwnd;
3514 wmsg->msg.message = msg;
3515 wmsg->msg.wParam = wParam;
3516 wmsg->msg.lParam = lParam;
3517 wmsg->msg.time = GetMessageTime ();
3519 post_msg (wmsg);
3522 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3523 between left and right keys as advertised. We test for this
3524 support dynamically, and set a flag when the support is absent. If
3525 absent, we keep track of the left and right control and alt keys
3526 ourselves. This is particularly necessary on keyboards that rely
3527 upon the AltGr key, which is represented as having the left control
3528 and right alt keys pressed. For these keyboards, we need to know
3529 when the left alt key has been pressed in addition to the AltGr key
3530 so that we can properly support M-AltGr-key sequences (such as M-@
3531 on Swedish keyboards). */
3533 #define EMACS_LCONTROL 0
3534 #define EMACS_RCONTROL 1
3535 #define EMACS_LMENU 2
3536 #define EMACS_RMENU 3
3538 static int modifiers[4];
3539 static int modifiers_recorded;
3540 static int modifier_key_support_tested;
3542 static void
3543 test_modifier_support (unsigned int wparam)
3545 unsigned int l, r;
3547 if (wparam != VK_CONTROL && wparam != VK_MENU)
3548 return;
3549 if (wparam == VK_CONTROL)
3551 l = VK_LCONTROL;
3552 r = VK_RCONTROL;
3554 else
3556 l = VK_LMENU;
3557 r = VK_RMENU;
3559 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3560 modifiers_recorded = 1;
3561 else
3562 modifiers_recorded = 0;
3563 modifier_key_support_tested = 1;
3566 static void
3567 record_keydown (unsigned int wparam, unsigned int lparam)
3569 int i;
3571 if (!modifier_key_support_tested)
3572 test_modifier_support (wparam);
3574 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3575 return;
3577 if (wparam == VK_CONTROL)
3578 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3579 else
3580 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3582 modifiers[i] = 1;
3585 static void
3586 record_keyup (unsigned int wparam, unsigned int lparam)
3588 int i;
3590 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3591 return;
3593 if (wparam == VK_CONTROL)
3594 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3595 else
3596 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3598 modifiers[i] = 0;
3601 /* Emacs can lose focus while a modifier key has been pressed. When
3602 it regains focus, be conservative and clear all modifiers since
3603 we cannot reconstruct the left and right modifier state. */
3604 static void
3605 reset_modifiers ()
3607 SHORT ctrl, alt;
3609 if (GetFocus () == NULL)
3610 /* Emacs doesn't have keyboard focus. Do nothing. */
3611 return;
3613 ctrl = GetAsyncKeyState (VK_CONTROL);
3614 alt = GetAsyncKeyState (VK_MENU);
3616 if (!(ctrl & 0x08000))
3617 /* Clear any recorded control modifier state. */
3618 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3620 if (!(alt & 0x08000))
3621 /* Clear any recorded alt modifier state. */
3622 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3624 /* Update the state of all modifier keys, because modifiers used in
3625 hot-key combinations can get stuck on if Emacs loses focus as a
3626 result of a hot-key being pressed. */
3628 BYTE keystate[256];
3630 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3632 GetKeyboardState (keystate);
3633 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3634 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3635 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3636 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3637 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3638 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3639 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3640 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3641 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3642 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3643 SetKeyboardState (keystate);
3647 /* Synchronize modifier state with what is reported with the current
3648 keystroke. Even if we cannot distinguish between left and right
3649 modifier keys, we know that, if no modifiers are set, then neither
3650 the left or right modifier should be set. */
3651 static void
3652 sync_modifiers ()
3654 if (!modifiers_recorded)
3655 return;
3657 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3658 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3660 if (!(GetKeyState (VK_MENU) & 0x8000))
3661 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3664 static int
3665 modifier_set (int vkey)
3667 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3668 return (GetKeyState (vkey) & 0x1);
3669 if (!modifiers_recorded)
3670 return (GetKeyState (vkey) & 0x8000);
3672 switch (vkey)
3674 case VK_LCONTROL:
3675 return modifiers[EMACS_LCONTROL];
3676 case VK_RCONTROL:
3677 return modifiers[EMACS_RCONTROL];
3678 case VK_LMENU:
3679 return modifiers[EMACS_LMENU];
3680 case VK_RMENU:
3681 return modifiers[EMACS_RMENU];
3683 return (GetKeyState (vkey) & 0x8000);
3686 /* Convert between the modifier bits W32 uses and the modifier bits
3687 Emacs uses. */
3689 unsigned int
3690 w32_key_to_modifier (int key)
3692 Lisp_Object key_mapping;
3694 switch (key)
3696 case VK_LWIN:
3697 key_mapping = Vw32_lwindow_modifier;
3698 break;
3699 case VK_RWIN:
3700 key_mapping = Vw32_rwindow_modifier;
3701 break;
3702 case VK_APPS:
3703 key_mapping = Vw32_apps_modifier;
3704 break;
3705 case VK_SCROLL:
3706 key_mapping = Vw32_scroll_lock_modifier;
3707 break;
3708 default:
3709 key_mapping = Qnil;
3712 /* NB. This code runs in the input thread, asychronously to the lisp
3713 thread, so we must be careful to ensure access to lisp data is
3714 thread-safe. The following code is safe because the modifier
3715 variable values are updated atomically from lisp and symbols are
3716 not relocated by GC. Also, we don't have to worry about seeing GC
3717 markbits here. */
3718 if (EQ (key_mapping, Qhyper))
3719 return hyper_modifier;
3720 if (EQ (key_mapping, Qsuper))
3721 return super_modifier;
3722 if (EQ (key_mapping, Qmeta))
3723 return meta_modifier;
3724 if (EQ (key_mapping, Qalt))
3725 return alt_modifier;
3726 if (EQ (key_mapping, Qctrl))
3727 return ctrl_modifier;
3728 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3729 return ctrl_modifier;
3730 if (EQ (key_mapping, Qshift))
3731 return shift_modifier;
3733 /* Don't generate any modifier if not explicitly requested. */
3734 return 0;
3737 unsigned int
3738 w32_get_modifiers ()
3740 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3741 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3742 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3743 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3744 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3745 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3746 (modifier_set (VK_MENU) ?
3747 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3750 /* We map the VK_* modifiers into console modifier constants
3751 so that we can use the same routines to handle both console
3752 and window input. */
3754 static int
3755 construct_console_modifiers ()
3757 int mods;
3759 mods = 0;
3760 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3761 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3762 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3763 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3764 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3765 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3766 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3767 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3768 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3769 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3770 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3772 return mods;
3775 static int
3776 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3778 int mods;
3780 /* Convert to emacs modifiers. */
3781 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3783 return mods;
3786 unsigned int
3787 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3789 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3790 return virt_key;
3792 if (virt_key == VK_RETURN)
3793 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3795 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3796 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3798 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3799 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3801 if (virt_key == VK_CLEAR)
3802 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3804 return virt_key;
3807 /* List of special key combinations which w32 would normally capture,
3808 but emacs should grab instead. Not directly visible to lisp, to
3809 simplify synchronization. Each item is an integer encoding a virtual
3810 key code and modifier combination to capture. */
3811 Lisp_Object w32_grabbed_keys;
3813 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3814 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3815 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3816 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3818 /* Register hot-keys for reserved key combinations when Emacs has
3819 keyboard focus, since this is the only way Emacs can receive key
3820 combinations like Alt-Tab which are used by the system. */
3822 static void
3823 register_hot_keys (hwnd)
3824 HWND hwnd;
3826 Lisp_Object keylist;
3828 /* Use GC_CONSP, since we are called asynchronously. */
3829 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3831 Lisp_Object key = XCAR (keylist);
3833 /* Deleted entries get set to nil. */
3834 if (!INTEGERP (key))
3835 continue;
3837 RegisterHotKey (hwnd, HOTKEY_ID (key),
3838 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3842 static void
3843 unregister_hot_keys (hwnd)
3844 HWND hwnd;
3846 Lisp_Object keylist;
3848 /* Use GC_CONSP, since we are called asynchronously. */
3849 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3851 Lisp_Object key = XCAR (keylist);
3853 if (!INTEGERP (key))
3854 continue;
3856 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3860 /* Main message dispatch loop. */
3862 static void
3863 w32_msg_pump (deferred_msg * msg_buf)
3865 MSG msg;
3866 int result;
3867 HWND focus_window;
3869 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3871 while (GetMessage (&msg, NULL, 0, 0))
3873 if (msg.hwnd == NULL)
3875 switch (msg.message)
3877 case WM_NULL:
3878 /* Produced by complete_deferred_msg; just ignore. */
3879 break;
3880 case WM_EMACS_CREATEWINDOW:
3881 w32_createwindow ((struct frame *) msg.wParam);
3882 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3883 abort ();
3884 break;
3885 case WM_EMACS_SETLOCALE:
3886 SetThreadLocale (msg.wParam);
3887 /* Reply is not expected. */
3888 break;
3889 case WM_EMACS_SETKEYBOARDLAYOUT:
3890 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3891 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3892 result, 0))
3893 abort ();
3894 break;
3895 case WM_EMACS_REGISTER_HOT_KEY:
3896 focus_window = GetFocus ();
3897 if (focus_window != NULL)
3898 RegisterHotKey (focus_window,
3899 HOTKEY_ID (msg.wParam),
3900 HOTKEY_MODIFIERS (msg.wParam),
3901 HOTKEY_VK_CODE (msg.wParam));
3902 /* Reply is not expected. */
3903 break;
3904 case WM_EMACS_UNREGISTER_HOT_KEY:
3905 focus_window = GetFocus ();
3906 if (focus_window != NULL)
3907 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3908 /* Mark item as erased. NB: this code must be
3909 thread-safe. The next line is okay because the cons
3910 cell is never made into garbage and is not relocated by
3911 GC. */
3912 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
3913 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3914 abort ();
3915 break;
3916 case WM_EMACS_TOGGLE_LOCK_KEY:
3918 int vk_code = (int) msg.wParam;
3919 int cur_state = (GetKeyState (vk_code) & 1);
3920 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3922 /* NB: This code must be thread-safe. It is safe to
3923 call NILP because symbols are not relocated by GC,
3924 and pointer here is not touched by GC (so the markbit
3925 can't be set). Numbers are safe because they are
3926 immediate values. */
3927 if (NILP (new_state)
3928 || (NUMBERP (new_state)
3929 && ((XUINT (new_state)) & 1) != cur_state))
3931 one_w32_display_info.faked_key = vk_code;
3933 keybd_event ((BYTE) vk_code,
3934 (BYTE) MapVirtualKey (vk_code, 0),
3935 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3936 keybd_event ((BYTE) vk_code,
3937 (BYTE) MapVirtualKey (vk_code, 0),
3938 KEYEVENTF_EXTENDEDKEY | 0, 0);
3939 keybd_event ((BYTE) vk_code,
3940 (BYTE) MapVirtualKey (vk_code, 0),
3941 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3942 cur_state = !cur_state;
3944 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3945 cur_state, 0))
3946 abort ();
3948 break;
3949 default:
3950 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3953 else
3955 DispatchMessage (&msg);
3958 /* Exit nested loop when our deferred message has completed. */
3959 if (msg_buf->completed)
3960 break;
3964 deferred_msg * deferred_msg_head;
3966 static deferred_msg *
3967 find_deferred_msg (HWND hwnd, UINT msg)
3969 deferred_msg * item;
3971 /* Don't actually need synchronization for read access, since
3972 modification of single pointer is always atomic. */
3973 /* enter_crit (); */
3975 for (item = deferred_msg_head; item != NULL; item = item->next)
3976 if (item->w32msg.msg.hwnd == hwnd
3977 && item->w32msg.msg.message == msg)
3978 break;
3980 /* leave_crit (); */
3982 return item;
3985 static LRESULT
3986 send_deferred_msg (deferred_msg * msg_buf,
3987 HWND hwnd,
3988 UINT msg,
3989 WPARAM wParam,
3990 LPARAM lParam)
3992 /* Only input thread can send deferred messages. */
3993 if (GetCurrentThreadId () != dwWindowsThreadId)
3994 abort ();
3996 /* It is an error to send a message that is already deferred. */
3997 if (find_deferred_msg (hwnd, msg) != NULL)
3998 abort ();
4000 /* Enforced synchronization is not needed because this is the only
4001 function that alters deferred_msg_head, and the following critical
4002 section is guaranteed to only be serially reentered (since only the
4003 input thread can call us). */
4005 /* enter_crit (); */
4007 msg_buf->completed = 0;
4008 msg_buf->next = deferred_msg_head;
4009 deferred_msg_head = msg_buf;
4010 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
4012 /* leave_crit (); */
4014 /* Start a new nested message loop to process other messages until
4015 this one is completed. */
4016 w32_msg_pump (msg_buf);
4018 deferred_msg_head = msg_buf->next;
4020 return msg_buf->result;
4023 void
4024 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
4026 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
4028 if (msg_buf == NULL)
4029 /* Message may have been cancelled, so don't abort(). */
4030 return;
4032 msg_buf->result = result;
4033 msg_buf->completed = 1;
4035 /* Ensure input thread is woken so it notices the completion. */
4036 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4039 void
4040 cancel_all_deferred_msgs ()
4042 deferred_msg * item;
4044 /* Don't actually need synchronization for read access, since
4045 modification of single pointer is always atomic. */
4046 /* enter_crit (); */
4048 for (item = deferred_msg_head; item != NULL; item = item->next)
4050 item->result = 0;
4051 item->completed = 1;
4054 /* leave_crit (); */
4056 /* Ensure input thread is woken so it notices the completion. */
4057 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4060 DWORD
4061 w32_msg_worker (dw)
4062 DWORD dw;
4064 MSG msg;
4065 deferred_msg dummy_buf;
4067 /* Ensure our message queue is created */
4069 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
4071 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
4072 abort ();
4074 memset (&dummy_buf, 0, sizeof (dummy_buf));
4075 dummy_buf.w32msg.msg.hwnd = NULL;
4076 dummy_buf.w32msg.msg.message = WM_NULL;
4078 /* This is the inital message loop which should only exit when the
4079 application quits. */
4080 w32_msg_pump (&dummy_buf);
4082 return 0;
4085 static void
4086 post_character_message (hwnd, msg, wParam, lParam, modifiers)
4087 HWND hwnd;
4088 UINT msg;
4089 WPARAM wParam;
4090 LPARAM lParam;
4091 DWORD modifiers;
4094 W32Msg wmsg;
4096 wmsg.dwModifiers = modifiers;
4098 /* Detect quit_char and set quit-flag directly. Note that we
4099 still need to post a message to ensure the main thread will be
4100 woken up if blocked in sys_select(), but we do NOT want to post
4101 the quit_char message itself (because it will usually be as if
4102 the user had typed quit_char twice). Instead, we post a dummy
4103 message that has no particular effect. */
4105 int c = wParam;
4106 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
4107 c = make_ctrl_char (c) & 0377;
4108 if (c == quit_char
4109 || (wmsg.dwModifiers == 0 &&
4110 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
4112 Vquit_flag = Qt;
4114 /* The choice of message is somewhat arbitrary, as long as
4115 the main thread handler just ignores it. */
4116 msg = WM_NULL;
4118 /* Interrupt any blocking system calls. */
4119 signal_quit ();
4121 /* As a safety precaution, forcibly complete any deferred
4122 messages. This is a kludge, but I don't see any particularly
4123 clean way to handle the situation where a deferred message is
4124 "dropped" in the lisp thread, and will thus never be
4125 completed, eg. by the user trying to activate the menubar
4126 when the lisp thread is busy, and then typing C-g when the
4127 menubar doesn't open promptly (with the result that the
4128 menubar never responds at all because the deferred
4129 WM_INITMENU message is never completed). Another problem
4130 situation is when the lisp thread calls SendMessage (to send
4131 a window manager command) when a message has been deferred;
4132 the lisp thread gets blocked indefinitely waiting for the
4133 deferred message to be completed, which itself is waiting for
4134 the lisp thread to respond.
4136 Note that we don't want to block the input thread waiting for
4137 a reponse from the lisp thread (although that would at least
4138 solve the deadlock problem above), because we want to be able
4139 to receive C-g to interrupt the lisp thread. */
4140 cancel_all_deferred_msgs ();
4144 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4147 /* Main window procedure */
4149 LRESULT CALLBACK
4150 w32_wnd_proc (hwnd, msg, wParam, lParam)
4151 HWND hwnd;
4152 UINT msg;
4153 WPARAM wParam;
4154 LPARAM lParam;
4156 struct frame *f;
4157 struct w32_display_info *dpyinfo = &one_w32_display_info;
4158 W32Msg wmsg;
4159 int windows_translate;
4160 int key;
4162 /* Note that it is okay to call x_window_to_frame, even though we are
4163 not running in the main lisp thread, because frame deletion
4164 requires the lisp thread to synchronize with this thread. Thus, if
4165 a frame struct is returned, it can be used without concern that the
4166 lisp thread might make it disappear while we are using it.
4168 NB. Walking the frame list in this thread is safe (as long as
4169 writes of Lisp_Object slots are atomic, which they are on Windows).
4170 Although delete-frame can destructively modify the frame list while
4171 we are walking it, a garbage collection cannot occur until after
4172 delete-frame has synchronized with this thread.
4174 It is also safe to use functions that make GDI calls, such as
4175 w32_clear_rect, because these functions must obtain a DC handle
4176 from the frame struct using get_frame_dc which is thread-aware. */
4178 switch (msg)
4180 case WM_ERASEBKGND:
4181 f = x_window_to_frame (dpyinfo, hwnd);
4182 if (f)
4184 HDC hdc = get_frame_dc (f);
4185 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4186 w32_clear_rect (f, hdc, &wmsg.rect);
4187 release_frame_dc (f, hdc);
4189 #if defined (W32_DEBUG_DISPLAY)
4190 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
4192 wmsg.rect.left, wmsg.rect.top,
4193 wmsg.rect.right, wmsg.rect.bottom));
4194 #endif /* W32_DEBUG_DISPLAY */
4196 return 1;
4197 case WM_PALETTECHANGED:
4198 /* ignore our own changes */
4199 if ((HWND)wParam != hwnd)
4201 f = x_window_to_frame (dpyinfo, hwnd);
4202 if (f)
4203 /* get_frame_dc will realize our palette and force all
4204 frames to be redrawn if needed. */
4205 release_frame_dc (f, get_frame_dc (f));
4207 return 0;
4208 case WM_PAINT:
4210 PAINTSTRUCT paintStruct;
4211 RECT update_rect;
4212 bzero (&update_rect, sizeof (update_rect));
4214 f = x_window_to_frame (dpyinfo, hwnd);
4215 if (f == 0)
4217 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
4218 return 0;
4221 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4222 fails. Apparently this can happen under some
4223 circumstances. */
4224 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
4226 enter_crit ();
4227 BeginPaint (hwnd, &paintStruct);
4229 /* The rectangles returned by GetUpdateRect and BeginPaint
4230 do not always match. Play it safe by assuming both areas
4231 are invalid. */
4232 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
4234 #if defined (W32_DEBUG_DISPLAY)
4235 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
4237 wmsg.rect.left, wmsg.rect.top,
4238 wmsg.rect.right, wmsg.rect.bottom));
4239 DebPrint ((" [update region is %d,%d-%d,%d]\n",
4240 update_rect.left, update_rect.top,
4241 update_rect.right, update_rect.bottom));
4242 #endif
4243 EndPaint (hwnd, &paintStruct);
4244 leave_crit ();
4246 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4248 return 0;
4251 /* If GetUpdateRect returns 0 (meaning there is no update
4252 region), assume the whole window needs to be repainted. */
4253 GetClientRect(hwnd, &wmsg.rect);
4254 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4255 return 0;
4258 case WM_INPUTLANGCHANGE:
4259 /* Inform lisp thread of keyboard layout changes. */
4260 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4262 /* Clear dead keys in the keyboard state; for simplicity only
4263 preserve modifier key states. */
4265 int i;
4266 BYTE keystate[256];
4268 GetKeyboardState (keystate);
4269 for (i = 0; i < 256; i++)
4270 if (1
4271 && i != VK_SHIFT
4272 && i != VK_LSHIFT
4273 && i != VK_RSHIFT
4274 && i != VK_CAPITAL
4275 && i != VK_NUMLOCK
4276 && i != VK_SCROLL
4277 && i != VK_CONTROL
4278 && i != VK_LCONTROL
4279 && i != VK_RCONTROL
4280 && i != VK_MENU
4281 && i != VK_LMENU
4282 && i != VK_RMENU
4283 && i != VK_LWIN
4284 && i != VK_RWIN)
4285 keystate[i] = 0;
4286 SetKeyboardState (keystate);
4288 goto dflt;
4290 case WM_HOTKEY:
4291 /* Synchronize hot keys with normal input. */
4292 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4293 return (0);
4295 case WM_KEYUP:
4296 case WM_SYSKEYUP:
4297 record_keyup (wParam, lParam);
4298 goto dflt;
4300 case WM_KEYDOWN:
4301 case WM_SYSKEYDOWN:
4302 /* Ignore keystrokes we fake ourself; see below. */
4303 if (dpyinfo->faked_key == wParam)
4305 dpyinfo->faked_key = 0;
4306 /* Make sure TranslateMessage sees them though (as long as
4307 they don't produce WM_CHAR messages). This ensures that
4308 indicator lights are toggled promptly on Windows 9x, for
4309 example. */
4310 if (lispy_function_keys[wParam] != 0)
4312 windows_translate = 1;
4313 goto translate;
4315 return 0;
4318 /* Synchronize modifiers with current keystroke. */
4319 sync_modifiers ();
4320 record_keydown (wParam, lParam);
4321 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4323 windows_translate = 0;
4325 switch (wParam)
4327 case VK_LWIN:
4328 if (NILP (Vw32_pass_lwindow_to_system))
4330 /* Prevent system from acting on keyup (which opens the
4331 Start menu if no other key was pressed) by simulating a
4332 press of Space which we will ignore. */
4333 if (GetAsyncKeyState (wParam) & 1)
4335 if (NUMBERP (Vw32_phantom_key_code))
4336 key = XUINT (Vw32_phantom_key_code) & 255;
4337 else
4338 key = VK_SPACE;
4339 dpyinfo->faked_key = key;
4340 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4343 if (!NILP (Vw32_lwindow_modifier))
4344 return 0;
4345 break;
4346 case VK_RWIN:
4347 if (NILP (Vw32_pass_rwindow_to_system))
4349 if (GetAsyncKeyState (wParam) & 1)
4351 if (NUMBERP (Vw32_phantom_key_code))
4352 key = XUINT (Vw32_phantom_key_code) & 255;
4353 else
4354 key = VK_SPACE;
4355 dpyinfo->faked_key = key;
4356 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4359 if (!NILP (Vw32_rwindow_modifier))
4360 return 0;
4361 break;
4362 case VK_APPS:
4363 if (!NILP (Vw32_apps_modifier))
4364 return 0;
4365 break;
4366 case VK_MENU:
4367 if (NILP (Vw32_pass_alt_to_system))
4368 /* Prevent DefWindowProc from activating the menu bar if an
4369 Alt key is pressed and released by itself. */
4370 return 0;
4371 windows_translate = 1;
4372 break;
4373 case VK_CAPITAL:
4374 /* Decide whether to treat as modifier or function key. */
4375 if (NILP (Vw32_enable_caps_lock))
4376 goto disable_lock_key;
4377 windows_translate = 1;
4378 break;
4379 case VK_NUMLOCK:
4380 /* Decide whether to treat as modifier or function key. */
4381 if (NILP (Vw32_enable_num_lock))
4382 goto disable_lock_key;
4383 windows_translate = 1;
4384 break;
4385 case VK_SCROLL:
4386 /* Decide whether to treat as modifier or function key. */
4387 if (NILP (Vw32_scroll_lock_modifier))
4388 goto disable_lock_key;
4389 windows_translate = 1;
4390 break;
4391 disable_lock_key:
4392 /* Ensure the appropriate lock key state (and indicator light)
4393 remains in the same state. We do this by faking another
4394 press of the relevant key. Apparently, this really is the
4395 only way to toggle the state of the indicator lights. */
4396 dpyinfo->faked_key = wParam;
4397 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4398 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4399 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4400 KEYEVENTF_EXTENDEDKEY | 0, 0);
4401 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4402 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4403 /* Ensure indicator lights are updated promptly on Windows 9x
4404 (TranslateMessage apparently does this), after forwarding
4405 input event. */
4406 post_character_message (hwnd, msg, wParam, lParam,
4407 w32_get_key_modifiers (wParam, lParam));
4408 windows_translate = 1;
4409 break;
4410 case VK_CONTROL:
4411 case VK_SHIFT:
4412 case VK_PROCESSKEY: /* Generated by IME. */
4413 windows_translate = 1;
4414 break;
4415 case VK_CANCEL:
4416 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4417 which is confusing for purposes of key binding; convert
4418 VK_CANCEL events into VK_PAUSE events. */
4419 wParam = VK_PAUSE;
4420 break;
4421 case VK_PAUSE:
4422 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4423 for purposes of key binding; convert these back into
4424 VK_NUMLOCK events, at least when we want to see NumLock key
4425 presses. (Note that there is never any possibility that
4426 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4427 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4428 wParam = VK_NUMLOCK;
4429 break;
4430 default:
4431 /* If not defined as a function key, change it to a WM_CHAR message. */
4432 if (lispy_function_keys[wParam] == 0)
4434 DWORD modifiers = construct_console_modifiers ();
4436 if (!NILP (Vw32_recognize_altgr)
4437 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4439 /* Always let TranslateMessage handle AltGr key chords;
4440 for some reason, ToAscii doesn't always process AltGr
4441 chords correctly. */
4442 windows_translate = 1;
4444 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4446 /* Handle key chords including any modifiers other
4447 than shift directly, in order to preserve as much
4448 modifier information as possible. */
4449 if ('A' <= wParam && wParam <= 'Z')
4451 /* Don't translate modified alphabetic keystrokes,
4452 so the user doesn't need to constantly switch
4453 layout to type control or meta keystrokes when
4454 the normal layout translates alphabetic
4455 characters to non-ascii characters. */
4456 if (!modifier_set (VK_SHIFT))
4457 wParam += ('a' - 'A');
4458 msg = WM_CHAR;
4460 else
4462 /* Try to handle other keystrokes by determining the
4463 base character (ie. translating the base key plus
4464 shift modifier). */
4465 int add;
4466 int isdead = 0;
4467 KEY_EVENT_RECORD key;
4469 key.bKeyDown = TRUE;
4470 key.wRepeatCount = 1;
4471 key.wVirtualKeyCode = wParam;
4472 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4473 key.uChar.AsciiChar = 0;
4474 key.dwControlKeyState = modifiers;
4476 add = w32_kbd_patch_key (&key);
4477 /* 0 means an unrecognised keycode, negative means
4478 dead key. Ignore both. */
4479 while (--add >= 0)
4481 /* Forward asciified character sequence. */
4482 post_character_message
4483 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4484 w32_get_key_modifiers (wParam, lParam));
4485 w32_kbd_patch_key (&key);
4487 return 0;
4490 else
4492 /* Let TranslateMessage handle everything else. */
4493 windows_translate = 1;
4498 translate:
4499 if (windows_translate)
4501 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4503 windows_msg.time = GetMessageTime ();
4504 TranslateMessage (&windows_msg);
4505 goto dflt;
4508 /* Fall through */
4510 case WM_SYSCHAR:
4511 case WM_CHAR:
4512 post_character_message (hwnd, msg, wParam, lParam,
4513 w32_get_key_modifiers (wParam, lParam));
4514 break;
4516 /* Simulate middle mouse button events when left and right buttons
4517 are used together, but only if user has two button mouse. */
4518 case WM_LBUTTONDOWN:
4519 case WM_RBUTTONDOWN:
4520 if (XINT (Vw32_num_mouse_buttons) > 2)
4521 goto handle_plain_button;
4524 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4525 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4527 if (button_state & this)
4528 return 0;
4530 if (button_state == 0)
4531 SetCapture (hwnd);
4533 button_state |= this;
4535 if (button_state & other)
4537 if (mouse_button_timer)
4539 KillTimer (hwnd, mouse_button_timer);
4540 mouse_button_timer = 0;
4542 /* Generate middle mouse event instead. */
4543 msg = WM_MBUTTONDOWN;
4544 button_state |= MMOUSE;
4546 else if (button_state & MMOUSE)
4548 /* Ignore button event if we've already generated a
4549 middle mouse down event. This happens if the
4550 user releases and press one of the two buttons
4551 after we've faked a middle mouse event. */
4552 return 0;
4554 else
4556 /* Flush out saved message. */
4557 post_msg (&saved_mouse_button_msg);
4559 wmsg.dwModifiers = w32_get_modifiers ();
4560 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4562 /* Clear message buffer. */
4563 saved_mouse_button_msg.msg.hwnd = 0;
4565 else
4567 /* Hold onto message for now. */
4568 mouse_button_timer =
4569 SetTimer (hwnd, MOUSE_BUTTON_ID,
4570 XINT (Vw32_mouse_button_tolerance), NULL);
4571 saved_mouse_button_msg.msg.hwnd = hwnd;
4572 saved_mouse_button_msg.msg.message = msg;
4573 saved_mouse_button_msg.msg.wParam = wParam;
4574 saved_mouse_button_msg.msg.lParam = lParam;
4575 saved_mouse_button_msg.msg.time = GetMessageTime ();
4576 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4579 return 0;
4581 case WM_LBUTTONUP:
4582 case WM_RBUTTONUP:
4583 if (XINT (Vw32_num_mouse_buttons) > 2)
4584 goto handle_plain_button;
4587 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4588 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4590 if ((button_state & this) == 0)
4591 return 0;
4593 button_state &= ~this;
4595 if (button_state & MMOUSE)
4597 /* Only generate event when second button is released. */
4598 if ((button_state & other) == 0)
4600 msg = WM_MBUTTONUP;
4601 button_state &= ~MMOUSE;
4603 if (button_state) abort ();
4605 else
4606 return 0;
4608 else
4610 /* Flush out saved message if necessary. */
4611 if (saved_mouse_button_msg.msg.hwnd)
4613 post_msg (&saved_mouse_button_msg);
4616 wmsg.dwModifiers = w32_get_modifiers ();
4617 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4619 /* Always clear message buffer and cancel timer. */
4620 saved_mouse_button_msg.msg.hwnd = 0;
4621 KillTimer (hwnd, mouse_button_timer);
4622 mouse_button_timer = 0;
4624 if (button_state == 0)
4625 ReleaseCapture ();
4627 return 0;
4629 case WM_XBUTTONDOWN:
4630 case WM_XBUTTONUP:
4631 if (w32_pass_extra_mouse_buttons_to_system)
4632 goto dflt;
4633 /* else fall through and process them. */
4634 case WM_MBUTTONDOWN:
4635 case WM_MBUTTONUP:
4636 handle_plain_button:
4638 BOOL up;
4639 int button;
4641 if (parse_button (msg, HIWORD (wParam), &button, &up))
4643 if (up) ReleaseCapture ();
4644 else SetCapture (hwnd);
4645 button = (button == 0) ? LMOUSE :
4646 ((button == 1) ? MMOUSE : RMOUSE);
4647 if (up)
4648 button_state &= ~button;
4649 else
4650 button_state |= button;
4654 wmsg.dwModifiers = w32_get_modifiers ();
4655 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4657 /* Need to return true for XBUTTON messages, false for others,
4658 to indicate that we processed the message. */
4659 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4661 case WM_MOUSEMOVE:
4662 /* If the mouse has just moved into the frame, start tracking
4663 it, so we will be notified when it leaves the frame. Mouse
4664 tracking only works under W98 and NT4 and later. On earlier
4665 versions, there is no way of telling when the mouse leaves the
4666 frame, so we just have to put up with help-echo and mouse
4667 highlighting remaining while the frame is not active. */
4668 if (track_mouse_event_fn && !track_mouse_window)
4670 TRACKMOUSEEVENT tme;
4671 tme.cbSize = sizeof (tme);
4672 tme.dwFlags = TME_LEAVE;
4673 tme.hwndTrack = hwnd;
4675 track_mouse_event_fn (&tme);
4676 track_mouse_window = hwnd;
4678 case WM_VSCROLL:
4679 if (XINT (Vw32_mouse_move_interval) <= 0
4680 || (msg == WM_MOUSEMOVE && button_state == 0))
4682 wmsg.dwModifiers = w32_get_modifiers ();
4683 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4684 return 0;
4687 /* Hang onto mouse move and scroll messages for a bit, to avoid
4688 sending such events to Emacs faster than it can process them.
4689 If we get more events before the timer from the first message
4690 expires, we just replace the first message. */
4692 if (saved_mouse_move_msg.msg.hwnd == 0)
4693 mouse_move_timer =
4694 SetTimer (hwnd, MOUSE_MOVE_ID,
4695 XINT (Vw32_mouse_move_interval), NULL);
4697 /* Hold onto message for now. */
4698 saved_mouse_move_msg.msg.hwnd = hwnd;
4699 saved_mouse_move_msg.msg.message = msg;
4700 saved_mouse_move_msg.msg.wParam = wParam;
4701 saved_mouse_move_msg.msg.lParam = lParam;
4702 saved_mouse_move_msg.msg.time = GetMessageTime ();
4703 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4705 return 0;
4707 case WM_MOUSEWHEEL:
4708 wmsg.dwModifiers = w32_get_modifiers ();
4709 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4710 return 0;
4712 case WM_DROPFILES:
4713 wmsg.dwModifiers = w32_get_modifiers ();
4714 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4715 return 0;
4717 case WM_TIMER:
4718 /* Flush out saved messages if necessary. */
4719 if (wParam == mouse_button_timer)
4721 if (saved_mouse_button_msg.msg.hwnd)
4723 post_msg (&saved_mouse_button_msg);
4724 saved_mouse_button_msg.msg.hwnd = 0;
4726 KillTimer (hwnd, mouse_button_timer);
4727 mouse_button_timer = 0;
4729 else if (wParam == mouse_move_timer)
4731 if (saved_mouse_move_msg.msg.hwnd)
4733 post_msg (&saved_mouse_move_msg);
4734 saved_mouse_move_msg.msg.hwnd = 0;
4736 KillTimer (hwnd, mouse_move_timer);
4737 mouse_move_timer = 0;
4739 else if (wParam == menu_free_timer)
4741 KillTimer (hwnd, menu_free_timer);
4742 menu_free_timer = 0;
4743 f = x_window_to_frame (dpyinfo, hwnd);
4744 if (!f->output_data.w32->menu_command_in_progress)
4746 /* Free memory used by owner-drawn and help-echo strings. */
4747 w32_free_menu_strings (hwnd);
4748 f->output_data.w32->menubar_active = 0;
4751 return 0;
4753 case WM_NCACTIVATE:
4754 /* Windows doesn't send us focus messages when putting up and
4755 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4756 The only indication we get that something happened is receiving
4757 this message afterwards. So this is a good time to reset our
4758 keyboard modifiers' state. */
4759 reset_modifiers ();
4760 goto dflt;
4762 case WM_INITMENU:
4763 button_state = 0;
4764 ReleaseCapture ();
4765 /* We must ensure menu bar is fully constructed and up to date
4766 before allowing user interaction with it. To achieve this
4767 we send this message to the lisp thread and wait for a
4768 reply (whose value is not actually needed) to indicate that
4769 the menu bar is now ready for use, so we can now return.
4771 To remain responsive in the meantime, we enter a nested message
4772 loop that can process all other messages.
4774 However, we skip all this if the message results from calling
4775 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4776 thread a message because it is blocked on us at this point. We
4777 set menubar_active before calling TrackPopupMenu to indicate
4778 this (there is no possibility of confusion with real menubar
4779 being active). */
4781 f = x_window_to_frame (dpyinfo, hwnd);
4782 if (f
4783 && (f->output_data.w32->menubar_active
4784 /* We can receive this message even in the absence of a
4785 menubar (ie. when the system menu is activated) - in this
4786 case we do NOT want to forward the message, otherwise it
4787 will cause the menubar to suddenly appear when the user
4788 had requested it to be turned off! */
4789 || f->output_data.w32->menubar_widget == NULL))
4790 return 0;
4793 deferred_msg msg_buf;
4795 /* Detect if message has already been deferred; in this case
4796 we cannot return any sensible value to ignore this. */
4797 if (find_deferred_msg (hwnd, msg) != NULL)
4798 abort ();
4800 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4803 case WM_EXITMENULOOP:
4804 f = x_window_to_frame (dpyinfo, hwnd);
4806 /* If a menu command is not already in progress, check again
4807 after a short delay, since Windows often (always?) sends the
4808 WM_EXITMENULOOP before the corresponding WM_COMMAND message. */
4809 if (f && !f->output_data.w32->menu_command_in_progress)
4810 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4811 goto dflt;
4813 case WM_MENUSELECT:
4814 /* Direct handling of help_echo in menus. Should be safe now
4815 that we generate the help_echo by placing a help event in the
4816 keyboard buffer. */
4818 HMENU menu = (HMENU) lParam;
4819 UINT menu_item = (UINT) LOWORD (wParam);
4820 UINT flags = (UINT) HIWORD (wParam);
4822 w32_menu_display_help (hwnd, menu, menu_item, flags);
4824 return 0;
4826 case WM_MEASUREITEM:
4827 f = x_window_to_frame (dpyinfo, hwnd);
4828 if (f)
4830 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4832 if (pMis->CtlType == ODT_MENU)
4834 /* Work out dimensions for popup menu titles. */
4835 char * title = (char *) pMis->itemData;
4836 HDC hdc = GetDC (hwnd);
4837 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4838 LOGFONT menu_logfont;
4839 HFONT old_font;
4840 SIZE size;
4842 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4843 menu_logfont.lfWeight = FW_BOLD;
4844 menu_font = CreateFontIndirect (&menu_logfont);
4845 old_font = SelectObject (hdc, menu_font);
4847 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4848 if (title)
4850 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4851 pMis->itemWidth = size.cx;
4852 if (pMis->itemHeight < size.cy)
4853 pMis->itemHeight = size.cy;
4855 else
4856 pMis->itemWidth = 0;
4858 SelectObject (hdc, old_font);
4859 DeleteObject (menu_font);
4860 ReleaseDC (hwnd, hdc);
4861 return TRUE;
4864 return 0;
4866 case WM_DRAWITEM:
4867 f = x_window_to_frame (dpyinfo, hwnd);
4868 if (f)
4870 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4872 if (pDis->CtlType == ODT_MENU)
4874 /* Draw popup menu title. */
4875 char * title = (char *) pDis->itemData;
4876 if (title)
4878 HDC hdc = pDis->hDC;
4879 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4880 LOGFONT menu_logfont;
4881 HFONT old_font;
4883 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4884 menu_logfont.lfWeight = FW_BOLD;
4885 menu_font = CreateFontIndirect (&menu_logfont);
4886 old_font = SelectObject (hdc, menu_font);
4888 /* Always draw title as if not selected. */
4889 ExtTextOut (hdc,
4890 pDis->rcItem.left
4891 + GetSystemMetrics (SM_CXMENUCHECK),
4892 pDis->rcItem.top,
4893 ETO_OPAQUE, &pDis->rcItem,
4894 title, strlen (title), NULL);
4896 SelectObject (hdc, old_font);
4897 DeleteObject (menu_font);
4899 return TRUE;
4902 return 0;
4904 #if 0
4905 /* Still not right - can't distinguish between clicks in the
4906 client area of the frame from clicks forwarded from the scroll
4907 bars - may have to hook WM_NCHITTEST to remember the mouse
4908 position and then check if it is in the client area ourselves. */
4909 case WM_MOUSEACTIVATE:
4910 /* Discard the mouse click that activates a frame, allowing the
4911 user to click anywhere without changing point (or worse!).
4912 Don't eat mouse clicks on scrollbars though!! */
4913 if (LOWORD (lParam) == HTCLIENT )
4914 return MA_ACTIVATEANDEAT;
4915 goto dflt;
4916 #endif
4918 case WM_MOUSELEAVE:
4919 /* No longer tracking mouse. */
4920 track_mouse_window = NULL;
4922 case WM_ACTIVATEAPP:
4923 case WM_ACTIVATE:
4924 case WM_WINDOWPOSCHANGED:
4925 case WM_SHOWWINDOW:
4926 /* Inform lisp thread that a frame might have just been obscured
4927 or exposed, so should recheck visibility of all frames. */
4928 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4929 goto dflt;
4931 case WM_SETFOCUS:
4932 dpyinfo->faked_key = 0;
4933 reset_modifiers ();
4934 register_hot_keys (hwnd);
4935 goto command;
4936 case WM_KILLFOCUS:
4937 unregister_hot_keys (hwnd);
4938 button_state = 0;
4939 ReleaseCapture ();
4940 /* Relinquish the system caret. */
4941 if (w32_system_caret_hwnd)
4943 w32_visible_system_caret_hwnd = NULL;
4944 w32_system_caret_hwnd = NULL;
4945 DestroyCaret ();
4947 goto command;
4948 case WM_COMMAND:
4949 f = x_window_to_frame (dpyinfo, hwnd);
4950 if (f && HIWORD (wParam) == 0)
4952 f->output_data.w32->menu_command_in_progress = 1;
4953 if (menu_free_timer)
4955 KillTimer (hwnd, menu_free_timer);
4956 menu_free_timer = 0;
4959 case WM_MOVE:
4960 case WM_SIZE:
4961 command:
4962 wmsg.dwModifiers = w32_get_modifiers ();
4963 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4964 goto dflt;
4966 case WM_CLOSE:
4967 wmsg.dwModifiers = w32_get_modifiers ();
4968 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4969 return 0;
4971 case WM_WINDOWPOSCHANGING:
4972 /* Don't restrict the sizing of tip frames. */
4973 if (hwnd == tip_window)
4974 return 0;
4976 WINDOWPLACEMENT wp;
4977 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4979 wp.length = sizeof (WINDOWPLACEMENT);
4980 GetWindowPlacement (hwnd, &wp);
4982 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4984 RECT rect;
4985 int wdiff;
4986 int hdiff;
4987 DWORD font_width;
4988 DWORD line_height;
4989 DWORD internal_border;
4990 DWORD scrollbar_extra;
4991 RECT wr;
4993 wp.length = sizeof(wp);
4994 GetWindowRect (hwnd, &wr);
4996 enter_crit ();
4998 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4999 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
5000 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
5001 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
5003 leave_crit ();
5005 memset (&rect, 0, sizeof (rect));
5006 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
5007 GetMenu (hwnd) != NULL);
5009 /* Force width and height of client area to be exact
5010 multiples of the character cell dimensions. */
5011 wdiff = (lppos->cx - (rect.right - rect.left)
5012 - 2 * internal_border - scrollbar_extra)
5013 % font_width;
5014 hdiff = (lppos->cy - (rect.bottom - rect.top)
5015 - 2 * internal_border)
5016 % line_height;
5018 if (wdiff || hdiff)
5020 /* For right/bottom sizing we can just fix the sizes.
5021 However for top/left sizing we will need to fix the X
5022 and Y positions as well. */
5024 lppos->cx -= wdiff;
5025 lppos->cy -= hdiff;
5027 if (wp.showCmd != SW_SHOWMAXIMIZED
5028 && (lppos->flags & SWP_NOMOVE) == 0)
5030 if (lppos->x != wr.left || lppos->y != wr.top)
5032 lppos->x += wdiff;
5033 lppos->y += hdiff;
5035 else
5037 lppos->flags |= SWP_NOMOVE;
5041 return 0;
5046 goto dflt;
5048 case WM_GETMINMAXINFO:
5049 /* Hack to correct bug that allows Emacs frames to be resized
5050 below the Minimum Tracking Size. */
5051 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
5052 /* Hack to allow resizing the Emacs frame above the screen size.
5053 Note that Windows 9x limits coordinates to 16-bits. */
5054 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
5055 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
5056 return 0;
5058 case WM_EMACS_CREATESCROLLBAR:
5059 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
5060 (struct scroll_bar *) lParam);
5062 case WM_EMACS_SHOWWINDOW:
5063 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
5065 case WM_EMACS_SETFOREGROUND:
5067 HWND foreground_window;
5068 DWORD foreground_thread, retval;
5070 /* On NT 5.0, and apparently Windows 98, it is necessary to
5071 attach to the thread that currently has focus in order to
5072 pull the focus away from it. */
5073 foreground_window = GetForegroundWindow ();
5074 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
5075 if (!foreground_window
5076 || foreground_thread == GetCurrentThreadId ()
5077 || !AttachThreadInput (GetCurrentThreadId (),
5078 foreground_thread, TRUE))
5079 foreground_thread = 0;
5081 retval = SetForegroundWindow ((HWND) wParam);
5083 /* Detach from the previous foreground thread. */
5084 if (foreground_thread)
5085 AttachThreadInput (GetCurrentThreadId (),
5086 foreground_thread, FALSE);
5088 return retval;
5091 case WM_EMACS_SETWINDOWPOS:
5093 WINDOWPOS * pos = (WINDOWPOS *) wParam;
5094 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5095 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
5098 case WM_EMACS_DESTROYWINDOW:
5099 DragAcceptFiles ((HWND) wParam, FALSE);
5100 return DestroyWindow ((HWND) wParam);
5102 case WM_EMACS_HIDE_CARET:
5103 return HideCaret (hwnd);
5105 case WM_EMACS_SHOW_CARET:
5106 return ShowCaret (hwnd);
5108 case WM_EMACS_DESTROY_CARET:
5109 w32_system_caret_hwnd = NULL;
5110 w32_visible_system_caret_hwnd = NULL;
5111 return DestroyCaret ();
5113 case WM_EMACS_TRACK_CARET:
5114 /* If there is currently no system caret, create one. */
5115 if (w32_system_caret_hwnd == NULL)
5117 /* Use the default caret width, and avoid changing it
5118 unneccesarily, as it confuses screen reader software. */
5119 w32_system_caret_hwnd = hwnd;
5120 CreateCaret (hwnd, NULL, 0,
5121 w32_system_caret_height);
5124 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
5125 return 0;
5126 /* Ensure visible caret gets turned on when requested. */
5127 else if (w32_use_visible_system_caret
5128 && w32_visible_system_caret_hwnd != hwnd)
5130 w32_visible_system_caret_hwnd = hwnd;
5131 return ShowCaret (hwnd);
5133 /* Ensure visible caret gets turned off when requested. */
5134 else if (!w32_use_visible_system_caret
5135 && w32_visible_system_caret_hwnd)
5137 w32_visible_system_caret_hwnd = NULL;
5138 return HideCaret (hwnd);
5140 else
5141 return 1;
5143 case WM_EMACS_TRACKPOPUPMENU:
5145 UINT flags;
5146 POINT *pos;
5147 int retval;
5148 pos = (POINT *)lParam;
5149 flags = TPM_CENTERALIGN;
5150 if (button_state & LMOUSE)
5151 flags |= TPM_LEFTBUTTON;
5152 else if (button_state & RMOUSE)
5153 flags |= TPM_RIGHTBUTTON;
5155 /* Remember we did a SetCapture on the initial mouse down event,
5156 so for safety, we make sure the capture is cancelled now. */
5157 ReleaseCapture ();
5158 button_state = 0;
5160 /* Use menubar_active to indicate that WM_INITMENU is from
5161 TrackPopupMenu below, and should be ignored. */
5162 f = x_window_to_frame (dpyinfo, hwnd);
5163 if (f)
5164 f->output_data.w32->menubar_active = 1;
5166 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
5167 0, hwnd, NULL))
5169 MSG amsg;
5170 /* Eat any mouse messages during popupmenu */
5171 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
5172 PM_REMOVE));
5173 /* Get the menu selection, if any */
5174 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
5176 retval = LOWORD (amsg.wParam);
5178 else
5180 retval = 0;
5183 else
5185 retval = -1;
5188 return retval;
5191 default:
5192 /* Check for messages registered at runtime. */
5193 if (msg == msh_mousewheel)
5195 wmsg.dwModifiers = w32_get_modifiers ();
5196 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5197 return 0;
5200 dflt:
5201 return DefWindowProc (hwnd, msg, wParam, lParam);
5205 /* The most common default return code for handled messages is 0. */
5206 return 0;
5209 void
5210 my_create_window (f)
5211 struct frame * f;
5213 MSG msg;
5215 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
5216 abort ();
5217 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5221 /* Create a tooltip window. Unlike my_create_window, we do not do this
5222 indirectly via the Window thread, as we do not need to process Window
5223 messages for the tooltip. Creating tooltips indirectly also creates
5224 deadlocks when tooltips are created for menu items. */
5225 void
5226 my_create_tip_window (f)
5227 struct frame *f;
5229 RECT rect;
5231 rect.left = rect.top = 0;
5232 rect.right = PIXEL_WIDTH (f);
5233 rect.bottom = PIXEL_HEIGHT (f);
5235 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
5236 FRAME_EXTERNAL_MENU_BAR (f));
5238 tip_window = FRAME_W32_WINDOW (f)
5239 = CreateWindow (EMACS_CLASS,
5240 f->namebuf,
5241 f->output_data.w32->dwStyle,
5242 f->output_data.w32->left_pos,
5243 f->output_data.w32->top_pos,
5244 rect.right - rect.left,
5245 rect.bottom - rect.top,
5246 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5247 NULL,
5248 hinst,
5249 NULL);
5251 if (tip_window)
5253 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
5254 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
5255 SetWindowLong (tip_window, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
5256 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5258 /* Tip frames have no scrollbars. */
5259 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
5261 /* Do this to discard the default setting specified by our parent. */
5262 ShowWindow (tip_window, SW_HIDE);
5267 /* Create and set up the w32 window for frame F. */
5269 static void
5270 w32_window (f, window_prompting, minibuffer_only)
5271 struct frame *f;
5272 long window_prompting;
5273 int minibuffer_only;
5275 BLOCK_INPUT;
5277 /* Use the resource name as the top-level window name
5278 for looking up resources. Make a non-Lisp copy
5279 for the window manager, so GC relocation won't bother it.
5281 Elsewhere we specify the window name for the window manager. */
5284 char *str = (char *) SDATA (Vx_resource_name);
5285 f->namebuf = (char *) xmalloc (strlen (str) + 1);
5286 strcpy (f->namebuf, str);
5289 my_create_window (f);
5291 validate_x_resource_name ();
5293 /* x_set_name normally ignores requests to set the name if the
5294 requested name is the same as the current name. This is the one
5295 place where that assumption isn't correct; f->name is set, but
5296 the server hasn't been told. */
5298 Lisp_Object name;
5299 int explicit = f->explicit_name;
5301 f->explicit_name = 0;
5302 name = f->name;
5303 f->name = Qnil;
5304 x_set_name (f, name, explicit);
5307 UNBLOCK_INPUT;
5309 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5310 initialize_frame_menubar (f);
5312 if (FRAME_W32_WINDOW (f) == 0)
5313 error ("Unable to create window");
5316 /* Handle the icon stuff for this window. Perhaps later we might
5317 want an x_set_icon_position which can be called interactively as
5318 well. */
5320 static void
5321 x_icon (f, parms)
5322 struct frame *f;
5323 Lisp_Object parms;
5325 Lisp_Object icon_x, icon_y;
5327 /* Set the position of the icon. Note that Windows 95 groups all
5328 icons in the tray. */
5329 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5330 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5331 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5333 CHECK_NUMBER (icon_x);
5334 CHECK_NUMBER (icon_y);
5336 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5337 error ("Both left and top icon corners of icon must be specified");
5339 BLOCK_INPUT;
5341 if (! EQ (icon_x, Qunbound))
5342 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5344 #if 0 /* TODO */
5345 /* Start up iconic or window? */
5346 x_wm_set_window_state
5347 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5348 ? IconicState
5349 : NormalState));
5351 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
5352 ? f->icon_name
5353 : f->name)));
5354 #endif
5356 UNBLOCK_INPUT;
5360 static void
5361 x_make_gc (f)
5362 struct frame *f;
5364 XGCValues gc_values;
5366 BLOCK_INPUT;
5368 /* Create the GC's of this frame.
5369 Note that many default values are used. */
5371 /* Normal video */
5372 gc_values.font = f->output_data.w32->font;
5374 /* Cursor has cursor-color background, background-color foreground. */
5375 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5376 gc_values.background = f->output_data.w32->cursor_pixel;
5377 f->output_data.w32->cursor_gc
5378 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5379 (GCFont | GCForeground | GCBackground),
5380 &gc_values);
5382 /* Reliefs. */
5383 f->output_data.w32->white_relief.gc = 0;
5384 f->output_data.w32->black_relief.gc = 0;
5386 UNBLOCK_INPUT;
5390 /* Handler for signals raised during x_create_frame and
5391 x_create_top_frame. FRAME is the frame which is partially
5392 constructed. */
5394 static Lisp_Object
5395 unwind_create_frame (frame)
5396 Lisp_Object frame;
5398 struct frame *f = XFRAME (frame);
5400 /* If frame is ``official'', nothing to do. */
5401 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
5403 #ifdef GLYPH_DEBUG
5404 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5405 #endif
5407 x_free_frame_resources (f);
5409 /* Check that reference counts are indeed correct. */
5410 xassert (dpyinfo->reference_count == dpyinfo_refcount);
5411 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
5413 return Qt;
5416 return Qnil;
5420 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5421 1, 1, 0,
5422 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5423 Returns an Emacs frame object.
5424 ALIST is an alist of frame parameters.
5425 If the parameters specify that the frame should not have a minibuffer,
5426 and do not specify a specific minibuffer window to use,
5427 then `default-minibuffer-frame' must be a frame whose minibuffer can
5428 be shared by the new frame.
5430 This function is an internal primitive--use `make-frame' instead. */)
5431 (parms)
5432 Lisp_Object parms;
5434 struct frame *f;
5435 Lisp_Object frame, tem;
5436 Lisp_Object name;
5437 int minibuffer_only = 0;
5438 long window_prompting = 0;
5439 int width, height;
5440 int count = SPECPDL_INDEX ();
5441 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5442 Lisp_Object display;
5443 struct w32_display_info *dpyinfo = NULL;
5444 Lisp_Object parent;
5445 struct kboard *kb;
5447 check_w32 ();
5449 /* Use this general default value to start with
5450 until we know if this frame has a specified name. */
5451 Vx_resource_name = Vinvocation_name;
5453 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5454 if (EQ (display, Qunbound))
5455 display = Qnil;
5456 dpyinfo = check_x_display_info (display);
5457 #ifdef MULTI_KBOARD
5458 kb = dpyinfo->kboard;
5459 #else
5460 kb = &the_only_kboard;
5461 #endif
5463 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5464 if (!STRINGP (name)
5465 && ! EQ (name, Qunbound)
5466 && ! NILP (name))
5467 error ("Invalid frame name--not a string or nil");
5469 if (STRINGP (name))
5470 Vx_resource_name = name;
5472 /* See if parent window is specified. */
5473 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5474 if (EQ (parent, Qunbound))
5475 parent = Qnil;
5476 if (! NILP (parent))
5477 CHECK_NUMBER (parent);
5479 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5480 /* No need to protect DISPLAY because that's not used after passing
5481 it to make_frame_without_minibuffer. */
5482 frame = Qnil;
5483 GCPRO4 (parms, parent, name, frame);
5484 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5485 RES_TYPE_SYMBOL);
5486 if (EQ (tem, Qnone) || NILP (tem))
5487 f = make_frame_without_minibuffer (Qnil, kb, display);
5488 else if (EQ (tem, Qonly))
5490 f = make_minibuffer_frame ();
5491 minibuffer_only = 1;
5493 else if (WINDOWP (tem))
5494 f = make_frame_without_minibuffer (tem, kb, display);
5495 else
5496 f = make_frame (1);
5498 XSETFRAME (frame, f);
5500 /* Note that Windows does support scroll bars. */
5501 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5502 /* By default, make scrollbars the system standard width. */
5503 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5505 f->output_method = output_w32;
5506 f->output_data.w32 =
5507 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5508 bzero (f->output_data.w32, sizeof (struct w32_output));
5509 FRAME_FONTSET (f) = -1;
5510 record_unwind_protect (unwind_create_frame, frame);
5512 f->icon_name
5513 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5514 if (! STRINGP (f->icon_name))
5515 f->icon_name = Qnil;
5517 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5518 #ifdef MULTI_KBOARD
5519 FRAME_KBOARD (f) = kb;
5520 #endif
5522 /* Specify the parent under which to make this window. */
5524 if (!NILP (parent))
5526 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5527 f->output_data.w32->explicit_parent = 1;
5529 else
5531 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5532 f->output_data.w32->explicit_parent = 0;
5535 /* Set the name; the functions to which we pass f expect the name to
5536 be set. */
5537 if (EQ (name, Qunbound) || NILP (name))
5539 f->name = build_string (dpyinfo->w32_id_name);
5540 f->explicit_name = 0;
5542 else
5544 f->name = name;
5545 f->explicit_name = 1;
5546 /* use the frame's title when getting resources for this frame. */
5547 specbind (Qx_resource_name, name);
5550 /* Extract the window parameters from the supplied values
5551 that are needed to determine window geometry. */
5553 Lisp_Object font;
5555 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5557 BLOCK_INPUT;
5558 /* First, try whatever font the caller has specified. */
5559 if (STRINGP (font))
5561 tem = Fquery_fontset (font, Qnil);
5562 if (STRINGP (tem))
5563 font = x_new_fontset (f, SDATA (tem));
5564 else
5565 font = x_new_font (f, SDATA (font));
5567 /* Try out a font which we hope has bold and italic variations. */
5568 if (!STRINGP (font))
5569 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5570 if (! STRINGP (font))
5571 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5572 /* If those didn't work, look for something which will at least work. */
5573 if (! STRINGP (font))
5574 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5575 UNBLOCK_INPUT;
5576 if (! STRINGP (font))
5577 font = build_string ("Fixedsys");
5579 x_default_parameter (f, parms, Qfont, font,
5580 "font", "Font", RES_TYPE_STRING);
5583 x_default_parameter (f, parms, Qborder_width, make_number (2),
5584 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5585 /* This defaults to 2 in order to match xterm. We recognize either
5586 internalBorderWidth or internalBorder (which is what xterm calls
5587 it). */
5588 if (NILP (Fassq (Qinternal_border_width, parms)))
5590 Lisp_Object value;
5592 value = w32_get_arg (parms, Qinternal_border_width,
5593 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5594 if (! EQ (value, Qunbound))
5595 parms = Fcons (Fcons (Qinternal_border_width, value),
5596 parms);
5598 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5599 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5600 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5601 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5602 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5604 /* Also do the stuff which must be set before the window exists. */
5605 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5606 "foreground", "Foreground", RES_TYPE_STRING);
5607 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5608 "background", "Background", RES_TYPE_STRING);
5609 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5610 "pointerColor", "Foreground", RES_TYPE_STRING);
5611 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5612 "cursorColor", "Foreground", RES_TYPE_STRING);
5613 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5614 "borderColor", "BorderColor", RES_TYPE_STRING);
5615 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5616 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5617 x_default_parameter (f, parms, Qline_spacing, Qnil,
5618 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5619 x_default_parameter (f, parms, Qleft_fringe, Qnil,
5620 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5621 x_default_parameter (f, parms, Qright_fringe, Qnil,
5622 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5625 /* Init faces before x_default_parameter is called for scroll-bar
5626 parameters because that function calls x_set_scroll_bar_width,
5627 which calls change_frame_size, which calls Fset_window_buffer,
5628 which runs hooks, which call Fvertical_motion. At the end, we
5629 end up in init_iterator with a null face cache, which should not
5630 happen. */
5631 init_frame_faces (f);
5633 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5634 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5635 x_default_parameter (f, parms, Qtool_bar_lines, make_number (1),
5636 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5638 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5639 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5640 x_default_parameter (f, parms, Qtitle, Qnil,
5641 "title", "Title", RES_TYPE_STRING);
5642 x_default_parameter (f, parms, Qfullscreen, Qnil,
5643 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5645 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5646 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5648 /* Add the tool-bar height to the initial frame height so that the
5649 user gets a text display area of the size he specified with -g or
5650 via .Xdefaults. Later changes of the tool-bar height don't
5651 change the frame size. This is done so that users can create
5652 tall Emacs frames without having to guess how tall the tool-bar
5653 will get. */
5654 if (FRAME_TOOL_BAR_LINES (f))
5656 int margin, relief, bar_height;
5658 relief = (tool_bar_button_relief >= 0
5659 ? tool_bar_button_relief
5660 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
5662 if (INTEGERP (Vtool_bar_button_margin)
5663 && XINT (Vtool_bar_button_margin) > 0)
5664 margin = XFASTINT (Vtool_bar_button_margin);
5665 else if (CONSP (Vtool_bar_button_margin)
5666 && INTEGERP (XCDR (Vtool_bar_button_margin))
5667 && XINT (XCDR (Vtool_bar_button_margin)) > 0)
5668 margin = XFASTINT (XCDR (Vtool_bar_button_margin));
5669 else
5670 margin = 0;
5672 bar_height = DEFAULT_TOOL_BAR_IMAGE_HEIGHT + 2 * margin + 2 * relief;
5673 f->height += (bar_height + CANON_Y_UNIT (f) - 1) / CANON_Y_UNIT (f);
5676 window_prompting = x_figure_window_size (f, parms);
5678 if (window_prompting & XNegative)
5680 if (window_prompting & YNegative)
5681 f->output_data.w32->win_gravity = SouthEastGravity;
5682 else
5683 f->output_data.w32->win_gravity = NorthEastGravity;
5685 else
5687 if (window_prompting & YNegative)
5688 f->output_data.w32->win_gravity = SouthWestGravity;
5689 else
5690 f->output_data.w32->win_gravity = NorthWestGravity;
5693 f->output_data.w32->size_hint_flags = window_prompting;
5695 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5696 f->no_split = minibuffer_only || EQ (tem, Qt);
5698 w32_window (f, window_prompting, minibuffer_only);
5699 x_icon (f, parms);
5701 x_make_gc (f);
5703 /* Now consider the frame official. */
5704 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5705 Vframe_list = Fcons (frame, Vframe_list);
5707 /* We need to do this after creating the window, so that the
5708 icon-creation functions can say whose icon they're describing. */
5709 x_default_parameter (f, parms, Qicon_type, Qnil,
5710 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5712 x_default_parameter (f, parms, Qauto_raise, Qnil,
5713 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5714 x_default_parameter (f, parms, Qauto_lower, Qnil,
5715 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5716 x_default_parameter (f, parms, Qcursor_type, Qbox,
5717 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5718 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5719 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5721 /* Dimensions, especially f->height, must be done via change_frame_size.
5722 Change will not be effected unless different from the current
5723 f->height. */
5724 width = f->width;
5725 height = f->height;
5727 f->height = 0;
5728 SET_FRAME_WIDTH (f, 0);
5729 change_frame_size (f, height, width, 1, 0, 0);
5731 /* Tell the server what size and position, etc, we want, and how
5732 badly we want them. This should be done after we have the menu
5733 bar so that its size can be taken into account. */
5734 BLOCK_INPUT;
5735 x_wm_set_size_hint (f, window_prompting, 0);
5736 UNBLOCK_INPUT;
5738 /* Avoid a bug that causes the new frame to never become visible if
5739 an echo area message is displayed during the following call1. */
5740 specbind(Qredisplay_dont_pause, Qt);
5742 /* Set up faces after all frame parameters are known. This call
5743 also merges in face attributes specified for new frames. If we
5744 don't do this, the `menu' face for instance won't have the right
5745 colors, and the menu bar won't appear in the specified colors for
5746 new frames. */
5747 call1 (Qface_set_after_frame_default, frame);
5749 /* Make the window appear on the frame and enable display, unless
5750 the caller says not to. However, with explicit parent, Emacs
5751 cannot control visibility, so don't try. */
5752 if (! f->output_data.w32->explicit_parent)
5754 Lisp_Object visibility;
5756 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5757 if (EQ (visibility, Qunbound))
5758 visibility = Qt;
5760 if (EQ (visibility, Qicon))
5761 x_iconify_frame (f);
5762 else if (! NILP (visibility))
5763 x_make_frame_visible (f);
5764 else
5765 /* Must have been Qnil. */
5768 UNGCPRO;
5770 /* Make sure windows on this frame appear in calls to next-window
5771 and similar functions. */
5772 Vwindow_list = Qnil;
5774 return unbind_to (count, frame);
5777 /* FRAME is used only to get a handle on the X display. We don't pass the
5778 display info directly because we're called from frame.c, which doesn't
5779 know about that structure. */
5780 Lisp_Object
5781 x_get_focus_frame (frame)
5782 struct frame *frame;
5784 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5785 Lisp_Object xfocus;
5786 if (! dpyinfo->w32_focus_frame)
5787 return Qnil;
5789 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5790 return xfocus;
5793 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5794 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
5795 (frame)
5796 Lisp_Object frame;
5798 x_focus_on_frame (check_x_frame (frame));
5799 return Qnil;
5803 /* Return the charset portion of a font name. */
5804 char * xlfd_charset_of_font (char * fontname)
5806 char *charset, *encoding;
5808 encoding = strrchr(fontname, '-');
5809 if (!encoding || encoding == fontname)
5810 return NULL;
5812 for (charset = encoding - 1; charset >= fontname; charset--)
5813 if (*charset == '-')
5814 break;
5816 if (charset == fontname || strcmp(charset, "-*-*") == 0)
5817 return NULL;
5819 return charset + 1;
5822 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5823 int size, char* filename);
5824 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
5825 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
5826 char * charset);
5827 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
5829 static struct font_info *
5830 w32_load_system_font (f,fontname,size)
5831 struct frame *f;
5832 char * fontname;
5833 int size;
5835 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5836 Lisp_Object font_names;
5838 /* Get a list of all the fonts that match this name. Once we
5839 have a list of matching fonts, we compare them against the fonts
5840 we already have loaded by comparing names. */
5841 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5843 if (!NILP (font_names))
5845 Lisp_Object tail;
5846 int i;
5848 /* First check if any are already loaded, as that is cheaper
5849 than loading another one. */
5850 for (i = 0; i < dpyinfo->n_fonts; i++)
5851 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5852 if (dpyinfo->font_table[i].name
5853 && (!strcmp (dpyinfo->font_table[i].name,
5854 SDATA (XCAR (tail)))
5855 || !strcmp (dpyinfo->font_table[i].full_name,
5856 SDATA (XCAR (tail)))))
5857 return (dpyinfo->font_table + i);
5859 fontname = (char *) SDATA (XCAR (font_names));
5861 else if (w32_strict_fontnames)
5863 /* If EnumFontFamiliesEx was available, we got a full list of
5864 fonts back so stop now to avoid the possibility of loading a
5865 random font. If we had to fall back to EnumFontFamilies, the
5866 list is incomplete, so continue whether the font we want was
5867 listed or not. */
5868 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5869 FARPROC enum_font_families_ex
5870 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5871 if (enum_font_families_ex)
5872 return NULL;
5875 /* Load the font and add it to the table. */
5877 char *full_name, *encoding, *charset;
5878 XFontStruct *font;
5879 struct font_info *fontp;
5880 LOGFONT lf;
5881 BOOL ok;
5882 int codepage;
5883 int i;
5885 if (!fontname || !x_to_w32_font (fontname, &lf))
5886 return (NULL);
5888 if (!*lf.lfFaceName)
5889 /* If no name was specified for the font, we get a random font
5890 from CreateFontIndirect - this is not particularly
5891 desirable, especially since CreateFontIndirect does not
5892 fill out the missing name in lf, so we never know what we
5893 ended up with. */
5894 return NULL;
5896 lf.lfQuality = DEFAULT_QUALITY;
5898 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5899 bzero (font, sizeof (*font));
5901 /* Set bdf to NULL to indicate that this is a Windows font. */
5902 font->bdf = NULL;
5904 BLOCK_INPUT;
5906 font->hfont = CreateFontIndirect (&lf);
5908 if (font->hfont == NULL)
5910 ok = FALSE;
5912 else
5914 HDC hdc;
5915 HANDLE oldobj;
5917 codepage = w32_codepage_for_font (fontname);
5919 hdc = GetDC (dpyinfo->root_window);
5920 oldobj = SelectObject (hdc, font->hfont);
5922 ok = GetTextMetrics (hdc, &font->tm);
5923 if (codepage == CP_UNICODE)
5924 font->double_byte_p = 1;
5925 else
5927 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
5928 don't report themselves as double byte fonts, when
5929 patently they are. So instead of trusting
5930 GetFontLanguageInfo, we check the properties of the
5931 codepage directly, since that is ultimately what we are
5932 working from anyway. */
5933 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
5934 CPINFO cpi = {0};
5935 GetCPInfo (codepage, &cpi);
5936 font->double_byte_p = cpi.MaxCharSize > 1;
5939 SelectObject (hdc, oldobj);
5940 ReleaseDC (dpyinfo->root_window, hdc);
5941 /* Fill out details in lf according to the font that was
5942 actually loaded. */
5943 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5944 lf.lfWidth = font->tm.tmAveCharWidth;
5945 lf.lfWeight = font->tm.tmWeight;
5946 lf.lfItalic = font->tm.tmItalic;
5947 lf.lfCharSet = font->tm.tmCharSet;
5948 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5949 ? VARIABLE_PITCH : FIXED_PITCH);
5950 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5951 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5953 w32_cache_char_metrics (font);
5956 UNBLOCK_INPUT;
5958 if (!ok)
5960 w32_unload_font (dpyinfo, font);
5961 return (NULL);
5964 /* Find a free slot in the font table. */
5965 for (i = 0; i < dpyinfo->n_fonts; ++i)
5966 if (dpyinfo->font_table[i].name == NULL)
5967 break;
5969 /* If no free slot found, maybe enlarge the font table. */
5970 if (i == dpyinfo->n_fonts
5971 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5973 int sz;
5974 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5975 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5976 dpyinfo->font_table
5977 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5980 fontp = dpyinfo->font_table + i;
5981 if (i == dpyinfo->n_fonts)
5982 ++dpyinfo->n_fonts;
5984 /* Now fill in the slots of *FONTP. */
5985 BLOCK_INPUT;
5986 fontp->font = font;
5987 fontp->font_idx = i;
5988 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5989 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5991 charset = xlfd_charset_of_font (fontname);
5993 /* Cache the W32 codepage for a font. This makes w32_encode_char
5994 (called for every glyph during redisplay) much faster. */
5995 fontp->codepage = codepage;
5997 /* Work out the font's full name. */
5998 full_name = (char *)xmalloc (100);
5999 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
6000 fontp->full_name = full_name;
6001 else
6003 /* If all else fails - just use the name we used to load it. */
6004 xfree (full_name);
6005 fontp->full_name = fontp->name;
6008 fontp->size = FONT_WIDTH (font);
6009 fontp->height = FONT_HEIGHT (font);
6011 /* The slot `encoding' specifies how to map a character
6012 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
6013 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
6014 (0:0x20..0x7F, 1:0xA0..0xFF,
6015 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
6016 2:0xA020..0xFF7F). For the moment, we don't know which charset
6017 uses this font. So, we set information in fontp->encoding[1]
6018 which is never used by any charset. If mapping can't be
6019 decided, set FONT_ENCODING_NOT_DECIDED. */
6021 /* SJIS fonts need to be set to type 4, all others seem to work as
6022 type FONT_ENCODING_NOT_DECIDED. */
6023 encoding = strrchr (fontp->name, '-');
6024 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
6025 fontp->encoding[1] = 4;
6026 else
6027 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
6029 /* The following three values are set to 0 under W32, which is
6030 what they get set to if XGetFontProperty fails under X. */
6031 fontp->baseline_offset = 0;
6032 fontp->relative_compose = 0;
6033 fontp->default_ascent = 0;
6035 /* Set global flag fonts_changed_p to non-zero if the font loaded
6036 has a character with a smaller width than any other character
6037 before, or if the font loaded has a smaller height than any
6038 other font loaded before. If this happens, it will make a
6039 glyph matrix reallocation necessary. */
6040 fonts_changed_p |= x_compute_min_glyph_bounds (f);
6041 UNBLOCK_INPUT;
6042 return fontp;
6046 /* Load font named FONTNAME of size SIZE for frame F, and return a
6047 pointer to the structure font_info while allocating it dynamically.
6048 If loading fails, return NULL. */
6049 struct font_info *
6050 w32_load_font (f,fontname,size)
6051 struct frame *f;
6052 char * fontname;
6053 int size;
6055 Lisp_Object bdf_fonts;
6056 struct font_info *retval = NULL;
6058 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
6060 while (!retval && CONSP (bdf_fonts))
6062 char *bdf_name, *bdf_file;
6063 Lisp_Object bdf_pair;
6065 bdf_name = SDATA (XCAR (bdf_fonts));
6066 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
6067 bdf_file = SDATA (XCDR (bdf_pair));
6069 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
6071 bdf_fonts = XCDR (bdf_fonts);
6074 if (retval)
6075 return retval;
6077 return w32_load_system_font(f, fontname, size);
6081 void
6082 w32_unload_font (dpyinfo, font)
6083 struct w32_display_info *dpyinfo;
6084 XFontStruct * font;
6086 if (font)
6088 if (font->per_char) xfree (font->per_char);
6089 if (font->bdf) w32_free_bdf_font (font->bdf);
6091 if (font->hfont) DeleteObject(font->hfont);
6092 xfree (font);
6096 /* The font conversion stuff between x and w32 */
6098 /* X font string is as follows (from faces.el)
6099 * (let ((- "[-?]")
6100 * (foundry "[^-]+")
6101 * (family "[^-]+")
6102 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
6103 * (weight\? "\\([^-]*\\)") ; 1
6104 * (slant "\\([ior]\\)") ; 2
6105 * (slant\? "\\([^-]?\\)") ; 2
6106 * (swidth "\\([^-]*\\)") ; 3
6107 * (adstyle "[^-]*") ; 4
6108 * (pixelsize "[0-9]+")
6109 * (pointsize "[0-9][0-9]+")
6110 * (resx "[0-9][0-9]+")
6111 * (resy "[0-9][0-9]+")
6112 * (spacing "[cmp?*]")
6113 * (avgwidth "[0-9]+")
6114 * (registry "[^-]+")
6115 * (encoding "[^-]+")
6119 static LONG
6120 x_to_w32_weight (lpw)
6121 char * lpw;
6123 if (!lpw) return (FW_DONTCARE);
6125 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
6126 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
6127 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
6128 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
6129 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
6130 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
6131 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
6132 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
6133 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
6134 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
6135 else
6136 return FW_DONTCARE;
6140 static char *
6141 w32_to_x_weight (fnweight)
6142 int fnweight;
6144 if (fnweight >= FW_HEAVY) return "heavy";
6145 if (fnweight >= FW_EXTRABOLD) return "extrabold";
6146 if (fnweight >= FW_BOLD) return "bold";
6147 if (fnweight >= FW_SEMIBOLD) return "demibold";
6148 if (fnweight >= FW_MEDIUM) return "medium";
6149 if (fnweight >= FW_NORMAL) return "normal";
6150 if (fnweight >= FW_LIGHT) return "light";
6151 if (fnweight >= FW_EXTRALIGHT) return "extralight";
6152 if (fnweight >= FW_THIN) return "thin";
6153 else
6154 return "*";
6157 static LONG
6158 x_to_w32_charset (lpcs)
6159 char * lpcs;
6161 Lisp_Object this_entry, w32_charset;
6162 char *charset;
6163 int len = strlen (lpcs);
6165 /* Support "*-#nnn" format for unknown charsets. */
6166 if (strncmp (lpcs, "*-#", 3) == 0)
6167 return atoi (lpcs + 3);
6169 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
6170 charset = alloca (len + 1);
6171 strcpy (charset, lpcs);
6172 lpcs = strchr (charset, '*');
6173 if (lpcs)
6174 *lpcs = 0;
6176 /* Look through w32-charset-info-alist for the character set.
6177 Format of each entry is
6178 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6180 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6182 if (NILP(this_entry))
6184 /* At startup, we want iso8859-1 fonts to come up properly. */
6185 if (stricmp(charset, "iso8859-1") == 0)
6186 return ANSI_CHARSET;
6187 else
6188 return DEFAULT_CHARSET;
6191 w32_charset = Fcar (Fcdr (this_entry));
6193 /* Translate Lisp symbol to number. */
6194 if (w32_charset == Qw32_charset_ansi)
6195 return ANSI_CHARSET;
6196 if (w32_charset == Qw32_charset_symbol)
6197 return SYMBOL_CHARSET;
6198 if (w32_charset == Qw32_charset_shiftjis)
6199 return SHIFTJIS_CHARSET;
6200 if (w32_charset == Qw32_charset_hangeul)
6201 return HANGEUL_CHARSET;
6202 if (w32_charset == Qw32_charset_chinesebig5)
6203 return CHINESEBIG5_CHARSET;
6204 if (w32_charset == Qw32_charset_gb2312)
6205 return GB2312_CHARSET;
6206 if (w32_charset == Qw32_charset_oem)
6207 return OEM_CHARSET;
6208 #ifdef JOHAB_CHARSET
6209 if (w32_charset == Qw32_charset_johab)
6210 return JOHAB_CHARSET;
6211 if (w32_charset == Qw32_charset_easteurope)
6212 return EASTEUROPE_CHARSET;
6213 if (w32_charset == Qw32_charset_turkish)
6214 return TURKISH_CHARSET;
6215 if (w32_charset == Qw32_charset_baltic)
6216 return BALTIC_CHARSET;
6217 if (w32_charset == Qw32_charset_russian)
6218 return RUSSIAN_CHARSET;
6219 if (w32_charset == Qw32_charset_arabic)
6220 return ARABIC_CHARSET;
6221 if (w32_charset == Qw32_charset_greek)
6222 return GREEK_CHARSET;
6223 if (w32_charset == Qw32_charset_hebrew)
6224 return HEBREW_CHARSET;
6225 if (w32_charset == Qw32_charset_vietnamese)
6226 return VIETNAMESE_CHARSET;
6227 if (w32_charset == Qw32_charset_thai)
6228 return THAI_CHARSET;
6229 if (w32_charset == Qw32_charset_mac)
6230 return MAC_CHARSET;
6231 #endif /* JOHAB_CHARSET */
6232 #ifdef UNICODE_CHARSET
6233 if (w32_charset == Qw32_charset_unicode)
6234 return UNICODE_CHARSET;
6235 #endif
6237 return DEFAULT_CHARSET;
6241 static char *
6242 w32_to_x_charset (fncharset)
6243 int fncharset;
6245 static char buf[32];
6246 Lisp_Object charset_type;
6248 switch (fncharset)
6250 case ANSI_CHARSET:
6251 /* Handle startup case of w32-charset-info-alist not
6252 being set up yet. */
6253 if (NILP(Vw32_charset_info_alist))
6254 return "iso8859-1";
6255 charset_type = Qw32_charset_ansi;
6256 break;
6257 case DEFAULT_CHARSET:
6258 charset_type = Qw32_charset_default;
6259 break;
6260 case SYMBOL_CHARSET:
6261 charset_type = Qw32_charset_symbol;
6262 break;
6263 case SHIFTJIS_CHARSET:
6264 charset_type = Qw32_charset_shiftjis;
6265 break;
6266 case HANGEUL_CHARSET:
6267 charset_type = Qw32_charset_hangeul;
6268 break;
6269 case GB2312_CHARSET:
6270 charset_type = Qw32_charset_gb2312;
6271 break;
6272 case CHINESEBIG5_CHARSET:
6273 charset_type = Qw32_charset_chinesebig5;
6274 break;
6275 case OEM_CHARSET:
6276 charset_type = Qw32_charset_oem;
6277 break;
6279 /* More recent versions of Windows (95 and NT4.0) define more
6280 character sets. */
6281 #ifdef EASTEUROPE_CHARSET
6282 case EASTEUROPE_CHARSET:
6283 charset_type = Qw32_charset_easteurope;
6284 break;
6285 case TURKISH_CHARSET:
6286 charset_type = Qw32_charset_turkish;
6287 break;
6288 case BALTIC_CHARSET:
6289 charset_type = Qw32_charset_baltic;
6290 break;
6291 case RUSSIAN_CHARSET:
6292 charset_type = Qw32_charset_russian;
6293 break;
6294 case ARABIC_CHARSET:
6295 charset_type = Qw32_charset_arabic;
6296 break;
6297 case GREEK_CHARSET:
6298 charset_type = Qw32_charset_greek;
6299 break;
6300 case HEBREW_CHARSET:
6301 charset_type = Qw32_charset_hebrew;
6302 break;
6303 case VIETNAMESE_CHARSET:
6304 charset_type = Qw32_charset_vietnamese;
6305 break;
6306 case THAI_CHARSET:
6307 charset_type = Qw32_charset_thai;
6308 break;
6309 case MAC_CHARSET:
6310 charset_type = Qw32_charset_mac;
6311 break;
6312 case JOHAB_CHARSET:
6313 charset_type = Qw32_charset_johab;
6314 break;
6315 #endif
6317 #ifdef UNICODE_CHARSET
6318 case UNICODE_CHARSET:
6319 charset_type = Qw32_charset_unicode;
6320 break;
6321 #endif
6322 default:
6323 /* Encode numerical value of unknown charset. */
6324 sprintf (buf, "*-#%u", fncharset);
6325 return buf;
6329 Lisp_Object rest;
6330 char * best_match = NULL;
6332 /* Look through w32-charset-info-alist for the character set.
6333 Prefer ISO codepages, and prefer lower numbers in the ISO
6334 range. Only return charsets for codepages which are installed.
6336 Format of each entry is
6337 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6339 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6341 char * x_charset;
6342 Lisp_Object w32_charset;
6343 Lisp_Object codepage;
6345 Lisp_Object this_entry = XCAR (rest);
6347 /* Skip invalid entries in alist. */
6348 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6349 || !CONSP (XCDR (this_entry))
6350 || !SYMBOLP (XCAR (XCDR (this_entry))))
6351 continue;
6353 x_charset = SDATA (XCAR (this_entry));
6354 w32_charset = XCAR (XCDR (this_entry));
6355 codepage = XCDR (XCDR (this_entry));
6357 /* Look for Same charset and a valid codepage (or non-int
6358 which means ignore). */
6359 if (w32_charset == charset_type
6360 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6361 || IsValidCodePage (XINT (codepage))))
6363 /* If we don't have a match already, then this is the
6364 best. */
6365 if (!best_match)
6366 best_match = x_charset;
6367 /* If this is an ISO codepage, and the best so far isn't,
6368 then this is better. */
6369 else if (strnicmp (best_match, "iso", 3) != 0
6370 && strnicmp (x_charset, "iso", 3) == 0)
6371 best_match = x_charset;
6372 /* If both are ISO8859 codepages, choose the one with the
6373 lowest number in the encoding field. */
6374 else if (strnicmp (best_match, "iso8859-", 8) == 0
6375 && strnicmp (x_charset, "iso8859-", 8) == 0)
6377 int best_enc = atoi (best_match + 8);
6378 int this_enc = atoi (x_charset + 8);
6379 if (this_enc > 0 && this_enc < best_enc)
6380 best_match = x_charset;
6385 /* If no match, encode the numeric value. */
6386 if (!best_match)
6388 sprintf (buf, "*-#%u", fncharset);
6389 return buf;
6392 strncpy(buf, best_match, 31);
6393 buf[31] = '\0';
6394 return buf;
6399 /* Return all the X charsets that map to a font. */
6400 static Lisp_Object
6401 w32_to_all_x_charsets (fncharset)
6402 int fncharset;
6404 static char buf[32];
6405 Lisp_Object charset_type;
6406 Lisp_Object retval = Qnil;
6408 switch (fncharset)
6410 case ANSI_CHARSET:
6411 /* Handle startup case of w32-charset-info-alist not
6412 being set up yet. */
6413 if (NILP(Vw32_charset_info_alist))
6414 return Fcons (build_string ("iso8859-1"), Qnil);
6416 charset_type = Qw32_charset_ansi;
6417 break;
6418 case DEFAULT_CHARSET:
6419 charset_type = Qw32_charset_default;
6420 break;
6421 case SYMBOL_CHARSET:
6422 charset_type = Qw32_charset_symbol;
6423 break;
6424 case SHIFTJIS_CHARSET:
6425 charset_type = Qw32_charset_shiftjis;
6426 break;
6427 case HANGEUL_CHARSET:
6428 charset_type = Qw32_charset_hangeul;
6429 break;
6430 case GB2312_CHARSET:
6431 charset_type = Qw32_charset_gb2312;
6432 break;
6433 case CHINESEBIG5_CHARSET:
6434 charset_type = Qw32_charset_chinesebig5;
6435 break;
6436 case OEM_CHARSET:
6437 charset_type = Qw32_charset_oem;
6438 break;
6440 /* More recent versions of Windows (95 and NT4.0) define more
6441 character sets. */
6442 #ifdef EASTEUROPE_CHARSET
6443 case EASTEUROPE_CHARSET:
6444 charset_type = Qw32_charset_easteurope;
6445 break;
6446 case TURKISH_CHARSET:
6447 charset_type = Qw32_charset_turkish;
6448 break;
6449 case BALTIC_CHARSET:
6450 charset_type = Qw32_charset_baltic;
6451 break;
6452 case RUSSIAN_CHARSET:
6453 charset_type = Qw32_charset_russian;
6454 break;
6455 case ARABIC_CHARSET:
6456 charset_type = Qw32_charset_arabic;
6457 break;
6458 case GREEK_CHARSET:
6459 charset_type = Qw32_charset_greek;
6460 break;
6461 case HEBREW_CHARSET:
6462 charset_type = Qw32_charset_hebrew;
6463 break;
6464 case VIETNAMESE_CHARSET:
6465 charset_type = Qw32_charset_vietnamese;
6466 break;
6467 case THAI_CHARSET:
6468 charset_type = Qw32_charset_thai;
6469 break;
6470 case MAC_CHARSET:
6471 charset_type = Qw32_charset_mac;
6472 break;
6473 case JOHAB_CHARSET:
6474 charset_type = Qw32_charset_johab;
6475 break;
6476 #endif
6478 #ifdef UNICODE_CHARSET
6479 case UNICODE_CHARSET:
6480 charset_type = Qw32_charset_unicode;
6481 break;
6482 #endif
6483 default:
6484 /* Encode numerical value of unknown charset. */
6485 sprintf (buf, "*-#%u", fncharset);
6486 return Fcons (build_string (buf), Qnil);
6490 Lisp_Object rest;
6491 /* Look through w32-charset-info-alist for the character set.
6492 Only return charsets for codepages which are installed.
6494 Format of each entry in Vw32_charset_info_alist is
6495 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6497 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6499 Lisp_Object x_charset;
6500 Lisp_Object w32_charset;
6501 Lisp_Object codepage;
6503 Lisp_Object this_entry = XCAR (rest);
6505 /* Skip invalid entries in alist. */
6506 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6507 || !CONSP (XCDR (this_entry))
6508 || !SYMBOLP (XCAR (XCDR (this_entry))))
6509 continue;
6511 x_charset = XCAR (this_entry);
6512 w32_charset = XCAR (XCDR (this_entry));
6513 codepage = XCDR (XCDR (this_entry));
6515 /* Look for Same charset and a valid codepage (or non-int
6516 which means ignore). */
6517 if (w32_charset == charset_type
6518 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6519 || IsValidCodePage (XINT (codepage))))
6521 retval = Fcons (x_charset, retval);
6525 /* If no match, encode the numeric value. */
6526 if (NILP (retval))
6528 sprintf (buf, "*-#%u", fncharset);
6529 return Fcons (build_string (buf), Qnil);
6532 return retval;
6536 /* Get the Windows codepage corresponding to the specified font. The
6537 charset info in the font name is used to look up
6538 w32-charset-to-codepage-alist. */
6540 w32_codepage_for_font (char *fontname)
6542 Lisp_Object codepage, entry;
6543 char *charset_str, *charset, *end;
6545 if (NILP (Vw32_charset_info_alist))
6546 return CP_DEFAULT;
6548 /* Extract charset part of font string. */
6549 charset = xlfd_charset_of_font (fontname);
6551 if (!charset)
6552 return CP_UNKNOWN;
6554 charset_str = (char *) alloca (strlen (charset) + 1);
6555 strcpy (charset_str, charset);
6557 #if 0
6558 /* Remove leading "*-". */
6559 if (strncmp ("*-", charset_str, 2) == 0)
6560 charset = charset_str + 2;
6561 else
6562 #endif
6563 charset = charset_str;
6565 /* Stop match at wildcard (including preceding '-'). */
6566 if (end = strchr (charset, '*'))
6568 if (end > charset && *(end-1) == '-')
6569 end--;
6570 *end = '\0';
6573 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6574 if (NILP (entry))
6575 return CP_UNKNOWN;
6577 codepage = Fcdr (Fcdr (entry));
6579 if (NILP (codepage))
6580 return CP_8BIT;
6581 else if (XFASTINT (codepage) == XFASTINT (Qt))
6582 return CP_UNICODE;
6583 else if (INTEGERP (codepage))
6584 return XINT (codepage);
6585 else
6586 return CP_UNKNOWN;
6590 static BOOL
6591 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6592 LOGFONT * lplogfont;
6593 char * lpxstr;
6594 int len;
6595 char * specific_charset;
6597 char* fonttype;
6598 char *fontname;
6599 char height_pixels[8];
6600 char height_dpi[8];
6601 char width_pixels[8];
6602 char *fontname_dash;
6603 int display_resy = (int) one_w32_display_info.resy;
6604 int display_resx = (int) one_w32_display_info.resx;
6605 int bufsz;
6606 struct coding_system coding;
6608 if (!lpxstr) abort ();
6610 if (!lplogfont)
6611 return FALSE;
6613 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6614 fonttype = "raster";
6615 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6616 fonttype = "outline";
6617 else
6618 fonttype = "unknown";
6620 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
6621 &coding);
6622 coding.src_multibyte = 0;
6623 coding.dst_multibyte = 1;
6624 coding.mode |= CODING_MODE_LAST_BLOCK;
6625 /* We explicitely disable composition handling because selection
6626 data should not contain any composition sequence. */
6627 coding.composing = COMPOSITION_DISABLED;
6628 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6630 fontname = alloca(sizeof(*fontname) * bufsz);
6631 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6632 strlen(lplogfont->lfFaceName), bufsz - 1);
6633 *(fontname + coding.produced) = '\0';
6635 /* Replace dashes with underscores so the dashes are not
6636 misinterpreted. */
6637 fontname_dash = fontname;
6638 while (fontname_dash = strchr (fontname_dash, '-'))
6639 *fontname_dash = '_';
6641 if (lplogfont->lfHeight)
6643 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6644 sprintf (height_dpi, "%u",
6645 abs (lplogfont->lfHeight) * 720 / display_resy);
6647 else
6649 strcpy (height_pixels, "*");
6650 strcpy (height_dpi, "*");
6652 if (lplogfont->lfWidth)
6653 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6654 else
6655 strcpy (width_pixels, "*");
6657 _snprintf (lpxstr, len - 1,
6658 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6659 fonttype, /* foundry */
6660 fontname, /* family */
6661 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6662 lplogfont->lfItalic?'i':'r', /* slant */
6663 /* setwidth name */
6664 /* add style name */
6665 height_pixels, /* pixel size */
6666 height_dpi, /* point size */
6667 display_resx, /* resx */
6668 display_resy, /* resy */
6669 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6670 ? 'p' : 'c', /* spacing */
6671 width_pixels, /* avg width */
6672 specific_charset ? specific_charset
6673 : w32_to_x_charset (lplogfont->lfCharSet)
6674 /* charset registry and encoding */
6677 lpxstr[len - 1] = 0; /* just to be sure */
6678 return (TRUE);
6681 static BOOL
6682 x_to_w32_font (lpxstr, lplogfont)
6683 char * lpxstr;
6684 LOGFONT * lplogfont;
6686 struct coding_system coding;
6688 if (!lplogfont) return (FALSE);
6690 memset (lplogfont, 0, sizeof (*lplogfont));
6692 /* Set default value for each field. */
6693 #if 1
6694 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6695 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6696 lplogfont->lfQuality = DEFAULT_QUALITY;
6697 #else
6698 /* go for maximum quality */
6699 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6700 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6701 lplogfont->lfQuality = PROOF_QUALITY;
6702 #endif
6704 lplogfont->lfCharSet = DEFAULT_CHARSET;
6705 lplogfont->lfWeight = FW_DONTCARE;
6706 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6708 if (!lpxstr)
6709 return FALSE;
6711 /* Provide a simple escape mechanism for specifying Windows font names
6712 * directly -- if font spec does not beginning with '-', assume this
6713 * format:
6714 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6717 if (*lpxstr == '-')
6719 int fields, tem;
6720 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6721 width[10], resy[10], remainder[50];
6722 char * encoding;
6723 int dpi = (int) one_w32_display_info.resy;
6725 fields = sscanf (lpxstr,
6726 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
6727 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6728 if (fields == EOF)
6729 return (FALSE);
6731 /* In the general case when wildcards cover more than one field,
6732 we don't know which field is which, so don't fill any in.
6733 However, we need to cope with this particular form, which is
6734 generated by font_list_1 (invoked by try_font_list):
6735 "-raster-6x10-*-gb2312*-*"
6736 and make sure to correctly parse the charset field. */
6737 if (fields == 3)
6739 fields = sscanf (lpxstr,
6740 "-%*[^-]-%49[^-]-*-%49s",
6741 name, remainder);
6743 else if (fields < 9)
6745 fields = 0;
6746 remainder[0] = 0;
6749 if (fields > 0 && name[0] != '*')
6751 int bufsize;
6752 unsigned char *buf;
6754 setup_coding_system
6755 (Fcheck_coding_system (Vlocale_coding_system), &coding);
6756 coding.src_multibyte = 1;
6757 coding.dst_multibyte = 1;
6758 bufsize = encoding_buffer_size (&coding, strlen (name));
6759 buf = (unsigned char *) alloca (bufsize);
6760 coding.mode |= CODING_MODE_LAST_BLOCK;
6761 encode_coding (&coding, name, buf, strlen (name), bufsize);
6762 if (coding.produced >= LF_FACESIZE)
6763 coding.produced = LF_FACESIZE - 1;
6764 buf[coding.produced] = 0;
6765 strcpy (lplogfont->lfFaceName, buf);
6767 else
6769 lplogfont->lfFaceName[0] = '\0';
6772 fields--;
6774 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6776 fields--;
6778 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6780 fields--;
6782 if (fields > 0 && pixels[0] != '*')
6783 lplogfont->lfHeight = atoi (pixels);
6785 fields--;
6786 fields--;
6787 if (fields > 0 && resy[0] != '*')
6789 tem = atoi (resy);
6790 if (tem > 0) dpi = tem;
6793 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6794 lplogfont->lfHeight = atoi (height) * dpi / 720;
6796 if (fields > 0)
6797 lplogfont->lfPitchAndFamily =
6798 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6800 fields--;
6802 if (fields > 0 && width[0] != '*')
6803 lplogfont->lfWidth = atoi (width) / 10;
6805 fields--;
6807 /* Strip the trailing '-' if present. (it shouldn't be, as it
6808 fails the test against xlfd-tight-regexp in fontset.el). */
6810 int len = strlen (remainder);
6811 if (len > 0 && remainder[len-1] == '-')
6812 remainder[len-1] = 0;
6814 encoding = remainder;
6815 #if 0
6816 if (strncmp (encoding, "*-", 2) == 0)
6817 encoding += 2;
6818 #endif
6819 lplogfont->lfCharSet = x_to_w32_charset (encoding);
6821 else
6823 int fields;
6824 char name[100], height[10], width[10], weight[20];
6826 fields = sscanf (lpxstr,
6827 "%99[^:]:%9[^:]:%9[^:]:%19s",
6828 name, height, width, weight);
6830 if (fields == EOF) return (FALSE);
6832 if (fields > 0)
6834 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6835 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6837 else
6839 lplogfont->lfFaceName[0] = 0;
6842 fields--;
6844 if (fields > 0)
6845 lplogfont->lfHeight = atoi (height);
6847 fields--;
6849 if (fields > 0)
6850 lplogfont->lfWidth = atoi (width);
6852 fields--;
6854 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6857 /* This makes TrueType fonts work better. */
6858 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6860 return (TRUE);
6863 /* Strip the pixel height and point height from the given xlfd, and
6864 return the pixel height. If no pixel height is specified, calculate
6865 one from the point height, or if that isn't defined either, return
6866 0 (which usually signifies a scalable font).
6868 static int
6869 xlfd_strip_height (char *fontname)
6871 int pixel_height, field_number;
6872 char *read_from, *write_to;
6874 xassert (fontname);
6876 pixel_height = field_number = 0;
6877 write_to = NULL;
6879 /* Look for height fields. */
6880 for (read_from = fontname; *read_from; read_from++)
6882 if (*read_from == '-')
6884 field_number++;
6885 if (field_number == 7) /* Pixel height. */
6887 read_from++;
6888 write_to = read_from;
6890 /* Find end of field. */
6891 for (;*read_from && *read_from != '-'; read_from++)
6894 /* Split the fontname at end of field. */
6895 if (*read_from)
6897 *read_from = '\0';
6898 read_from++;
6900 pixel_height = atoi (write_to);
6901 /* Blank out field. */
6902 if (read_from > write_to)
6904 *write_to = '-';
6905 write_to++;
6907 /* If the pixel height field is at the end (partial xlfd),
6908 return now. */
6909 else
6910 return pixel_height;
6912 /* If we got a pixel height, the point height can be
6913 ignored. Just blank it out and break now. */
6914 if (pixel_height)
6916 /* Find end of point size field. */
6917 for (; *read_from && *read_from != '-'; read_from++)
6920 if (*read_from)
6921 read_from++;
6923 /* Blank out the point size field. */
6924 if (read_from > write_to)
6926 *write_to = '-';
6927 write_to++;
6929 else
6930 return pixel_height;
6932 break;
6934 /* If the point height is already blank, break now. */
6935 if (*read_from == '-')
6937 read_from++;
6938 break;
6941 else if (field_number == 8)
6943 /* If we didn't get a pixel height, try to get the point
6944 height and convert that. */
6945 int point_size;
6946 char *point_size_start = read_from++;
6948 /* Find end of field. */
6949 for (; *read_from && *read_from != '-'; read_from++)
6952 if (*read_from)
6954 *read_from = '\0';
6955 read_from++;
6958 point_size = atoi (point_size_start);
6960 /* Convert to pixel height. */
6961 pixel_height = point_size
6962 * one_w32_display_info.height_in / 720;
6964 /* Blank out this field and break. */
6965 *write_to = '-';
6966 write_to++;
6967 break;
6972 /* Shift the rest of the font spec into place. */
6973 if (write_to && read_from > write_to)
6975 for (; *read_from; read_from++, write_to++)
6976 *write_to = *read_from;
6977 *write_to = '\0';
6980 return pixel_height;
6983 /* Assume parameter 1 is fully qualified, no wildcards. */
6984 static BOOL
6985 w32_font_match (fontname, pattern)
6986 char * fontname;
6987 char * pattern;
6989 char *regex = alloca (strlen (pattern) * 2 + 3);
6990 char *font_name_copy = alloca (strlen (fontname) + 1);
6991 char *ptr;
6993 /* Copy fontname so we can modify it during comparison. */
6994 strcpy (font_name_copy, fontname);
6996 ptr = regex;
6997 *ptr++ = '^';
6999 /* Turn pattern into a regexp and do a regexp match. */
7000 for (; *pattern; pattern++)
7002 if (*pattern == '?')
7003 *ptr++ = '.';
7004 else if (*pattern == '*')
7006 *ptr++ = '.';
7007 *ptr++ = '*';
7009 else
7010 *ptr++ = *pattern;
7012 *ptr = '$';
7013 *(ptr + 1) = '\0';
7015 /* Strip out font heights and compare them seperately, since
7016 rounding error can cause mismatches. This also allows a
7017 comparison between a font that declares only a pixel height and a
7018 pattern that declares the point height.
7021 int font_height, pattern_height;
7023 font_height = xlfd_strip_height (font_name_copy);
7024 pattern_height = xlfd_strip_height (regex);
7026 /* Compare now, and don't bother doing expensive regexp matching
7027 if the heights differ. */
7028 if (font_height && pattern_height && (font_height != pattern_height))
7029 return FALSE;
7032 return (fast_c_string_match_ignore_case (build_string (regex),
7033 font_name_copy) >= 0);
7036 /* Callback functions, and a structure holding info they need, for
7037 listing system fonts on W32. We need one set of functions to do the
7038 job properly, but these don't work on NT 3.51 and earlier, so we
7039 have a second set which don't handle character sets properly to
7040 fall back on.
7042 In both cases, there are two passes made. The first pass gets one
7043 font from each family, the second pass lists all the fonts from
7044 each family. */
7046 typedef struct enumfont_t
7048 HDC hdc;
7049 int numFonts;
7050 LOGFONT logfont;
7051 XFontStruct *size_ref;
7052 Lisp_Object pattern;
7053 Lisp_Object list;
7054 } enumfont_t;
7057 static void
7058 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
7061 static int CALLBACK
7062 enum_font_cb2 (lplf, lptm, FontType, lpef)
7063 ENUMLOGFONT * lplf;
7064 NEWTEXTMETRIC * lptm;
7065 int FontType;
7066 enumfont_t * lpef;
7068 /* Ignore struck out and underlined versions of fonts. */
7069 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
7070 return 1;
7072 /* Only return fonts with names starting with @ if they were
7073 explicitly specified, since Microsoft uses an initial @ to
7074 denote fonts for vertical writing, without providing a more
7075 convenient way of identifying them. */
7076 if (lplf->elfLogFont.lfFaceName[0] == '@'
7077 && lpef->logfont.lfFaceName[0] != '@')
7078 return 1;
7080 /* Check that the character set matches if it was specified */
7081 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
7082 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
7083 return 1;
7085 if (FontType == RASTER_FONTTYPE)
7087 /* DBCS raster fonts have problems displaying, so skip them. */
7088 int charset = lplf->elfLogFont.lfCharSet;
7089 if (charset == SHIFTJIS_CHARSET
7090 || charset == HANGEUL_CHARSET
7091 || charset == CHINESEBIG5_CHARSET
7092 || charset == GB2312_CHARSET
7093 #ifdef JOHAB_CHARSET
7094 || charset == JOHAB_CHARSET
7095 #endif
7097 return 1;
7101 char buf[100];
7102 Lisp_Object width = Qnil;
7103 Lisp_Object charset_list = Qnil;
7104 char *charset = NULL;
7106 /* Truetype fonts do not report their true metrics until loaded */
7107 if (FontType != RASTER_FONTTYPE)
7109 if (!NILP (lpef->pattern))
7111 /* Scalable fonts are as big as you want them to be. */
7112 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
7113 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
7114 width = make_number (lpef->logfont.lfWidth);
7116 else
7118 lplf->elfLogFont.lfHeight = 0;
7119 lplf->elfLogFont.lfWidth = 0;
7123 /* Make sure the height used here is the same as everywhere
7124 else (ie character height, not cell height). */
7125 if (lplf->elfLogFont.lfHeight > 0)
7127 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
7128 if (FontType == RASTER_FONTTYPE)
7129 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
7130 else
7131 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
7134 if (!NILP (lpef->pattern))
7136 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
7138 /* We already checked charsets above, but DEFAULT_CHARSET
7139 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
7140 if (charset
7141 && strncmp (charset, "*-*", 3) != 0
7142 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
7143 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
7144 return 1;
7147 if (charset)
7148 charset_list = Fcons (build_string (charset), Qnil);
7149 else
7150 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
7152 /* Loop through the charsets. */
7153 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
7155 Lisp_Object this_charset = Fcar (charset_list);
7156 charset = SDATA (this_charset);
7158 /* List bold and italic variations if w32-enable-synthesized-fonts
7159 is non-nil and this is a plain font. */
7160 if (w32_enable_synthesized_fonts
7161 && lplf->elfLogFont.lfWeight == FW_NORMAL
7162 && lplf->elfLogFont.lfItalic == FALSE)
7164 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7165 charset, width);
7166 /* bold. */
7167 lplf->elfLogFont.lfWeight = FW_BOLD;
7168 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7169 charset, width);
7170 /* bold italic. */
7171 lplf->elfLogFont.lfItalic = TRUE;
7172 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7173 charset, width);
7174 /* italic. */
7175 lplf->elfLogFont.lfWeight = FW_NORMAL;
7176 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7177 charset, width);
7179 else
7180 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7181 charset, width);
7185 return 1;
7188 static void
7189 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
7190 enumfont_t * lpef;
7191 LOGFONT * logfont;
7192 char * match_charset;
7193 Lisp_Object width;
7195 char buf[100];
7197 if (!w32_to_x_font (logfont, buf, 100, match_charset))
7198 return;
7200 if (NILP (lpef->pattern)
7201 || w32_font_match (buf, SDATA (lpef->pattern)))
7203 /* Check if we already listed this font. This may happen if
7204 w32_enable_synthesized_fonts is non-nil, and there are real
7205 bold and italic versions of the font. */
7206 Lisp_Object font_name = build_string (buf);
7207 if (NILP (Fmember (font_name, lpef->list)))
7209 Lisp_Object entry = Fcons (font_name, width);
7210 lpef->list = Fcons (entry, lpef->list);
7211 lpef->numFonts++;
7217 static int CALLBACK
7218 enum_font_cb1 (lplf, lptm, FontType, lpef)
7219 ENUMLOGFONT * lplf;
7220 NEWTEXTMETRIC * lptm;
7221 int FontType;
7222 enumfont_t * lpef;
7224 return EnumFontFamilies (lpef->hdc,
7225 lplf->elfLogFont.lfFaceName,
7226 (FONTENUMPROC) enum_font_cb2,
7227 (LPARAM) lpef);
7231 static int CALLBACK
7232 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
7233 ENUMLOGFONTEX * lplf;
7234 NEWTEXTMETRICEX * lptm;
7235 int font_type;
7236 enumfont_t * lpef;
7238 /* We are not interested in the extra info we get back from the 'Ex
7239 version - only the fact that we get character set variations
7240 enumerated seperately. */
7241 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
7242 font_type, lpef);
7245 static int CALLBACK
7246 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
7247 ENUMLOGFONTEX * lplf;
7248 NEWTEXTMETRICEX * lptm;
7249 int font_type;
7250 enumfont_t * lpef;
7252 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7253 FARPROC enum_font_families_ex
7254 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7255 /* We don't really expect EnumFontFamiliesEx to disappear once we
7256 get here, so don't bother handling it gracefully. */
7257 if (enum_font_families_ex == NULL)
7258 error ("gdi32.dll has disappeared!");
7259 return enum_font_families_ex (lpef->hdc,
7260 &lplf->elfLogFont,
7261 (FONTENUMPROC) enum_fontex_cb2,
7262 (LPARAM) lpef, 0);
7265 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
7266 and xterm.c in Emacs 20.3) */
7268 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
7270 char *fontname, *ptnstr;
7271 Lisp_Object list, tem, newlist = Qnil;
7272 int n_fonts = 0;
7274 list = Vw32_bdf_filename_alist;
7275 ptnstr = SDATA (pattern);
7277 for ( ; CONSP (list); list = XCDR (list))
7279 tem = XCAR (list);
7280 if (CONSP (tem))
7281 fontname = SDATA (XCAR (tem));
7282 else if (STRINGP (tem))
7283 fontname = SDATA (tem);
7284 else
7285 continue;
7287 if (w32_font_match (fontname, ptnstr))
7289 newlist = Fcons (XCAR (tem), newlist);
7290 n_fonts++;
7291 if (n_fonts >= max_names)
7292 break;
7296 return newlist;
7300 /* Return a list of names of available fonts matching PATTERN on frame
7301 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
7302 to be listed. Frame F NULL means we have not yet created any
7303 frame, which means we can't get proper size info, as we don't have
7304 a device context to use for GetTextMetrics.
7305 MAXNAMES sets a limit on how many fonts to match. */
7307 Lisp_Object
7308 w32_list_fonts (f, pattern, size, maxnames)
7309 struct frame *f;
7310 Lisp_Object pattern;
7311 int size;
7312 int maxnames;
7314 Lisp_Object patterns, key = Qnil, tem, tpat;
7315 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
7316 struct w32_display_info *dpyinfo = &one_w32_display_info;
7317 int n_fonts = 0;
7319 patterns = Fassoc (pattern, Valternate_fontname_alist);
7320 if (NILP (patterns))
7321 patterns = Fcons (pattern, Qnil);
7323 for (; CONSP (patterns); patterns = XCDR (patterns))
7325 enumfont_t ef;
7326 int codepage;
7328 tpat = XCAR (patterns);
7330 if (!STRINGP (tpat))
7331 continue;
7333 /* Avoid expensive EnumFontFamilies functions if we are not
7334 going to be able to output one of these anyway. */
7335 codepage = w32_codepage_for_font (SDATA (tpat));
7336 if (codepage != CP_8BIT && codepage != CP_UNICODE
7337 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
7338 && !IsValidCodePage(codepage))
7339 continue;
7341 /* See if we cached the result for this particular query.
7342 The cache is an alist of the form:
7343 ((PATTERN (FONTNAME . WIDTH) ...) ...)
7345 if (tem = XCDR (dpyinfo->name_list_element),
7346 !NILP (list = Fassoc (tpat, tem)))
7348 list = Fcdr_safe (list);
7349 /* We have a cached list. Don't have to get the list again. */
7350 goto label_cached;
7353 BLOCK_INPUT;
7354 /* At first, put PATTERN in the cache. */
7355 ef.pattern = tpat;
7356 ef.list = Qnil;
7357 ef.numFonts = 0;
7359 /* Use EnumFontFamiliesEx where it is available, as it knows
7360 about character sets. Fall back to EnumFontFamilies for
7361 older versions of NT that don't support the 'Ex function. */
7362 x_to_w32_font (SDATA (tpat), &ef.logfont);
7364 LOGFONT font_match_pattern;
7365 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7366 FARPROC enum_font_families_ex
7367 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7369 /* We do our own pattern matching so we can handle wildcards. */
7370 font_match_pattern.lfFaceName[0] = 0;
7371 font_match_pattern.lfPitchAndFamily = 0;
7372 /* We can use the charset, because if it is a wildcard it will
7373 be DEFAULT_CHARSET anyway. */
7374 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
7376 ef.hdc = GetDC (dpyinfo->root_window);
7378 if (enum_font_families_ex)
7379 enum_font_families_ex (ef.hdc,
7380 &font_match_pattern,
7381 (FONTENUMPROC) enum_fontex_cb1,
7382 (LPARAM) &ef, 0);
7383 else
7384 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
7385 (LPARAM)&ef);
7387 ReleaseDC (dpyinfo->root_window, ef.hdc);
7390 UNBLOCK_INPUT;
7391 list = ef.list;
7393 /* Make a list of the fonts we got back.
7394 Store that in the font cache for the display. */
7395 XSETCDR (dpyinfo->name_list_element,
7396 Fcons (Fcons (tpat, list),
7397 XCDR (dpyinfo->name_list_element)));
7399 label_cached:
7400 if (NILP (list)) continue; /* Try the remaining alternatives. */
7402 newlist = second_best = Qnil;
7404 /* Make a list of the fonts that have the right width. */
7405 for (; CONSP (list); list = XCDR (list))
7407 int found_size;
7408 tem = XCAR (list);
7410 if (!CONSP (tem))
7411 continue;
7412 if (NILP (XCAR (tem)))
7413 continue;
7414 if (!size)
7416 newlist = Fcons (XCAR (tem), newlist);
7417 n_fonts++;
7418 if (n_fonts >= maxnames)
7419 break;
7420 else
7421 continue;
7423 if (!INTEGERP (XCDR (tem)))
7425 /* Since we don't yet know the size of the font, we must
7426 load it and try GetTextMetrics. */
7427 W32FontStruct thisinfo;
7428 LOGFONT lf;
7429 HDC hdc;
7430 HANDLE oldobj;
7432 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
7433 continue;
7435 BLOCK_INPUT;
7436 thisinfo.bdf = NULL;
7437 thisinfo.hfont = CreateFontIndirect (&lf);
7438 if (thisinfo.hfont == NULL)
7439 continue;
7441 hdc = GetDC (dpyinfo->root_window);
7442 oldobj = SelectObject (hdc, thisinfo.hfont);
7443 if (GetTextMetrics (hdc, &thisinfo.tm))
7444 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
7445 else
7446 XSETCDR (tem, make_number (0));
7447 SelectObject (hdc, oldobj);
7448 ReleaseDC (dpyinfo->root_window, hdc);
7449 DeleteObject(thisinfo.hfont);
7450 UNBLOCK_INPUT;
7452 found_size = XINT (XCDR (tem));
7453 if (found_size == size)
7455 newlist = Fcons (XCAR (tem), newlist);
7456 n_fonts++;
7457 if (n_fonts >= maxnames)
7458 break;
7460 /* keep track of the closest matching size in case
7461 no exact match is found. */
7462 else if (found_size > 0)
7464 if (NILP (second_best))
7465 second_best = tem;
7467 else if (found_size < size)
7469 if (XINT (XCDR (second_best)) > size
7470 || XINT (XCDR (second_best)) < found_size)
7471 second_best = tem;
7473 else
7475 if (XINT (XCDR (second_best)) > size
7476 && XINT (XCDR (second_best)) >
7477 found_size)
7478 second_best = tem;
7483 if (!NILP (newlist))
7484 break;
7485 else if (!NILP (second_best))
7487 newlist = Fcons (XCAR (second_best), Qnil);
7488 break;
7492 /* Include any bdf fonts. */
7493 if (n_fonts < maxnames)
7495 Lisp_Object combined[2];
7496 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
7497 combined[1] = newlist;
7498 newlist = Fnconc(2, combined);
7501 return newlist;
7505 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
7506 struct font_info *
7507 w32_get_font_info (f, font_idx)
7508 FRAME_PTR f;
7509 int font_idx;
7511 return (FRAME_W32_FONT_TABLE (f) + font_idx);
7515 struct font_info*
7516 w32_query_font (struct frame *f, char *fontname)
7518 int i;
7519 struct font_info *pfi;
7521 pfi = FRAME_W32_FONT_TABLE (f);
7523 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
7525 if (strcmp(pfi->name, fontname) == 0) return pfi;
7528 return NULL;
7531 /* Find a CCL program for a font specified by FONTP, and set the member
7532 `encoder' of the structure. */
7534 void
7535 w32_find_ccl_program (fontp)
7536 struct font_info *fontp;
7538 Lisp_Object list, elt;
7540 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7542 elt = XCAR (list);
7543 if (CONSP (elt)
7544 && STRINGP (XCAR (elt))
7545 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7546 >= 0))
7547 break;
7549 if (! NILP (list))
7551 struct ccl_program *ccl
7552 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7554 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7555 xfree (ccl);
7556 else
7557 fontp->font_encoder = ccl;
7562 /* Find BDF files in a specified directory. (use GCPRO when calling,
7563 as this calls lisp to get a directory listing). */
7564 static Lisp_Object
7565 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
7567 Lisp_Object filelist, list = Qnil;
7568 char fontname[100];
7570 if (!STRINGP(directory))
7571 return Qnil;
7573 filelist = Fdirectory_files (directory, Qt,
7574 build_string (".*\\.[bB][dD][fF]"), Qt);
7576 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7578 Lisp_Object filename = XCAR (filelist);
7579 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
7580 store_in_alist (&list, build_string (fontname), filename);
7582 return list;
7585 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
7586 1, 1, 0,
7587 doc: /* Return a list of BDF fonts in DIR.
7588 The list is suitable for appending to w32-bdf-filename-alist. Fonts
7589 which do not contain an xlfd description will not be included in the
7590 list. DIR may be a list of directories. */)
7591 (directory)
7592 Lisp_Object directory;
7594 Lisp_Object list = Qnil;
7595 struct gcpro gcpro1, gcpro2;
7597 if (!CONSP (directory))
7598 return w32_find_bdf_fonts_in_dir (directory);
7600 for ( ; CONSP (directory); directory = XCDR (directory))
7602 Lisp_Object pair[2];
7603 pair[0] = list;
7604 pair[1] = Qnil;
7605 GCPRO2 (directory, list);
7606 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7607 list = Fnconc( 2, pair );
7608 UNGCPRO;
7610 return list;
7614 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7615 doc: /* Internal function called by `color-defined-p', which see. */)
7616 (color, frame)
7617 Lisp_Object color, frame;
7619 XColor foo;
7620 FRAME_PTR f = check_x_frame (frame);
7622 CHECK_STRING (color);
7624 if (w32_defined_color (f, SDATA (color), &foo, 0))
7625 return Qt;
7626 else
7627 return Qnil;
7630 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7631 doc: /* Internal function called by `color-values', which see. */)
7632 (color, frame)
7633 Lisp_Object color, frame;
7635 XColor foo;
7636 FRAME_PTR f = check_x_frame (frame);
7638 CHECK_STRING (color);
7640 if (w32_defined_color (f, SDATA (color), &foo, 0))
7642 Lisp_Object rgb[3];
7644 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7645 | GetRValue (foo.pixel));
7646 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7647 | GetGValue (foo.pixel));
7648 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7649 | GetBValue (foo.pixel));
7650 return Flist (3, rgb);
7652 else
7653 return Qnil;
7656 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7657 doc: /* Internal function called by `display-color-p', which see. */)
7658 (display)
7659 Lisp_Object display;
7661 struct w32_display_info *dpyinfo = check_x_display_info (display);
7663 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7664 return Qnil;
7666 return Qt;
7669 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
7670 Sx_display_grayscale_p, 0, 1, 0,
7671 doc: /* Return t if the X display supports shades of gray.
7672 Note that color displays do support shades of gray.
7673 The optional argument DISPLAY specifies which display to ask about.
7674 DISPLAY should be either a frame or a display name (a string).
7675 If omitted or nil, that stands for the selected frame's display. */)
7676 (display)
7677 Lisp_Object display;
7679 struct w32_display_info *dpyinfo = check_x_display_info (display);
7681 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7682 return Qnil;
7684 return Qt;
7687 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
7688 Sx_display_pixel_width, 0, 1, 0,
7689 doc: /* Returns the width in pixels of DISPLAY.
7690 The optional argument DISPLAY specifies which display to ask about.
7691 DISPLAY should be either a frame or a display name (a string).
7692 If omitted or nil, that stands for the selected frame's display. */)
7693 (display)
7694 Lisp_Object display;
7696 struct w32_display_info *dpyinfo = check_x_display_info (display);
7698 return make_number (dpyinfo->width);
7701 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7702 Sx_display_pixel_height, 0, 1, 0,
7703 doc: /* Returns the height in pixels of DISPLAY.
7704 The optional argument DISPLAY specifies which display to ask about.
7705 DISPLAY should be either a frame or a display name (a string).
7706 If omitted or nil, that stands for the selected frame's display. */)
7707 (display)
7708 Lisp_Object display;
7710 struct w32_display_info *dpyinfo = check_x_display_info (display);
7712 return make_number (dpyinfo->height);
7715 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7716 0, 1, 0,
7717 doc: /* Returns the number of bitplanes of DISPLAY.
7718 The optional argument DISPLAY specifies which display to ask about.
7719 DISPLAY should be either a frame or a display name (a string).
7720 If omitted or nil, that stands for the selected frame's display. */)
7721 (display)
7722 Lisp_Object display;
7724 struct w32_display_info *dpyinfo = check_x_display_info (display);
7726 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7729 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7730 0, 1, 0,
7731 doc: /* Returns the number of color cells of DISPLAY.
7732 The optional argument DISPLAY specifies which display to ask about.
7733 DISPLAY should be either a frame or a display name (a string).
7734 If omitted or nil, that stands for the selected frame's display. */)
7735 (display)
7736 Lisp_Object display;
7738 struct w32_display_info *dpyinfo = check_x_display_info (display);
7739 HDC hdc;
7740 int cap;
7742 hdc = GetDC (dpyinfo->root_window);
7743 if (dpyinfo->has_palette)
7744 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7745 else
7746 cap = GetDeviceCaps (hdc,NUMCOLORS);
7748 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
7749 and because probably is more meaningful on Windows anyway */
7750 if (cap < 0)
7751 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
7753 ReleaseDC (dpyinfo->root_window, hdc);
7755 return make_number (cap);
7758 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7759 Sx_server_max_request_size,
7760 0, 1, 0,
7761 doc: /* Returns the maximum request size of the server of DISPLAY.
7762 The optional argument DISPLAY specifies which display to ask about.
7763 DISPLAY should be either a frame or a display name (a string).
7764 If omitted or nil, that stands for the selected frame's display. */)
7765 (display)
7766 Lisp_Object display;
7768 struct w32_display_info *dpyinfo = check_x_display_info (display);
7770 return make_number (1);
7773 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7774 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
7775 The optional argument DISPLAY specifies which display to ask about.
7776 DISPLAY should be either a frame or a display name (a string).
7777 If omitted or nil, that stands for the selected frame's display. */)
7778 (display)
7779 Lisp_Object display;
7781 return build_string ("Microsoft Corp.");
7784 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7785 doc: /* Returns the version numbers of the server of DISPLAY.
7786 The value is a list of three integers: the major and minor
7787 version numbers, and the vendor-specific release
7788 number. See also the function `x-server-vendor'.
7790 The optional argument DISPLAY specifies which display to ask about.
7791 DISPLAY should be either a frame or a display name (a string).
7792 If omitted or nil, that stands for the selected frame's display. */)
7793 (display)
7794 Lisp_Object display;
7796 return Fcons (make_number (w32_major_version),
7797 Fcons (make_number (w32_minor_version),
7798 Fcons (make_number (w32_build_number), Qnil)));
7801 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7802 doc: /* Returns the number of screens on the server of DISPLAY.
7803 The optional argument DISPLAY specifies which display to ask about.
7804 DISPLAY should be either a frame or a display name (a string).
7805 If omitted or nil, that stands for the selected frame's display. */)
7806 (display)
7807 Lisp_Object display;
7809 return make_number (1);
7812 DEFUN ("x-display-mm-height", Fx_display_mm_height,
7813 Sx_display_mm_height, 0, 1, 0,
7814 doc: /* Returns the height in millimeters of DISPLAY.
7815 The optional argument DISPLAY specifies which display to ask about.
7816 DISPLAY should be either a frame or a display name (a string).
7817 If omitted or nil, that stands for the selected frame's display. */)
7818 (display)
7819 Lisp_Object display;
7821 struct w32_display_info *dpyinfo = check_x_display_info (display);
7822 HDC hdc;
7823 int cap;
7825 hdc = GetDC (dpyinfo->root_window);
7827 cap = GetDeviceCaps (hdc, VERTSIZE);
7829 ReleaseDC (dpyinfo->root_window, hdc);
7831 return make_number (cap);
7834 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7835 doc: /* Returns the width in millimeters of DISPLAY.
7836 The optional argument DISPLAY specifies which display to ask about.
7837 DISPLAY should be either a frame or a display name (a string).
7838 If omitted or nil, that stands for the selected frame's display. */)
7839 (display)
7840 Lisp_Object display;
7842 struct w32_display_info *dpyinfo = check_x_display_info (display);
7844 HDC hdc;
7845 int cap;
7847 hdc = GetDC (dpyinfo->root_window);
7849 cap = GetDeviceCaps (hdc, HORZSIZE);
7851 ReleaseDC (dpyinfo->root_window, hdc);
7853 return make_number (cap);
7856 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7857 Sx_display_backing_store, 0, 1, 0,
7858 doc: /* Returns an indication of whether DISPLAY does backing store.
7859 The value may be `always', `when-mapped', or `not-useful'.
7860 The optional argument DISPLAY specifies which display to ask about.
7861 DISPLAY should be either a frame or a display name (a string).
7862 If omitted or nil, that stands for the selected frame's display. */)
7863 (display)
7864 Lisp_Object display;
7866 return intern ("not-useful");
7869 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7870 Sx_display_visual_class, 0, 1, 0,
7871 doc: /* Returns the visual class of DISPLAY.
7872 The value is one of the symbols `static-gray', `gray-scale',
7873 `static-color', `pseudo-color', `true-color', or `direct-color'.
7875 The optional argument DISPLAY specifies which display to ask about.
7876 DISPLAY should be either a frame or a display name (a string).
7877 If omitted or nil, that stands for the selected frame's display. */)
7878 (display)
7879 Lisp_Object display;
7881 struct w32_display_info *dpyinfo = check_x_display_info (display);
7882 Lisp_Object result = Qnil;
7884 if (dpyinfo->has_palette)
7885 result = intern ("pseudo-color");
7886 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
7887 result = intern ("static-grey");
7888 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
7889 result = intern ("static-color");
7890 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
7891 result = intern ("true-color");
7893 return result;
7896 DEFUN ("x-display-save-under", Fx_display_save_under,
7897 Sx_display_save_under, 0, 1, 0,
7898 doc: /* Returns t if DISPLAY supports the save-under feature.
7899 The optional argument DISPLAY specifies which display to ask about.
7900 DISPLAY should be either a frame or a display name (a string).
7901 If omitted or nil, that stands for the selected frame's display. */)
7902 (display)
7903 Lisp_Object display;
7905 return Qnil;
7909 x_pixel_width (f)
7910 register struct frame *f;
7912 return PIXEL_WIDTH (f);
7916 x_pixel_height (f)
7917 register struct frame *f;
7919 return PIXEL_HEIGHT (f);
7923 x_char_width (f)
7924 register struct frame *f;
7926 return FONT_WIDTH (f->output_data.w32->font);
7930 x_char_height (f)
7931 register struct frame *f;
7933 return f->output_data.w32->line_height;
7937 x_screen_planes (f)
7938 register struct frame *f;
7940 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7943 /* Return the display structure for the display named NAME.
7944 Open a new connection if necessary. */
7946 struct w32_display_info *
7947 x_display_info_for_name (name)
7948 Lisp_Object name;
7950 Lisp_Object names;
7951 struct w32_display_info *dpyinfo;
7953 CHECK_STRING (name);
7955 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7956 dpyinfo;
7957 dpyinfo = dpyinfo->next, names = XCDR (names))
7959 Lisp_Object tem;
7960 tem = Fstring_equal (XCAR (XCAR (names)), name);
7961 if (!NILP (tem))
7962 return dpyinfo;
7965 /* Use this general default value to start with. */
7966 Vx_resource_name = Vinvocation_name;
7968 validate_x_resource_name ();
7970 dpyinfo = w32_term_init (name, (unsigned char *)0,
7971 (char *) SDATA (Vx_resource_name));
7973 if (dpyinfo == 0)
7974 error ("Cannot connect to server %s", SDATA (name));
7976 w32_in_use = 1;
7977 XSETFASTINT (Vwindow_system_version, 3);
7979 return dpyinfo;
7982 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7983 1, 3, 0, doc: /* Open a connection to a server.
7984 DISPLAY is the name of the display to connect to.
7985 Optional second arg XRM-STRING is a string of resources in xrdb format.
7986 If the optional third arg MUST-SUCCEED is non-nil,
7987 terminate Emacs if we can't open the connection. */)
7988 (display, xrm_string, must_succeed)
7989 Lisp_Object display, xrm_string, must_succeed;
7991 unsigned char *xrm_option;
7992 struct w32_display_info *dpyinfo;
7994 /* If initialization has already been done, return now to avoid
7995 overwriting critical parts of one_w32_display_info. */
7996 if (w32_in_use)
7997 return Qnil;
7999 CHECK_STRING (display);
8000 if (! NILP (xrm_string))
8001 CHECK_STRING (xrm_string);
8003 if (! EQ (Vwindow_system, intern ("w32")))
8004 error ("Not using Microsoft Windows");
8006 /* Allow color mapping to be defined externally; first look in user's
8007 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
8009 Lisp_Object color_file;
8010 struct gcpro gcpro1;
8012 color_file = build_string("~/rgb.txt");
8014 GCPRO1 (color_file);
8016 if (NILP (Ffile_readable_p (color_file)))
8017 color_file =
8018 Fexpand_file_name (build_string ("rgb.txt"),
8019 Fsymbol_value (intern ("data-directory")));
8021 Vw32_color_map = Fw32_load_color_file (color_file);
8023 UNGCPRO;
8025 if (NILP (Vw32_color_map))
8026 Vw32_color_map = Fw32_default_color_map ();
8028 if (! NILP (xrm_string))
8029 xrm_option = (unsigned char *) SDATA (xrm_string);
8030 else
8031 xrm_option = (unsigned char *) 0;
8033 /* Use this general default value to start with. */
8034 /* First remove .exe suffix from invocation-name - it looks ugly. */
8036 char basename[ MAX_PATH ], *str;
8038 strcpy (basename, SDATA (Vinvocation_name));
8039 str = strrchr (basename, '.');
8040 if (str) *str = 0;
8041 Vinvocation_name = build_string (basename);
8043 Vx_resource_name = Vinvocation_name;
8045 validate_x_resource_name ();
8047 /* This is what opens the connection and sets x_current_display.
8048 This also initializes many symbols, such as those used for input. */
8049 dpyinfo = w32_term_init (display, xrm_option,
8050 (char *) SDATA (Vx_resource_name));
8052 if (dpyinfo == 0)
8054 if (!NILP (must_succeed))
8055 fatal ("Cannot connect to server %s.\n",
8056 SDATA (display));
8057 else
8058 error ("Cannot connect to server %s", SDATA (display));
8061 w32_in_use = 1;
8063 XSETFASTINT (Vwindow_system_version, 3);
8064 return Qnil;
8067 DEFUN ("x-close-connection", Fx_close_connection,
8068 Sx_close_connection, 1, 1, 0,
8069 doc: /* Close the connection to DISPLAY's server.
8070 For DISPLAY, specify either a frame or a display name (a string).
8071 If DISPLAY is nil, that stands for the selected frame's display. */)
8072 (display)
8073 Lisp_Object display;
8075 struct w32_display_info *dpyinfo = check_x_display_info (display);
8076 int i;
8078 if (dpyinfo->reference_count > 0)
8079 error ("Display still has frames on it");
8081 BLOCK_INPUT;
8082 /* Free the fonts in the font table. */
8083 for (i = 0; i < dpyinfo->n_fonts; i++)
8084 if (dpyinfo->font_table[i].name)
8086 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
8087 xfree (dpyinfo->font_table[i].full_name);
8088 xfree (dpyinfo->font_table[i].name);
8089 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
8091 x_destroy_all_bitmaps (dpyinfo);
8093 x_delete_display (dpyinfo);
8094 UNBLOCK_INPUT;
8096 return Qnil;
8099 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
8100 doc: /* Return the list of display names that Emacs has connections to. */)
8103 Lisp_Object tail, result;
8105 result = Qnil;
8106 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
8107 result = Fcons (XCAR (XCAR (tail)), result);
8109 return result;
8112 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
8113 doc: /* This is a noop on W32 systems. */)
8114 (on, display)
8115 Lisp_Object display, on;
8117 return Qnil;
8121 /***********************************************************************
8122 Image types
8123 ***********************************************************************/
8125 /* Value is the number of elements of vector VECTOR. */
8127 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
8129 /* List of supported image types. Use define_image_type to add new
8130 types. Use lookup_image_type to find a type for a given symbol. */
8132 static struct image_type *image_types;
8134 /* The symbol `image' which is the car of the lists used to represent
8135 images in Lisp. */
8137 extern Lisp_Object Qimage;
8139 /* The symbol `xbm' which is used as the type symbol for XBM images. */
8141 Lisp_Object Qxbm;
8143 /* Keywords. */
8145 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
8146 extern Lisp_Object QCdata, QCtype;
8147 Lisp_Object QCascent, QCmargin, QCrelief;
8148 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
8149 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
8151 /* Other symbols. */
8153 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
8155 /* Time in seconds after which images should be removed from the cache
8156 if not displayed. */
8158 Lisp_Object Vimage_cache_eviction_delay;
8160 /* Function prototypes. */
8162 static void define_image_type P_ ((struct image_type *type));
8163 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
8164 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
8165 static void x_laplace P_ ((struct frame *, struct image *));
8166 static void x_emboss P_ ((struct frame *, struct image *));
8167 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
8168 Lisp_Object));
8171 /* Define a new image type from TYPE. This adds a copy of TYPE to
8172 image_types and adds the symbol *TYPE->type to Vimage_types. */
8174 static void
8175 define_image_type (type)
8176 struct image_type *type;
8178 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
8179 The initialized data segment is read-only. */
8180 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
8181 bcopy (type, p, sizeof *p);
8182 p->next = image_types;
8183 image_types = p;
8184 Vimage_types = Fcons (*p->type, Vimage_types);
8188 /* Look up image type SYMBOL, and return a pointer to its image_type
8189 structure. Value is null if SYMBOL is not a known image type. */
8191 static INLINE struct image_type *
8192 lookup_image_type (symbol)
8193 Lisp_Object symbol;
8195 struct image_type *type;
8197 for (type = image_types; type; type = type->next)
8198 if (EQ (symbol, *type->type))
8199 break;
8201 return type;
8205 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
8206 valid image specification is a list whose car is the symbol
8207 `image', and whose rest is a property list. The property list must
8208 contain a value for key `:type'. That value must be the name of a
8209 supported image type. The rest of the property list depends on the
8210 image type. */
8213 valid_image_p (object)
8214 Lisp_Object object;
8216 int valid_p = 0;
8218 if (CONSP (object) && EQ (XCAR (object), Qimage))
8220 Lisp_Object tem;
8222 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
8223 if (EQ (XCAR (tem), QCtype))
8225 tem = XCDR (tem);
8226 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
8228 struct image_type *type;
8229 type = lookup_image_type (XCAR (tem));
8230 if (type)
8231 valid_p = type->valid_p (object);
8234 break;
8238 return valid_p;
8242 /* Log error message with format string FORMAT and argument ARG.
8243 Signaling an error, e.g. when an image cannot be loaded, is not a
8244 good idea because this would interrupt redisplay, and the error
8245 message display would lead to another redisplay. This function
8246 therefore simply displays a message. */
8248 static void
8249 image_error (format, arg1, arg2)
8250 char *format;
8251 Lisp_Object arg1, arg2;
8253 add_to_log (format, arg1, arg2);
8258 /***********************************************************************
8259 Image specifications
8260 ***********************************************************************/
8262 enum image_value_type
8264 IMAGE_DONT_CHECK_VALUE_TYPE,
8265 IMAGE_STRING_VALUE,
8266 IMAGE_STRING_OR_NIL_VALUE,
8267 IMAGE_SYMBOL_VALUE,
8268 IMAGE_POSITIVE_INTEGER_VALUE,
8269 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
8270 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
8271 IMAGE_ASCENT_VALUE,
8272 IMAGE_INTEGER_VALUE,
8273 IMAGE_FUNCTION_VALUE,
8274 IMAGE_NUMBER_VALUE,
8275 IMAGE_BOOL_VALUE
8278 /* Structure used when parsing image specifications. */
8280 struct image_keyword
8282 /* Name of keyword. */
8283 char *name;
8285 /* The type of value allowed. */
8286 enum image_value_type type;
8288 /* Non-zero means key must be present. */
8289 int mandatory_p;
8291 /* Used to recognize duplicate keywords in a property list. */
8292 int count;
8294 /* The value that was found. */
8295 Lisp_Object value;
8299 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
8300 int, Lisp_Object));
8301 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
8304 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
8305 has the format (image KEYWORD VALUE ...). One of the keyword/
8306 value pairs must be `:type TYPE'. KEYWORDS is a vector of
8307 image_keywords structures of size NKEYWORDS describing other
8308 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
8310 static int
8311 parse_image_spec (spec, keywords, nkeywords, type)
8312 Lisp_Object spec;
8313 struct image_keyword *keywords;
8314 int nkeywords;
8315 Lisp_Object type;
8317 int i;
8318 Lisp_Object plist;
8320 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
8321 return 0;
8323 plist = XCDR (spec);
8324 while (CONSP (plist))
8326 Lisp_Object key, value;
8328 /* First element of a pair must be a symbol. */
8329 key = XCAR (plist);
8330 plist = XCDR (plist);
8331 if (!SYMBOLP (key))
8332 return 0;
8334 /* There must follow a value. */
8335 if (!CONSP (plist))
8336 return 0;
8337 value = XCAR (plist);
8338 plist = XCDR (plist);
8340 /* Find key in KEYWORDS. Error if not found. */
8341 for (i = 0; i < nkeywords; ++i)
8342 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
8343 break;
8345 if (i == nkeywords)
8346 continue;
8348 /* Record that we recognized the keyword. If a keywords
8349 was found more than once, it's an error. */
8350 keywords[i].value = value;
8351 ++keywords[i].count;
8353 if (keywords[i].count > 1)
8354 return 0;
8356 /* Check type of value against allowed type. */
8357 switch (keywords[i].type)
8359 case IMAGE_STRING_VALUE:
8360 if (!STRINGP (value))
8361 return 0;
8362 break;
8364 case IMAGE_STRING_OR_NIL_VALUE:
8365 if (!STRINGP (value) && !NILP (value))
8366 return 0;
8367 break;
8369 case IMAGE_SYMBOL_VALUE:
8370 if (!SYMBOLP (value))
8371 return 0;
8372 break;
8374 case IMAGE_POSITIVE_INTEGER_VALUE:
8375 if (!INTEGERP (value) || XINT (value) <= 0)
8376 return 0;
8377 break;
8379 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
8380 if (INTEGERP (value) && XINT (value) >= 0)
8381 break;
8382 if (CONSP (value)
8383 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
8384 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
8385 break;
8386 return 0;
8388 case IMAGE_ASCENT_VALUE:
8389 if (SYMBOLP (value) && EQ (value, Qcenter))
8390 break;
8391 else if (INTEGERP (value)
8392 && XINT (value) >= 0
8393 && XINT (value) <= 100)
8394 break;
8395 return 0;
8397 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
8398 if (!INTEGERP (value) || XINT (value) < 0)
8399 return 0;
8400 break;
8402 case IMAGE_DONT_CHECK_VALUE_TYPE:
8403 break;
8405 case IMAGE_FUNCTION_VALUE:
8406 value = indirect_function (value);
8407 if (SUBRP (value)
8408 || COMPILEDP (value)
8409 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
8410 break;
8411 return 0;
8413 case IMAGE_NUMBER_VALUE:
8414 if (!INTEGERP (value) && !FLOATP (value))
8415 return 0;
8416 break;
8418 case IMAGE_INTEGER_VALUE:
8419 if (!INTEGERP (value))
8420 return 0;
8421 break;
8423 case IMAGE_BOOL_VALUE:
8424 if (!NILP (value) && !EQ (value, Qt))
8425 return 0;
8426 break;
8428 default:
8429 abort ();
8430 break;
8433 if (EQ (key, QCtype) && !EQ (type, value))
8434 return 0;
8437 /* Check that all mandatory fields are present. */
8438 for (i = 0; i < nkeywords; ++i)
8439 if (keywords[i].mandatory_p && keywords[i].count == 0)
8440 return 0;
8442 return NILP (plist);
8446 /* Return the value of KEY in image specification SPEC. Value is nil
8447 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
8448 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
8450 static Lisp_Object
8451 image_spec_value (spec, key, found)
8452 Lisp_Object spec, key;
8453 int *found;
8455 Lisp_Object tail;
8457 xassert (valid_image_p (spec));
8459 for (tail = XCDR (spec);
8460 CONSP (tail) && CONSP (XCDR (tail));
8461 tail = XCDR (XCDR (tail)))
8463 if (EQ (XCAR (tail), key))
8465 if (found)
8466 *found = 1;
8467 return XCAR (XCDR (tail));
8471 if (found)
8472 *found = 0;
8473 return Qnil;
8477 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
8478 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
8479 PIXELS non-nil means return the size in pixels, otherwise return the
8480 size in canonical character units.
8481 FRAME is the frame on which the image will be displayed. FRAME nil
8482 or omitted means use the selected frame. */)
8483 (spec, pixels, frame)
8484 Lisp_Object spec, pixels, frame;
8486 Lisp_Object size;
8488 size = Qnil;
8489 if (valid_image_p (spec))
8491 struct frame *f = check_x_frame (frame);
8492 int id = lookup_image (f, spec);
8493 struct image *img = IMAGE_FROM_ID (f, id);
8494 int width = img->width + 2 * img->hmargin;
8495 int height = img->height + 2 * img->vmargin;
8497 if (NILP (pixels))
8498 size = Fcons (make_float ((double) width / CANON_X_UNIT (f)),
8499 make_float ((double) height / CANON_Y_UNIT (f)));
8500 else
8501 size = Fcons (make_number (width), make_number (height));
8503 else
8504 error ("Invalid image specification");
8506 return size;
8510 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
8511 doc: /* Return t if image SPEC has a mask bitmap.
8512 FRAME is the frame on which the image will be displayed. FRAME nil
8513 or omitted means use the selected frame. */)
8514 (spec, frame)
8515 Lisp_Object spec, frame;
8517 Lisp_Object mask;
8519 mask = Qnil;
8520 if (valid_image_p (spec))
8522 struct frame *f = check_x_frame (frame);
8523 int id = lookup_image (f, spec);
8524 struct image *img = IMAGE_FROM_ID (f, id);
8525 if (img->mask)
8526 mask = Qt;
8528 else
8529 error ("Invalid image specification");
8531 return mask;
8535 /***********************************************************************
8536 Image type independent image structures
8537 ***********************************************************************/
8539 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
8540 static void free_image P_ ((struct frame *f, struct image *img));
8541 static void x_destroy_x_image P_ ((XImage *));
8544 /* Allocate and return a new image structure for image specification
8545 SPEC. SPEC has a hash value of HASH. */
8547 static struct image *
8548 make_image (spec, hash)
8549 Lisp_Object spec;
8550 unsigned hash;
8552 struct image *img = (struct image *) xmalloc (sizeof *img);
8554 xassert (valid_image_p (spec));
8555 bzero (img, sizeof *img);
8556 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
8557 xassert (img->type != NULL);
8558 img->spec = spec;
8559 img->data.lisp_val = Qnil;
8560 img->ascent = DEFAULT_IMAGE_ASCENT;
8561 img->hash = hash;
8562 return img;
8566 /* Free image IMG which was used on frame F, including its resources. */
8568 static void
8569 free_image (f, img)
8570 struct frame *f;
8571 struct image *img;
8573 if (img)
8575 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8577 /* Remove IMG from the hash table of its cache. */
8578 if (img->prev)
8579 img->prev->next = img->next;
8580 else
8581 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
8583 if (img->next)
8584 img->next->prev = img->prev;
8586 c->images[img->id] = NULL;
8588 /* Free resources, then free IMG. */
8589 img->type->free (f, img);
8590 xfree (img);
8595 /* Prepare image IMG for display on frame F. Must be called before
8596 drawing an image. */
8598 void
8599 prepare_image_for_display (f, img)
8600 struct frame *f;
8601 struct image *img;
8603 EMACS_TIME t;
8605 /* We're about to display IMG, so set its timestamp to `now'. */
8606 EMACS_GET_TIME (t);
8607 img->timestamp = EMACS_SECS (t);
8609 /* If IMG doesn't have a pixmap yet, load it now, using the image
8610 type dependent loader function. */
8611 if (img->pixmap == 0 && !img->load_failed_p)
8612 img->load_failed_p = img->type->load (f, img) == 0;
8616 /* Value is the number of pixels for the ascent of image IMG when
8617 drawn in face FACE. */
8620 image_ascent (img, face)
8621 struct image *img;
8622 struct face *face;
8624 int height = img->height + img->vmargin;
8625 int ascent;
8627 if (img->ascent == CENTERED_IMAGE_ASCENT)
8629 if (face->font)
8630 ascent = height / 2 - (FONT_DESCENT(face->font)
8631 - FONT_BASE(face->font)) / 2;
8632 else
8633 ascent = height / 2;
8635 else
8636 ascent = (int) (height * img->ascent / 100.0);
8638 return ascent;
8643 /* Image background colors. */
8645 /* Find the "best" corner color of a bitmap. XIMG is assumed to a device
8646 context with the bitmap selected. */
8647 static COLORREF
8648 four_corners_best (img_dc, width, height)
8649 HDC img_dc;
8650 unsigned long width, height;
8652 COLORREF corners[4], best;
8653 int i, best_count;
8655 /* Get the colors at the corners of img_dc. */
8656 corners[0] = GetPixel (img_dc, 0, 0);
8657 corners[1] = GetPixel (img_dc, width - 1, 0);
8658 corners[2] = GetPixel (img_dc, width - 1, height - 1);
8659 corners[3] = GetPixel (img_dc, 0, height - 1);
8661 /* Choose the most frequently found color as background. */
8662 for (i = best_count = 0; i < 4; ++i)
8664 int j, n;
8666 for (j = n = 0; j < 4; ++j)
8667 if (corners[i] == corners[j])
8668 ++n;
8670 if (n > best_count)
8671 best = corners[i], best_count = n;
8674 return best;
8677 /* Return the `background' field of IMG. If IMG doesn't have one yet,
8678 it is guessed heuristically. If non-zero, IMG_DC is an existing
8679 device context with the image selected to use for the heuristic. */
8681 unsigned long
8682 image_background (img, f, img_dc)
8683 struct image *img;
8684 struct frame *f;
8685 HDC img_dc;
8687 if (! img->background_valid)
8688 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8690 int free_ximg = !img_dc;
8691 HGDIOBJ prev;
8693 if (free_ximg)
8695 HDC frame_dc = get_frame_dc (f);
8696 img_dc = CreateCompatibleDC (frame_dc);
8697 release_frame_dc (f, frame_dc);
8699 prev = SelectObject (img_dc, img->pixmap);
8702 img->background = four_corners_best (img_dc, img->width, img->height);
8704 if (free_ximg)
8706 SelectObject (img_dc, prev);
8707 DeleteDC (img_dc);
8710 img->background_valid = 1;
8713 return img->background;
8716 /* Return the `background_transparent' field of IMG. If IMG doesn't
8717 have one yet, it is guessed heuristically. If non-zero, MASK is an
8718 existing XImage object to use for the heuristic. */
8721 image_background_transparent (img, f, mask)
8722 struct image *img;
8723 struct frame *f;
8724 HDC mask;
8726 if (! img->background_transparent_valid)
8727 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8729 if (img->mask)
8731 int free_mask = !mask;
8732 HGDIOBJ prev;
8734 if (free_mask)
8736 HDC frame_dc = get_frame_dc (f);
8737 mask = CreateCompatibleDC (frame_dc);
8738 release_frame_dc (f, frame_dc);
8740 prev = SelectObject (mask, img->mask);
8743 img->background_transparent
8744 = !four_corners_best (mask, img->width, img->height);
8746 if (free_mask)
8748 SelectObject (mask, prev);
8749 DeleteDC (mask);
8752 else
8753 img->background_transparent = 0;
8755 img->background_transparent_valid = 1;
8758 return img->background_transparent;
8762 /***********************************************************************
8763 Helper functions for X image types
8764 ***********************************************************************/
8766 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
8767 int, int));
8768 static void x_clear_image P_ ((struct frame *f, struct image *img));
8769 static unsigned long x_alloc_image_color P_ ((struct frame *f,
8770 struct image *img,
8771 Lisp_Object color_name,
8772 unsigned long dflt));
8775 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
8776 free the pixmap if any. MASK_P non-zero means clear the mask
8777 pixmap if any. COLORS_P non-zero means free colors allocated for
8778 the image, if any. */
8780 static void
8781 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
8782 struct frame *f;
8783 struct image *img;
8784 int pixmap_p, mask_p, colors_p;
8786 if (pixmap_p && img->pixmap)
8788 DeleteObject (img->pixmap);
8789 img->pixmap = NULL;
8790 img->background_valid = 0;
8793 if (mask_p && img->mask)
8795 DeleteObject (img->mask);
8796 img->mask = NULL;
8797 img->background_transparent_valid = 0;
8800 if (colors_p && img->ncolors)
8802 #if 0 /* TODO: color table support. */
8803 x_free_colors (f, img->colors, img->ncolors);
8804 #endif
8805 xfree (img->colors);
8806 img->colors = NULL;
8807 img->ncolors = 0;
8811 /* Free X resources of image IMG which is used on frame F. */
8813 static void
8814 x_clear_image (f, img)
8815 struct frame *f;
8816 struct image *img;
8818 if (img->pixmap)
8820 BLOCK_INPUT;
8821 DeleteObject (img->pixmap);
8822 img->pixmap = 0;
8823 UNBLOCK_INPUT;
8826 if (img->ncolors)
8828 #if 0 /* TODO: color table support */
8830 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8832 /* If display has an immutable color map, freeing colors is not
8833 necessary and some servers don't allow it. So don't do it. */
8834 if (class != StaticColor
8835 && class != StaticGray
8836 && class != TrueColor)
8838 Colormap cmap;
8839 BLOCK_INPUT;
8840 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8841 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8842 img->ncolors, 0);
8843 UNBLOCK_INPUT;
8845 #endif
8847 xfree (img->colors);
8848 img->colors = NULL;
8849 img->ncolors = 0;
8854 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8855 cannot be allocated, use DFLT. Add a newly allocated color to
8856 IMG->colors, so that it can be freed again. Value is the pixel
8857 color. */
8859 static unsigned long
8860 x_alloc_image_color (f, img, color_name, dflt)
8861 struct frame *f;
8862 struct image *img;
8863 Lisp_Object color_name;
8864 unsigned long dflt;
8866 XColor color;
8867 unsigned long result;
8869 xassert (STRINGP (color_name));
8871 if (w32_defined_color (f, SDATA (color_name), &color, 1))
8873 /* This isn't called frequently so we get away with simply
8874 reallocating the color vector to the needed size, here. */
8875 ++img->ncolors;
8876 img->colors =
8877 (unsigned long *) xrealloc (img->colors,
8878 img->ncolors * sizeof *img->colors);
8879 img->colors[img->ncolors - 1] = color.pixel;
8880 result = color.pixel;
8882 else
8883 result = dflt;
8884 return result;
8889 /***********************************************************************
8890 Image Cache
8891 ***********************************************************************/
8893 static void cache_image P_ ((struct frame *f, struct image *img));
8894 static void postprocess_image P_ ((struct frame *, struct image *));
8895 static void x_disable_image P_ ((struct frame *, struct image *));
8898 /* Return a new, initialized image cache that is allocated from the
8899 heap. Call free_image_cache to free an image cache. */
8901 struct image_cache *
8902 make_image_cache ()
8904 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8905 int size;
8907 bzero (c, sizeof *c);
8908 c->size = 50;
8909 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8910 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8911 c->buckets = (struct image **) xmalloc (size);
8912 bzero (c->buckets, size);
8913 return c;
8917 /* Free image cache of frame F. Be aware that X frames share images
8918 caches. */
8920 void
8921 free_image_cache (f)
8922 struct frame *f;
8924 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8925 if (c)
8927 int i;
8929 /* Cache should not be referenced by any frame when freed. */
8930 xassert (c->refcount == 0);
8932 for (i = 0; i < c->used; ++i)
8933 free_image (f, c->images[i]);
8934 xfree (c->images);
8935 xfree (c);
8936 xfree (c->buckets);
8937 FRAME_X_IMAGE_CACHE (f) = NULL;
8942 /* Clear image cache of frame F. FORCE_P non-zero means free all
8943 images. FORCE_P zero means clear only images that haven't been
8944 displayed for some time. Should be called from time to time to
8945 reduce the number of loaded images. If image-eviction-seconds is
8946 non-nil, this frees images in the cache which weren't displayed for
8947 at least that many seconds. */
8949 void
8950 clear_image_cache (f, force_p)
8951 struct frame *f;
8952 int force_p;
8954 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8956 if (c && INTEGERP (Vimage_cache_eviction_delay))
8958 EMACS_TIME t;
8959 unsigned long old;
8960 int i, nfreed;
8962 EMACS_GET_TIME (t);
8963 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8965 /* Block input so that we won't be interrupted by a SIGIO
8966 while being in an inconsistent state. */
8967 BLOCK_INPUT;
8969 for (i = nfreed = 0; i < c->used; ++i)
8971 struct image *img = c->images[i];
8972 if (img != NULL
8973 && (force_p || (img->timestamp < old)))
8975 free_image (f, img);
8976 ++nfreed;
8980 /* We may be clearing the image cache because, for example,
8981 Emacs was iconified for a longer period of time. In that
8982 case, current matrices may still contain references to
8983 images freed above. So, clear these matrices. */
8984 if (nfreed)
8986 Lisp_Object tail, frame;
8988 FOR_EACH_FRAME (tail, frame)
8990 struct frame *f = XFRAME (frame);
8991 if (FRAME_W32_P (f)
8992 && FRAME_X_IMAGE_CACHE (f) == c)
8993 clear_current_matrices (f);
8996 ++windows_or_buffers_changed;
8999 UNBLOCK_INPUT;
9004 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
9005 0, 1, 0,
9006 doc: /* Clear the image cache of FRAME.
9007 FRAME nil or omitted means use the selected frame.
9008 FRAME t means clear the image caches of all frames. */)
9009 (frame)
9010 Lisp_Object frame;
9012 if (EQ (frame, Qt))
9014 Lisp_Object tail;
9016 FOR_EACH_FRAME (tail, frame)
9017 if (FRAME_W32_P (XFRAME (frame)))
9018 clear_image_cache (XFRAME (frame), 1);
9020 else
9021 clear_image_cache (check_x_frame (frame), 1);
9023 return Qnil;
9027 /* Compute masks and transform image IMG on frame F, as specified
9028 by the image's specification, */
9030 static void
9031 postprocess_image (f, img)
9032 struct frame *f;
9033 struct image *img;
9035 /* Manipulation of the image's mask. */
9036 if (img->pixmap)
9038 Lisp_Object conversion, spec;
9039 Lisp_Object mask;
9041 spec = img->spec;
9043 /* `:heuristic-mask t'
9044 `:mask heuristic'
9045 means build a mask heuristically.
9046 `:heuristic-mask (R G B)'
9047 `:mask (heuristic (R G B))'
9048 means build a mask from color (R G B) in the
9049 image.
9050 `:mask nil'
9051 means remove a mask, if any. */
9053 mask = image_spec_value (spec, QCheuristic_mask, NULL);
9054 if (!NILP (mask))
9055 x_build_heuristic_mask (f, img, mask);
9056 else
9058 int found_p;
9060 mask = image_spec_value (spec, QCmask, &found_p);
9062 if (EQ (mask, Qheuristic))
9063 x_build_heuristic_mask (f, img, Qt);
9064 else if (CONSP (mask)
9065 && EQ (XCAR (mask), Qheuristic))
9067 if (CONSP (XCDR (mask)))
9068 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
9069 else
9070 x_build_heuristic_mask (f, img, XCDR (mask));
9072 else if (NILP (mask) && found_p && img->mask)
9074 DeleteObject (img->mask);
9075 img->mask = NULL;
9080 /* Should we apply an image transformation algorithm? */
9081 conversion = image_spec_value (spec, QCconversion, NULL);
9082 if (EQ (conversion, Qdisabled))
9083 x_disable_image (f, img);
9084 else if (EQ (conversion, Qlaplace))
9085 x_laplace (f, img);
9086 else if (EQ (conversion, Qemboss))
9087 x_emboss (f, img);
9088 else if (CONSP (conversion)
9089 && EQ (XCAR (conversion), Qedge_detection))
9091 Lisp_Object tem;
9092 tem = XCDR (conversion);
9093 if (CONSP (tem))
9094 x_edge_detection (f, img,
9095 Fplist_get (tem, QCmatrix),
9096 Fplist_get (tem, QCcolor_adjustment));
9102 /* Return the id of image with Lisp specification SPEC on frame F.
9103 SPEC must be a valid Lisp image specification (see valid_image_p). */
9106 lookup_image (f, spec)
9107 struct frame *f;
9108 Lisp_Object spec;
9110 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9111 struct image *img;
9112 int i;
9113 unsigned hash;
9114 struct gcpro gcpro1;
9115 EMACS_TIME now;
9117 /* F must be a window-system frame, and SPEC must be a valid image
9118 specification. */
9119 xassert (FRAME_WINDOW_P (f));
9120 xassert (valid_image_p (spec));
9122 GCPRO1 (spec);
9124 /* Look up SPEC in the hash table of the image cache. */
9125 hash = sxhash (spec, 0);
9126 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
9128 for (img = c->buckets[i]; img; img = img->next)
9129 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
9130 break;
9132 /* If not found, create a new image and cache it. */
9133 if (img == NULL)
9135 extern Lisp_Object Qpostscript;
9137 BLOCK_INPUT;
9138 img = make_image (spec, hash);
9139 cache_image (f, img);
9140 img->load_failed_p = img->type->load (f, img) == 0;
9142 /* If we can't load the image, and we don't have a width and
9143 height, use some arbitrary width and height so that we can
9144 draw a rectangle for it. */
9145 if (img->load_failed_p)
9147 Lisp_Object value;
9149 value = image_spec_value (spec, QCwidth, NULL);
9150 img->width = (INTEGERP (value)
9151 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
9152 value = image_spec_value (spec, QCheight, NULL);
9153 img->height = (INTEGERP (value)
9154 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
9156 else
9158 /* Handle image type independent image attributes
9159 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF',
9160 `:background COLOR'. */
9161 Lisp_Object ascent, margin, relief, bg;
9163 ascent = image_spec_value (spec, QCascent, NULL);
9164 if (INTEGERP (ascent))
9165 img->ascent = XFASTINT (ascent);
9166 else if (EQ (ascent, Qcenter))
9167 img->ascent = CENTERED_IMAGE_ASCENT;
9169 margin = image_spec_value (spec, QCmargin, NULL);
9170 if (INTEGERP (margin) && XINT (margin) >= 0)
9171 img->vmargin = img->hmargin = XFASTINT (margin);
9172 else if (CONSP (margin) && INTEGERP (XCAR (margin))
9173 && INTEGERP (XCDR (margin)))
9175 if (XINT (XCAR (margin)) > 0)
9176 img->hmargin = XFASTINT (XCAR (margin));
9177 if (XINT (XCDR (margin)) > 0)
9178 img->vmargin = XFASTINT (XCDR (margin));
9181 relief = image_spec_value (spec, QCrelief, NULL);
9182 if (INTEGERP (relief))
9184 img->relief = XINT (relief);
9185 img->hmargin += abs (img->relief);
9186 img->vmargin += abs (img->relief);
9189 if (! img->background_valid)
9191 bg = image_spec_value (img->spec, QCbackground, NULL);
9192 if (!NILP (bg))
9194 img->background
9195 = x_alloc_image_color (f, img, bg,
9196 FRAME_BACKGROUND_PIXEL (f));
9197 img->background_valid = 1;
9201 /* Do image transformations and compute masks, unless we
9202 don't have the image yet. */
9203 if (!EQ (*img->type->type, Qpostscript))
9204 postprocess_image (f, img);
9207 UNBLOCK_INPUT;
9208 xassert (!interrupt_input_blocked);
9211 /* We're using IMG, so set its timestamp to `now'. */
9212 EMACS_GET_TIME (now);
9213 img->timestamp = EMACS_SECS (now);
9215 UNGCPRO;
9217 /* Value is the image id. */
9218 return img->id;
9222 /* Cache image IMG in the image cache of frame F. */
9224 static void
9225 cache_image (f, img)
9226 struct frame *f;
9227 struct image *img;
9229 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9230 int i;
9232 /* Find a free slot in c->images. */
9233 for (i = 0; i < c->used; ++i)
9234 if (c->images[i] == NULL)
9235 break;
9237 /* If no free slot found, maybe enlarge c->images. */
9238 if (i == c->used && c->used == c->size)
9240 c->size *= 2;
9241 c->images = (struct image **) xrealloc (c->images,
9242 c->size * sizeof *c->images);
9245 /* Add IMG to c->images, and assign IMG an id. */
9246 c->images[i] = img;
9247 img->id = i;
9248 if (i == c->used)
9249 ++c->used;
9251 /* Add IMG to the cache's hash table. */
9252 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
9253 img->next = c->buckets[i];
9254 if (img->next)
9255 img->next->prev = img;
9256 img->prev = NULL;
9257 c->buckets[i] = img;
9261 /* Call FN on every image in the image cache of frame F. Used to mark
9262 Lisp Objects in the image cache. */
9264 void
9265 forall_images_in_image_cache (f, fn)
9266 struct frame *f;
9267 void (*fn) P_ ((struct image *img));
9269 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
9271 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9272 if (c)
9274 int i;
9275 for (i = 0; i < c->used; ++i)
9276 if (c->images[i])
9277 fn (c->images[i]);
9284 /***********************************************************************
9285 W32 support code
9286 ***********************************************************************/
9288 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
9289 XImage **, Pixmap *));
9290 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
9293 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
9294 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
9295 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
9296 via xmalloc. DEPTH of zero signifies a 24 bit image, otherwise
9297 DEPTH should indicate the bit depth of the image. Print error
9298 messages via image_error if an error occurs. Value is non-zero if
9299 successful. */
9301 static int
9302 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
9303 struct frame *f;
9304 int width, height, depth;
9305 XImage **ximg;
9306 Pixmap *pixmap;
9308 BITMAPINFOHEADER *header;
9309 HDC hdc;
9310 int scanline_width_bits;
9311 int remainder;
9312 int palette_colors = 0;
9314 if (depth == 0)
9315 depth = 24;
9317 if (depth != 1 && depth != 4 && depth != 8
9318 && depth != 16 && depth != 24 && depth != 32)
9320 image_error ("Invalid image bit depth specified", Qnil, Qnil);
9321 return 0;
9324 scanline_width_bits = width * depth;
9325 remainder = scanline_width_bits % 32;
9327 if (remainder)
9328 scanline_width_bits += 32 - remainder;
9330 /* Bitmaps with a depth less than 16 need a palette. */
9331 /* BITMAPINFO structure already contains the first RGBQUAD. */
9332 if (depth < 16)
9333 palette_colors = 1 << depth - 1;
9335 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
9336 if (*ximg == NULL)
9338 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
9339 return 0;
9342 header = &((*ximg)->info.bmiHeader);
9343 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
9344 header->biSize = sizeof (*header);
9345 header->biWidth = width;
9346 header->biHeight = -height; /* negative indicates a top-down bitmap. */
9347 header->biPlanes = 1;
9348 header->biBitCount = depth;
9349 header->biCompression = BI_RGB;
9350 header->biClrUsed = palette_colors;
9352 /* TODO: fill in palette. */
9353 if (depth == 1)
9355 (*ximg)->info.bmiColors[0].rgbBlue = 0;
9356 (*ximg)->info.bmiColors[0].rgbGreen = 0;
9357 (*ximg)->info.bmiColors[0].rgbRed = 0;
9358 (*ximg)->info.bmiColors[0].rgbReserved = 0;
9359 (*ximg)->info.bmiColors[1].rgbBlue = 255;
9360 (*ximg)->info.bmiColors[1].rgbGreen = 255;
9361 (*ximg)->info.bmiColors[1].rgbRed = 255;
9362 (*ximg)->info.bmiColors[1].rgbReserved = 0;
9365 hdc = get_frame_dc (f);
9367 /* Create a DIBSection and raster array for the bitmap,
9368 and store its handle in *pixmap. */
9369 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
9370 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
9371 &((*ximg)->data), NULL, 0);
9373 /* Realize display palette and garbage all frames. */
9374 release_frame_dc (f, hdc);
9376 if (*pixmap == NULL)
9378 DWORD err = GetLastError();
9379 Lisp_Object errcode;
9380 /* All system errors are < 10000, so the following is safe. */
9381 XSETINT (errcode, (int) err);
9382 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
9383 x_destroy_x_image (*ximg);
9384 return 0;
9387 return 1;
9391 /* Destroy XImage XIMG. Free XIMG->data. */
9393 static void
9394 x_destroy_x_image (ximg)
9395 XImage *ximg;
9397 xassert (interrupt_input_blocked);
9398 if (ximg)
9400 /* Data will be freed by DestroyObject. */
9401 ximg->data = NULL;
9402 xfree (ximg);
9407 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
9408 are width and height of both the image and pixmap. */
9410 static void
9411 x_put_x_image (f, ximg, pixmap, width, height)
9412 struct frame *f;
9413 XImage *ximg;
9414 Pixmap pixmap;
9416 #if 0 /* I don't think this is necessary looking at where it is used. */
9417 HDC hdc = get_frame_dc (f);
9418 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
9419 release_frame_dc (f, hdc);
9420 #endif
9424 /***********************************************************************
9425 File Handling
9426 ***********************************************************************/
9428 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
9429 static char *slurp_file P_ ((char *, int *));
9432 /* Find image file FILE. Look in data-directory, then
9433 x-bitmap-file-path. Value is the full name of the file found, or
9434 nil if not found. */
9436 static Lisp_Object
9437 x_find_image_file (file)
9438 Lisp_Object file;
9440 Lisp_Object file_found, search_path;
9441 struct gcpro gcpro1, gcpro2;
9442 int fd;
9444 file_found = Qnil;
9445 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
9446 GCPRO2 (file_found, search_path);
9448 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
9449 fd = openp (search_path, file, Qnil, &file_found, Qnil);
9451 if (fd == -1)
9452 file_found = Qnil;
9453 else
9454 close (fd);
9456 UNGCPRO;
9457 return file_found;
9461 /* Read FILE into memory. Value is a pointer to a buffer allocated
9462 with xmalloc holding FILE's contents. Value is null if an error
9463 occurred. *SIZE is set to the size of the file. */
9465 static char *
9466 slurp_file (file, size)
9467 char *file;
9468 int *size;
9470 FILE *fp = NULL;
9471 char *buf = NULL;
9472 struct stat st;
9474 if (stat (file, &st) == 0
9475 && (fp = fopen (file, "r")) != NULL
9476 && (buf = (char *) xmalloc (st.st_size),
9477 fread (buf, 1, st.st_size, fp) == st.st_size))
9479 *size = st.st_size;
9480 fclose (fp);
9482 else
9484 if (fp)
9485 fclose (fp);
9486 if (buf)
9488 xfree (buf);
9489 buf = NULL;
9493 return buf;
9498 /***********************************************************************
9499 XBM images
9500 ***********************************************************************/
9502 static int xbm_scan P_ ((char **, char *, char *, int *));
9503 static int xbm_load P_ ((struct frame *f, struct image *img));
9504 static int xbm_load_image P_ ((struct frame *f, struct image *img,
9505 char *, char *));
9506 static int xbm_image_p P_ ((Lisp_Object object));
9507 static int xbm_read_bitmap_data P_ ((char *, char *, int *, int *,
9508 unsigned char **));
9509 static int xbm_file_p P_ ((Lisp_Object));
9512 /* Indices of image specification fields in xbm_format, below. */
9514 enum xbm_keyword_index
9516 XBM_TYPE,
9517 XBM_FILE,
9518 XBM_WIDTH,
9519 XBM_HEIGHT,
9520 XBM_DATA,
9521 XBM_FOREGROUND,
9522 XBM_BACKGROUND,
9523 XBM_ASCENT,
9524 XBM_MARGIN,
9525 XBM_RELIEF,
9526 XBM_ALGORITHM,
9527 XBM_HEURISTIC_MASK,
9528 XBM_MASK,
9529 XBM_LAST
9532 /* Vector of image_keyword structures describing the format
9533 of valid XBM image specifications. */
9535 static struct image_keyword xbm_format[XBM_LAST] =
9537 {":type", IMAGE_SYMBOL_VALUE, 1},
9538 {":file", IMAGE_STRING_VALUE, 0},
9539 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9540 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9541 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9542 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
9543 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
9544 {":ascent", IMAGE_ASCENT_VALUE, 0},
9545 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9546 {":relief", IMAGE_INTEGER_VALUE, 0},
9547 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9548 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9549 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9552 /* Structure describing the image type XBM. */
9554 static struct image_type xbm_type =
9556 &Qxbm,
9557 xbm_image_p,
9558 xbm_load,
9559 x_clear_image,
9560 NULL
9563 /* Tokens returned from xbm_scan. */
9565 enum xbm_token
9567 XBM_TK_IDENT = 256,
9568 XBM_TK_NUMBER
9572 /* Return non-zero if OBJECT is a valid XBM-type image specification.
9573 A valid specification is a list starting with the symbol `image'
9574 The rest of the list is a property list which must contain an
9575 entry `:type xbm..
9577 If the specification specifies a file to load, it must contain
9578 an entry `:file FILENAME' where FILENAME is a string.
9580 If the specification is for a bitmap loaded from memory it must
9581 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
9582 WIDTH and HEIGHT are integers > 0. DATA may be:
9584 1. a string large enough to hold the bitmap data, i.e. it must
9585 have a size >= (WIDTH + 7) / 8 * HEIGHT
9587 2. a bool-vector of size >= WIDTH * HEIGHT
9589 3. a vector of strings or bool-vectors, one for each line of the
9590 bitmap.
9592 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
9593 may not be specified in this case because they are defined in the
9594 XBM file.
9596 Both the file and data forms may contain the additional entries
9597 `:background COLOR' and `:foreground COLOR'. If not present,
9598 foreground and background of the frame on which the image is
9599 displayed is used. */
9601 static int
9602 xbm_image_p (object)
9603 Lisp_Object object;
9605 struct image_keyword kw[XBM_LAST];
9607 bcopy (xbm_format, kw, sizeof kw);
9608 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
9609 return 0;
9611 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
9613 if (kw[XBM_FILE].count)
9615 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
9616 return 0;
9618 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
9620 /* In-memory XBM file. */
9621 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
9622 return 0;
9624 else
9626 Lisp_Object data;
9627 int width, height;
9629 /* Entries for `:width', `:height' and `:data' must be present. */
9630 if (!kw[XBM_WIDTH].count
9631 || !kw[XBM_HEIGHT].count
9632 || !kw[XBM_DATA].count)
9633 return 0;
9635 data = kw[XBM_DATA].value;
9636 width = XFASTINT (kw[XBM_WIDTH].value);
9637 height = XFASTINT (kw[XBM_HEIGHT].value);
9639 /* Check type of data, and width and height against contents of
9640 data. */
9641 if (VECTORP (data))
9643 int i;
9645 /* Number of elements of the vector must be >= height. */
9646 if (XVECTOR (data)->size < height)
9647 return 0;
9649 /* Each string or bool-vector in data must be large enough
9650 for one line of the image. */
9651 for (i = 0; i < height; ++i)
9653 Lisp_Object elt = XVECTOR (data)->contents[i];
9655 if (STRINGP (elt))
9657 if (SCHARS (elt)
9658 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
9659 return 0;
9661 else if (BOOL_VECTOR_P (elt))
9663 if (XBOOL_VECTOR (elt)->size < width)
9664 return 0;
9666 else
9667 return 0;
9670 else if (STRINGP (data))
9672 if (SCHARS (data)
9673 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
9674 return 0;
9676 else if (BOOL_VECTOR_P (data))
9678 if (XBOOL_VECTOR (data)->size < width * height)
9679 return 0;
9681 else
9682 return 0;
9685 return 1;
9689 /* Scan a bitmap file. FP is the stream to read from. Value is
9690 either an enumerator from enum xbm_token, or a character for a
9691 single-character token, or 0 at end of file. If scanning an
9692 identifier, store the lexeme of the identifier in SVAL. If
9693 scanning a number, store its value in *IVAL. */
9695 static int
9696 xbm_scan (s, end, sval, ival)
9697 char **s, *end;
9698 char *sval;
9699 int *ival;
9701 int c;
9703 loop:
9705 /* Skip white space. */
9706 while (*s < end && (c = *(*s)++, isspace (c)))
9709 if (*s >= end)
9710 c = 0;
9711 else if (isdigit (c))
9713 int value = 0, digit;
9715 if (c == '0' && *s < end)
9717 c = *(*s)++;
9718 if (c == 'x' || c == 'X')
9720 while (*s < end)
9722 c = *(*s)++;
9723 if (isdigit (c))
9724 digit = c - '0';
9725 else if (c >= 'a' && c <= 'f')
9726 digit = c - 'a' + 10;
9727 else if (c >= 'A' && c <= 'F')
9728 digit = c - 'A' + 10;
9729 else
9730 break;
9731 value = 16 * value + digit;
9734 else if (isdigit (c))
9736 value = c - '0';
9737 while (*s < end
9738 && (c = *(*s)++, isdigit (c)))
9739 value = 8 * value + c - '0';
9742 else
9744 value = c - '0';
9745 while (*s < end
9746 && (c = *(*s)++, isdigit (c)))
9747 value = 10 * value + c - '0';
9750 if (*s < end)
9751 *s = *s - 1;
9752 *ival = value;
9753 c = XBM_TK_NUMBER;
9755 else if (isalpha (c) || c == '_')
9757 *sval++ = c;
9758 while (*s < end
9759 && (c = *(*s)++, (isalnum (c) || c == '_')))
9760 *sval++ = c;
9761 *sval = 0;
9762 if (*s < end)
9763 *s = *s - 1;
9764 c = XBM_TK_IDENT;
9766 else if (c == '/' && **s == '*')
9768 /* C-style comment. */
9769 ++*s;
9770 while (**s && (**s != '*' || *(*s + 1) != '/'))
9771 ++*s;
9772 if (**s)
9774 *s += 2;
9775 goto loop;
9779 return c;
9783 /* XBM bits seem to be backward within bytes compared with how
9784 Windows does things. */
9785 static unsigned char reflect_byte (unsigned char orig)
9787 int i;
9788 unsigned char reflected = 0x00;
9789 for (i = 0; i < 8; i++)
9791 if (orig & (0x01 << i))
9792 reflected |= 0x80 >> i;
9794 return reflected;
9798 /* Create a Windows bitmap from X bitmap data. */
9799 static HBITMAP
9800 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
9802 int i, j, w1, w2;
9803 char *bits, *p;
9804 HBITMAP bmp;
9806 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
9807 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
9808 bits = (char *) xmalloc (height * w2);
9809 bzero (bits, height * w2);
9810 for (i = 0; i < height; i++)
9812 p = bits + i*w2;
9813 for (j = 0; j < w1; j++)
9814 *p++ = reflect_byte(*data++);
9816 bmp = CreateBitmap (width, height, 1, 1, bits);
9817 xfree (bits);
9819 return bmp;
9823 /* Replacement for XReadBitmapFileData which isn't available under old
9824 X versions. CONTENTS is a pointer to a buffer to parse; END is the
9825 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
9826 the image. Return in *DATA the bitmap data allocated with xmalloc.
9827 Value is non-zero if successful. DATA null means just test if
9828 CONTENTS looks like an in-memory XBM file. */
9830 static int
9831 xbm_read_bitmap_data (contents, end, width, height, data)
9832 char *contents, *end;
9833 int *width, *height;
9834 unsigned char **data;
9836 char *s = contents;
9837 char buffer[BUFSIZ];
9838 int padding_p = 0;
9839 int v10 = 0;
9840 int bytes_per_line, i, nbytes;
9841 unsigned char *p;
9842 int value;
9843 int LA1;
9845 #define match() \
9846 LA1 = xbm_scan (&s, end, buffer, &value)
9848 #define expect(TOKEN) \
9849 if (LA1 != (TOKEN)) \
9850 goto failure; \
9851 else \
9852 match ()
9854 #define expect_ident(IDENT) \
9855 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
9856 match (); \
9857 else \
9858 goto failure
9860 *width = *height = -1;
9861 if (data)
9862 *data = NULL;
9863 LA1 = xbm_scan (&s, end, buffer, &value);
9865 /* Parse defines for width, height and hot-spots. */
9866 while (LA1 == '#')
9868 match ();
9869 expect_ident ("define");
9870 expect (XBM_TK_IDENT);
9872 if (LA1 == XBM_TK_NUMBER);
9874 char *p = strrchr (buffer, '_');
9875 p = p ? p + 1 : buffer;
9876 if (strcmp (p, "width") == 0)
9877 *width = value;
9878 else if (strcmp (p, "height") == 0)
9879 *height = value;
9881 expect (XBM_TK_NUMBER);
9884 if (*width < 0 || *height < 0)
9885 goto failure;
9886 else if (data == NULL)
9887 goto success;
9889 /* Parse bits. Must start with `static'. */
9890 expect_ident ("static");
9891 if (LA1 == XBM_TK_IDENT)
9893 if (strcmp (buffer, "unsigned") == 0)
9895 match ();
9896 expect_ident ("char");
9898 else if (strcmp (buffer, "short") == 0)
9900 match ();
9901 v10 = 1;
9902 if (*width % 16 && *width % 16 < 9)
9903 padding_p = 1;
9905 else if (strcmp (buffer, "char") == 0)
9906 match ();
9907 else
9908 goto failure;
9910 else
9911 goto failure;
9913 expect (XBM_TK_IDENT);
9914 expect ('[');
9915 expect (']');
9916 expect ('=');
9917 expect ('{');
9919 bytes_per_line = (*width + 7) / 8 + padding_p;
9920 nbytes = bytes_per_line * *height;
9921 p = *data = (char *) xmalloc (nbytes);
9923 if (v10)
9925 for (i = 0; i < nbytes; i += 2)
9927 int val = value;
9928 expect (XBM_TK_NUMBER);
9930 *p++ = ~ val;
9931 if (!padding_p || ((i + 2) % bytes_per_line))
9932 *p++ = ~ (value >> 8);
9934 if (LA1 == ',' || LA1 == '}')
9935 match ();
9936 else
9937 goto failure;
9940 else
9942 for (i = 0; i < nbytes; ++i)
9944 int val = value;
9945 expect (XBM_TK_NUMBER);
9947 *p++ = ~ val;
9949 if (LA1 == ',' || LA1 == '}')
9950 match ();
9951 else
9952 goto failure;
9956 success:
9957 return 1;
9959 failure:
9961 if (data && *data)
9963 xfree (*data);
9964 *data = NULL;
9966 return 0;
9968 #undef match
9969 #undef expect
9970 #undef expect_ident
9974 /* Load XBM image IMG which will be displayed on frame F from buffer
9975 CONTENTS. END is the end of the buffer. Value is non-zero if
9976 successful. */
9978 static int
9979 xbm_load_image (f, img, contents, end)
9980 struct frame *f;
9981 struct image *img;
9982 char *contents, *end;
9984 int rc;
9985 unsigned char *data;
9986 int success_p = 0;
9988 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
9989 if (rc)
9991 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9992 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9993 Lisp_Object value;
9995 xassert (img->width > 0 && img->height > 0);
9997 /* Get foreground and background colors, maybe allocate colors. */
9998 value = image_spec_value (img->spec, QCforeground, NULL);
9999 if (!NILP (value))
10000 foreground = x_alloc_image_color (f, img, value, foreground);
10001 value = image_spec_value (img->spec, QCbackground, NULL);
10002 if (!NILP (value))
10004 background = x_alloc_image_color (f, img, value, background);
10005 img->background = background;
10006 img->background_valid = 1;
10008 img->pixmap
10009 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
10011 xfree (data);
10013 if (img->pixmap == 0)
10015 x_clear_image (f, img);
10016 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
10018 else
10019 success_p = 1;
10021 else
10022 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10024 return success_p;
10028 /* Value is non-zero if DATA looks like an in-memory XBM file. */
10030 static int
10031 xbm_file_p (data)
10032 Lisp_Object data;
10034 int w, h;
10035 return (STRINGP (data)
10036 && xbm_read_bitmap_data (SDATA (data),
10037 (SDATA (data)
10038 + SBYTES (data)),
10039 &w, &h, NULL));
10043 /* Fill image IMG which is used on frame F with pixmap data. Value is
10044 non-zero if successful. */
10046 static int
10047 xbm_load (f, img)
10048 struct frame *f;
10049 struct image *img;
10051 int success_p = 0;
10052 Lisp_Object file_name;
10054 xassert (xbm_image_p (img->spec));
10056 /* If IMG->spec specifies a file name, create a non-file spec from it. */
10057 file_name = image_spec_value (img->spec, QCfile, NULL);
10058 if (STRINGP (file_name))
10060 Lisp_Object file;
10061 char *contents;
10062 int size;
10063 struct gcpro gcpro1;
10065 file = x_find_image_file (file_name);
10066 GCPRO1 (file);
10067 if (!STRINGP (file))
10069 image_error ("Cannot find image file `%s'", file_name, Qnil);
10070 UNGCPRO;
10071 return 0;
10074 contents = slurp_file (SDATA (file), &size);
10075 if (contents == NULL)
10077 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10078 UNGCPRO;
10079 return 0;
10082 success_p = xbm_load_image (f, img, contents, contents + size);
10083 UNGCPRO;
10085 else
10087 struct image_keyword fmt[XBM_LAST];
10088 Lisp_Object data;
10089 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
10090 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
10091 char *bits;
10092 int parsed_p;
10093 int in_memory_file_p = 0;
10095 /* See if data looks like an in-memory XBM file. */
10096 data = image_spec_value (img->spec, QCdata, NULL);
10097 in_memory_file_p = xbm_file_p (data);
10099 /* Parse the image specification. */
10100 bcopy (xbm_format, fmt, sizeof fmt);
10101 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
10102 xassert (parsed_p);
10104 /* Get specified width, and height. */
10105 if (!in_memory_file_p)
10107 img->width = XFASTINT (fmt[XBM_WIDTH].value);
10108 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
10109 xassert (img->width > 0 && img->height > 0);
10112 /* Get foreground and background colors, maybe allocate colors. */
10113 if (fmt[XBM_FOREGROUND].count
10114 && STRINGP (fmt[XBM_FOREGROUND].value))
10115 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
10116 foreground);
10117 if (fmt[XBM_BACKGROUND].count
10118 && STRINGP (fmt[XBM_BACKGROUND].value))
10119 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
10120 background);
10122 if (in_memory_file_p)
10123 success_p = xbm_load_image (f, img, SDATA (data),
10124 (SDATA (data)
10125 + SBYTES (data)));
10126 else
10128 if (VECTORP (data))
10130 int i;
10131 char *p;
10132 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
10134 p = bits = (char *) alloca (nbytes * img->height);
10135 for (i = 0; i < img->height; ++i, p += nbytes)
10137 Lisp_Object line = XVECTOR (data)->contents[i];
10138 if (STRINGP (line))
10139 bcopy (SDATA (line), p, nbytes);
10140 else
10141 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
10144 else if (STRINGP (data))
10145 bits = SDATA (data);
10146 else
10147 bits = XBOOL_VECTOR (data)->data;
10149 /* Create the pixmap. */
10150 img->pixmap
10151 = w32_create_pixmap_from_bitmap_data (img->width, img->height,
10152 bits);
10154 if (img->pixmap)
10155 success_p = 1;
10156 else
10158 image_error ("Unable to create pixmap for XBM image `%s'",
10159 img->spec, Qnil);
10160 x_clear_image (f, img);
10165 return success_p;
10170 /***********************************************************************
10171 XPM images
10172 ***********************************************************************/
10174 #if HAVE_XPM
10176 static int xpm_image_p P_ ((Lisp_Object object));
10177 static int xpm_load P_ ((struct frame *f, struct image *img));
10178 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
10180 #include "X11/xpm.h"
10182 /* The symbol `xpm' identifying XPM-format images. */
10184 Lisp_Object Qxpm;
10186 /* Indices of image specification fields in xpm_format, below. */
10188 enum xpm_keyword_index
10190 XPM_TYPE,
10191 XPM_FILE,
10192 XPM_DATA,
10193 XPM_ASCENT,
10194 XPM_MARGIN,
10195 XPM_RELIEF,
10196 XPM_ALGORITHM,
10197 XPM_HEURISTIC_MASK,
10198 XPM_MASK,
10199 XPM_COLOR_SYMBOLS,
10200 XPM_BACKGROUND,
10201 XPM_LAST
10204 /* Vector of image_keyword structures describing the format
10205 of valid XPM image specifications. */
10207 static struct image_keyword xpm_format[XPM_LAST] =
10209 {":type", IMAGE_SYMBOL_VALUE, 1},
10210 {":file", IMAGE_STRING_VALUE, 0},
10211 {":data", IMAGE_STRING_VALUE, 0},
10212 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10213 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10214 {":relief", IMAGE_INTEGER_VALUE, 0},
10215 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10216 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10217 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10218 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10219 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
10222 /* Structure describing the image type XPM. */
10224 static struct image_type xpm_type =
10226 &Qxpm,
10227 xpm_image_p,
10228 xpm_load,
10229 x_clear_image,
10230 NULL
10234 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
10235 for XPM images. Such a list must consist of conses whose car and
10236 cdr are strings. */
10238 static int
10239 xpm_valid_color_symbols_p (color_symbols)
10240 Lisp_Object color_symbols;
10242 while (CONSP (color_symbols))
10244 Lisp_Object sym = XCAR (color_symbols);
10245 if (!CONSP (sym)
10246 || !STRINGP (XCAR (sym))
10247 || !STRINGP (XCDR (sym)))
10248 break;
10249 color_symbols = XCDR (color_symbols);
10252 return NILP (color_symbols);
10256 /* Value is non-zero if OBJECT is a valid XPM image specification. */
10258 static int
10259 xpm_image_p (object)
10260 Lisp_Object object;
10262 struct image_keyword fmt[XPM_LAST];
10263 bcopy (xpm_format, fmt, sizeof fmt);
10264 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
10265 /* Either `:file' or `:data' must be present. */
10266 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
10267 /* Either no `:color-symbols' or it's a list of conses
10268 whose car and cdr are strings. */
10269 && (fmt[XPM_COLOR_SYMBOLS].count == 0
10270 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
10271 && (fmt[XPM_ASCENT].count == 0
10272 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
10276 /* Load image IMG which will be displayed on frame F. Value is
10277 non-zero if successful. */
10279 static int
10280 xpm_load (f, img)
10281 struct frame *f;
10282 struct image *img;
10284 int rc, i;
10285 XpmAttributes attrs;
10286 Lisp_Object specified_file, color_symbols;
10288 /* Configure the XPM lib. Use the visual of frame F. Allocate
10289 close colors. Return colors allocated. */
10290 bzero (&attrs, sizeof attrs);
10291 attrs.visual = FRAME_X_VISUAL (f);
10292 attrs.colormap = FRAME_X_COLORMAP (f);
10293 attrs.valuemask |= XpmVisual;
10294 attrs.valuemask |= XpmColormap;
10295 attrs.valuemask |= XpmReturnAllocPixels;
10296 #ifdef XpmAllocCloseColors
10297 attrs.alloc_close_colors = 1;
10298 attrs.valuemask |= XpmAllocCloseColors;
10299 #else
10300 attrs.closeness = 600;
10301 attrs.valuemask |= XpmCloseness;
10302 #endif
10304 /* If image specification contains symbolic color definitions, add
10305 these to `attrs'. */
10306 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
10307 if (CONSP (color_symbols))
10309 Lisp_Object tail;
10310 XpmColorSymbol *xpm_syms;
10311 int i, size;
10313 attrs.valuemask |= XpmColorSymbols;
10315 /* Count number of symbols. */
10316 attrs.numsymbols = 0;
10317 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
10318 ++attrs.numsymbols;
10320 /* Allocate an XpmColorSymbol array. */
10321 size = attrs.numsymbols * sizeof *xpm_syms;
10322 xpm_syms = (XpmColorSymbol *) alloca (size);
10323 bzero (xpm_syms, size);
10324 attrs.colorsymbols = xpm_syms;
10326 /* Fill the color symbol array. */
10327 for (tail = color_symbols, i = 0;
10328 CONSP (tail);
10329 ++i, tail = XCDR (tail))
10331 Lisp_Object name = XCAR (XCAR (tail));
10332 Lisp_Object color = XCDR (XCAR (tail));
10333 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
10334 strcpy (xpm_syms[i].name, SDATA (name));
10335 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
10336 strcpy (xpm_syms[i].value, SDATA (color));
10340 /* Create a pixmap for the image, either from a file, or from a
10341 string buffer containing data in the same format as an XPM file. */
10342 BLOCK_INPUT;
10343 specified_file = image_spec_value (img->spec, QCfile, NULL);
10344 if (STRINGP (specified_file))
10346 Lisp_Object file = x_find_image_file (specified_file);
10347 if (!STRINGP (file))
10349 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10350 UNBLOCK_INPUT;
10351 return 0;
10354 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
10355 SDATA (file), &img->pixmap, &img->mask,
10356 &attrs);
10358 else
10360 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
10361 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
10362 SDATA (buffer),
10363 &img->pixmap, &img->mask,
10364 &attrs);
10366 UNBLOCK_INPUT;
10368 if (rc == XpmSuccess)
10370 /* Remember allocated colors. */
10371 img->ncolors = attrs.nalloc_pixels;
10372 img->colors = (unsigned long *) xmalloc (img->ncolors
10373 * sizeof *img->colors);
10374 for (i = 0; i < attrs.nalloc_pixels; ++i)
10375 img->colors[i] = attrs.alloc_pixels[i];
10377 img->width = attrs.width;
10378 img->height = attrs.height;
10379 xassert (img->width > 0 && img->height > 0);
10381 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
10382 BLOCK_INPUT;
10383 XpmFreeAttributes (&attrs);
10384 UNBLOCK_INPUT;
10386 else
10388 switch (rc)
10390 case XpmOpenFailed:
10391 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
10392 break;
10394 case XpmFileInvalid:
10395 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
10396 break;
10398 case XpmNoMemory:
10399 image_error ("Out of memory (%s)", img->spec, Qnil);
10400 break;
10402 case XpmColorFailed:
10403 image_error ("Color allocation error (%s)", img->spec, Qnil);
10404 break;
10406 default:
10407 image_error ("Unknown error (%s)", img->spec, Qnil);
10408 break;
10412 return rc == XpmSuccess;
10415 #endif /* HAVE_XPM != 0 */
10418 #if 0 /* TODO : Color tables on W32. */
10419 /***********************************************************************
10420 Color table
10421 ***********************************************************************/
10423 /* An entry in the color table mapping an RGB color to a pixel color. */
10425 struct ct_color
10427 int r, g, b;
10428 unsigned long pixel;
10430 /* Next in color table collision list. */
10431 struct ct_color *next;
10434 /* The bucket vector size to use. Must be prime. */
10436 #define CT_SIZE 101
10438 /* Value is a hash of the RGB color given by R, G, and B. */
10440 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
10442 /* The color hash table. */
10444 struct ct_color **ct_table;
10446 /* Number of entries in the color table. */
10448 int ct_colors_allocated;
10450 /* Function prototypes. */
10452 static void init_color_table P_ ((void));
10453 static void free_color_table P_ ((void));
10454 static unsigned long *colors_in_color_table P_ ((int *n));
10455 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
10456 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
10459 /* Initialize the color table. */
10461 static void
10462 init_color_table ()
10464 int size = CT_SIZE * sizeof (*ct_table);
10465 ct_table = (struct ct_color **) xmalloc (size);
10466 bzero (ct_table, size);
10467 ct_colors_allocated = 0;
10471 /* Free memory associated with the color table. */
10473 static void
10474 free_color_table ()
10476 int i;
10477 struct ct_color *p, *next;
10479 for (i = 0; i < CT_SIZE; ++i)
10480 for (p = ct_table[i]; p; p = next)
10482 next = p->next;
10483 xfree (p);
10486 xfree (ct_table);
10487 ct_table = NULL;
10491 /* Value is a pixel color for RGB color R, G, B on frame F. If an
10492 entry for that color already is in the color table, return the
10493 pixel color of that entry. Otherwise, allocate a new color for R,
10494 G, B, and make an entry in the color table. */
10496 static unsigned long
10497 lookup_rgb_color (f, r, g, b)
10498 struct frame *f;
10499 int r, g, b;
10501 unsigned hash = CT_HASH_RGB (r, g, b);
10502 int i = hash % CT_SIZE;
10503 struct ct_color *p;
10505 for (p = ct_table[i]; p; p = p->next)
10506 if (p->r == r && p->g == g && p->b == b)
10507 break;
10509 if (p == NULL)
10511 COLORREF color;
10512 Colormap cmap;
10513 int rc;
10515 color = PALETTERGB (r, g, b);
10517 ++ct_colors_allocated;
10519 p = (struct ct_color *) xmalloc (sizeof *p);
10520 p->r = r;
10521 p->g = g;
10522 p->b = b;
10523 p->pixel = color;
10524 p->next = ct_table[i];
10525 ct_table[i] = p;
10528 return p->pixel;
10532 /* Look up pixel color PIXEL which is used on frame F in the color
10533 table. If not already present, allocate it. Value is PIXEL. */
10535 static unsigned long
10536 lookup_pixel_color (f, pixel)
10537 struct frame *f;
10538 unsigned long pixel;
10540 int i = pixel % CT_SIZE;
10541 struct ct_color *p;
10543 for (p = ct_table[i]; p; p = p->next)
10544 if (p->pixel == pixel)
10545 break;
10547 if (p == NULL)
10549 XColor color;
10550 Colormap cmap;
10551 int rc;
10553 BLOCK_INPUT;
10555 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10556 color.pixel = pixel;
10557 XQueryColor (NULL, cmap, &color);
10558 rc = x_alloc_nearest_color (f, cmap, &color);
10559 UNBLOCK_INPUT;
10561 if (rc)
10563 ++ct_colors_allocated;
10565 p = (struct ct_color *) xmalloc (sizeof *p);
10566 p->r = color.red;
10567 p->g = color.green;
10568 p->b = color.blue;
10569 p->pixel = pixel;
10570 p->next = ct_table[i];
10571 ct_table[i] = p;
10573 else
10574 return FRAME_FOREGROUND_PIXEL (f);
10576 return p->pixel;
10580 /* Value is a vector of all pixel colors contained in the color table,
10581 allocated via xmalloc. Set *N to the number of colors. */
10583 static unsigned long *
10584 colors_in_color_table (n)
10585 int *n;
10587 int i, j;
10588 struct ct_color *p;
10589 unsigned long *colors;
10591 if (ct_colors_allocated == 0)
10593 *n = 0;
10594 colors = NULL;
10596 else
10598 colors = (unsigned long *) xmalloc (ct_colors_allocated
10599 * sizeof *colors);
10600 *n = ct_colors_allocated;
10602 for (i = j = 0; i < CT_SIZE; ++i)
10603 for (p = ct_table[i]; p; p = p->next)
10604 colors[j++] = p->pixel;
10607 return colors;
10610 #endif /* TODO */
10613 /***********************************************************************
10614 Algorithms
10615 ***********************************************************************/
10616 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
10617 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
10618 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
10619 static void XPutPixel (XImage *, int, int, COLORREF);
10621 /* Non-zero means draw a cross on images having `:conversion
10622 disabled'. */
10624 int cross_disabled_images;
10626 /* Edge detection matrices for different edge-detection
10627 strategies. */
10629 static int emboss_matrix[9] = {
10630 /* x - 1 x x + 1 */
10631 2, -1, 0, /* y - 1 */
10632 -1, 0, 1, /* y */
10633 0, 1, -2 /* y + 1 */
10636 static int laplace_matrix[9] = {
10637 /* x - 1 x x + 1 */
10638 1, 0, 0, /* y - 1 */
10639 0, 0, 0, /* y */
10640 0, 0, -1 /* y + 1 */
10643 /* Value is the intensity of the color whose red/green/blue values
10644 are R, G, and B. */
10646 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
10649 /* On frame F, return an array of XColor structures describing image
10650 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
10651 non-zero means also fill the red/green/blue members of the XColor
10652 structures. Value is a pointer to the array of XColors structures,
10653 allocated with xmalloc; it must be freed by the caller. */
10655 static XColor *
10656 x_to_xcolors (f, img, rgb_p)
10657 struct frame *f;
10658 struct image *img;
10659 int rgb_p;
10661 int x, y;
10662 XColor *colors, *p;
10663 HDC hdc, bmpdc;
10664 HGDIOBJ prev;
10666 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
10668 /* Load the image into a memory device context. */
10669 hdc = get_frame_dc (f);
10670 bmpdc = CreateCompatibleDC (hdc);
10671 release_frame_dc (f, hdc);
10672 prev = SelectObject (bmpdc, img->pixmap);
10674 /* Fill the `pixel' members of the XColor array. I wished there
10675 were an easy and portable way to circumvent XGetPixel. */
10676 p = colors;
10677 for (y = 0; y < img->height; ++y)
10679 XColor *row = p;
10681 for (x = 0; x < img->width; ++x, ++p)
10683 /* TODO: palette support needed here? */
10684 p->pixel = GetPixel (bmpdc, x, y);
10686 if (rgb_p)
10688 p->red = 256 * GetRValue (p->pixel);
10689 p->green = 256 * GetGValue (p->pixel);
10690 p->blue = 256 * GetBValue (p->pixel);
10695 SelectObject (bmpdc, prev);
10696 DeleteDC (bmpdc);
10698 return colors;
10701 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
10702 created with CreateDIBSection, with the pointer to the bit values
10703 stored in ximg->data. */
10705 static void XPutPixel (ximg, x, y, color)
10706 XImage * ximg;
10707 int x, y;
10708 COLORREF color;
10710 int width = ximg->info.bmiHeader.biWidth;
10711 int height = ximg->info.bmiHeader.biHeight;
10712 int rowbytes = width * 3;
10713 unsigned char * pixel;
10715 /* Don't support putting pixels in images with palettes. */
10716 xassert (ximg->info.bmiHeader.biBitCount == 24);
10718 /* Ensure scanlines are aligned on 4 byte boundaries. */
10719 if (rowbytes % 4)
10720 rowbytes += 4 - (rowbytes % 4);
10722 pixel = ximg->data + y * rowbytes + x * 3;
10723 *pixel = GetRValue (color);
10724 *(pixel + 1) = GetGValue (color);
10725 *(pixel + 2) = GetBValue (color);
10729 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
10730 RGB members are set. F is the frame on which this all happens.
10731 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
10733 static void
10734 x_from_xcolors (f, img, colors)
10735 struct frame *f;
10736 struct image *img;
10737 XColor *colors;
10739 int x, y;
10740 XImage *oimg;
10741 Pixmap pixmap;
10742 XColor *p;
10743 #if 0 /* TODO: color tables. */
10744 init_color_table ();
10745 #endif
10746 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
10747 &oimg, &pixmap);
10748 p = colors;
10749 for (y = 0; y < img->height; ++y)
10750 for (x = 0; x < img->width; ++x, ++p)
10752 unsigned long pixel;
10753 #if 0 /* TODO: color tables. */
10754 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
10755 #else
10756 pixel = PALETTERGB (p->red / 256, p->green / 256, p->blue / 256);
10757 #endif
10758 XPutPixel (oimg, x, y, pixel);
10761 xfree (colors);
10762 x_clear_image_1 (f, img, 1, 0, 1);
10764 x_put_x_image (f, oimg, pixmap, img->width, img->height);
10765 x_destroy_x_image (oimg);
10766 img->pixmap = pixmap;
10767 #if 0 /* TODO: color tables. */
10768 img->colors = colors_in_color_table (&img->ncolors);
10769 free_color_table ();
10770 #endif
10774 /* On frame F, perform edge-detection on image IMG.
10776 MATRIX is a nine-element array specifying the transformation
10777 matrix. See emboss_matrix for an example.
10779 COLOR_ADJUST is a color adjustment added to each pixel of the
10780 outgoing image. */
10782 static void
10783 x_detect_edges (f, img, matrix, color_adjust)
10784 struct frame *f;
10785 struct image *img;
10786 int matrix[9], color_adjust;
10788 XColor *colors = x_to_xcolors (f, img, 1);
10789 XColor *new, *p;
10790 int x, y, i, sum;
10792 for (i = sum = 0; i < 9; ++i)
10793 sum += abs (matrix[i]);
10795 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
10797 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
10799 for (y = 0; y < img->height; ++y)
10801 p = COLOR (new, 0, y);
10802 p->red = p->green = p->blue = 0xffff/2;
10803 p = COLOR (new, img->width - 1, y);
10804 p->red = p->green = p->blue = 0xffff/2;
10807 for (x = 1; x < img->width - 1; ++x)
10809 p = COLOR (new, x, 0);
10810 p->red = p->green = p->blue = 0xffff/2;
10811 p = COLOR (new, x, img->height - 1);
10812 p->red = p->green = p->blue = 0xffff/2;
10815 for (y = 1; y < img->height - 1; ++y)
10817 p = COLOR (new, 1, y);
10819 for (x = 1; x < img->width - 1; ++x, ++p)
10821 int r, g, b, y1, x1;
10823 r = g = b = i = 0;
10824 for (y1 = y - 1; y1 < y + 2; ++y1)
10825 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
10826 if (matrix[i])
10828 XColor *t = COLOR (colors, x1, y1);
10829 r += matrix[i] * t->red;
10830 g += matrix[i] * t->green;
10831 b += matrix[i] * t->blue;
10834 r = (r / sum + color_adjust) & 0xffff;
10835 g = (g / sum + color_adjust) & 0xffff;
10836 b = (b / sum + color_adjust) & 0xffff;
10837 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
10841 xfree (colors);
10842 x_from_xcolors (f, img, new);
10844 #undef COLOR
10848 /* Perform the pre-defined `emboss' edge-detection on image IMG
10849 on frame F. */
10851 static void
10852 x_emboss (f, img)
10853 struct frame *f;
10854 struct image *img;
10856 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
10860 /* Transform image IMG which is used on frame F with a Laplace
10861 edge-detection algorithm. The result is an image that can be used
10862 to draw disabled buttons, for example. */
10864 static void
10865 x_laplace (f, img)
10866 struct frame *f;
10867 struct image *img;
10869 x_detect_edges (f, img, laplace_matrix, 45000);
10873 /* Perform edge-detection on image IMG on frame F, with specified
10874 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
10876 MATRIX must be either
10878 - a list of at least 9 numbers in row-major form
10879 - a vector of at least 9 numbers
10881 COLOR_ADJUST nil means use a default; otherwise it must be a
10882 number. */
10884 static void
10885 x_edge_detection (f, img, matrix, color_adjust)
10886 struct frame *f;
10887 struct image *img;
10888 Lisp_Object matrix, color_adjust;
10890 int i = 0;
10891 int trans[9];
10893 if (CONSP (matrix))
10895 for (i = 0;
10896 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
10897 ++i, matrix = XCDR (matrix))
10898 trans[i] = XFLOATINT (XCAR (matrix));
10900 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
10902 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
10903 trans[i] = XFLOATINT (AREF (matrix, i));
10906 if (NILP (color_adjust))
10907 color_adjust = make_number (0xffff / 2);
10909 if (i == 9 && NUMBERP (color_adjust))
10910 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
10914 /* Transform image IMG on frame F so that it looks disabled. */
10916 static void
10917 x_disable_image (f, img)
10918 struct frame *f;
10919 struct image *img;
10921 struct w32_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
10923 if (dpyinfo->n_planes * dpyinfo->n_cbits >= 2)
10925 /* Color (or grayscale). Convert to gray, and equalize. Just
10926 drawing such images with a stipple can look very odd, so
10927 we're using this method instead. */
10928 XColor *colors = x_to_xcolors (f, img, 1);
10929 XColor *p, *end;
10930 const int h = 15000;
10931 const int l = 30000;
10933 for (p = colors, end = colors + img->width * img->height;
10934 p < end;
10935 ++p)
10937 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
10938 int i2 = (0xffff - h - l) * i / 0xffff + l;
10939 p->red = p->green = p->blue = i2;
10942 x_from_xcolors (f, img, colors);
10945 /* Draw a cross over the disabled image, if we must or if we
10946 should. */
10947 if (dpyinfo->n_planes * dpyinfo->n_cbits < 2 || cross_disabled_images)
10949 HDC hdc, bmpdc;
10950 HGDIOBJ prev;
10952 hdc = get_frame_dc (f);
10953 bmpdc = CreateCompatibleDC (hdc);
10954 release_frame_dc (f, hdc);
10956 prev = SelectObject (bmpdc, img->pixmap);
10958 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
10959 MoveToEx (bmpdc, 0, 0, NULL);
10960 LineTo (bmpdc, img->width - 1, img->height - 1);
10961 MoveToEx (bmpdc, 0, img->height - 1, NULL);
10962 LineTo (bmpdc, img->width - 1, 0);
10964 if (img->mask)
10966 SelectObject (bmpdc, img->mask);
10967 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
10968 MoveToEx (bmpdc, 0, 0, NULL);
10969 LineTo (bmpdc, img->width - 1, img->height - 1);
10970 MoveToEx (bmpdc, 0, img->height - 1, NULL);
10971 LineTo (bmpdc, img->width - 1, 0);
10973 SelectObject (bmpdc, prev);
10974 DeleteDC (bmpdc);
10979 /* Build a mask for image IMG which is used on frame F. FILE is the
10980 name of an image file, for error messages. HOW determines how to
10981 determine the background color of IMG. If it is a list '(R G B)',
10982 with R, G, and B being integers >= 0, take that as the color of the
10983 background. Otherwise, determine the background color of IMG
10984 heuristically. Value is non-zero if successful. */
10986 static int
10987 x_build_heuristic_mask (f, img, how)
10988 struct frame *f;
10989 struct image *img;
10990 Lisp_Object how;
10992 HDC img_dc, frame_dc;
10993 HGDIOBJ prev;
10994 char *mask_img;
10995 int x, y, rc, use_img_background;
10996 unsigned long bg = 0;
10997 int row_width;
10999 if (img->mask)
11001 DeleteObject (img->mask);
11002 img->mask = NULL;
11003 img->background_transparent_valid = 0;
11006 /* Create the bit array serving as mask. */
11007 row_width = (img->width + 7) / 8;
11008 mask_img = xmalloc (row_width * img->height);
11009 bzero (mask_img, row_width * img->height);
11011 /* Create a memory device context for IMG->pixmap. */
11012 frame_dc = get_frame_dc (f);
11013 img_dc = CreateCompatibleDC (frame_dc);
11014 release_frame_dc (f, frame_dc);
11015 prev = SelectObject (img_dc, img->pixmap);
11017 /* Determine the background color of img_dc. If HOW is `(R G B)'
11018 take that as color. Otherwise, use the image's background color. */
11019 use_img_background = 1;
11021 if (CONSP (how))
11023 int rgb[3], i;
11025 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
11027 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
11028 how = XCDR (how);
11031 if (i == 3 && NILP (how))
11033 char color_name[30];
11034 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
11035 bg = x_alloc_image_color (f, img, build_string (color_name), 0);
11036 use_img_background = 0;
11040 if (use_img_background)
11041 bg = four_corners_best (img_dc, img->width, img->height);
11043 /* Set all bits in mask_img to 1 whose color in ximg is different
11044 from the background color bg. */
11045 for (y = 0; y < img->height; ++y)
11046 for (x = 0; x < img->width; ++x)
11048 COLORREF p = GetPixel (img_dc, x, y);
11049 if (p != bg)
11050 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
11053 /* Create the mask image. */
11054 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
11055 mask_img);
11057 /* Fill in the background_transparent field while we have the mask handy. */
11058 SelectObject (img_dc, img->mask);
11060 image_background_transparent (img, f, img_dc);
11062 /* Put mask_img into img->mask. */
11063 x_destroy_x_image (mask_img);
11064 SelectObject (img_dc, prev);
11065 DeleteDC (img_dc);
11067 return 1;
11071 /***********************************************************************
11072 PBM (mono, gray, color)
11073 ***********************************************************************/
11075 static int pbm_image_p P_ ((Lisp_Object object));
11076 static int pbm_load P_ ((struct frame *f, struct image *img));
11077 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
11079 /* The symbol `pbm' identifying images of this type. */
11081 Lisp_Object Qpbm;
11083 /* Indices of image specification fields in gs_format, below. */
11085 enum pbm_keyword_index
11087 PBM_TYPE,
11088 PBM_FILE,
11089 PBM_DATA,
11090 PBM_ASCENT,
11091 PBM_MARGIN,
11092 PBM_RELIEF,
11093 PBM_ALGORITHM,
11094 PBM_HEURISTIC_MASK,
11095 PBM_MASK,
11096 PBM_FOREGROUND,
11097 PBM_BACKGROUND,
11098 PBM_LAST
11101 /* Vector of image_keyword structures describing the format
11102 of valid user-defined image specifications. */
11104 static struct image_keyword pbm_format[PBM_LAST] =
11106 {":type", IMAGE_SYMBOL_VALUE, 1},
11107 {":file", IMAGE_STRING_VALUE, 0},
11108 {":data", IMAGE_STRING_VALUE, 0},
11109 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11110 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11111 {":relief", IMAGE_INTEGER_VALUE, 0},
11112 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11113 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11114 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11115 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
11116 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11119 /* Structure describing the image type `pbm'. */
11121 static struct image_type pbm_type =
11123 &Qpbm,
11124 pbm_image_p,
11125 pbm_load,
11126 x_clear_image,
11127 NULL
11131 /* Return non-zero if OBJECT is a valid PBM image specification. */
11133 static int
11134 pbm_image_p (object)
11135 Lisp_Object object;
11137 struct image_keyword fmt[PBM_LAST];
11139 bcopy (pbm_format, fmt, sizeof fmt);
11141 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
11142 || (fmt[PBM_ASCENT].count
11143 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
11144 return 0;
11146 /* Must specify either :data or :file. */
11147 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
11151 /* Scan a decimal number from *S and return it. Advance *S while
11152 reading the number. END is the end of the string. Value is -1 at
11153 end of input. */
11155 static int
11156 pbm_scan_number (s, end)
11157 unsigned char **s, *end;
11159 int c, val = -1;
11161 while (*s < end)
11163 /* Skip white-space. */
11164 while (*s < end && (c = *(*s)++, isspace (c)))
11167 if (c == '#')
11169 /* Skip comment to end of line. */
11170 while (*s < end && (c = *(*s)++, c != '\n'))
11173 else if (isdigit (c))
11175 /* Read decimal number. */
11176 val = c - '0';
11177 while (*s < end && (c = *(*s)++, isdigit (c)))
11178 val = 10 * val + c - '0';
11179 break;
11181 else
11182 break;
11185 return val;
11189 /* Read FILE into memory. Value is a pointer to a buffer allocated
11190 with xmalloc holding FILE's contents. Value is null if an error
11191 occurred. *SIZE is set to the size of the file. */
11193 static char *
11194 pbm_read_file (file, size)
11195 Lisp_Object file;
11196 int *size;
11198 FILE *fp = NULL;
11199 char *buf = NULL;
11200 struct stat st;
11202 if (stat (SDATA (file), &st) == 0
11203 && (fp = fopen (SDATA (file), "r")) != NULL
11204 && (buf = (char *) xmalloc (st.st_size),
11205 fread (buf, 1, st.st_size, fp) == st.st_size))
11207 *size = st.st_size;
11208 fclose (fp);
11210 else
11212 if (fp)
11213 fclose (fp);
11214 if (buf)
11216 xfree (buf);
11217 buf = NULL;
11221 return buf;
11225 /* Load PBM image IMG for use on frame F. */
11227 static int
11228 pbm_load (f, img)
11229 struct frame *f;
11230 struct image *img;
11232 int raw_p, x, y;
11233 int width, height, max_color_idx = 0;
11234 XImage *ximg;
11235 Lisp_Object file, specified_file;
11236 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
11237 struct gcpro gcpro1;
11238 unsigned char *contents = NULL;
11239 unsigned char *end, *p;
11240 int size;
11242 specified_file = image_spec_value (img->spec, QCfile, NULL);
11243 file = Qnil;
11244 GCPRO1 (file);
11246 if (STRINGP (specified_file))
11248 file = x_find_image_file (specified_file);
11249 if (!STRINGP (file))
11251 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11252 UNGCPRO;
11253 return 0;
11256 contents = slurp_file (SDATA (file), &size);
11257 if (contents == NULL)
11259 image_error ("Error reading `%s'", file, Qnil);
11260 UNGCPRO;
11261 return 0;
11264 p = contents;
11265 end = contents + size;
11267 else
11269 Lisp_Object data;
11270 data = image_spec_value (img->spec, QCdata, NULL);
11271 p = SDATA (data);
11272 end = p + SBYTES (data);
11275 /* Check magic number. */
11276 if (end - p < 2 || *p++ != 'P')
11278 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11279 error:
11280 xfree (contents);
11281 UNGCPRO;
11282 return 0;
11285 switch (*p++)
11287 case '1':
11288 raw_p = 0, type = PBM_MONO;
11289 break;
11291 case '2':
11292 raw_p = 0, type = PBM_GRAY;
11293 break;
11295 case '3':
11296 raw_p = 0, type = PBM_COLOR;
11297 break;
11299 case '4':
11300 raw_p = 1, type = PBM_MONO;
11301 break;
11303 case '5':
11304 raw_p = 1, type = PBM_GRAY;
11305 break;
11307 case '6':
11308 raw_p = 1, type = PBM_COLOR;
11309 break;
11311 default:
11312 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11313 goto error;
11316 /* Read width, height, maximum color-component. Characters
11317 starting with `#' up to the end of a line are ignored. */
11318 width = pbm_scan_number (&p, end);
11319 height = pbm_scan_number (&p, end);
11321 if (type != PBM_MONO)
11323 max_color_idx = pbm_scan_number (&p, end);
11324 if (raw_p && max_color_idx > 255)
11325 max_color_idx = 255;
11328 if (width < 0
11329 || height < 0
11330 || (type != PBM_MONO && max_color_idx < 0))
11331 goto error;
11333 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11334 goto error;
11336 #if 0 /* TODO: color tables. */
11337 /* Initialize the color hash table. */
11338 init_color_table ();
11339 #endif
11341 if (type == PBM_MONO)
11343 int c = 0, g;
11344 struct image_keyword fmt[PBM_LAST];
11345 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
11346 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
11348 /* Parse the image specification. */
11349 bcopy (pbm_format, fmt, sizeof fmt);
11350 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
11352 /* Get foreground and background colors, maybe allocate colors. */
11353 if (fmt[PBM_FOREGROUND].count
11354 && STRINGP (fmt[PBM_FOREGROUND].value))
11355 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
11356 if (fmt[PBM_BACKGROUND].count
11357 && STRINGP (fmt[PBM_BACKGROUND].value))
11359 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
11360 img->background = bg;
11361 img->background_valid = 1;
11364 for (y = 0; y < height; ++y)
11365 for (x = 0; x < width; ++x)
11367 if (raw_p)
11369 if ((x & 7) == 0)
11370 c = *p++;
11371 g = c & 0x80;
11372 c <<= 1;
11374 else
11375 g = pbm_scan_number (&p, end);
11377 XPutPixel (ximg, x, y, g ? fg : bg);
11380 else
11382 for (y = 0; y < height; ++y)
11383 for (x = 0; x < width; ++x)
11385 int r, g, b;
11387 if (type == PBM_GRAY)
11388 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
11389 else if (raw_p)
11391 r = *p++;
11392 g = *p++;
11393 b = *p++;
11395 else
11397 r = pbm_scan_number (&p, end);
11398 g = pbm_scan_number (&p, end);
11399 b = pbm_scan_number (&p, end);
11402 if (r < 0 || g < 0 || b < 0)
11404 x_destroy_x_image (ximg);
11405 image_error ("Invalid pixel value in image `%s'",
11406 img->spec, Qnil);
11407 goto error;
11410 /* RGB values are now in the range 0..max_color_idx.
11411 Scale this to the range 0..0xff supported by W32. */
11412 r = (int) ((double) r * 255 / max_color_idx);
11413 g = (int) ((double) g * 255 / max_color_idx);
11414 b = (int) ((double) b * 255 / max_color_idx);
11415 XPutPixel (ximg, x, y,
11416 #if 0 /* TODO: color tables. */
11417 lookup_rgb_color (f, r, g, b));
11418 #else
11419 PALETTERGB (r, g, b));
11420 #endif
11424 #if 0 /* TODO: color tables. */
11425 /* Store in IMG->colors the colors allocated for the image, and
11426 free the color table. */
11427 img->colors = colors_in_color_table (&img->ncolors);
11428 free_color_table ();
11429 #endif
11430 /* Maybe fill in the background field while we have ximg handy. */
11431 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11432 IMAGE_BACKGROUND (img, f, ximg);
11434 /* Put the image into a pixmap. */
11435 x_put_x_image (f, ximg, img->pixmap, width, height);
11436 x_destroy_x_image (ximg);
11438 img->width = width;
11439 img->height = height;
11441 UNGCPRO;
11442 xfree (contents);
11443 return 1;
11447 /***********************************************************************
11449 ***********************************************************************/
11451 #if HAVE_PNG
11453 #include <png.h>
11455 /* Function prototypes. */
11457 static int png_image_p P_ ((Lisp_Object object));
11458 static int png_load P_ ((struct frame *f, struct image *img));
11460 /* The symbol `png' identifying images of this type. */
11462 Lisp_Object Qpng;
11464 /* Indices of image specification fields in png_format, below. */
11466 enum png_keyword_index
11468 PNG_TYPE,
11469 PNG_DATA,
11470 PNG_FILE,
11471 PNG_ASCENT,
11472 PNG_MARGIN,
11473 PNG_RELIEF,
11474 PNG_ALGORITHM,
11475 PNG_HEURISTIC_MASK,
11476 PNG_MASK,
11477 PNG_BACKGROUND,
11478 PNG_LAST
11481 /* Vector of image_keyword structures describing the format
11482 of valid user-defined image specifications. */
11484 static struct image_keyword png_format[PNG_LAST] =
11486 {":type", IMAGE_SYMBOL_VALUE, 1},
11487 {":data", IMAGE_STRING_VALUE, 0},
11488 {":file", IMAGE_STRING_VALUE, 0},
11489 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11490 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11491 {":relief", IMAGE_INTEGER_VALUE, 0},
11492 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11493 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11494 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11495 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11498 /* Structure describing the image type `png'. */
11500 static struct image_type png_type =
11502 &Qpng,
11503 png_image_p,
11504 png_load,
11505 x_clear_image,
11506 NULL
11510 /* Return non-zero if OBJECT is a valid PNG image specification. */
11512 static int
11513 png_image_p (object)
11514 Lisp_Object object;
11516 struct image_keyword fmt[PNG_LAST];
11517 bcopy (png_format, fmt, sizeof fmt);
11519 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
11520 || (fmt[PNG_ASCENT].count
11521 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
11522 return 0;
11524 /* Must specify either the :data or :file keyword. */
11525 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
11529 /* Error and warning handlers installed when the PNG library
11530 is initialized. */
11532 static void
11533 my_png_error (png_ptr, msg)
11534 png_struct *png_ptr;
11535 char *msg;
11537 xassert (png_ptr != NULL);
11538 image_error ("PNG error: %s", build_string (msg), Qnil);
11539 longjmp (png_ptr->jmpbuf, 1);
11543 static void
11544 my_png_warning (png_ptr, msg)
11545 png_struct *png_ptr;
11546 char *msg;
11548 xassert (png_ptr != NULL);
11549 image_error ("PNG warning: %s", build_string (msg), Qnil);
11552 /* Memory source for PNG decoding. */
11554 struct png_memory_storage
11556 unsigned char *bytes; /* The data */
11557 size_t len; /* How big is it? */
11558 int index; /* Where are we? */
11562 /* Function set as reader function when reading PNG image from memory.
11563 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
11564 bytes from the input to DATA. */
11566 static void
11567 png_read_from_memory (png_ptr, data, length)
11568 png_structp png_ptr;
11569 png_bytep data;
11570 png_size_t length;
11572 struct png_memory_storage *tbr
11573 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
11575 if (length > tbr->len - tbr->index)
11576 png_error (png_ptr, "Read error");
11578 bcopy (tbr->bytes + tbr->index, data, length);
11579 tbr->index = tbr->index + length;
11582 /* Load PNG image IMG for use on frame F. Value is non-zero if
11583 successful. */
11585 static int
11586 png_load (f, img)
11587 struct frame *f;
11588 struct image *img;
11590 Lisp_Object file, specified_file;
11591 Lisp_Object specified_data;
11592 int x, y, i;
11593 XImage *ximg, *mask_img = NULL;
11594 struct gcpro gcpro1;
11595 png_struct *png_ptr = NULL;
11596 png_info *info_ptr = NULL, *end_info = NULL;
11597 FILE *volatile fp = NULL;
11598 png_byte sig[8];
11599 png_byte *volatile pixels = NULL;
11600 png_byte **volatile rows = NULL;
11601 png_uint_32 width, height;
11602 int bit_depth, color_type, interlace_type;
11603 png_byte channels;
11604 png_uint_32 row_bytes;
11605 int transparent_p;
11606 char *gamma_str;
11607 double screen_gamma, image_gamma;
11608 int intent;
11609 struct png_memory_storage tbr; /* Data to be read */
11611 /* Find out what file to load. */
11612 specified_file = image_spec_value (img->spec, QCfile, NULL);
11613 specified_data = image_spec_value (img->spec, QCdata, NULL);
11614 file = Qnil;
11615 GCPRO1 (file);
11617 if (NILP (specified_data))
11619 file = x_find_image_file (specified_file);
11620 if (!STRINGP (file))
11622 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11623 UNGCPRO;
11624 return 0;
11627 /* Open the image file. */
11628 fp = fopen (SDATA (file), "rb");
11629 if (!fp)
11631 image_error ("Cannot open image file `%s'", file, Qnil);
11632 UNGCPRO;
11633 fclose (fp);
11634 return 0;
11637 /* Check PNG signature. */
11638 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
11639 || !png_check_sig (sig, sizeof sig))
11641 image_error ("Not a PNG file:` %s'", file, Qnil);
11642 UNGCPRO;
11643 fclose (fp);
11644 return 0;
11647 else
11649 /* Read from memory. */
11650 tbr.bytes = SDATA (specified_data);
11651 tbr.len = SBYTES (specified_data);
11652 tbr.index = 0;
11654 /* Check PNG signature. */
11655 if (tbr.len < sizeof sig
11656 || !png_check_sig (tbr.bytes, sizeof sig))
11658 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
11659 UNGCPRO;
11660 return 0;
11663 /* Need to skip past the signature. */
11664 tbr.bytes += sizeof (sig);
11667 /* Initialize read and info structs for PNG lib. */
11668 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
11669 my_png_error, my_png_warning);
11670 if (!png_ptr)
11672 if (fp) fclose (fp);
11673 UNGCPRO;
11674 return 0;
11677 info_ptr = png_create_info_struct (png_ptr);
11678 if (!info_ptr)
11680 png_destroy_read_struct (&png_ptr, NULL, NULL);
11681 if (fp) fclose (fp);
11682 UNGCPRO;
11683 return 0;
11686 end_info = png_create_info_struct (png_ptr);
11687 if (!end_info)
11689 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
11690 if (fp) fclose (fp);
11691 UNGCPRO;
11692 return 0;
11695 /* Set error jump-back. We come back here when the PNG library
11696 detects an error. */
11697 if (setjmp (png_ptr->jmpbuf))
11699 error:
11700 if (png_ptr)
11701 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11702 xfree (pixels);
11703 xfree (rows);
11704 if (fp) fclose (fp);
11705 UNGCPRO;
11706 return 0;
11709 /* Read image info. */
11710 if (!NILP (specified_data))
11711 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
11712 else
11713 png_init_io (png_ptr, fp);
11715 png_set_sig_bytes (png_ptr, sizeof sig);
11716 png_read_info (png_ptr, info_ptr);
11717 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
11718 &interlace_type, NULL, NULL);
11720 /* If image contains simply transparency data, we prefer to
11721 construct a clipping mask. */
11722 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
11723 transparent_p = 1;
11724 else
11725 transparent_p = 0;
11727 /* This function is easier to write if we only have to handle
11728 one data format: RGB or RGBA with 8 bits per channel. Let's
11729 transform other formats into that format. */
11731 /* Strip more than 8 bits per channel. */
11732 if (bit_depth == 16)
11733 png_set_strip_16 (png_ptr);
11735 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
11736 if available. */
11737 png_set_expand (png_ptr);
11739 /* Convert grayscale images to RGB. */
11740 if (color_type == PNG_COLOR_TYPE_GRAY
11741 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
11742 png_set_gray_to_rgb (png_ptr);
11744 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
11745 gamma_str = getenv ("SCREEN_GAMMA");
11746 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
11748 /* Tell the PNG lib to handle gamma correction for us. */
11750 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
11751 if (png_get_sRGB (png_ptr, info_ptr, &intent))
11752 /* There is a special chunk in the image specifying the gamma. */
11753 png_set_sRGB (png_ptr, info_ptr, intent);
11754 else
11755 #endif
11756 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
11757 /* Image contains gamma information. */
11758 png_set_gamma (png_ptr, screen_gamma, image_gamma);
11759 else
11760 /* Use a default of 0.5 for the image gamma. */
11761 png_set_gamma (png_ptr, screen_gamma, 0.5);
11763 /* Handle alpha channel by combining the image with a background
11764 color. Do this only if a real alpha channel is supplied. For
11765 simple transparency, we prefer a clipping mask. */
11766 if (!transparent_p)
11768 png_color_16 *image_background;
11769 Lisp_Object specified_bg
11770 = image_spec_value (img->spec, QCbackground, NULL);
11773 if (STRINGP (specified_bg))
11774 /* The user specified `:background', use that. */
11776 COLORREF color;
11777 if (w32_defined_color (f, SDATA (specified_bg), &color, 0))
11779 png_color_16 user_bg;
11781 bzero (&user_bg, sizeof user_bg);
11782 user_bg.red = color.red;
11783 user_bg.green = color.green;
11784 user_bg.blue = color.blue;
11786 png_set_background (png_ptr, &user_bg,
11787 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11790 else if (png_get_bKGD (png_ptr, info_ptr, &image_background))
11791 /* Image contains a background color with which to
11792 combine the image. */
11793 png_set_background (png_ptr, image_background,
11794 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
11795 else
11797 /* Image does not contain a background color with which
11798 to combine the image data via an alpha channel. Use
11799 the frame's background instead. */
11800 XColor color;
11801 Colormap cmap;
11802 png_color_16 frame_background;
11804 cmap = FRAME_X_COLORMAP (f);
11805 color.pixel = FRAME_BACKGROUND_PIXEL (f);
11806 x_query_color (f, &color);
11808 bzero (&frame_background, sizeof frame_background);
11809 frame_background.red = color.red;
11810 frame_background.green = color.green;
11811 frame_background.blue = color.blue;
11813 png_set_background (png_ptr, &frame_background,
11814 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11818 /* Update info structure. */
11819 png_read_update_info (png_ptr, info_ptr);
11821 /* Get number of channels. Valid values are 1 for grayscale images
11822 and images with a palette, 2 for grayscale images with transparency
11823 information (alpha channel), 3 for RGB images, and 4 for RGB
11824 images with alpha channel, i.e. RGBA. If conversions above were
11825 sufficient we should only have 3 or 4 channels here. */
11826 channels = png_get_channels (png_ptr, info_ptr);
11827 xassert (channels == 3 || channels == 4);
11829 /* Number of bytes needed for one row of the image. */
11830 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
11832 /* Allocate memory for the image. */
11833 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
11834 rows = (png_byte **) xmalloc (height * sizeof *rows);
11835 for (i = 0; i < height; ++i)
11836 rows[i] = pixels + i * row_bytes;
11838 /* Read the entire image. */
11839 png_read_image (png_ptr, rows);
11840 png_read_end (png_ptr, info_ptr);
11841 if (fp)
11843 fclose (fp);
11844 fp = NULL;
11847 /* Create the X image and pixmap. */
11848 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11849 &img->pixmap))
11850 goto error;
11852 /* Create an image and pixmap serving as mask if the PNG image
11853 contains an alpha channel. */
11854 if (channels == 4
11855 && !transparent_p
11856 && !x_create_x_image_and_pixmap (f, width, height, 1,
11857 &mask_img, &img->mask))
11859 x_destroy_x_image (ximg);
11860 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
11861 img->pixmap = 0;
11862 goto error;
11865 /* Fill the X image and mask from PNG data. */
11866 init_color_table ();
11868 for (y = 0; y < height; ++y)
11870 png_byte *p = rows[y];
11872 for (x = 0; x < width; ++x)
11874 unsigned r, g, b;
11876 r = *p++ << 8;
11877 g = *p++ << 8;
11878 b = *p++ << 8;
11879 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
11881 /* An alpha channel, aka mask channel, associates variable
11882 transparency with an image. Where other image formats
11883 support binary transparency---fully transparent or fully
11884 opaque---PNG allows up to 254 levels of partial transparency.
11885 The PNG library implements partial transparency by combining
11886 the image with a specified background color.
11888 I'm not sure how to handle this here nicely: because the
11889 background on which the image is displayed may change, for
11890 real alpha channel support, it would be necessary to create
11891 a new image for each possible background.
11893 What I'm doing now is that a mask is created if we have
11894 boolean transparency information. Otherwise I'm using
11895 the frame's background color to combine the image with. */
11897 if (channels == 4)
11899 if (mask_img)
11900 XPutPixel (mask_img, x, y, *p > 0);
11901 ++p;
11906 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11907 /* Set IMG's background color from the PNG image, unless the user
11908 overrode it. */
11910 png_color_16 *bg;
11911 if (png_get_bKGD (png_ptr, info_ptr, &bg))
11913 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
11914 img->background_valid = 1;
11918 /* Remember colors allocated for this image. */
11919 img->colors = colors_in_color_table (&img->ncolors);
11920 free_color_table ();
11922 /* Clean up. */
11923 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11924 xfree (rows);
11925 xfree (pixels);
11927 img->width = width;
11928 img->height = height;
11930 /* Maybe fill in the background field while we have ximg handy. */
11931 IMAGE_BACKGROUND (img, f, ximg);
11933 /* Put the image into the pixmap, then free the X image and its buffer. */
11934 x_put_x_image (f, ximg, img->pixmap, width, height);
11935 x_destroy_x_image (ximg);
11937 /* Same for the mask. */
11938 if (mask_img)
11940 /* Fill in the background_transparent field while we have the mask
11941 handy. */
11942 image_background_transparent (img, f, mask_img);
11944 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
11945 x_destroy_x_image (mask_img);
11948 UNGCPRO;
11949 return 1;
11952 #endif /* HAVE_PNG != 0 */
11956 /***********************************************************************
11957 JPEG
11958 ***********************************************************************/
11960 #if HAVE_JPEG
11962 /* Work around a warning about HAVE_STDLIB_H being redefined in
11963 jconfig.h. */
11964 #ifdef HAVE_STDLIB_H
11965 #define HAVE_STDLIB_H_1
11966 #undef HAVE_STDLIB_H
11967 #endif /* HAVE_STLIB_H */
11969 #include <jpeglib.h>
11970 #include <jerror.h>
11971 #include <setjmp.h>
11973 #ifdef HAVE_STLIB_H_1
11974 #define HAVE_STDLIB_H 1
11975 #endif
11977 static int jpeg_image_p P_ ((Lisp_Object object));
11978 static int jpeg_load P_ ((struct frame *f, struct image *img));
11980 /* The symbol `jpeg' identifying images of this type. */
11982 Lisp_Object Qjpeg;
11984 /* Indices of image specification fields in gs_format, below. */
11986 enum jpeg_keyword_index
11988 JPEG_TYPE,
11989 JPEG_DATA,
11990 JPEG_FILE,
11991 JPEG_ASCENT,
11992 JPEG_MARGIN,
11993 JPEG_RELIEF,
11994 JPEG_ALGORITHM,
11995 JPEG_HEURISTIC_MASK,
11996 JPEG_MASK,
11997 JPEG_BACKGROUND,
11998 JPEG_LAST
12001 /* Vector of image_keyword structures describing the format
12002 of valid user-defined image specifications. */
12004 static struct image_keyword jpeg_format[JPEG_LAST] =
12006 {":type", IMAGE_SYMBOL_VALUE, 1},
12007 {":data", IMAGE_STRING_VALUE, 0},
12008 {":file", IMAGE_STRING_VALUE, 0},
12009 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12010 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12011 {":relief", IMAGE_INTEGER_VALUE, 0},
12012 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12013 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12014 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12015 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12018 /* Structure describing the image type `jpeg'. */
12020 static struct image_type jpeg_type =
12022 &Qjpeg,
12023 jpeg_image_p,
12024 jpeg_load,
12025 x_clear_image,
12026 NULL
12030 /* Return non-zero if OBJECT is a valid JPEG image specification. */
12032 static int
12033 jpeg_image_p (object)
12034 Lisp_Object object;
12036 struct image_keyword fmt[JPEG_LAST];
12038 bcopy (jpeg_format, fmt, sizeof fmt);
12040 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
12041 || (fmt[JPEG_ASCENT].count
12042 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
12043 return 0;
12045 /* Must specify either the :data or :file keyword. */
12046 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
12050 struct my_jpeg_error_mgr
12052 struct jpeg_error_mgr pub;
12053 jmp_buf setjmp_buffer;
12056 static void
12057 my_error_exit (cinfo)
12058 j_common_ptr cinfo;
12060 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
12061 longjmp (mgr->setjmp_buffer, 1);
12064 /* Init source method for JPEG data source manager. Called by
12065 jpeg_read_header() before any data is actually read. See
12066 libjpeg.doc from the JPEG lib distribution. */
12068 static void
12069 our_init_source (cinfo)
12070 j_decompress_ptr cinfo;
12075 /* Fill input buffer method for JPEG data source manager. Called
12076 whenever more data is needed. We read the whole image in one step,
12077 so this only adds a fake end of input marker at the end. */
12079 static boolean
12080 our_fill_input_buffer (cinfo)
12081 j_decompress_ptr cinfo;
12083 /* Insert a fake EOI marker. */
12084 struct jpeg_source_mgr *src = cinfo->src;
12085 static JOCTET buffer[2];
12087 buffer[0] = (JOCTET) 0xFF;
12088 buffer[1] = (JOCTET) JPEG_EOI;
12090 src->next_input_byte = buffer;
12091 src->bytes_in_buffer = 2;
12092 return TRUE;
12096 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
12097 is the JPEG data source manager. */
12099 static void
12100 our_skip_input_data (cinfo, num_bytes)
12101 j_decompress_ptr cinfo;
12102 long num_bytes;
12104 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
12106 if (src)
12108 if (num_bytes > src->bytes_in_buffer)
12109 ERREXIT (cinfo, JERR_INPUT_EOF);
12111 src->bytes_in_buffer -= num_bytes;
12112 src->next_input_byte += num_bytes;
12117 /* Method to terminate data source. Called by
12118 jpeg_finish_decompress() after all data has been processed. */
12120 static void
12121 our_term_source (cinfo)
12122 j_decompress_ptr cinfo;
12127 /* Set up the JPEG lib for reading an image from DATA which contains
12128 LEN bytes. CINFO is the decompression info structure created for
12129 reading the image. */
12131 static void
12132 jpeg_memory_src (cinfo, data, len)
12133 j_decompress_ptr cinfo;
12134 JOCTET *data;
12135 unsigned int len;
12137 struct jpeg_source_mgr *src;
12139 if (cinfo->src == NULL)
12141 /* First time for this JPEG object? */
12142 cinfo->src = (struct jpeg_source_mgr *)
12143 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
12144 sizeof (struct jpeg_source_mgr));
12145 src = (struct jpeg_source_mgr *) cinfo->src;
12146 src->next_input_byte = data;
12149 src = (struct jpeg_source_mgr *) cinfo->src;
12150 src->init_source = our_init_source;
12151 src->fill_input_buffer = our_fill_input_buffer;
12152 src->skip_input_data = our_skip_input_data;
12153 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
12154 src->term_source = our_term_source;
12155 src->bytes_in_buffer = len;
12156 src->next_input_byte = data;
12160 /* Load image IMG for use on frame F. Patterned after example.c
12161 from the JPEG lib. */
12163 static int
12164 jpeg_load (f, img)
12165 struct frame *f;
12166 struct image *img;
12168 struct jpeg_decompress_struct cinfo;
12169 struct my_jpeg_error_mgr mgr;
12170 Lisp_Object file, specified_file;
12171 Lisp_Object specified_data;
12172 FILE * volatile fp = NULL;
12173 JSAMPARRAY buffer;
12174 int row_stride, x, y;
12175 XImage *ximg = NULL;
12176 int rc;
12177 unsigned long *colors;
12178 int width, height;
12179 struct gcpro gcpro1;
12181 /* Open the JPEG file. */
12182 specified_file = image_spec_value (img->spec, QCfile, NULL);
12183 specified_data = image_spec_value (img->spec, QCdata, NULL);
12184 file = Qnil;
12185 GCPRO1 (file);
12187 if (NILP (specified_data))
12189 file = x_find_image_file (specified_file);
12190 if (!STRINGP (file))
12192 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12193 UNGCPRO;
12194 return 0;
12197 fp = fopen (SDATA (file), "r");
12198 if (fp == NULL)
12200 image_error ("Cannot open `%s'", file, Qnil);
12201 UNGCPRO;
12202 return 0;
12206 /* Customize libjpeg's error handling to call my_error_exit when an
12207 error is detected. This function will perform a longjmp. */
12208 cinfo.err = jpeg_std_error (&mgr.pub);
12209 mgr.pub.error_exit = my_error_exit;
12211 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
12213 if (rc == 1)
12215 /* Called from my_error_exit. Display a JPEG error. */
12216 char buffer[JMSG_LENGTH_MAX];
12217 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
12218 image_error ("Error reading JPEG image `%s': %s", img->spec,
12219 build_string (buffer));
12222 /* Close the input file and destroy the JPEG object. */
12223 if (fp)
12224 fclose (fp);
12225 jpeg_destroy_decompress (&cinfo);
12227 /* If we already have an XImage, free that. */
12228 x_destroy_x_image (ximg);
12230 /* Free pixmap and colors. */
12231 x_clear_image (f, img);
12233 UNGCPRO;
12234 return 0;
12237 /* Create the JPEG decompression object. Let it read from fp.
12238 Read the JPEG image header. */
12239 jpeg_create_decompress (&cinfo);
12241 if (NILP (specified_data))
12242 jpeg_stdio_src (&cinfo, fp);
12243 else
12244 jpeg_memory_src (&cinfo, SDATA (specified_data),
12245 SBYTES (specified_data));
12247 jpeg_read_header (&cinfo, TRUE);
12249 /* Customize decompression so that color quantization will be used.
12250 Start decompression. */
12251 cinfo.quantize_colors = TRUE;
12252 jpeg_start_decompress (&cinfo);
12253 width = img->width = cinfo.output_width;
12254 height = img->height = cinfo.output_height;
12256 /* Create X image and pixmap. */
12257 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
12258 &img->pixmap))
12259 longjmp (mgr.setjmp_buffer, 2);
12261 /* Allocate colors. When color quantization is used,
12262 cinfo.actual_number_of_colors has been set with the number of
12263 colors generated, and cinfo.colormap is a two-dimensional array
12264 of color indices in the range 0..cinfo.actual_number_of_colors.
12265 No more than 255 colors will be generated. */
12267 int i, ir, ig, ib;
12269 if (cinfo.out_color_components > 2)
12270 ir = 0, ig = 1, ib = 2;
12271 else if (cinfo.out_color_components > 1)
12272 ir = 0, ig = 1, ib = 0;
12273 else
12274 ir = 0, ig = 0, ib = 0;
12276 /* Use the color table mechanism because it handles colors that
12277 cannot be allocated nicely. Such colors will be replaced with
12278 a default color, and we don't have to care about which colors
12279 can be freed safely, and which can't. */
12280 init_color_table ();
12281 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
12282 * sizeof *colors);
12284 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
12286 /* Multiply RGB values with 255 because X expects RGB values
12287 in the range 0..0xffff. */
12288 int r = cinfo.colormap[ir][i] << 8;
12289 int g = cinfo.colormap[ig][i] << 8;
12290 int b = cinfo.colormap[ib][i] << 8;
12291 colors[i] = lookup_rgb_color (f, r, g, b);
12294 /* Remember those colors actually allocated. */
12295 img->colors = colors_in_color_table (&img->ncolors);
12296 free_color_table ();
12299 /* Read pixels. */
12300 row_stride = width * cinfo.output_components;
12301 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
12302 row_stride, 1);
12303 for (y = 0; y < height; ++y)
12305 jpeg_read_scanlines (&cinfo, buffer, 1);
12306 for (x = 0; x < cinfo.output_width; ++x)
12307 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
12310 /* Clean up. */
12311 jpeg_finish_decompress (&cinfo);
12312 jpeg_destroy_decompress (&cinfo);
12313 if (fp)
12314 fclose (fp);
12316 /* Maybe fill in the background field while we have ximg handy. */
12317 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12318 IMAGE_BACKGROUND (img, f, ximg);
12320 /* Put the image into the pixmap. */
12321 x_put_x_image (f, ximg, img->pixmap, width, height);
12322 x_destroy_x_image (ximg);
12323 UNBLOCK_INPUT;
12324 UNGCPRO;
12325 return 1;
12328 #endif /* HAVE_JPEG */
12332 /***********************************************************************
12333 TIFF
12334 ***********************************************************************/
12336 #if HAVE_TIFF
12338 #include <tiffio.h>
12340 static int tiff_image_p P_ ((Lisp_Object object));
12341 static int tiff_load P_ ((struct frame *f, struct image *img));
12343 /* The symbol `tiff' identifying images of this type. */
12345 Lisp_Object Qtiff;
12347 /* Indices of image specification fields in tiff_format, below. */
12349 enum tiff_keyword_index
12351 TIFF_TYPE,
12352 TIFF_DATA,
12353 TIFF_FILE,
12354 TIFF_ASCENT,
12355 TIFF_MARGIN,
12356 TIFF_RELIEF,
12357 TIFF_ALGORITHM,
12358 TIFF_HEURISTIC_MASK,
12359 TIFF_MASK,
12360 TIFF_BACKGROUND,
12361 TIFF_LAST
12364 /* Vector of image_keyword structures describing the format
12365 of valid user-defined image specifications. */
12367 static struct image_keyword tiff_format[TIFF_LAST] =
12369 {":type", IMAGE_SYMBOL_VALUE, 1},
12370 {":data", IMAGE_STRING_VALUE, 0},
12371 {":file", IMAGE_STRING_VALUE, 0},
12372 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12373 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12374 {":relief", IMAGE_INTEGER_VALUE, 0},
12375 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12376 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12377 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12378 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12381 /* Structure describing the image type `tiff'. */
12383 static struct image_type tiff_type =
12385 &Qtiff,
12386 tiff_image_p,
12387 tiff_load,
12388 x_clear_image,
12389 NULL
12393 /* Return non-zero if OBJECT is a valid TIFF image specification. */
12395 static int
12396 tiff_image_p (object)
12397 Lisp_Object object;
12399 struct image_keyword fmt[TIFF_LAST];
12400 bcopy (tiff_format, fmt, sizeof fmt);
12402 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
12403 || (fmt[TIFF_ASCENT].count
12404 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
12405 return 0;
12407 /* Must specify either the :data or :file keyword. */
12408 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
12412 /* Reading from a memory buffer for TIFF images Based on the PNG
12413 memory source, but we have to provide a lot of extra functions.
12414 Blah.
12416 We really only need to implement read and seek, but I am not
12417 convinced that the TIFF library is smart enough not to destroy
12418 itself if we only hand it the function pointers we need to
12419 override. */
12421 typedef struct
12423 unsigned char *bytes;
12424 size_t len;
12425 int index;
12427 tiff_memory_source;
12429 static size_t
12430 tiff_read_from_memory (data, buf, size)
12431 thandle_t data;
12432 tdata_t buf;
12433 tsize_t size;
12435 tiff_memory_source *src = (tiff_memory_source *) data;
12437 if (size > src->len - src->index)
12438 return (size_t) -1;
12439 bcopy (src->bytes + src->index, buf, size);
12440 src->index += size;
12441 return size;
12444 static size_t
12445 tiff_write_from_memory (data, buf, size)
12446 thandle_t data;
12447 tdata_t buf;
12448 tsize_t size;
12450 return (size_t) -1;
12453 static toff_t
12454 tiff_seek_in_memory (data, off, whence)
12455 thandle_t data;
12456 toff_t off;
12457 int whence;
12459 tiff_memory_source *src = (tiff_memory_source *) data;
12460 int idx;
12462 switch (whence)
12464 case SEEK_SET: /* Go from beginning of source. */
12465 idx = off;
12466 break;
12468 case SEEK_END: /* Go from end of source. */
12469 idx = src->len + off;
12470 break;
12472 case SEEK_CUR: /* Go from current position. */
12473 idx = src->index + off;
12474 break;
12476 default: /* Invalid `whence'. */
12477 return -1;
12480 if (idx > src->len || idx < 0)
12481 return -1;
12483 src->index = idx;
12484 return src->index;
12487 static int
12488 tiff_close_memory (data)
12489 thandle_t data;
12491 /* NOOP */
12492 return 0;
12495 static int
12496 tiff_mmap_memory (data, pbase, psize)
12497 thandle_t data;
12498 tdata_t *pbase;
12499 toff_t *psize;
12501 /* It is already _IN_ memory. */
12502 return 0;
12505 static void
12506 tiff_unmap_memory (data, base, size)
12507 thandle_t data;
12508 tdata_t base;
12509 toff_t size;
12511 /* We don't need to do this. */
12514 static toff_t
12515 tiff_size_of_memory (data)
12516 thandle_t data;
12518 return ((tiff_memory_source *) data)->len;
12522 static void
12523 tiff_error_handler (title, format, ap)
12524 const char *title, *format;
12525 va_list ap;
12527 char buf[512];
12528 int len;
12530 len = sprintf (buf, "TIFF error: %s ", title);
12531 vsprintf (buf + len, format, ap);
12532 add_to_log (buf, Qnil, Qnil);
12536 static void
12537 tiff_warning_handler (title, format, ap)
12538 const char *title, *format;
12539 va_list ap;
12541 char buf[512];
12542 int len;
12544 len = sprintf (buf, "TIFF warning: %s ", title);
12545 vsprintf (buf + len, format, ap);
12546 add_to_log (buf, Qnil, Qnil);
12550 /* Load TIFF image IMG for use on frame F. Value is non-zero if
12551 successful. */
12553 static int
12554 tiff_load (f, img)
12555 struct frame *f;
12556 struct image *img;
12558 Lisp_Object file, specified_file;
12559 Lisp_Object specified_data;
12560 TIFF *tiff;
12561 int width, height, x, y;
12562 uint32 *buf;
12563 int rc;
12564 XImage *ximg;
12565 struct gcpro gcpro1;
12566 tiff_memory_source memsrc;
12568 specified_file = image_spec_value (img->spec, QCfile, NULL);
12569 specified_data = image_spec_value (img->spec, QCdata, NULL);
12570 file = Qnil;
12571 GCPRO1 (file);
12573 TIFFSetErrorHandler (tiff_error_handler);
12574 TIFFSetWarningHandler (tiff_warning_handler);
12576 if (NILP (specified_data))
12578 /* Read from a file */
12579 file = x_find_image_file (specified_file);
12580 if (!STRINGP (file))
12582 image_error ("Cannot find image file `%s'", file, Qnil);
12583 UNGCPRO;
12584 return 0;
12587 /* Try to open the image file. */
12588 tiff = TIFFOpen (SDATA (file), "r");
12589 if (tiff == NULL)
12591 image_error ("Cannot open `%s'", file, Qnil);
12592 UNGCPRO;
12593 return 0;
12596 else
12598 /* Memory source! */
12599 memsrc.bytes = SDATA (specified_data);
12600 memsrc.len = SBYTES (specified_data);
12601 memsrc.index = 0;
12603 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
12604 (TIFFReadWriteProc) tiff_read_from_memory,
12605 (TIFFReadWriteProc) tiff_write_from_memory,
12606 tiff_seek_in_memory,
12607 tiff_close_memory,
12608 tiff_size_of_memory,
12609 tiff_mmap_memory,
12610 tiff_unmap_memory);
12612 if (!tiff)
12614 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
12615 UNGCPRO;
12616 return 0;
12620 /* Get width and height of the image, and allocate a raster buffer
12621 of width x height 32-bit values. */
12622 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
12623 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
12624 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
12626 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
12627 TIFFClose (tiff);
12628 if (!rc)
12630 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
12631 xfree (buf);
12632 UNGCPRO;
12633 return 0;
12636 /* Create the X image and pixmap. */
12637 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12639 xfree (buf);
12640 UNGCPRO;
12641 return 0;
12644 /* Initialize the color table. */
12645 init_color_table ();
12647 /* Process the pixel raster. Origin is in the lower-left corner. */
12648 for (y = 0; y < height; ++y)
12650 uint32 *row = buf + y * width;
12652 for (x = 0; x < width; ++x)
12654 uint32 abgr = row[x];
12655 int r = TIFFGetR (abgr) << 8;
12656 int g = TIFFGetG (abgr) << 8;
12657 int b = TIFFGetB (abgr) << 8;
12658 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
12662 /* Remember the colors allocated for the image. Free the color table. */
12663 img->colors = colors_in_color_table (&img->ncolors);
12664 free_color_table ();
12666 img->width = width;
12667 img->height = height;
12669 /* Maybe fill in the background field while we have ximg handy. */
12670 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12671 IMAGE_BACKGROUND (img, f, ximg);
12673 /* Put the image into the pixmap, then free the X image and its buffer. */
12674 x_put_x_image (f, ximg, img->pixmap, width, height);
12675 x_destroy_x_image (ximg);
12676 xfree (buf);
12678 UNGCPRO;
12679 return 1;
12682 #endif /* HAVE_TIFF != 0 */
12686 /***********************************************************************
12688 ***********************************************************************/
12690 #if HAVE_GIF
12692 #include <gif_lib.h>
12694 static int gif_image_p P_ ((Lisp_Object object));
12695 static int gif_load P_ ((struct frame *f, struct image *img));
12697 /* The symbol `gif' identifying images of this type. */
12699 Lisp_Object Qgif;
12701 /* Indices of image specification fields in gif_format, below. */
12703 enum gif_keyword_index
12705 GIF_TYPE,
12706 GIF_DATA,
12707 GIF_FILE,
12708 GIF_ASCENT,
12709 GIF_MARGIN,
12710 GIF_RELIEF,
12711 GIF_ALGORITHM,
12712 GIF_HEURISTIC_MASK,
12713 GIF_MASK,
12714 GIF_IMAGE,
12715 GIF_BACKGROUND,
12716 GIF_LAST
12719 /* Vector of image_keyword structures describing the format
12720 of valid user-defined image specifications. */
12722 static struct image_keyword gif_format[GIF_LAST] =
12724 {":type", IMAGE_SYMBOL_VALUE, 1},
12725 {":data", IMAGE_STRING_VALUE, 0},
12726 {":file", IMAGE_STRING_VALUE, 0},
12727 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12728 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12729 {":relief", IMAGE_INTEGER_VALUE, 0},
12730 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12731 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12732 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12733 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12734 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12737 /* Structure describing the image type `gif'. */
12739 static struct image_type gif_type =
12741 &Qgif,
12742 gif_image_p,
12743 gif_load,
12744 x_clear_image,
12745 NULL
12748 /* Return non-zero if OBJECT is a valid GIF image specification. */
12750 static int
12751 gif_image_p (object)
12752 Lisp_Object object;
12754 struct image_keyword fmt[GIF_LAST];
12755 bcopy (gif_format, fmt, sizeof fmt);
12757 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
12758 || (fmt[GIF_ASCENT].count
12759 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
12760 return 0;
12762 /* Must specify either the :data or :file keyword. */
12763 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
12766 /* Reading a GIF image from memory
12767 Based on the PNG memory stuff to a certain extent. */
12769 typedef struct
12771 unsigned char *bytes;
12772 size_t len;
12773 int index;
12775 gif_memory_source;
12777 /* Make the current memory source available to gif_read_from_memory.
12778 It's done this way because not all versions of libungif support
12779 a UserData field in the GifFileType structure. */
12780 static gif_memory_source *current_gif_memory_src;
12782 static int
12783 gif_read_from_memory (file, buf, len)
12784 GifFileType *file;
12785 GifByteType *buf;
12786 int len;
12788 gif_memory_source *src = current_gif_memory_src;
12790 if (len > src->len - src->index)
12791 return -1;
12793 bcopy (src->bytes + src->index, buf, len);
12794 src->index += len;
12795 return len;
12799 /* Load GIF image IMG for use on frame F. Value is non-zero if
12800 successful. */
12802 static int
12803 gif_load (f, img)
12804 struct frame *f;
12805 struct image *img;
12807 Lisp_Object file, specified_file;
12808 Lisp_Object specified_data;
12809 int rc, width, height, x, y, i;
12810 XImage *ximg;
12811 ColorMapObject *gif_color_map;
12812 unsigned long pixel_colors[256];
12813 GifFileType *gif;
12814 struct gcpro gcpro1;
12815 Lisp_Object image;
12816 int ino, image_left, image_top, image_width, image_height;
12817 gif_memory_source memsrc;
12818 unsigned char *raster;
12820 specified_file = image_spec_value (img->spec, QCfile, NULL);
12821 specified_data = image_spec_value (img->spec, QCdata, NULL);
12822 file = Qnil;
12823 GCPRO1 (file);
12825 if (NILP (specified_data))
12827 file = x_find_image_file (specified_file);
12828 if (!STRINGP (file))
12830 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12831 UNGCPRO;
12832 return 0;
12835 /* Open the GIF file. */
12836 gif = DGifOpenFileName (SDATA (file));
12837 if (gif == NULL)
12839 image_error ("Cannot open `%s'", file, Qnil);
12840 UNGCPRO;
12841 return 0;
12844 else
12846 /* Read from memory! */
12847 current_gif_memory_src = &memsrc;
12848 memsrc.bytes = SDATA (specified_data);
12849 memsrc.len = SBYTES (specified_data);
12850 memsrc.index = 0;
12852 gif = DGifOpen(&memsrc, gif_read_from_memory);
12853 if (!gif)
12855 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
12856 UNGCPRO;
12857 return 0;
12861 /* Read entire contents. */
12862 rc = DGifSlurp (gif);
12863 if (rc == GIF_ERROR)
12865 image_error ("Error reading `%s'", img->spec, Qnil);
12866 DGifCloseFile (gif);
12867 UNGCPRO;
12868 return 0;
12871 image = image_spec_value (img->spec, QCindex, NULL);
12872 ino = INTEGERP (image) ? XFASTINT (image) : 0;
12873 if (ino >= gif->ImageCount)
12875 image_error ("Invalid image number `%s' in image `%s'",
12876 image, img->spec);
12877 DGifCloseFile (gif);
12878 UNGCPRO;
12879 return 0;
12882 width = img->width = gif->SWidth;
12883 height = img->height = gif->SHeight;
12885 /* Create the X image and pixmap. */
12886 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12888 DGifCloseFile (gif);
12889 UNGCPRO;
12890 return 0;
12893 /* Allocate colors. */
12894 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
12895 if (!gif_color_map)
12896 gif_color_map = gif->SColorMap;
12897 init_color_table ();
12898 bzero (pixel_colors, sizeof pixel_colors);
12900 for (i = 0; i < gif_color_map->ColorCount; ++i)
12902 int r = gif_color_map->Colors[i].Red << 8;
12903 int g = gif_color_map->Colors[i].Green << 8;
12904 int b = gif_color_map->Colors[i].Blue << 8;
12905 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
12908 img->colors = colors_in_color_table (&img->ncolors);
12909 free_color_table ();
12911 /* Clear the part of the screen image that are not covered by
12912 the image from the GIF file. Full animated GIF support
12913 requires more than can be done here (see the gif89 spec,
12914 disposal methods). Let's simply assume that the part
12915 not covered by a sub-image is in the frame's background color. */
12916 image_top = gif->SavedImages[ino].ImageDesc.Top;
12917 image_left = gif->SavedImages[ino].ImageDesc.Left;
12918 image_width = gif->SavedImages[ino].ImageDesc.Width;
12919 image_height = gif->SavedImages[ino].ImageDesc.Height;
12921 for (y = 0; y < image_top; ++y)
12922 for (x = 0; x < width; ++x)
12923 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12925 for (y = image_top + image_height; y < height; ++y)
12926 for (x = 0; x < width; ++x)
12927 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12929 for (y = image_top; y < image_top + image_height; ++y)
12931 for (x = 0; x < image_left; ++x)
12932 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12933 for (x = image_left + image_width; x < width; ++x)
12934 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12937 /* Read the GIF image into the X image. We use a local variable
12938 `raster' here because RasterBits below is a char *, and invites
12939 problems with bytes >= 0x80. */
12940 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
12942 if (gif->SavedImages[ino].ImageDesc.Interlace)
12944 static int interlace_start[] = {0, 4, 2, 1};
12945 static int interlace_increment[] = {8, 8, 4, 2};
12946 int pass;
12947 int row = interlace_start[0];
12949 pass = 0;
12951 for (y = 0; y < image_height; y++)
12953 if (row >= image_height)
12955 row = interlace_start[++pass];
12956 while (row >= image_height)
12957 row = interlace_start[++pass];
12960 for (x = 0; x < image_width; x++)
12962 int i = raster[(y * image_width) + x];
12963 XPutPixel (ximg, x + image_left, row + image_top,
12964 pixel_colors[i]);
12967 row += interlace_increment[pass];
12970 else
12972 for (y = 0; y < image_height; ++y)
12973 for (x = 0; x < image_width; ++x)
12975 int i = raster[y* image_width + x];
12976 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
12980 DGifCloseFile (gif);
12982 /* Maybe fill in the background field while we have ximg handy. */
12983 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12984 IMAGE_BACKGROUND (img, f, ximg);
12986 /* Put the image into the pixmap, then free the X image and its buffer. */
12987 x_put_x_image (f, ximg, img->pixmap, width, height);
12988 x_destroy_x_image (ximg);
12990 UNGCPRO;
12991 return 1;
12994 #endif /* HAVE_GIF != 0 */
12998 /***********************************************************************
12999 Ghostscript
13000 ***********************************************************************/
13002 Lisp_Object Qpostscript;
13004 #ifdef HAVE_GHOSTSCRIPT
13005 static int gs_image_p P_ ((Lisp_Object object));
13006 static int gs_load P_ ((struct frame *f, struct image *img));
13007 static void gs_clear_image P_ ((struct frame *f, struct image *img));
13009 /* The symbol `postscript' identifying images of this type. */
13011 /* Keyword symbols. */
13013 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
13015 /* Indices of image specification fields in gs_format, below. */
13017 enum gs_keyword_index
13019 GS_TYPE,
13020 GS_PT_WIDTH,
13021 GS_PT_HEIGHT,
13022 GS_FILE,
13023 GS_LOADER,
13024 GS_BOUNDING_BOX,
13025 GS_ASCENT,
13026 GS_MARGIN,
13027 GS_RELIEF,
13028 GS_ALGORITHM,
13029 GS_HEURISTIC_MASK,
13030 GS_MASK,
13031 GS_BACKGROUND,
13032 GS_LAST
13035 /* Vector of image_keyword structures describing the format
13036 of valid user-defined image specifications. */
13038 static struct image_keyword gs_format[GS_LAST] =
13040 {":type", IMAGE_SYMBOL_VALUE, 1},
13041 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13042 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13043 {":file", IMAGE_STRING_VALUE, 1},
13044 {":loader", IMAGE_FUNCTION_VALUE, 0},
13045 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
13046 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
13047 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
13048 {":relief", IMAGE_INTEGER_VALUE, 0},
13049 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13050 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13051 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13052 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
13055 /* Structure describing the image type `ghostscript'. */
13057 static struct image_type gs_type =
13059 &Qpostscript,
13060 gs_image_p,
13061 gs_load,
13062 gs_clear_image,
13063 NULL
13067 /* Free X resources of Ghostscript image IMG which is used on frame F. */
13069 static void
13070 gs_clear_image (f, img)
13071 struct frame *f;
13072 struct image *img;
13074 /* IMG->data.ptr_val may contain a recorded colormap. */
13075 xfree (img->data.ptr_val);
13076 x_clear_image (f, img);
13080 /* Return non-zero if OBJECT is a valid Ghostscript image
13081 specification. */
13083 static int
13084 gs_image_p (object)
13085 Lisp_Object object;
13087 struct image_keyword fmt[GS_LAST];
13088 Lisp_Object tem;
13089 int i;
13091 bcopy (gs_format, fmt, sizeof fmt);
13093 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
13094 || (fmt[GS_ASCENT].count
13095 && XFASTINT (fmt[GS_ASCENT].value) > 100))
13096 return 0;
13098 /* Bounding box must be a list or vector containing 4 integers. */
13099 tem = fmt[GS_BOUNDING_BOX].value;
13100 if (CONSP (tem))
13102 for (i = 0; i < 4; ++i, tem = XCDR (tem))
13103 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
13104 return 0;
13105 if (!NILP (tem))
13106 return 0;
13108 else if (VECTORP (tem))
13110 if (XVECTOR (tem)->size != 4)
13111 return 0;
13112 for (i = 0; i < 4; ++i)
13113 if (!INTEGERP (XVECTOR (tem)->contents[i]))
13114 return 0;
13116 else
13117 return 0;
13119 return 1;
13123 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
13124 if successful. */
13126 static int
13127 gs_load (f, img)
13128 struct frame *f;
13129 struct image *img;
13131 char buffer[100];
13132 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
13133 struct gcpro gcpro1, gcpro2;
13134 Lisp_Object frame;
13135 double in_width, in_height;
13136 Lisp_Object pixel_colors = Qnil;
13138 /* Compute pixel size of pixmap needed from the given size in the
13139 image specification. Sizes in the specification are in pt. 1 pt
13140 = 1/72 in, xdpi and ydpi are stored in the frame's X display
13141 info. */
13142 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
13143 in_width = XFASTINT (pt_width) / 72.0;
13144 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
13145 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
13146 in_height = XFASTINT (pt_height) / 72.0;
13147 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
13149 /* Create the pixmap. */
13150 BLOCK_INPUT;
13151 xassert (img->pixmap == 0);
13152 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13153 img->width, img->height,
13154 one_w32_display_info.n_cbits);
13155 UNBLOCK_INPUT;
13157 if (!img->pixmap)
13159 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
13160 return 0;
13163 /* Call the loader to fill the pixmap. It returns a process object
13164 if successful. We do not record_unwind_protect here because
13165 other places in redisplay like calling window scroll functions
13166 don't either. Let the Lisp loader use `unwind-protect' instead. */
13167 GCPRO2 (window_and_pixmap_id, pixel_colors);
13169 sprintf (buffer, "%lu %lu",
13170 (unsigned long) FRAME_W32_WINDOW (f),
13171 (unsigned long) img->pixmap);
13172 window_and_pixmap_id = build_string (buffer);
13174 sprintf (buffer, "%lu %lu",
13175 FRAME_FOREGROUND_PIXEL (f),
13176 FRAME_BACKGROUND_PIXEL (f));
13177 pixel_colors = build_string (buffer);
13179 XSETFRAME (frame, f);
13180 loader = image_spec_value (img->spec, QCloader, NULL);
13181 if (NILP (loader))
13182 loader = intern ("gs-load-image");
13184 img->data.lisp_val = call6 (loader, frame, img->spec,
13185 make_number (img->width),
13186 make_number (img->height),
13187 window_and_pixmap_id,
13188 pixel_colors);
13189 UNGCPRO;
13190 return PROCESSP (img->data.lisp_val);
13194 /* Kill the Ghostscript process that was started to fill PIXMAP on
13195 frame F. Called from XTread_socket when receiving an event
13196 telling Emacs that Ghostscript has finished drawing. */
13198 void
13199 x_kill_gs_process (pixmap, f)
13200 Pixmap pixmap;
13201 struct frame *f;
13203 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
13204 int class, i;
13205 struct image *img;
13207 /* Find the image containing PIXMAP. */
13208 for (i = 0; i < c->used; ++i)
13209 if (c->images[i]->pixmap == pixmap)
13210 break;
13212 /* Should someone in between have cleared the image cache, for
13213 instance, give up. */
13214 if (i == c->used)
13215 return;
13217 /* Kill the GS process. We should have found PIXMAP in the image
13218 cache and its image should contain a process object. */
13219 img = c->images[i];
13220 xassert (PROCESSP (img->data.lisp_val));
13221 Fkill_process (img->data.lisp_val, Qnil);
13222 img->data.lisp_val = Qnil;
13224 /* On displays with a mutable colormap, figure out the colors
13225 allocated for the image by looking at the pixels of an XImage for
13226 img->pixmap. */
13227 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
13228 if (class != StaticColor && class != StaticGray && class != TrueColor)
13230 XImage *ximg;
13232 BLOCK_INPUT;
13234 /* Try to get an XImage for img->pixmep. */
13235 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
13236 0, 0, img->width, img->height, ~0, ZPixmap);
13237 if (ximg)
13239 int x, y;
13241 /* Initialize the color table. */
13242 init_color_table ();
13244 /* For each pixel of the image, look its color up in the
13245 color table. After having done so, the color table will
13246 contain an entry for each color used by the image. */
13247 for (y = 0; y < img->height; ++y)
13248 for (x = 0; x < img->width; ++x)
13250 unsigned long pixel = XGetPixel (ximg, x, y);
13251 lookup_pixel_color (f, pixel);
13254 /* Record colors in the image. Free color table and XImage. */
13255 img->colors = colors_in_color_table (&img->ncolors);
13256 free_color_table ();
13257 XDestroyImage (ximg);
13259 #if 0 /* This doesn't seem to be the case. If we free the colors
13260 here, we get a BadAccess later in x_clear_image when
13261 freeing the colors. */
13262 /* We have allocated colors once, but Ghostscript has also
13263 allocated colors on behalf of us. So, to get the
13264 reference counts right, free them once. */
13265 if (img->ncolors)
13266 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
13267 img->colors, img->ncolors, 0);
13268 #endif
13270 else
13271 image_error ("Cannot get X image of `%s'; colors will not be freed",
13272 img->spec, Qnil);
13274 UNBLOCK_INPUT;
13277 /* Now that we have the pixmap, compute mask and transform the
13278 image if requested. */
13279 BLOCK_INPUT;
13280 postprocess_image (f, img);
13281 UNBLOCK_INPUT;
13284 #endif /* HAVE_GHOSTSCRIPT */
13287 /***********************************************************************
13288 Window properties
13289 ***********************************************************************/
13291 DEFUN ("x-change-window-property", Fx_change_window_property,
13292 Sx_change_window_property, 2, 3, 0,
13293 doc: /* Change window property PROP to VALUE on the X window of FRAME.
13294 PROP and VALUE must be strings. FRAME nil or omitted means use the
13295 selected frame. Value is VALUE. */)
13296 (prop, value, frame)
13297 Lisp_Object frame, prop, value;
13299 #if 0 /* TODO : port window properties to W32 */
13300 struct frame *f = check_x_frame (frame);
13301 Atom prop_atom;
13303 CHECK_STRING (prop);
13304 CHECK_STRING (value);
13306 BLOCK_INPUT;
13307 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13308 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13309 prop_atom, XA_STRING, 8, PropModeReplace,
13310 SDATA (value), SCHARS (value));
13312 /* Make sure the property is set when we return. */
13313 XFlush (FRAME_W32_DISPLAY (f));
13314 UNBLOCK_INPUT;
13316 #endif /* TODO */
13318 return value;
13322 DEFUN ("x-delete-window-property", Fx_delete_window_property,
13323 Sx_delete_window_property, 1, 2, 0,
13324 doc: /* Remove window property PROP from X window of FRAME.
13325 FRAME nil or omitted means use the selected frame. Value is PROP. */)
13326 (prop, frame)
13327 Lisp_Object prop, frame;
13329 #if 0 /* TODO : port window properties to W32 */
13331 struct frame *f = check_x_frame (frame);
13332 Atom prop_atom;
13334 CHECK_STRING (prop);
13335 BLOCK_INPUT;
13336 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13337 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
13339 /* Make sure the property is removed when we return. */
13340 XFlush (FRAME_W32_DISPLAY (f));
13341 UNBLOCK_INPUT;
13342 #endif /* TODO */
13344 return prop;
13348 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
13349 1, 2, 0,
13350 doc: /* Value is the value of window property PROP on FRAME.
13351 If FRAME is nil or omitted, use the selected frame. Value is nil
13352 if FRAME hasn't a property with name PROP or if PROP has no string
13353 value. */)
13354 (prop, frame)
13355 Lisp_Object prop, frame;
13357 #if 0 /* TODO : port window properties to W32 */
13359 struct frame *f = check_x_frame (frame);
13360 Atom prop_atom;
13361 int rc;
13362 Lisp_Object prop_value = Qnil;
13363 char *tmp_data = NULL;
13364 Atom actual_type;
13365 int actual_format;
13366 unsigned long actual_size, bytes_remaining;
13368 CHECK_STRING (prop);
13369 BLOCK_INPUT;
13370 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13371 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13372 prop_atom, 0, 0, False, XA_STRING,
13373 &actual_type, &actual_format, &actual_size,
13374 &bytes_remaining, (unsigned char **) &tmp_data);
13375 if (rc == Success)
13377 int size = bytes_remaining;
13379 XFree (tmp_data);
13380 tmp_data = NULL;
13382 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13383 prop_atom, 0, bytes_remaining,
13384 False, XA_STRING,
13385 &actual_type, &actual_format,
13386 &actual_size, &bytes_remaining,
13387 (unsigned char **) &tmp_data);
13388 if (rc == Success)
13389 prop_value = make_string (tmp_data, size);
13391 XFree (tmp_data);
13394 UNBLOCK_INPUT;
13396 return prop_value;
13398 #endif /* TODO */
13399 return Qnil;
13404 /***********************************************************************
13405 Busy cursor
13406 ***********************************************************************/
13408 /* If non-null, an asynchronous timer that, when it expires, displays
13409 an hourglass cursor on all frames. */
13411 static struct atimer *hourglass_atimer;
13413 /* Non-zero means an hourglass cursor is currently shown. */
13415 static int hourglass_shown_p;
13417 /* Number of seconds to wait before displaying an hourglass cursor. */
13419 static Lisp_Object Vhourglass_delay;
13421 /* Default number of seconds to wait before displaying an hourglass
13422 cursor. */
13424 #define DEFAULT_HOURGLASS_DELAY 1
13426 /* Function prototypes. */
13428 static void show_hourglass P_ ((struct atimer *));
13429 static void hide_hourglass P_ ((void));
13432 /* Cancel a currently active hourglass timer, and start a new one. */
13434 void
13435 start_hourglass ()
13437 #if 0 /* TODO: cursor shape changes. */
13438 EMACS_TIME delay;
13439 int secs, usecs = 0;
13441 cancel_hourglass ();
13443 if (INTEGERP (Vhourglass_delay)
13444 && XINT (Vhourglass_delay) > 0)
13445 secs = XFASTINT (Vhourglass_delay);
13446 else if (FLOATP (Vhourglass_delay)
13447 && XFLOAT_DATA (Vhourglass_delay) > 0)
13449 Lisp_Object tem;
13450 tem = Ftruncate (Vhourglass_delay, Qnil);
13451 secs = XFASTINT (tem);
13452 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
13454 else
13455 secs = DEFAULT_HOURGLASS_DELAY;
13457 EMACS_SET_SECS_USECS (delay, secs, usecs);
13458 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
13459 show_hourglass, NULL);
13460 #endif
13464 /* Cancel the hourglass cursor timer if active, hide an hourglass
13465 cursor if shown. */
13467 void
13468 cancel_hourglass ()
13470 if (hourglass_atimer)
13472 cancel_atimer (hourglass_atimer);
13473 hourglass_atimer = NULL;
13476 if (hourglass_shown_p)
13477 hide_hourglass ();
13481 /* Timer function of hourglass_atimer. TIMER is equal to
13482 hourglass_atimer.
13484 Display an hourglass cursor on all frames by mapping the frames'
13485 hourglass_window. Set the hourglass_p flag in the frames'
13486 output_data.x structure to indicate that an hourglass cursor is
13487 shown on the frames. */
13489 static void
13490 show_hourglass (timer)
13491 struct atimer *timer;
13493 #if 0 /* TODO: cursor shape changes. */
13494 /* The timer implementation will cancel this timer automatically
13495 after this function has run. Set hourglass_atimer to null
13496 so that we know the timer doesn't have to be canceled. */
13497 hourglass_atimer = NULL;
13499 if (!hourglass_shown_p)
13501 Lisp_Object rest, frame;
13503 BLOCK_INPUT;
13505 FOR_EACH_FRAME (rest, frame)
13506 if (FRAME_W32_P (XFRAME (frame)))
13508 struct frame *f = XFRAME (frame);
13510 f->output_data.w32->hourglass_p = 1;
13512 if (!f->output_data.w32->hourglass_window)
13514 unsigned long mask = CWCursor;
13515 XSetWindowAttributes attrs;
13517 attrs.cursor = f->output_data.w32->hourglass_cursor;
13519 f->output_data.w32->hourglass_window
13520 = XCreateWindow (FRAME_X_DISPLAY (f),
13521 FRAME_OUTER_WINDOW (f),
13522 0, 0, 32000, 32000, 0, 0,
13523 InputOnly,
13524 CopyFromParent,
13525 mask, &attrs);
13528 XMapRaised (FRAME_X_DISPLAY (f),
13529 f->output_data.w32->hourglass_window);
13530 XFlush (FRAME_X_DISPLAY (f));
13533 hourglass_shown_p = 1;
13534 UNBLOCK_INPUT;
13536 #endif
13540 /* Hide the hourglass cursor on all frames, if it is currently shown. */
13542 static void
13543 hide_hourglass ()
13545 #if 0 /* TODO: cursor shape changes. */
13546 if (hourglass_shown_p)
13548 Lisp_Object rest, frame;
13550 BLOCK_INPUT;
13551 FOR_EACH_FRAME (rest, frame)
13553 struct frame *f = XFRAME (frame);
13555 if (FRAME_W32_P (f)
13556 /* Watch out for newly created frames. */
13557 && f->output_data.x->hourglass_window)
13559 XUnmapWindow (FRAME_X_DISPLAY (f),
13560 f->output_data.x->hourglass_window);
13561 /* Sync here because XTread_socket looks at the
13562 hourglass_p flag that is reset to zero below. */
13563 XSync (FRAME_X_DISPLAY (f), False);
13564 f->output_data.x->hourglass_p = 0;
13568 hourglass_shown_p = 0;
13569 UNBLOCK_INPUT;
13571 #endif
13576 /***********************************************************************
13577 Tool tips
13578 ***********************************************************************/
13580 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
13581 Lisp_Object, Lisp_Object));
13582 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
13583 Lisp_Object, int, int, int *, int *));
13585 /* The frame of a currently visible tooltip. */
13587 Lisp_Object tip_frame;
13589 /* If non-nil, a timer started that hides the last tooltip when it
13590 fires. */
13592 Lisp_Object tip_timer;
13593 Window tip_window;
13595 /* If non-nil, a vector of 3 elements containing the last args
13596 with which x-show-tip was called. See there. */
13598 Lisp_Object last_show_tip_args;
13600 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
13602 Lisp_Object Vx_max_tooltip_size;
13605 static Lisp_Object
13606 unwind_create_tip_frame (frame)
13607 Lisp_Object frame;
13609 Lisp_Object deleted;
13611 deleted = unwind_create_frame (frame);
13612 if (EQ (deleted, Qt))
13614 tip_window = NULL;
13615 tip_frame = Qnil;
13618 return deleted;
13622 /* Create a frame for a tooltip on the display described by DPYINFO.
13623 PARMS is a list of frame parameters. TEXT is the string to
13624 display in the tip frame. Value is the frame.
13626 Note that functions called here, esp. x_default_parameter can
13627 signal errors, for instance when a specified color name is
13628 undefined. We have to make sure that we're in a consistent state
13629 when this happens. */
13631 static Lisp_Object
13632 x_create_tip_frame (dpyinfo, parms, text)
13633 struct w32_display_info *dpyinfo;
13634 Lisp_Object parms, text;
13636 struct frame *f;
13637 Lisp_Object frame, tem;
13638 Lisp_Object name;
13639 long window_prompting = 0;
13640 int width, height;
13641 int count = SPECPDL_INDEX ();
13642 struct gcpro gcpro1, gcpro2, gcpro3;
13643 struct kboard *kb;
13644 int face_change_count_before = face_change_count;
13645 Lisp_Object buffer;
13646 struct buffer *old_buffer;
13648 check_w32 ();
13650 /* Use this general default value to start with until we know if
13651 this frame has a specified name. */
13652 Vx_resource_name = Vinvocation_name;
13654 #ifdef MULTI_KBOARD
13655 kb = dpyinfo->kboard;
13656 #else
13657 kb = &the_only_kboard;
13658 #endif
13660 /* Get the name of the frame to use for resource lookup. */
13661 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
13662 if (!STRINGP (name)
13663 && !EQ (name, Qunbound)
13664 && !NILP (name))
13665 error ("Invalid frame name--not a string or nil");
13666 Vx_resource_name = name;
13668 frame = Qnil;
13669 GCPRO3 (parms, name, frame);
13670 /* Make a frame without minibuffer nor mode-line. */
13671 f = make_frame (0);
13672 f->wants_modeline = 0;
13673 XSETFRAME (frame, f);
13675 buffer = Fget_buffer_create (build_string (" *tip*"));
13676 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
13677 old_buffer = current_buffer;
13678 set_buffer_internal_1 (XBUFFER (buffer));
13679 current_buffer->truncate_lines = Qnil;
13680 Ferase_buffer ();
13681 Finsert (1, &text);
13682 set_buffer_internal_1 (old_buffer);
13684 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
13685 record_unwind_protect (unwind_create_tip_frame, frame);
13687 /* By setting the output method, we're essentially saying that
13688 the frame is live, as per FRAME_LIVE_P. If we get a signal
13689 from this point on, x_destroy_window might screw up reference
13690 counts etc. */
13691 f->output_method = output_w32;
13692 f->output_data.w32 =
13693 (struct w32_output *) xmalloc (sizeof (struct w32_output));
13694 bzero (f->output_data.w32, sizeof (struct w32_output));
13696 FRAME_FONTSET (f) = -1;
13697 f->icon_name = Qnil;
13699 #if 0 /* GLYPH_DEBUG TODO: image support. */
13700 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
13701 dpyinfo_refcount = dpyinfo->reference_count;
13702 #endif /* GLYPH_DEBUG */
13703 #ifdef MULTI_KBOARD
13704 FRAME_KBOARD (f) = kb;
13705 #endif
13706 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13707 f->output_data.w32->explicit_parent = 0;
13709 /* Set the name; the functions to which we pass f expect the name to
13710 be set. */
13711 if (EQ (name, Qunbound) || NILP (name))
13713 f->name = build_string (dpyinfo->w32_id_name);
13714 f->explicit_name = 0;
13716 else
13718 f->name = name;
13719 f->explicit_name = 1;
13720 /* use the frame's title when getting resources for this frame. */
13721 specbind (Qx_resource_name, name);
13724 /* Extract the window parameters from the supplied values
13725 that are needed to determine window geometry. */
13727 Lisp_Object font;
13729 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
13731 BLOCK_INPUT;
13732 /* First, try whatever font the caller has specified. */
13733 if (STRINGP (font))
13735 tem = Fquery_fontset (font, Qnil);
13736 if (STRINGP (tem))
13737 font = x_new_fontset (f, SDATA (tem));
13738 else
13739 font = x_new_font (f, SDATA (font));
13742 /* Try out a font which we hope has bold and italic variations. */
13743 if (!STRINGP (font))
13744 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
13745 if (! STRINGP (font))
13746 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
13747 /* If those didn't work, look for something which will at least work. */
13748 if (! STRINGP (font))
13749 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
13750 UNBLOCK_INPUT;
13751 if (! STRINGP (font))
13752 font = build_string ("Fixedsys");
13754 x_default_parameter (f, parms, Qfont, font,
13755 "font", "Font", RES_TYPE_STRING);
13758 x_default_parameter (f, parms, Qborder_width, make_number (2),
13759 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
13760 /* This defaults to 2 in order to match xterm. We recognize either
13761 internalBorderWidth or internalBorder (which is what xterm calls
13762 it). */
13763 if (NILP (Fassq (Qinternal_border_width, parms)))
13765 Lisp_Object value;
13767 value = w32_get_arg (parms, Qinternal_border_width,
13768 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
13769 if (! EQ (value, Qunbound))
13770 parms = Fcons (Fcons (Qinternal_border_width, value),
13771 parms);
13773 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
13774 "internalBorderWidth", "internalBorderWidth",
13775 RES_TYPE_NUMBER);
13777 /* Also do the stuff which must be set before the window exists. */
13778 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
13779 "foreground", "Foreground", RES_TYPE_STRING);
13780 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
13781 "background", "Background", RES_TYPE_STRING);
13782 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
13783 "pointerColor", "Foreground", RES_TYPE_STRING);
13784 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
13785 "cursorColor", "Foreground", RES_TYPE_STRING);
13786 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
13787 "borderColor", "BorderColor", RES_TYPE_STRING);
13789 /* Init faces before x_default_parameter is called for scroll-bar
13790 parameters because that function calls x_set_scroll_bar_width,
13791 which calls change_frame_size, which calls Fset_window_buffer,
13792 which runs hooks, which call Fvertical_motion. At the end, we
13793 end up in init_iterator with a null face cache, which should not
13794 happen. */
13795 init_frame_faces (f);
13797 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
13798 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13800 window_prompting = x_figure_window_size (f, parms);
13802 /* No fringes on tip frame. */
13803 f->output_data.w32->fringes_extra = 0;
13804 f->output_data.w32->fringe_cols = 0;
13805 f->output_data.w32->left_fringe_width = 0;
13806 f->output_data.w32->right_fringe_width = 0;
13808 if (window_prompting & XNegative)
13810 if (window_prompting & YNegative)
13811 f->output_data.w32->win_gravity = SouthEastGravity;
13812 else
13813 f->output_data.w32->win_gravity = NorthEastGravity;
13815 else
13817 if (window_prompting & YNegative)
13818 f->output_data.w32->win_gravity = SouthWestGravity;
13819 else
13820 f->output_data.w32->win_gravity = NorthWestGravity;
13823 f->output_data.w32->size_hint_flags = window_prompting;
13825 BLOCK_INPUT;
13826 my_create_tip_window (f);
13827 UNBLOCK_INPUT;
13829 x_make_gc (f);
13831 x_default_parameter (f, parms, Qauto_raise, Qnil,
13832 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13833 x_default_parameter (f, parms, Qauto_lower, Qnil,
13834 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13835 x_default_parameter (f, parms, Qcursor_type, Qbox,
13836 "cursorType", "CursorType", RES_TYPE_SYMBOL);
13838 /* Dimensions, especially f->height, must be done via change_frame_size.
13839 Change will not be effected unless different from the current
13840 f->height. */
13841 width = f->width;
13842 height = f->height;
13843 f->height = 0;
13844 SET_FRAME_WIDTH (f, 0);
13845 change_frame_size (f, height, width, 1, 0, 0);
13847 /* Add `tooltip' frame parameter's default value. */
13848 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
13849 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
13850 Qnil));
13852 /* Set up faces after all frame parameters are known. This call
13853 also merges in face attributes specified for new frames.
13855 Frame parameters may be changed if .Xdefaults contains
13856 specifications for the default font. For example, if there is an
13857 `Emacs.default.attributeBackground: pink', the `background-color'
13858 attribute of the frame get's set, which let's the internal border
13859 of the tooltip frame appear in pink. Prevent this. */
13861 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
13863 /* Set tip_frame here, so that */
13864 tip_frame = frame;
13865 call1 (Qface_set_after_frame_default, frame);
13867 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
13868 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
13869 Qnil));
13872 f->no_split = 1;
13874 UNGCPRO;
13876 /* It is now ok to make the frame official even if we get an error
13877 below. And the frame needs to be on Vframe_list or making it
13878 visible won't work. */
13879 Vframe_list = Fcons (frame, Vframe_list);
13881 /* Now that the frame is official, it counts as a reference to
13882 its display. */
13883 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
13885 /* Setting attributes of faces of the tooltip frame from resources
13886 and similar will increment face_change_count, which leads to the
13887 clearing of all current matrices. Since this isn't necessary
13888 here, avoid it by resetting face_change_count to the value it
13889 had before we created the tip frame. */
13890 face_change_count = face_change_count_before;
13892 /* Discard the unwind_protect. */
13893 return unbind_to (count, frame);
13897 /* Compute where to display tip frame F. PARMS is the list of frame
13898 parameters for F. DX and DY are specified offsets from the current
13899 location of the mouse. WIDTH and HEIGHT are the width and height
13900 of the tooltip. Return coordinates relative to the root window of
13901 the display in *ROOT_X, and *ROOT_Y. */
13903 static void
13904 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
13905 struct frame *f;
13906 Lisp_Object parms, dx, dy;
13907 int width, height;
13908 int *root_x, *root_y;
13910 Lisp_Object left, top;
13912 /* User-specified position? */
13913 left = Fcdr (Fassq (Qleft, parms));
13914 top = Fcdr (Fassq (Qtop, parms));
13916 /* Move the tooltip window where the mouse pointer is. Resize and
13917 show it. */
13918 if (!INTEGERP (left) || !INTEGERP (top))
13920 POINT pt;
13922 BLOCK_INPUT;
13923 GetCursorPos (&pt);
13924 *root_x = pt.x;
13925 *root_y = pt.y;
13926 UNBLOCK_INPUT;
13929 if (INTEGERP (top))
13930 *root_y = XINT (top);
13931 else if (*root_y + XINT (dy) - height < 0)
13932 *root_y -= XINT (dy);
13933 else
13935 *root_y -= height;
13936 *root_y += XINT (dy);
13939 if (INTEGERP (left))
13940 *root_x = XINT (left);
13941 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
13942 /* It fits to the right of the pointer. */
13943 *root_x += XINT (dx);
13944 else if (width + XINT (dx) <= *root_x)
13945 /* It fits to the left of the pointer. */
13946 *root_x -= width + XINT (dx);
13947 else
13948 /* Put it left justified on the screen -- it ought to fit that way. */
13949 *root_x = 0;
13953 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
13954 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
13955 A tooltip window is a small window displaying a string.
13957 FRAME nil or omitted means use the selected frame.
13959 PARMS is an optional list of frame parameters which can be
13960 used to change the tooltip's appearance.
13962 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
13963 means use the default timeout of 5 seconds.
13965 If the list of frame parameters PARAMS contains a `left' parameter,
13966 the tooltip is displayed at that x-position. Otherwise it is
13967 displayed at the mouse position, with offset DX added (default is 5 if
13968 DX isn't specified). Likewise for the y-position; if a `top' frame
13969 parameter is specified, it determines the y-position of the tooltip
13970 window, otherwise it is displayed at the mouse position, with offset
13971 DY added (default is -10).
13973 A tooltip's maximum size is specified by `x-max-tooltip-size'.
13974 Text larger than the specified size is clipped. */)
13975 (string, frame, parms, timeout, dx, dy)
13976 Lisp_Object string, frame, parms, timeout, dx, dy;
13978 struct frame *f;
13979 struct window *w;
13980 int root_x, root_y;
13981 struct buffer *old_buffer;
13982 struct text_pos pos;
13983 int i, width, height;
13984 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
13985 int old_windows_or_buffers_changed = windows_or_buffers_changed;
13986 int count = SPECPDL_INDEX ();
13988 specbind (Qinhibit_redisplay, Qt);
13990 GCPRO4 (string, parms, frame, timeout);
13992 CHECK_STRING (string);
13993 f = check_x_frame (frame);
13994 if (NILP (timeout))
13995 timeout = make_number (5);
13996 else
13997 CHECK_NATNUM (timeout);
13999 if (NILP (dx))
14000 dx = make_number (5);
14001 else
14002 CHECK_NUMBER (dx);
14004 if (NILP (dy))
14005 dy = make_number (-10);
14006 else
14007 CHECK_NUMBER (dy);
14009 if (NILP (last_show_tip_args))
14010 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
14012 if (!NILP (tip_frame))
14014 Lisp_Object last_string = AREF (last_show_tip_args, 0);
14015 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
14016 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
14018 if (EQ (frame, last_frame)
14019 && !NILP (Fequal (last_string, string))
14020 && !NILP (Fequal (last_parms, parms)))
14022 struct frame *f = XFRAME (tip_frame);
14024 /* Only DX and DY have changed. */
14025 if (!NILP (tip_timer))
14027 Lisp_Object timer = tip_timer;
14028 tip_timer = Qnil;
14029 call1 (Qcancel_timer, timer);
14032 BLOCK_INPUT;
14033 compute_tip_xy (f, parms, dx, dy, PIXEL_WIDTH (f),
14034 PIXEL_HEIGHT (f), &root_x, &root_y);
14036 /* Put tooltip in topmost group and in position. */
14037 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14038 root_x, root_y, 0, 0,
14039 SWP_NOSIZE | SWP_NOACTIVATE);
14041 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14042 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14043 0, 0, 0, 0,
14044 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14046 UNBLOCK_INPUT;
14047 goto start_timer;
14051 /* Hide a previous tip, if any. */
14052 Fx_hide_tip ();
14054 ASET (last_show_tip_args, 0, string);
14055 ASET (last_show_tip_args, 1, frame);
14056 ASET (last_show_tip_args, 2, parms);
14058 /* Add default values to frame parameters. */
14059 if (NILP (Fassq (Qname, parms)))
14060 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
14061 if (NILP (Fassq (Qinternal_border_width, parms)))
14062 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
14063 if (NILP (Fassq (Qborder_width, parms)))
14064 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
14065 if (NILP (Fassq (Qborder_color, parms)))
14066 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
14067 if (NILP (Fassq (Qbackground_color, parms)))
14068 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
14069 parms);
14071 /* Block input until the tip has been fully drawn, to avoid crashes
14072 when drawing tips in menus. */
14073 BLOCK_INPUT;
14075 /* Create a frame for the tooltip, and record it in the global
14076 variable tip_frame. */
14077 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
14078 f = XFRAME (frame);
14080 /* Set up the frame's root window. */
14081 w = XWINDOW (FRAME_ROOT_WINDOW (f));
14082 w->left = w->top = make_number (0);
14084 if (CONSP (Vx_max_tooltip_size)
14085 && INTEGERP (XCAR (Vx_max_tooltip_size))
14086 && XINT (XCAR (Vx_max_tooltip_size)) > 0
14087 && INTEGERP (XCDR (Vx_max_tooltip_size))
14088 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
14090 w->width = XCAR (Vx_max_tooltip_size);
14091 w->height = XCDR (Vx_max_tooltip_size);
14093 else
14095 w->width = make_number (80);
14096 w->height = make_number (40);
14099 f->window_width = XINT (w->width);
14100 adjust_glyphs (f);
14101 w->pseudo_window_p = 1;
14103 /* Display the tooltip text in a temporary buffer. */
14104 old_buffer = current_buffer;
14105 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
14106 current_buffer->truncate_lines = Qnil;
14107 clear_glyph_matrix (w->desired_matrix);
14108 clear_glyph_matrix (w->current_matrix);
14109 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
14110 try_window (FRAME_ROOT_WINDOW (f), pos);
14112 /* Compute width and height of the tooltip. */
14113 width = height = 0;
14114 for (i = 0; i < w->desired_matrix->nrows; ++i)
14116 struct glyph_row *row = &w->desired_matrix->rows[i];
14117 struct glyph *last;
14118 int row_width;
14120 /* Stop at the first empty row at the end. */
14121 if (!row->enabled_p || !row->displays_text_p)
14122 break;
14124 /* Let the row go over the full width of the frame. */
14125 row->full_width_p = 1;
14127 #ifdef TODO /* Investigate why some fonts need more width than is
14128 calculated for some tooltips. */
14129 /* There's a glyph at the end of rows that is use to place
14130 the cursor there. Don't include the width of this glyph. */
14131 if (row->used[TEXT_AREA])
14133 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
14134 row_width = row->pixel_width - last->pixel_width;
14136 else
14137 #endif
14138 row_width = row->pixel_width;
14140 /* TODO: find why tips do not draw along baseline as instructed. */
14141 height += row->height;
14142 width = max (width, row_width);
14145 /* Add the frame's internal border to the width and height the X
14146 window should have. */
14147 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14148 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14150 /* Move the tooltip window where the mouse pointer is. Resize and
14151 show it. */
14152 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
14155 /* Adjust Window size to take border into account. */
14156 RECT rect;
14157 rect.left = rect.top = 0;
14158 rect.right = width;
14159 rect.bottom = height;
14160 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
14161 FRAME_EXTERNAL_MENU_BAR (f));
14163 /* Position and size tooltip, and put it in the topmost group. */
14164 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14165 root_x, root_y, rect.right - rect.left,
14166 rect.bottom - rect.top, SWP_NOACTIVATE);
14168 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14169 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14170 0, 0, 0, 0,
14171 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14173 /* Let redisplay know that we have made the frame visible already. */
14174 f->async_visible = 1;
14176 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
14179 /* Draw into the window. */
14180 w->must_be_updated_p = 1;
14181 update_single_window (w, 1);
14183 UNBLOCK_INPUT;
14185 /* Restore original current buffer. */
14186 set_buffer_internal_1 (old_buffer);
14187 windows_or_buffers_changed = old_windows_or_buffers_changed;
14189 start_timer:
14190 /* Let the tip disappear after timeout seconds. */
14191 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
14192 intern ("x-hide-tip"));
14194 UNGCPRO;
14195 return unbind_to (count, Qnil);
14199 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
14200 doc: /* Hide the current tooltip window, if there is any.
14201 Value is t if tooltip was open, nil otherwise. */)
14204 int count;
14205 Lisp_Object deleted, frame, timer;
14206 struct gcpro gcpro1, gcpro2;
14208 /* Return quickly if nothing to do. */
14209 if (NILP (tip_timer) && NILP (tip_frame))
14210 return Qnil;
14212 frame = tip_frame;
14213 timer = tip_timer;
14214 GCPRO2 (frame, timer);
14215 tip_frame = tip_timer = deleted = Qnil;
14217 count = SPECPDL_INDEX ();
14218 specbind (Qinhibit_redisplay, Qt);
14219 specbind (Qinhibit_quit, Qt);
14221 if (!NILP (timer))
14222 call1 (Qcancel_timer, timer);
14224 if (FRAMEP (frame))
14226 Fdelete_frame (frame, Qnil);
14227 deleted = Qt;
14230 UNGCPRO;
14231 return unbind_to (count, deleted);
14236 /***********************************************************************
14237 File selection dialog
14238 ***********************************************************************/
14239 extern Lisp_Object Qfile_name_history;
14241 /* Callback for altering the behaviour of the Open File dialog.
14242 Makes the Filename text field contain "Current Directory" and be
14243 read-only when "Directories" is selected in the filter. This
14244 allows us to work around the fact that the standard Open File
14245 dialog does not support directories. */
14246 UINT CALLBACK
14247 file_dialog_callback (hwnd, msg, wParam, lParam)
14248 HWND hwnd;
14249 UINT msg;
14250 WPARAM wParam;
14251 LPARAM lParam;
14253 if (msg == WM_NOTIFY)
14255 OFNOTIFY * notify = (OFNOTIFY *)lParam;
14256 /* Detect when the Filter dropdown is changed. */
14257 if (notify->hdr.code == CDN_TYPECHANGE)
14259 HWND dialog = GetParent (hwnd);
14260 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
14262 /* Directories is in index 2. */
14263 if (notify->lpOFN->nFilterIndex == 2)
14265 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14266 "Current Directory");
14267 EnableWindow (edit_control, FALSE);
14269 else
14271 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14272 "");
14273 EnableWindow (edit_control, TRUE);
14277 return 0;
14280 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
14281 doc: /* Read file name, prompting with PROMPT in directory DIR.
14282 Use a file selection dialog.
14283 Select DEFAULT-FILENAME in the dialog's file selection box, if
14284 specified. Ensure that file exists if MUSTMATCH is non-nil. */)
14285 (prompt, dir, default_filename, mustmatch)
14286 Lisp_Object prompt, dir, default_filename, mustmatch;
14288 struct frame *f = SELECTED_FRAME ();
14289 Lisp_Object file = Qnil;
14290 int count = SPECPDL_INDEX ();
14291 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
14292 char filename[MAX_PATH + 1];
14293 char init_dir[MAX_PATH + 1];
14295 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
14296 CHECK_STRING (prompt);
14297 CHECK_STRING (dir);
14299 /* Create the dialog with PROMPT as title, using DIR as initial
14300 directory and using "*" as pattern. */
14301 dir = Fexpand_file_name (dir, Qnil);
14302 strncpy (init_dir, SDATA (dir), MAX_PATH);
14303 init_dir[MAX_PATH] = '\0';
14304 unixtodos_filename (init_dir);
14306 if (STRINGP (default_filename))
14308 char *file_name_only;
14309 char *full_path_name = SDATA (default_filename);
14311 unixtodos_filename (full_path_name);
14313 file_name_only = strrchr (full_path_name, '\\');
14314 if (!file_name_only)
14315 file_name_only = full_path_name;
14316 else
14318 file_name_only++;
14321 strncpy (filename, file_name_only, MAX_PATH);
14322 filename[MAX_PATH] = '\0';
14324 else
14325 filename[0] = '\0';
14328 OPENFILENAME file_details;
14330 /* Prevent redisplay. */
14331 specbind (Qinhibit_redisplay, Qt);
14332 BLOCK_INPUT;
14334 bzero (&file_details, sizeof (file_details));
14335 file_details.lStructSize = sizeof (file_details);
14336 file_details.hwndOwner = FRAME_W32_WINDOW (f);
14337 /* Undocumented Bug in Common File Dialog:
14338 If a filter is not specified, shell links are not resolved. */
14339 file_details.lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
14340 file_details.lpstrFile = filename;
14341 file_details.nMaxFile = sizeof (filename);
14342 file_details.lpstrInitialDir = init_dir;
14343 file_details.lpstrTitle = SDATA (prompt);
14344 file_details.Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
14345 | OFN_EXPLORER | OFN_ENABLEHOOK);
14346 if (!NILP (mustmatch))
14347 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
14349 file_details.lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
14351 if (GetOpenFileName (&file_details))
14353 dostounix_filename (filename);
14354 if (file_details.nFilterIndex == 2)
14356 /* "Folder Only" selected - strip dummy file name. */
14357 char * last = strrchr (filename, '/');
14358 *last = '\0';
14361 file = DECODE_FILE(build_string (filename));
14363 /* User cancelled the dialog without making a selection. */
14364 else if (!CommDlgExtendedError ())
14365 file = Qnil;
14366 /* An error occurred, fallback on reading from the mini-buffer. */
14367 else
14368 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
14369 dir, mustmatch, dir, Qfile_name_history,
14370 default_filename, Qnil);
14372 UNBLOCK_INPUT;
14373 file = unbind_to (count, file);
14376 UNGCPRO;
14378 /* Make "Cancel" equivalent to C-g. */
14379 if (NILP (file))
14380 Fsignal (Qquit, Qnil);
14382 return unbind_to (count, file);
14387 /***********************************************************************
14388 w32 specialized functions
14389 ***********************************************************************/
14391 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
14392 doc: /* Select a font using the W32 font dialog.
14393 Returns an X font string corresponding to the selection. */)
14394 (frame, include_proportional)
14395 Lisp_Object frame, include_proportional;
14397 FRAME_PTR f = check_x_frame (frame);
14398 CHOOSEFONT cf;
14399 LOGFONT lf;
14400 TEXTMETRIC tm;
14401 HDC hdc;
14402 HANDLE oldobj;
14403 char buf[100];
14405 bzero (&cf, sizeof (cf));
14406 bzero (&lf, sizeof (lf));
14408 cf.lStructSize = sizeof (cf);
14409 cf.hwndOwner = FRAME_W32_WINDOW (f);
14410 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
14412 /* Unless include_proportional is non-nil, limit the selection to
14413 monospaced fonts. */
14414 if (NILP (include_proportional))
14415 cf.Flags |= CF_FIXEDPITCHONLY;
14417 cf.lpLogFont = &lf;
14419 /* Initialize as much of the font details as we can from the current
14420 default font. */
14421 hdc = GetDC (FRAME_W32_WINDOW (f));
14422 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
14423 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
14424 if (GetTextMetrics (hdc, &tm))
14426 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
14427 lf.lfWeight = tm.tmWeight;
14428 lf.lfItalic = tm.tmItalic;
14429 lf.lfUnderline = tm.tmUnderlined;
14430 lf.lfStrikeOut = tm.tmStruckOut;
14431 lf.lfCharSet = tm.tmCharSet;
14432 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
14434 SelectObject (hdc, oldobj);
14435 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
14437 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
14438 return Qnil;
14440 return build_string (buf);
14443 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
14444 Sw32_send_sys_command, 1, 2, 0,
14445 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
14446 Some useful values for command are #xf030 to maximise frame (#xf020
14447 to minimize), #xf120 to restore frame to original size, and #xf100
14448 to activate the menubar for keyboard access. #xf140 activates the
14449 screen saver if defined.
14451 If optional parameter FRAME is not specified, use selected frame. */)
14452 (command, frame)
14453 Lisp_Object command, frame;
14455 FRAME_PTR f = check_x_frame (frame);
14457 CHECK_NUMBER (command);
14459 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
14461 return Qnil;
14464 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
14465 doc: /* Get Windows to perform OPERATION on DOCUMENT.
14466 This is a wrapper around the ShellExecute system function, which
14467 invokes the application registered to handle OPERATION for DOCUMENT.
14468 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
14469 nil for the default action), and DOCUMENT is typically the name of a
14470 document file or URL, but can also be a program executable to run or
14471 a directory to open in the Windows Explorer.
14473 If DOCUMENT is a program executable, PARAMETERS can be a string
14474 containing command line parameters, but otherwise should be nil.
14476 SHOW-FLAG can be used to control whether the invoked application is hidden
14477 or minimized. If SHOW-FLAG is nil, the application is displayed normally,
14478 otherwise it is an integer representing a ShowWindow flag:
14480 0 - start hidden
14481 1 - start normally
14482 3 - start maximized
14483 6 - start minimized */)
14484 (operation, document, parameters, show_flag)
14485 Lisp_Object operation, document, parameters, show_flag;
14487 Lisp_Object current_dir;
14489 CHECK_STRING (document);
14491 /* Encode filename and current directory. */
14492 current_dir = ENCODE_FILE (current_buffer->directory);
14493 document = ENCODE_FILE (document);
14494 if ((int) ShellExecute (NULL,
14495 (STRINGP (operation) ?
14496 SDATA (operation) : NULL),
14497 SDATA (document),
14498 (STRINGP (parameters) ?
14499 SDATA (parameters) : NULL),
14500 SDATA (current_dir),
14501 (INTEGERP (show_flag) ?
14502 XINT (show_flag) : SW_SHOWDEFAULT))
14503 > 32)
14504 return Qt;
14505 error ("ShellExecute failed: %s", w32_strerror (0));
14508 /* Lookup virtual keycode from string representing the name of a
14509 non-ascii keystroke into the corresponding virtual key, using
14510 lispy_function_keys. */
14511 static int
14512 lookup_vk_code (char *key)
14514 int i;
14516 for (i = 0; i < 256; i++)
14517 if (lispy_function_keys[i] != 0
14518 && strcmp (lispy_function_keys[i], key) == 0)
14519 return i;
14521 return -1;
14524 /* Convert a one-element vector style key sequence to a hot key
14525 definition. */
14526 static int
14527 w32_parse_hot_key (key)
14528 Lisp_Object key;
14530 /* Copied from Fdefine_key and store_in_keymap. */
14531 register Lisp_Object c;
14532 int vk_code;
14533 int lisp_modifiers;
14534 int w32_modifiers;
14535 struct gcpro gcpro1;
14537 CHECK_VECTOR (key);
14539 if (XFASTINT (Flength (key)) != 1)
14540 return Qnil;
14542 GCPRO1 (key);
14544 c = Faref (key, make_number (0));
14546 if (CONSP (c) && lucid_event_type_list_p (c))
14547 c = Fevent_convert_list (c);
14549 UNGCPRO;
14551 if (! INTEGERP (c) && ! SYMBOLP (c))
14552 error ("Key definition is invalid");
14554 /* Work out the base key and the modifiers. */
14555 if (SYMBOLP (c))
14557 c = parse_modifiers (c);
14558 lisp_modifiers = Fcar (Fcdr (c));
14559 c = Fcar (c);
14560 if (!SYMBOLP (c))
14561 abort ();
14562 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
14564 else if (INTEGERP (c))
14566 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
14567 /* Many ascii characters are their own virtual key code. */
14568 vk_code = XINT (c) & CHARACTERBITS;
14571 if (vk_code < 0 || vk_code > 255)
14572 return Qnil;
14574 if ((lisp_modifiers & meta_modifier) != 0
14575 && !NILP (Vw32_alt_is_meta))
14576 lisp_modifiers |= alt_modifier;
14578 /* Supply defs missing from mingw32. */
14579 #ifndef MOD_ALT
14580 #define MOD_ALT 0x0001
14581 #define MOD_CONTROL 0x0002
14582 #define MOD_SHIFT 0x0004
14583 #define MOD_WIN 0x0008
14584 #endif
14586 /* Convert lisp modifiers to Windows hot-key form. */
14587 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
14588 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
14589 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
14590 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
14592 return HOTKEY (vk_code, w32_modifiers);
14595 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
14596 Sw32_register_hot_key, 1, 1, 0,
14597 doc: /* Register KEY as a hot-key combination.
14598 Certain key combinations like Alt-Tab are reserved for system use on
14599 Windows, and therefore are normally intercepted by the system. However,
14600 most of these key combinations can be received by registering them as
14601 hot-keys, overriding their special meaning.
14603 KEY must be a one element key definition in vector form that would be
14604 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
14605 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
14606 is always interpreted as the Windows modifier keys.
14608 The return value is the hotkey-id if registered, otherwise nil. */)
14609 (key)
14610 Lisp_Object key;
14612 key = w32_parse_hot_key (key);
14614 if (NILP (Fmemq (key, w32_grabbed_keys)))
14616 /* Reuse an empty slot if possible. */
14617 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
14619 /* Safe to add new key to list, even if we have focus. */
14620 if (NILP (item))
14621 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
14622 else
14623 XSETCAR (item, key);
14625 /* Notify input thread about new hot-key definition, so that it
14626 takes effect without needing to switch focus. */
14627 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
14628 (WPARAM) key, 0);
14631 return key;
14634 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
14635 Sw32_unregister_hot_key, 1, 1, 0,
14636 doc: /* Unregister HOTKEY as a hot-key combination. */)
14637 (key)
14638 Lisp_Object key;
14640 Lisp_Object item;
14642 if (!INTEGERP (key))
14643 key = w32_parse_hot_key (key);
14645 item = Fmemq (key, w32_grabbed_keys);
14647 if (!NILP (item))
14649 /* Notify input thread about hot-key definition being removed, so
14650 that it takes effect without needing focus switch. */
14651 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
14652 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
14654 MSG msg;
14655 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14657 return Qt;
14659 return Qnil;
14662 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
14663 Sw32_registered_hot_keys, 0, 0, 0,
14664 doc: /* Return list of registered hot-key IDs. */)
14667 return Fcopy_sequence (w32_grabbed_keys);
14670 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
14671 Sw32_reconstruct_hot_key, 1, 1, 0,
14672 doc: /* Convert hot-key ID to a lisp key combination. */)
14673 (hotkeyid)
14674 Lisp_Object hotkeyid;
14676 int vk_code, w32_modifiers;
14677 Lisp_Object key;
14679 CHECK_NUMBER (hotkeyid);
14681 vk_code = HOTKEY_VK_CODE (hotkeyid);
14682 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
14684 if (lispy_function_keys[vk_code])
14685 key = intern (lispy_function_keys[vk_code]);
14686 else
14687 key = make_number (vk_code);
14689 key = Fcons (key, Qnil);
14690 if (w32_modifiers & MOD_SHIFT)
14691 key = Fcons (Qshift, key);
14692 if (w32_modifiers & MOD_CONTROL)
14693 key = Fcons (Qctrl, key);
14694 if (w32_modifiers & MOD_ALT)
14695 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
14696 if (w32_modifiers & MOD_WIN)
14697 key = Fcons (Qhyper, key);
14699 return key;
14702 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
14703 Sw32_toggle_lock_key, 1, 2, 0,
14704 doc: /* Toggle the state of the lock key KEY.
14705 KEY can be `capslock', `kp-numlock', or `scroll'.
14706 If the optional parameter NEW-STATE is a number, then the state of KEY
14707 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
14708 (key, new_state)
14709 Lisp_Object key, new_state;
14711 int vk_code;
14713 if (EQ (key, intern ("capslock")))
14714 vk_code = VK_CAPITAL;
14715 else if (EQ (key, intern ("kp-numlock")))
14716 vk_code = VK_NUMLOCK;
14717 else if (EQ (key, intern ("scroll")))
14718 vk_code = VK_SCROLL;
14719 else
14720 return Qnil;
14722 if (!dwWindowsThreadId)
14723 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
14725 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
14726 (WPARAM) vk_code, (LPARAM) new_state))
14728 MSG msg;
14729 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14730 return make_number (msg.wParam);
14732 return Qnil;
14735 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
14736 doc: /* Return storage information about the file system FILENAME is on.
14737 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
14738 storage of the file system, FREE is the free storage, and AVAIL is the
14739 storage available to a non-superuser. All 3 numbers are in bytes.
14740 If the underlying system call fails, value is nil. */)
14741 (filename)
14742 Lisp_Object filename;
14744 Lisp_Object encoded, value;
14746 CHECK_STRING (filename);
14747 filename = Fexpand_file_name (filename, Qnil);
14748 encoded = ENCODE_FILE (filename);
14750 value = Qnil;
14752 /* Determining the required information on Windows turns out, sadly,
14753 to be more involved than one would hope. The original Win32 api
14754 call for this will return bogus information on some systems, but we
14755 must dynamically probe for the replacement api, since that was
14756 added rather late on. */
14758 HMODULE hKernel = GetModuleHandle ("kernel32");
14759 BOOL (*pfn_GetDiskFreeSpaceEx)
14760 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
14761 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
14763 /* On Windows, we may need to specify the root directory of the
14764 volume holding FILENAME. */
14765 char rootname[MAX_PATH];
14766 char *name = SDATA (encoded);
14768 /* find the root name of the volume if given */
14769 if (isalpha (name[0]) && name[1] == ':')
14771 rootname[0] = name[0];
14772 rootname[1] = name[1];
14773 rootname[2] = '\\';
14774 rootname[3] = 0;
14776 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
14778 char *str = rootname;
14779 int slashes = 4;
14782 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
14783 break;
14784 *str++ = *name++;
14786 while ( *name );
14788 *str++ = '\\';
14789 *str = 0;
14792 if (pfn_GetDiskFreeSpaceEx)
14794 /* Unsigned large integers cannot be cast to double, so
14795 use signed ones instead. */
14796 LARGE_INTEGER availbytes;
14797 LARGE_INTEGER freebytes;
14798 LARGE_INTEGER totalbytes;
14800 if (pfn_GetDiskFreeSpaceEx(rootname,
14801 (ULARGE_INTEGER *)&availbytes,
14802 (ULARGE_INTEGER *)&totalbytes,
14803 (ULARGE_INTEGER *)&freebytes))
14804 value = list3 (make_float ((double) totalbytes.QuadPart),
14805 make_float ((double) freebytes.QuadPart),
14806 make_float ((double) availbytes.QuadPart));
14808 else
14810 DWORD sectors_per_cluster;
14811 DWORD bytes_per_sector;
14812 DWORD free_clusters;
14813 DWORD total_clusters;
14815 if (GetDiskFreeSpace(rootname,
14816 &sectors_per_cluster,
14817 &bytes_per_sector,
14818 &free_clusters,
14819 &total_clusters))
14820 value = list3 (make_float ((double) total_clusters
14821 * sectors_per_cluster * bytes_per_sector),
14822 make_float ((double) free_clusters
14823 * sectors_per_cluster * bytes_per_sector),
14824 make_float ((double) free_clusters
14825 * sectors_per_cluster * bytes_per_sector));
14829 return value;
14832 /***********************************************************************
14833 Initialization
14834 ***********************************************************************/
14836 void
14837 syms_of_w32fns ()
14839 HMODULE user32_lib = GetModuleHandle ("user32.dll");
14841 /* This is zero if not using MS-Windows. */
14842 w32_in_use = 0;
14844 /* TrackMouseEvent not available in all versions of Windows, so must load
14845 it dynamically. Do it once, here, instead of every time it is used. */
14846 track_mouse_event_fn = GetProcAddress (user32_lib, "TrackMouseEvent");
14847 track_mouse_window = NULL;
14849 w32_visible_system_caret_hwnd = NULL;
14851 Qauto_raise = intern ("auto-raise");
14852 staticpro (&Qauto_raise);
14853 Qauto_lower = intern ("auto-lower");
14854 staticpro (&Qauto_lower);
14855 Qborder_color = intern ("border-color");
14856 staticpro (&Qborder_color);
14857 Qborder_width = intern ("border-width");
14858 staticpro (&Qborder_width);
14859 Qcursor_color = intern ("cursor-color");
14860 staticpro (&Qcursor_color);
14861 Qcursor_type = intern ("cursor-type");
14862 staticpro (&Qcursor_type);
14863 Qgeometry = intern ("geometry");
14864 staticpro (&Qgeometry);
14865 Qicon_left = intern ("icon-left");
14866 staticpro (&Qicon_left);
14867 Qicon_top = intern ("icon-top");
14868 staticpro (&Qicon_top);
14869 Qicon_type = intern ("icon-type");
14870 staticpro (&Qicon_type);
14871 Qicon_name = intern ("icon-name");
14872 staticpro (&Qicon_name);
14873 Qinternal_border_width = intern ("internal-border-width");
14874 staticpro (&Qinternal_border_width);
14875 Qleft = intern ("left");
14876 staticpro (&Qleft);
14877 Qright = intern ("right");
14878 staticpro (&Qright);
14879 Qmouse_color = intern ("mouse-color");
14880 staticpro (&Qmouse_color);
14881 Qnone = intern ("none");
14882 staticpro (&Qnone);
14883 Qparent_id = intern ("parent-id");
14884 staticpro (&Qparent_id);
14885 Qscroll_bar_width = intern ("scroll-bar-width");
14886 staticpro (&Qscroll_bar_width);
14887 Qsuppress_icon = intern ("suppress-icon");
14888 staticpro (&Qsuppress_icon);
14889 Qundefined_color = intern ("undefined-color");
14890 staticpro (&Qundefined_color);
14891 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
14892 staticpro (&Qvertical_scroll_bars);
14893 Qvisibility = intern ("visibility");
14894 staticpro (&Qvisibility);
14895 Qwindow_id = intern ("window-id");
14896 staticpro (&Qwindow_id);
14897 Qx_frame_parameter = intern ("x-frame-parameter");
14898 staticpro (&Qx_frame_parameter);
14899 Qx_resource_name = intern ("x-resource-name");
14900 staticpro (&Qx_resource_name);
14901 Quser_position = intern ("user-position");
14902 staticpro (&Quser_position);
14903 Quser_size = intern ("user-size");
14904 staticpro (&Quser_size);
14905 Qscreen_gamma = intern ("screen-gamma");
14906 staticpro (&Qscreen_gamma);
14907 Qline_spacing = intern ("line-spacing");
14908 staticpro (&Qline_spacing);
14909 Qcenter = intern ("center");
14910 staticpro (&Qcenter);
14911 Qcancel_timer = intern ("cancel-timer");
14912 staticpro (&Qcancel_timer);
14913 Qfullscreen = intern ("fullscreen");
14914 staticpro (&Qfullscreen);
14915 Qfullwidth = intern ("fullwidth");
14916 staticpro (&Qfullwidth);
14917 Qfullheight = intern ("fullheight");
14918 staticpro (&Qfullheight);
14919 Qfullboth = intern ("fullboth");
14920 staticpro (&Qfullboth);
14922 Qhyper = intern ("hyper");
14923 staticpro (&Qhyper);
14924 Qsuper = intern ("super");
14925 staticpro (&Qsuper);
14926 Qmeta = intern ("meta");
14927 staticpro (&Qmeta);
14928 Qalt = intern ("alt");
14929 staticpro (&Qalt);
14930 Qctrl = intern ("ctrl");
14931 staticpro (&Qctrl);
14932 Qcontrol = intern ("control");
14933 staticpro (&Qcontrol);
14934 Qshift = intern ("shift");
14935 staticpro (&Qshift);
14936 /* This is the end of symbol initialization. */
14938 /* Text property `display' should be nonsticky by default. */
14939 Vtext_property_default_nonsticky
14940 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
14943 Qlaplace = intern ("laplace");
14944 staticpro (&Qlaplace);
14945 Qemboss = intern ("emboss");
14946 staticpro (&Qemboss);
14947 Qedge_detection = intern ("edge-detection");
14948 staticpro (&Qedge_detection);
14949 Qheuristic = intern ("heuristic");
14950 staticpro (&Qheuristic);
14951 QCmatrix = intern (":matrix");
14952 staticpro (&QCmatrix);
14953 QCcolor_adjustment = intern (":color-adjustment");
14954 staticpro (&QCcolor_adjustment);
14955 QCmask = intern (":mask");
14956 staticpro (&QCmask);
14958 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
14959 staticpro (&Qface_set_after_frame_default);
14961 Fput (Qundefined_color, Qerror_conditions,
14962 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
14963 Fput (Qundefined_color, Qerror_message,
14964 build_string ("Undefined color"));
14966 staticpro (&w32_grabbed_keys);
14967 w32_grabbed_keys = Qnil;
14969 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
14970 doc: /* An array of color name mappings for windows. */);
14971 Vw32_color_map = Qnil;
14973 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
14974 doc: /* Non-nil if alt key presses are passed on to Windows.
14975 When non-nil, for example, alt pressed and released and then space will
14976 open the System menu. When nil, Emacs silently swallows alt key events. */);
14977 Vw32_pass_alt_to_system = Qnil;
14979 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
14980 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
14981 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
14982 Vw32_alt_is_meta = Qt;
14984 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
14985 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
14986 XSETINT (Vw32_quit_key, 0);
14988 DEFVAR_LISP ("w32-pass-lwindow-to-system",
14989 &Vw32_pass_lwindow_to_system,
14990 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
14991 When non-nil, the Start menu is opened by tapping the key. */);
14992 Vw32_pass_lwindow_to_system = Qt;
14994 DEFVAR_LISP ("w32-pass-rwindow-to-system",
14995 &Vw32_pass_rwindow_to_system,
14996 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
14997 When non-nil, the Start menu is opened by tapping the key. */);
14998 Vw32_pass_rwindow_to_system = Qt;
15000 DEFVAR_INT ("w32-phantom-key-code",
15001 &Vw32_phantom_key_code,
15002 doc: /* Virtual key code used to generate \"phantom\" key presses.
15003 Value is a number between 0 and 255.
15005 Phantom key presses are generated in order to stop the system from
15006 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
15007 `w32-pass-rwindow-to-system' is nil. */);
15008 /* Although 255 is technically not a valid key code, it works and
15009 means that this hack won't interfere with any real key code. */
15010 Vw32_phantom_key_code = 255;
15012 DEFVAR_LISP ("w32-enable-num-lock",
15013 &Vw32_enable_num_lock,
15014 doc: /* Non-nil if Num Lock should act normally.
15015 Set to nil to see Num Lock as the key `kp-numlock'. */);
15016 Vw32_enable_num_lock = Qt;
15018 DEFVAR_LISP ("w32-enable-caps-lock",
15019 &Vw32_enable_caps_lock,
15020 doc: /* Non-nil if Caps Lock should act normally.
15021 Set to nil to see Caps Lock as the key `capslock'. */);
15022 Vw32_enable_caps_lock = Qt;
15024 DEFVAR_LISP ("w32-scroll-lock-modifier",
15025 &Vw32_scroll_lock_modifier,
15026 doc: /* Modifier to use for the Scroll Lock on state.
15027 The value can be hyper, super, meta, alt, control or shift for the
15028 respective modifier, or nil to see Scroll Lock as the key `scroll'.
15029 Any other value will cause the key to be ignored. */);
15030 Vw32_scroll_lock_modifier = Qt;
15032 DEFVAR_LISP ("w32-lwindow-modifier",
15033 &Vw32_lwindow_modifier,
15034 doc: /* Modifier to use for the left \"Windows\" key.
15035 The value can be hyper, super, meta, alt, control or shift for the
15036 respective modifier, or nil to appear as the key `lwindow'.
15037 Any other value will cause the key to be ignored. */);
15038 Vw32_lwindow_modifier = Qnil;
15040 DEFVAR_LISP ("w32-rwindow-modifier",
15041 &Vw32_rwindow_modifier,
15042 doc: /* Modifier to use for the right \"Windows\" key.
15043 The value can be hyper, super, meta, alt, control or shift for the
15044 respective modifier, or nil to appear as the key `rwindow'.
15045 Any other value will cause the key to be ignored. */);
15046 Vw32_rwindow_modifier = Qnil;
15048 DEFVAR_LISP ("w32-apps-modifier",
15049 &Vw32_apps_modifier,
15050 doc: /* Modifier to use for the \"Apps\" key.
15051 The value can be hyper, super, meta, alt, control or shift for the
15052 respective modifier, or nil to appear as the key `apps'.
15053 Any other value will cause the key to be ignored. */);
15054 Vw32_apps_modifier = Qnil;
15056 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
15057 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
15058 w32_enable_synthesized_fonts = 0;
15060 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
15061 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
15062 Vw32_enable_palette = Qt;
15064 DEFVAR_INT ("w32-mouse-button-tolerance",
15065 &Vw32_mouse_button_tolerance,
15066 doc: /* Analogue of double click interval for faking middle mouse events.
15067 The value is the minimum time in milliseconds that must elapse between
15068 left/right button down events before they are considered distinct events.
15069 If both mouse buttons are depressed within this interval, a middle mouse
15070 button down event is generated instead. */);
15071 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
15073 DEFVAR_INT ("w32-mouse-move-interval",
15074 &Vw32_mouse_move_interval,
15075 doc: /* Minimum interval between mouse move events.
15076 The value is the minimum time in milliseconds that must elapse between
15077 successive mouse move (or scroll bar drag) events before they are
15078 reported as lisp events. */);
15079 XSETINT (Vw32_mouse_move_interval, 0);
15081 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
15082 &w32_pass_extra_mouse_buttons_to_system,
15083 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
15084 Recent versions of Windows support mice with up to five buttons.
15085 Since most applications don't support these extra buttons, most mouse
15086 drivers will allow you to map them to functions at the system level.
15087 If this variable is non-nil, Emacs will pass them on, allowing the
15088 system to handle them. */);
15089 w32_pass_extra_mouse_buttons_to_system = 0;
15091 init_x_parm_symbols ();
15093 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
15094 doc: /* List of directories to search for bitmap files for w32. */);
15095 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
15097 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
15098 doc: /* The shape of the pointer when over text.
15099 Changing the value does not affect existing frames
15100 unless you set the mouse color. */);
15101 Vx_pointer_shape = Qnil;
15103 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
15104 doc: /* The name Emacs uses to look up resources; for internal use only.
15105 `x-get-resource' uses this as the first component of the instance name
15106 when requesting resource values.
15107 Emacs initially sets `x-resource-name' to the name under which Emacs
15108 was invoked, or to the value specified with the `-name' or `-rn'
15109 switches, if present. */);
15110 Vx_resource_name = Qnil;
15112 Vx_nontext_pointer_shape = Qnil;
15114 Vx_mode_pointer_shape = Qnil;
15116 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
15117 doc: /* The shape of the pointer when Emacs is busy.
15118 This variable takes effect when you create a new frame
15119 or when you set the mouse color. */);
15120 Vx_hourglass_pointer_shape = Qnil;
15122 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
15123 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
15124 display_hourglass_p = 1;
15126 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
15127 doc: /* *Seconds to wait before displaying an hourglass pointer.
15128 Value must be an integer or float. */);
15129 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
15131 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
15132 &Vx_sensitive_text_pointer_shape,
15133 doc: /* The shape of the pointer when over mouse-sensitive text.
15134 This variable takes effect when you create a new frame
15135 or when you set the mouse color. */);
15136 Vx_sensitive_text_pointer_shape = Qnil;
15138 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
15139 &Vx_window_horizontal_drag_shape,
15140 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
15141 This variable takes effect when you create a new frame
15142 or when you set the mouse color. */);
15143 Vx_window_horizontal_drag_shape = Qnil;
15145 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
15146 doc: /* A string indicating the foreground color of the cursor box. */);
15147 Vx_cursor_fore_pixel = Qnil;
15149 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
15150 doc: /* Maximum size for tooltips.
15151 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
15152 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
15154 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
15155 doc: /* Non-nil if no window manager is in use.
15156 Emacs doesn't try to figure this out; this is always nil
15157 unless you set it to something else. */);
15158 /* We don't have any way to find this out, so set it to nil
15159 and maybe the user would like to set it to t. */
15160 Vx_no_window_manager = Qnil;
15162 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
15163 &Vx_pixel_size_width_font_regexp,
15164 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
15166 Since Emacs gets width of a font matching with this regexp from
15167 PIXEL_SIZE field of the name, font finding mechanism gets faster for
15168 such a font. This is especially effective for such large fonts as
15169 Chinese, Japanese, and Korean. */);
15170 Vx_pixel_size_width_font_regexp = Qnil;
15172 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
15173 doc: /* Time after which cached images are removed from the cache.
15174 When an image has not been displayed this many seconds, remove it
15175 from the image cache. Value must be an integer or nil with nil
15176 meaning don't clear the cache. */);
15177 Vimage_cache_eviction_delay = make_number (30 * 60);
15179 DEFVAR_LISP ("w32-bdf-filename-alist",
15180 &Vw32_bdf_filename_alist,
15181 doc: /* List of bdf fonts and their corresponding filenames. */);
15182 Vw32_bdf_filename_alist = Qnil;
15184 DEFVAR_BOOL ("w32-strict-fontnames",
15185 &w32_strict_fontnames,
15186 doc: /* Non-nil means only use fonts that are exact matches for those requested.
15187 Default is nil, which allows old fontnames that are not XLFD compliant,
15188 and allows third-party CJK display to work by specifying false charset
15189 fields to trick Emacs into translating to Big5, SJIS etc.
15190 Setting this to t will prevent wrong fonts being selected when
15191 fontsets are automatically created. */);
15192 w32_strict_fontnames = 0;
15194 DEFVAR_BOOL ("w32-strict-painting",
15195 &w32_strict_painting,
15196 doc: /* Non-nil means use strict rules for repainting frames.
15197 Set this to nil to get the old behaviour for repainting; this should
15198 only be necessary if the default setting causes problems. */);
15199 w32_strict_painting = 1;
15201 DEFVAR_LISP ("w32-charset-info-alist",
15202 &Vw32_charset_info_alist,
15203 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
15204 Each entry should be of the form:
15206 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
15208 where CHARSET_NAME is a string used in font names to identify the charset,
15209 WINDOWS_CHARSET is a symbol that can be one of:
15210 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
15211 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
15212 w32-charset-chinesebig5,
15213 #ifdef JOHAB_CHARSET
15214 w32-charset-johab, w32-charset-hebrew,
15215 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
15216 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
15217 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
15218 #endif
15219 #ifdef UNICODE_CHARSET
15220 w32-charset-unicode,
15221 #endif
15222 or w32-charset-oem.
15223 CODEPAGE should be an integer specifying the codepage that should be used
15224 to display the character set, t to do no translation and output as Unicode,
15225 or nil to do no translation and output as 8 bit (or multibyte on far-east
15226 versions of Windows) characters. */);
15227 Vw32_charset_info_alist = Qnil;
15229 staticpro (&Qw32_charset_ansi);
15230 Qw32_charset_ansi = intern ("w32-charset-ansi");
15231 staticpro (&Qw32_charset_symbol);
15232 Qw32_charset_symbol = intern ("w32-charset-symbol");
15233 staticpro (&Qw32_charset_shiftjis);
15234 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
15235 staticpro (&Qw32_charset_hangeul);
15236 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
15237 staticpro (&Qw32_charset_chinesebig5);
15238 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
15239 staticpro (&Qw32_charset_gb2312);
15240 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
15241 staticpro (&Qw32_charset_oem);
15242 Qw32_charset_oem = intern ("w32-charset-oem");
15244 #ifdef JOHAB_CHARSET
15246 static int w32_extra_charsets_defined = 1;
15247 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
15248 doc: /* Internal variable. */);
15250 staticpro (&Qw32_charset_johab);
15251 Qw32_charset_johab = intern ("w32-charset-johab");
15252 staticpro (&Qw32_charset_easteurope);
15253 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
15254 staticpro (&Qw32_charset_turkish);
15255 Qw32_charset_turkish = intern ("w32-charset-turkish");
15256 staticpro (&Qw32_charset_baltic);
15257 Qw32_charset_baltic = intern ("w32-charset-baltic");
15258 staticpro (&Qw32_charset_russian);
15259 Qw32_charset_russian = intern ("w32-charset-russian");
15260 staticpro (&Qw32_charset_arabic);
15261 Qw32_charset_arabic = intern ("w32-charset-arabic");
15262 staticpro (&Qw32_charset_greek);
15263 Qw32_charset_greek = intern ("w32-charset-greek");
15264 staticpro (&Qw32_charset_hebrew);
15265 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
15266 staticpro (&Qw32_charset_vietnamese);
15267 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
15268 staticpro (&Qw32_charset_thai);
15269 Qw32_charset_thai = intern ("w32-charset-thai");
15270 staticpro (&Qw32_charset_mac);
15271 Qw32_charset_mac = intern ("w32-charset-mac");
15273 #endif
15275 #ifdef UNICODE_CHARSET
15277 static int w32_unicode_charset_defined = 1;
15278 DEFVAR_BOOL ("w32-unicode-charset-defined",
15279 &w32_unicode_charset_defined,
15280 doc: /* Internal variable. */);
15282 staticpro (&Qw32_charset_unicode);
15283 Qw32_charset_unicode = intern ("w32-charset-unicode");
15284 #endif
15286 defsubr (&Sx_get_resource);
15287 #if 0 /* TODO: Port to W32 */
15288 defsubr (&Sx_change_window_property);
15289 defsubr (&Sx_delete_window_property);
15290 defsubr (&Sx_window_property);
15291 #endif
15292 defsubr (&Sxw_display_color_p);
15293 defsubr (&Sx_display_grayscale_p);
15294 defsubr (&Sxw_color_defined_p);
15295 defsubr (&Sxw_color_values);
15296 defsubr (&Sx_server_max_request_size);
15297 defsubr (&Sx_server_vendor);
15298 defsubr (&Sx_server_version);
15299 defsubr (&Sx_display_pixel_width);
15300 defsubr (&Sx_display_pixel_height);
15301 defsubr (&Sx_display_mm_width);
15302 defsubr (&Sx_display_mm_height);
15303 defsubr (&Sx_display_screens);
15304 defsubr (&Sx_display_planes);
15305 defsubr (&Sx_display_color_cells);
15306 defsubr (&Sx_display_visual_class);
15307 defsubr (&Sx_display_backing_store);
15308 defsubr (&Sx_display_save_under);
15309 defsubr (&Sx_parse_geometry);
15310 defsubr (&Sx_create_frame);
15311 defsubr (&Sx_open_connection);
15312 defsubr (&Sx_close_connection);
15313 defsubr (&Sx_display_list);
15314 defsubr (&Sx_synchronize);
15316 /* W32 specific functions */
15318 defsubr (&Sw32_focus_frame);
15319 defsubr (&Sw32_select_font);
15320 defsubr (&Sw32_define_rgb_color);
15321 defsubr (&Sw32_default_color_map);
15322 defsubr (&Sw32_load_color_file);
15323 defsubr (&Sw32_send_sys_command);
15324 defsubr (&Sw32_shell_execute);
15325 defsubr (&Sw32_register_hot_key);
15326 defsubr (&Sw32_unregister_hot_key);
15327 defsubr (&Sw32_registered_hot_keys);
15328 defsubr (&Sw32_reconstruct_hot_key);
15329 defsubr (&Sw32_toggle_lock_key);
15330 defsubr (&Sw32_find_bdf_fonts);
15332 defsubr (&Sfile_system_info);
15334 /* Setting callback functions for fontset handler. */
15335 get_font_info_func = w32_get_font_info;
15337 #if 0 /* This function pointer doesn't seem to be used anywhere.
15338 And the pointer assigned has the wrong type, anyway. */
15339 list_fonts_func = w32_list_fonts;
15340 #endif
15342 load_font_func = w32_load_font;
15343 find_ccl_program_func = w32_find_ccl_program;
15344 query_font_func = w32_query_font;
15345 set_frame_fontset_func = x_set_font;
15346 check_window_system_func = check_w32;
15348 /* Images. */
15349 Qxbm = intern ("xbm");
15350 staticpro (&Qxbm);
15351 QCconversion = intern (":conversion");
15352 staticpro (&QCconversion);
15353 QCheuristic_mask = intern (":heuristic-mask");
15354 staticpro (&QCheuristic_mask);
15355 QCcolor_symbols = intern (":color-symbols");
15356 staticpro (&QCcolor_symbols);
15357 QCascent = intern (":ascent");
15358 staticpro (&QCascent);
15359 QCmargin = intern (":margin");
15360 staticpro (&QCmargin);
15361 QCrelief = intern (":relief");
15362 staticpro (&QCrelief);
15363 Qpostscript = intern ("postscript");
15364 staticpro (&Qpostscript);
15365 #if 0 /* TODO: These need entries at top of file. */
15366 QCloader = intern (":loader");
15367 staticpro (&QCloader);
15368 QCbounding_box = intern (":bounding-box");
15369 staticpro (&QCbounding_box);
15370 QCpt_width = intern (":pt-width");
15371 staticpro (&QCpt_width);
15372 QCpt_height = intern (":pt-height");
15373 staticpro (&QCpt_height);
15374 #endif
15375 QCindex = intern (":index");
15376 staticpro (&QCindex);
15377 Qpbm = intern ("pbm");
15378 staticpro (&Qpbm);
15380 #if HAVE_XPM
15381 Qxpm = intern ("xpm");
15382 staticpro (&Qxpm);
15383 #endif
15385 #if HAVE_JPEG
15386 Qjpeg = intern ("jpeg");
15387 staticpro (&Qjpeg);
15388 #endif
15390 #if HAVE_TIFF
15391 Qtiff = intern ("tiff");
15392 staticpro (&Qtiff);
15393 #endif
15395 #if HAVE_GIF
15396 Qgif = intern ("gif");
15397 staticpro (&Qgif);
15398 #endif
15400 #if HAVE_PNG
15401 Qpng = intern ("png");
15402 staticpro (&Qpng);
15403 #endif
15405 defsubr (&Sclear_image_cache);
15406 defsubr (&Simage_size);
15407 defsubr (&Simage_mask_p);
15409 #if GLYPH_DEBUG
15410 defsubr (&Simagep);
15411 defsubr (&Slookup_image);
15412 #endif
15414 hourglass_atimer = NULL;
15415 hourglass_shown_p = 0;
15416 defsubr (&Sx_show_tip);
15417 defsubr (&Sx_hide_tip);
15418 tip_timer = Qnil;
15419 staticpro (&tip_timer);
15420 tip_frame = Qnil;
15421 staticpro (&tip_frame);
15423 last_show_tip_args = Qnil;
15424 staticpro (&last_show_tip_args);
15426 defsubr (&Sx_file_dialog);
15430 void
15431 init_xfns ()
15433 image_types = NULL;
15434 Vimage_types = Qnil;
15436 define_image_type (&pbm_type);
15437 define_image_type (&xbm_type);
15438 #if 0 /* TODO : Image support for W32 */
15439 define_image_type (&gs_type);
15440 #endif
15442 #if HAVE_XPM
15443 define_image_type (&xpm_type);
15444 #endif
15446 #if HAVE_JPEG
15447 define_image_type (&jpeg_type);
15448 #endif
15450 #if HAVE_TIFF
15451 define_image_type (&tiff_type);
15452 #endif
15454 #if HAVE_GIF
15455 define_image_type (&gif_type);
15456 #endif
15458 #if HAVE_PNG
15459 define_image_type (&png_type);
15460 #endif
15463 #undef abort
15465 void
15466 w32_abort()
15468 int button;
15469 button = MessageBox (NULL,
15470 "A fatal error has occurred!\n\n"
15471 "Select Abort to exit, Retry to debug, Ignore to continue",
15472 "Emacs Abort Dialog",
15473 MB_ICONEXCLAMATION | MB_TASKMODAL
15474 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
15475 switch (button)
15477 case IDRETRY:
15478 DebugBreak ();
15479 break;
15480 case IDIGNORE:
15481 break;
15482 case IDABORT:
15483 default:
15484 abort ();
15485 break;
15489 /* For convenience when debugging. */
15491 w32_last_error()
15493 return GetLastError ();