Clean up some white spaces, mainly in my own change log entries. (rost)
[emacs.git] / src / w32fns.c
blob86984597e99453a4a37a505bd3a78d4af5ae782f
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;
287 typedef BOOL (WINAPI * TrackMouseEvent_Proc) (
288 IN OUT LPTRACKMOUSEEVENT lpEventTrack
291 TrackMouseEvent_Proc track_mouse_event_fn=NULL;
293 /* W95 mousewheel handler */
294 unsigned int msh_mousewheel = 0;
296 /* Timers */
297 #define MOUSE_BUTTON_ID 1
298 #define MOUSE_MOVE_ID 2
299 #define MENU_FREE_ID 3
300 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
301 is received. */
302 #define MENU_FREE_DELAY 1000
303 static unsigned menu_free_timer = 0;
305 /* The below are defined in frame.c. */
307 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
308 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
309 extern Lisp_Object Qtool_bar_lines;
311 extern Lisp_Object Vwindow_system_version;
313 Lisp_Object Qface_set_after_frame_default;
315 #ifdef GLYPH_DEBUG
316 int image_cache_refcount, dpyinfo_refcount;
317 #endif
320 /* From w32term.c. */
321 extern Lisp_Object Vw32_num_mouse_buttons;
322 extern Lisp_Object Vw32_recognize_altgr;
324 extern HWND w32_system_caret_hwnd;
326 extern int w32_system_caret_height;
327 extern int w32_system_caret_x;
328 extern int w32_system_caret_y;
329 extern int w32_use_visible_system_caret;
331 static HWND w32_visible_system_caret_hwnd;
334 /* Error if we are not connected to MS-Windows. */
335 void
336 check_w32 ()
338 if (! w32_in_use)
339 error ("MS-Windows not in use or not initialized");
342 /* Nonzero if we can use mouse menus.
343 You should not call this unless HAVE_MENUS is defined. */
346 have_menus_p ()
348 return w32_in_use;
351 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
352 and checking validity for W32. */
354 FRAME_PTR
355 check_x_frame (frame)
356 Lisp_Object frame;
358 FRAME_PTR f;
360 if (NILP (frame))
361 frame = selected_frame;
362 CHECK_LIVE_FRAME (frame);
363 f = XFRAME (frame);
364 if (! FRAME_W32_P (f))
365 error ("non-w32 frame used");
366 return f;
369 /* Let the user specify a display with a frame.
370 nil stands for the selected frame--or, if that is not a w32 frame,
371 the first display on the list. */
373 static struct w32_display_info *
374 check_x_display_info (frame)
375 Lisp_Object frame;
377 if (NILP (frame))
379 struct frame *sf = XFRAME (selected_frame);
381 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
382 return FRAME_W32_DISPLAY_INFO (sf);
383 else
384 return &one_w32_display_info;
386 else if (STRINGP (frame))
387 return x_display_info_for_name (frame);
388 else
390 FRAME_PTR f;
392 CHECK_LIVE_FRAME (frame);
393 f = XFRAME (frame);
394 if (! FRAME_W32_P (f))
395 error ("non-w32 frame used");
396 return FRAME_W32_DISPLAY_INFO (f);
400 /* Return the Emacs frame-object corresponding to an w32 window.
401 It could be the frame's main window or an icon window. */
403 /* This function can be called during GC, so use GC_xxx type test macros. */
405 struct frame *
406 x_window_to_frame (dpyinfo, wdesc)
407 struct w32_display_info *dpyinfo;
408 HWND wdesc;
410 Lisp_Object tail, frame;
411 struct frame *f;
413 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
415 frame = XCAR (tail);
416 if (!GC_FRAMEP (frame))
417 continue;
418 f = XFRAME (frame);
419 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
420 continue;
421 if (f->output_data.w32->hourglass_window == wdesc)
422 return f;
424 if (FRAME_W32_WINDOW (f) == wdesc)
425 return f;
427 return 0;
432 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
433 id, which is just an int that this section returns. Bitmaps are
434 reference counted so they can be shared among frames.
436 Bitmap indices are guaranteed to be > 0, so a negative number can
437 be used to indicate no bitmap.
439 If you use x_create_bitmap_from_data, then you must keep track of
440 the bitmaps yourself. That is, creating a bitmap from the same
441 data more than once will not be caught. */
444 /* Functions to access the contents of a bitmap, given an id. */
447 x_bitmap_height (f, id)
448 FRAME_PTR f;
449 int id;
451 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
455 x_bitmap_width (f, id)
456 FRAME_PTR f;
457 int id;
459 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
463 x_bitmap_pixmap (f, id)
464 FRAME_PTR f;
465 int id;
467 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
471 /* Allocate a new bitmap record. Returns index of new record. */
473 static int
474 x_allocate_bitmap_record (f)
475 FRAME_PTR f;
477 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
478 int i;
480 if (dpyinfo->bitmaps == NULL)
482 dpyinfo->bitmaps_size = 10;
483 dpyinfo->bitmaps
484 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
485 dpyinfo->bitmaps_last = 1;
486 return 1;
489 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
490 return ++dpyinfo->bitmaps_last;
492 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
493 if (dpyinfo->bitmaps[i].refcount == 0)
494 return i + 1;
496 dpyinfo->bitmaps_size *= 2;
497 dpyinfo->bitmaps
498 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
499 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
500 return ++dpyinfo->bitmaps_last;
503 /* Add one reference to the reference count of the bitmap with id ID. */
505 void
506 x_reference_bitmap (f, id)
507 FRAME_PTR f;
508 int id;
510 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
513 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
516 x_create_bitmap_from_data (f, bits, width, height)
517 struct frame *f;
518 char *bits;
519 unsigned int width, height;
521 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
522 Pixmap bitmap;
523 int id;
525 bitmap = CreateBitmap (width, height,
526 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
527 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
528 bits);
530 if (! bitmap)
531 return -1;
533 id = x_allocate_bitmap_record (f);
534 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
535 dpyinfo->bitmaps[id - 1].file = NULL;
536 dpyinfo->bitmaps[id - 1].hinst = NULL;
537 dpyinfo->bitmaps[id - 1].refcount = 1;
538 dpyinfo->bitmaps[id - 1].depth = 1;
539 dpyinfo->bitmaps[id - 1].height = height;
540 dpyinfo->bitmaps[id - 1].width = width;
542 return id;
545 /* Create bitmap from file FILE for frame F. */
548 x_create_bitmap_from_file (f, file)
549 struct frame *f;
550 Lisp_Object file;
552 return -1;
553 #if 0 /* TODO : bitmap support */
554 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
555 unsigned int width, height;
556 HBITMAP bitmap;
557 int xhot, yhot, result, id;
558 Lisp_Object found;
559 int fd;
560 char *filename;
561 HINSTANCE hinst;
563 /* Look for an existing bitmap with the same name. */
564 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
566 if (dpyinfo->bitmaps[id].refcount
567 && dpyinfo->bitmaps[id].file
568 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
570 ++dpyinfo->bitmaps[id].refcount;
571 return id + 1;
575 /* Search bitmap-file-path for the file, if appropriate. */
576 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
577 if (fd < 0)
578 return -1;
579 emacs_close (fd);
581 filename = (char *) SDATA (found);
583 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
585 if (hinst == NULL)
586 return -1;
589 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
590 filename, &width, &height, &bitmap, &xhot, &yhot);
591 if (result != BitmapSuccess)
592 return -1;
594 id = x_allocate_bitmap_record (f);
595 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
596 dpyinfo->bitmaps[id - 1].refcount = 1;
597 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SCHARS (file) + 1);
598 dpyinfo->bitmaps[id - 1].depth = 1;
599 dpyinfo->bitmaps[id - 1].height = height;
600 dpyinfo->bitmaps[id - 1].width = width;
601 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
603 return id;
604 #endif /* TODO */
607 /* Remove reference to bitmap with id number ID. */
609 void
610 x_destroy_bitmap (f, id)
611 FRAME_PTR f;
612 int id;
614 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
616 if (id > 0)
618 --dpyinfo->bitmaps[id - 1].refcount;
619 if (dpyinfo->bitmaps[id - 1].refcount == 0)
621 BLOCK_INPUT;
622 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
623 if (dpyinfo->bitmaps[id - 1].file)
625 xfree (dpyinfo->bitmaps[id - 1].file);
626 dpyinfo->bitmaps[id - 1].file = NULL;
628 UNBLOCK_INPUT;
633 /* Free all the bitmaps for the display specified by DPYINFO. */
635 static void
636 x_destroy_all_bitmaps (dpyinfo)
637 struct w32_display_info *dpyinfo;
639 int i;
640 for (i = 0; i < dpyinfo->bitmaps_last; i++)
641 if (dpyinfo->bitmaps[i].refcount > 0)
643 DeleteObject (dpyinfo->bitmaps[i].pixmap);
644 if (dpyinfo->bitmaps[i].file)
645 xfree (dpyinfo->bitmaps[i].file);
647 dpyinfo->bitmaps_last = 0;
650 /* Connect the frame-parameter names for W32 frames
651 to the ways of passing the parameter values to the window system.
653 The name of a parameter, as a Lisp symbol,
654 has an `x-frame-parameter' property which is an integer in Lisp
655 but can be interpreted as an `enum x_frame_parm' in C. */
657 enum x_frame_parm
659 X_PARM_FOREGROUND_COLOR,
660 X_PARM_BACKGROUND_COLOR,
661 X_PARM_MOUSE_COLOR,
662 X_PARM_CURSOR_COLOR,
663 X_PARM_BORDER_COLOR,
664 X_PARM_ICON_TYPE,
665 X_PARM_FONT,
666 X_PARM_BORDER_WIDTH,
667 X_PARM_INTERNAL_BORDER_WIDTH,
668 X_PARM_NAME,
669 X_PARM_AUTORAISE,
670 X_PARM_AUTOLOWER,
671 X_PARM_VERT_SCROLL_BAR,
672 X_PARM_VISIBILITY,
673 X_PARM_MENU_BAR_LINES
677 struct x_frame_parm_table
679 char *name;
680 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
683 BOOL my_show_window P_ ((struct frame *, HWND, int));
684 void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
685 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
686 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
687 static void x_change_window_heights P_ ((Lisp_Object, int));
688 /* TODO: Native Input Method support; see x_create_im. */
689 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
690 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
691 static void x_set_fullscreen P_ ((struct frame *, Lisp_Object, Lisp_Object));
692 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
693 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
694 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
695 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
696 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
697 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
698 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
699 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
700 static void x_set_fringe_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
701 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
702 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
703 Lisp_Object));
704 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
705 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
706 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
707 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
708 Lisp_Object));
709 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
710 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
711 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
712 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
713 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
714 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
715 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
716 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
717 Lisp_Object));
719 static struct x_frame_parm_table x_frame_parms[] =
721 {"auto-raise", x_set_autoraise},
722 {"auto-lower", x_set_autolower},
723 {"background-color", x_set_background_color},
724 {"border-color", x_set_border_color},
725 {"border-width", x_set_border_width},
726 {"cursor-color", x_set_cursor_color},
727 {"cursor-type", x_set_cursor_type},
728 {"font", x_set_font},
729 {"foreground-color", x_set_foreground_color},
730 {"icon-name", x_set_icon_name},
731 {"icon-type", x_set_icon_type},
732 {"internal-border-width", x_set_internal_border_width},
733 {"menu-bar-lines", x_set_menu_bar_lines},
734 {"mouse-color", x_set_mouse_color},
735 {"name", x_explicitly_set_name},
736 {"scroll-bar-width", x_set_scroll_bar_width},
737 {"title", x_set_title},
738 {"unsplittable", x_set_unsplittable},
739 {"vertical-scroll-bars", x_set_vertical_scroll_bars},
740 {"visibility", x_set_visibility},
741 {"tool-bar-lines", x_set_tool_bar_lines},
742 {"screen-gamma", x_set_screen_gamma},
743 {"line-spacing", x_set_line_spacing},
744 {"left-fringe", x_set_fringe_width},
745 {"right-fringe", x_set_fringe_width},
746 {"fullscreen", x_set_fullscreen},
749 /* Attach the `x-frame-parameter' properties to
750 the Lisp symbol names of parameters relevant to W32. */
752 void
753 init_x_parm_symbols ()
755 int i;
757 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
758 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
759 make_number (i));
762 /* Really try to move where we want to be in case of fullscreen. Some WMs
763 moves the window where we tell them. Some (mwm, twm) moves the outer
764 window manager window there instead.
765 Try to compensate for those WM here. */
766 static void
767 x_fullscreen_move (f, new_top, new_left)
768 struct frame *f;
769 int new_top;
770 int new_left;
772 if (new_top != f->output_data.w32->top_pos
773 || new_left != f->output_data.w32->left_pos)
775 int move_x = new_left;
776 int move_y = new_top;
778 f->output_data.w32->want_fullscreen |= FULLSCREEN_MOVE_WAIT;
779 x_set_offset (f, move_x, move_y, 1);
783 /* Change the parameters of frame F as specified by ALIST.
784 If a parameter is not specially recognized, do nothing;
785 otherwise call the `x_set_...' function for that parameter. */
787 void
788 x_set_frame_parameters (f, alist)
789 FRAME_PTR f;
790 Lisp_Object alist;
792 Lisp_Object tail;
794 /* If both of these parameters are present, it's more efficient to
795 set them both at once. So we wait until we've looked at the
796 entire list before we set them. */
797 int width, height;
799 /* Same here. */
800 Lisp_Object left, top;
802 /* Same with these. */
803 Lisp_Object icon_left, icon_top;
805 /* Record in these vectors all the parms specified. */
806 Lisp_Object *parms;
807 Lisp_Object *values;
808 int i, p;
809 int left_no_change = 0, top_no_change = 0;
810 int icon_left_no_change = 0, icon_top_no_change = 0;
811 int fullscreen_is_being_set = 0;
813 struct gcpro gcpro1, gcpro2;
815 i = 0;
816 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
817 i++;
819 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
820 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
822 /* Extract parm names and values into those vectors. */
824 i = 0;
825 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
827 Lisp_Object elt;
829 elt = Fcar (tail);
830 parms[i] = Fcar (elt);
831 values[i] = Fcdr (elt);
832 i++;
834 /* TAIL and ALIST are not used again below here. */
835 alist = tail = Qnil;
837 GCPRO2 (*parms, *values);
838 gcpro1.nvars = i;
839 gcpro2.nvars = i;
841 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
842 because their values appear in VALUES and strings are not valid. */
843 top = left = Qunbound;
844 icon_left = icon_top = Qunbound;
846 /* Provide default values for HEIGHT and WIDTH. */
847 if (FRAME_NEW_WIDTH (f))
848 width = FRAME_NEW_WIDTH (f);
849 else
850 width = FRAME_WIDTH (f);
852 if (FRAME_NEW_HEIGHT (f))
853 height = FRAME_NEW_HEIGHT (f);
854 else
855 height = FRAME_HEIGHT (f);
857 /* Process foreground_color and background_color before anything else.
858 They are independent of other properties, but other properties (e.g.,
859 cursor_color) are dependent upon them. */
860 /* Process default font as well, since fringe widths depends on it. */
861 for (p = 0; p < i; p++)
863 Lisp_Object prop, val;
865 prop = parms[p];
866 val = values[p];
867 if (EQ (prop, Qforeground_color)
868 || EQ (prop, Qbackground_color)
869 || EQ (prop, Qfont)
870 || EQ (prop, Qfullscreen))
872 register Lisp_Object param_index, old_value;
874 old_value = get_frame_param (f, prop);
875 fullscreen_is_being_set |= EQ (prop, Qfullscreen);
877 if (NILP (Fequal (val, old_value)))
879 store_frame_param (f, prop, val);
881 param_index = Fget (prop, Qx_frame_parameter);
882 if (NATNUMP (param_index)
883 && (XFASTINT (param_index)
884 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
885 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
890 /* Now process them in reverse of specified order. */
891 for (i--; i >= 0; i--)
893 Lisp_Object prop, val;
895 prop = parms[i];
896 val = values[i];
898 if (EQ (prop, Qwidth) && NUMBERP (val))
899 width = XFASTINT (val);
900 else if (EQ (prop, Qheight) && NUMBERP (val))
901 height = XFASTINT (val);
902 else if (EQ (prop, Qtop))
903 top = val;
904 else if (EQ (prop, Qleft))
905 left = val;
906 else if (EQ (prop, Qicon_top))
907 icon_top = val;
908 else if (EQ (prop, Qicon_left))
909 icon_left = val;
910 else if (EQ (prop, Qforeground_color)
911 || EQ (prop, Qbackground_color)
912 || EQ (prop, Qfont)
913 || EQ (prop, Qfullscreen))
914 /* Processed above. */
915 continue;
916 else
918 register Lisp_Object param_index, old_value;
920 old_value = get_frame_param (f, prop);
922 store_frame_param (f, prop, val);
924 param_index = Fget (prop, Qx_frame_parameter);
925 if (NATNUMP (param_index)
926 && (XFASTINT (param_index)
927 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
928 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
932 /* Don't die if just one of these was set. */
933 if (EQ (left, Qunbound))
935 left_no_change = 1;
936 if (f->output_data.w32->left_pos < 0)
937 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
938 else
939 XSETINT (left, f->output_data.w32->left_pos);
941 if (EQ (top, Qunbound))
943 top_no_change = 1;
944 if (f->output_data.w32->top_pos < 0)
945 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
946 else
947 XSETINT (top, f->output_data.w32->top_pos);
950 /* If one of the icon positions was not set, preserve or default it. */
951 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
953 icon_left_no_change = 1;
954 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
955 if (NILP (icon_left))
956 XSETINT (icon_left, 0);
958 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
960 icon_top_no_change = 1;
961 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
962 if (NILP (icon_top))
963 XSETINT (icon_top, 0);
966 if (FRAME_VISIBLE_P (f) && fullscreen_is_being_set)
968 /* If the frame is visible already and the fullscreen parameter is
969 being set, it is too late to set WM manager hints to specify
970 size and position.
971 Here we first get the width, height and position that applies to
972 fullscreen. We then move the frame to the appropriate
973 position. Resize of the frame is taken care of in the code after
974 this if-statement. */
975 int new_left, new_top;
977 x_fullscreen_adjust (f, &width, &height, &new_top, &new_left);
978 x_fullscreen_move (f, new_top, new_left);
981 /* Don't set these parameters unless they've been explicitly
982 specified. The window might be mapped or resized while we're in
983 this function, and we don't want to override that unless the lisp
984 code has asked for it.
986 Don't set these parameters unless they actually differ from the
987 window's current parameters; the window may not actually exist
988 yet. */
990 Lisp_Object frame;
992 check_frame_size (f, &height, &width);
994 XSETFRAME (frame, f);
996 if (width != FRAME_WIDTH (f)
997 || height != FRAME_HEIGHT (f)
998 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
999 Fset_frame_size (frame, make_number (width), make_number (height));
1001 if ((!NILP (left) || !NILP (top))
1002 && ! (left_no_change && top_no_change)
1003 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
1004 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
1006 int leftpos = 0;
1007 int toppos = 0;
1009 /* Record the signs. */
1010 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
1011 if (EQ (left, Qminus))
1012 f->output_data.w32->size_hint_flags |= XNegative;
1013 else if (INTEGERP (left))
1015 leftpos = XINT (left);
1016 if (leftpos < 0)
1017 f->output_data.w32->size_hint_flags |= XNegative;
1019 else if (CONSP (left) && EQ (XCAR (left), Qminus)
1020 && CONSP (XCDR (left))
1021 && INTEGERP (XCAR (XCDR (left))))
1023 leftpos = - XINT (XCAR (XCDR (left)));
1024 f->output_data.w32->size_hint_flags |= XNegative;
1026 else if (CONSP (left) && EQ (XCAR (left), Qplus)
1027 && CONSP (XCDR (left))
1028 && INTEGERP (XCAR (XCDR (left))))
1030 leftpos = XINT (XCAR (XCDR (left)));
1033 if (EQ (top, Qminus))
1034 f->output_data.w32->size_hint_flags |= YNegative;
1035 else if (INTEGERP (top))
1037 toppos = XINT (top);
1038 if (toppos < 0)
1039 f->output_data.w32->size_hint_flags |= YNegative;
1041 else if (CONSP (top) && EQ (XCAR (top), Qminus)
1042 && CONSP (XCDR (top))
1043 && INTEGERP (XCAR (XCDR (top))))
1045 toppos = - XINT (XCAR (XCDR (top)));
1046 f->output_data.w32->size_hint_flags |= YNegative;
1048 else if (CONSP (top) && EQ (XCAR (top), Qplus)
1049 && CONSP (XCDR (top))
1050 && INTEGERP (XCAR (XCDR (top))))
1052 toppos = XINT (XCAR (XCDR (top)));
1056 /* Store the numeric value of the position. */
1057 f->output_data.w32->top_pos = toppos;
1058 f->output_data.w32->left_pos = leftpos;
1060 f->output_data.w32->win_gravity = NorthWestGravity;
1062 /* Actually set that position, and convert to absolute. */
1063 x_set_offset (f, leftpos, toppos, -1);
1066 if ((!NILP (icon_left) || !NILP (icon_top))
1067 && ! (icon_left_no_change && icon_top_no_change))
1068 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1071 UNGCPRO;
1074 /* Store the screen positions of frame F into XPTR and YPTR.
1075 These are the positions of the containing window manager window,
1076 not Emacs's own window. */
1078 void
1079 x_real_positions (f, xptr, yptr)
1080 FRAME_PTR f;
1081 int *xptr, *yptr;
1083 POINT pt;
1084 RECT rect;
1086 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1087 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1089 pt.x = rect.left;
1090 pt.y = rect.top;
1092 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1094 /* Remember x_pixels_diff and y_pixels_diff. */
1095 f->output_data.w32->x_pixels_diff = pt.x - rect.left;
1096 f->output_data.w32->y_pixels_diff = pt.y - rect.top;
1098 *xptr = pt.x;
1099 *yptr = pt.y;
1102 /* Insert a description of internally-recorded parameters of frame X
1103 into the parameter alist *ALISTPTR that is to be given to the user.
1104 Only parameters that are specific to W32
1105 and whose values are not correctly recorded in the frame's
1106 param_alist need to be considered here. */
1108 void
1109 x_report_frame_params (f, alistptr)
1110 struct frame *f;
1111 Lisp_Object *alistptr;
1113 char buf[16];
1114 Lisp_Object tem;
1116 /* Represent negative positions (off the top or left screen edge)
1117 in a way that Fmodify_frame_parameters will understand correctly. */
1118 XSETINT (tem, f->output_data.w32->left_pos);
1119 if (f->output_data.w32->left_pos >= 0)
1120 store_in_alist (alistptr, Qleft, tem);
1121 else
1122 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1124 XSETINT (tem, f->output_data.w32->top_pos);
1125 if (f->output_data.w32->top_pos >= 0)
1126 store_in_alist (alistptr, Qtop, tem);
1127 else
1128 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1130 store_in_alist (alistptr, Qborder_width,
1131 make_number (f->output_data.w32->border_width));
1132 store_in_alist (alistptr, Qinternal_border_width,
1133 make_number (f->output_data.w32->internal_border_width));
1134 store_in_alist (alistptr, Qleft_fringe,
1135 make_number (f->output_data.w32->left_fringe_width));
1136 store_in_alist (alistptr, Qright_fringe,
1137 make_number (f->output_data.w32->right_fringe_width));
1138 store_in_alist (alistptr, Qscroll_bar_width,
1139 make_number (FRAME_HAS_VERTICAL_SCROLL_BARS (f)
1140 ? FRAME_SCROLL_BAR_PIXEL_WIDTH(f)
1141 : 0));
1142 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1143 store_in_alist (alistptr, Qwindow_id,
1144 build_string (buf));
1145 store_in_alist (alistptr, Qicon_name, f->icon_name);
1146 FRAME_SAMPLE_VISIBILITY (f);
1147 store_in_alist (alistptr, Qvisibility,
1148 (FRAME_VISIBLE_P (f) ? Qt
1149 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1150 store_in_alist (alistptr, Qdisplay,
1151 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1155 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
1156 Sw32_define_rgb_color, 4, 4, 0,
1157 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
1158 This adds or updates a named color to w32-color-map, making it
1159 available for use. The original entry's RGB ref is returned, or nil
1160 if the entry is new. */)
1161 (red, green, blue, name)
1162 Lisp_Object red, green, blue, name;
1164 Lisp_Object rgb;
1165 Lisp_Object oldrgb = Qnil;
1166 Lisp_Object entry;
1168 CHECK_NUMBER (red);
1169 CHECK_NUMBER (green);
1170 CHECK_NUMBER (blue);
1171 CHECK_STRING (name);
1173 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1175 BLOCK_INPUT;
1177 /* replace existing entry in w32-color-map or add new entry. */
1178 entry = Fassoc (name, Vw32_color_map);
1179 if (NILP (entry))
1181 entry = Fcons (name, rgb);
1182 Vw32_color_map = Fcons (entry, Vw32_color_map);
1184 else
1186 oldrgb = Fcdr (entry);
1187 Fsetcdr (entry, rgb);
1190 UNBLOCK_INPUT;
1192 return (oldrgb);
1195 DEFUN ("w32-load-color-file", Fw32_load_color_file,
1196 Sw32_load_color_file, 1, 1, 0,
1197 doc: /* Create an alist of color entries from an external file.
1198 Assign this value to w32-color-map to replace the existing color map.
1200 The file should define one named RGB color per line like so:
1201 R G B name
1202 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
1203 (filename)
1204 Lisp_Object filename;
1206 FILE *fp;
1207 Lisp_Object cmap = Qnil;
1208 Lisp_Object abspath;
1210 CHECK_STRING (filename);
1211 abspath = Fexpand_file_name (filename, Qnil);
1213 fp = fopen (SDATA (filename), "rt");
1214 if (fp)
1216 char buf[512];
1217 int red, green, blue;
1218 int num;
1220 BLOCK_INPUT;
1222 while (fgets (buf, sizeof (buf), fp) != NULL) {
1223 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1225 char *name = buf + num;
1226 num = strlen (name) - 1;
1227 if (name[num] == '\n')
1228 name[num] = 0;
1229 cmap = Fcons (Fcons (build_string (name),
1230 make_number (RGB (red, green, blue))),
1231 cmap);
1234 fclose (fp);
1236 UNBLOCK_INPUT;
1239 return cmap;
1242 /* The default colors for the w32 color map */
1243 typedef struct colormap_t
1245 char *name;
1246 COLORREF colorref;
1247 } colormap_t;
1249 colormap_t w32_color_map[] =
1251 {"snow" , PALETTERGB (255,250,250)},
1252 {"ghost white" , PALETTERGB (248,248,255)},
1253 {"GhostWhite" , PALETTERGB (248,248,255)},
1254 {"white smoke" , PALETTERGB (245,245,245)},
1255 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1256 {"gainsboro" , PALETTERGB (220,220,220)},
1257 {"floral white" , PALETTERGB (255,250,240)},
1258 {"FloralWhite" , PALETTERGB (255,250,240)},
1259 {"old lace" , PALETTERGB (253,245,230)},
1260 {"OldLace" , PALETTERGB (253,245,230)},
1261 {"linen" , PALETTERGB (250,240,230)},
1262 {"antique white" , PALETTERGB (250,235,215)},
1263 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1264 {"papaya whip" , PALETTERGB (255,239,213)},
1265 {"PapayaWhip" , PALETTERGB (255,239,213)},
1266 {"blanched almond" , PALETTERGB (255,235,205)},
1267 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1268 {"bisque" , PALETTERGB (255,228,196)},
1269 {"peach puff" , PALETTERGB (255,218,185)},
1270 {"PeachPuff" , PALETTERGB (255,218,185)},
1271 {"navajo white" , PALETTERGB (255,222,173)},
1272 {"NavajoWhite" , PALETTERGB (255,222,173)},
1273 {"moccasin" , PALETTERGB (255,228,181)},
1274 {"cornsilk" , PALETTERGB (255,248,220)},
1275 {"ivory" , PALETTERGB (255,255,240)},
1276 {"lemon chiffon" , PALETTERGB (255,250,205)},
1277 {"LemonChiffon" , PALETTERGB (255,250,205)},
1278 {"seashell" , PALETTERGB (255,245,238)},
1279 {"honeydew" , PALETTERGB (240,255,240)},
1280 {"mint cream" , PALETTERGB (245,255,250)},
1281 {"MintCream" , PALETTERGB (245,255,250)},
1282 {"azure" , PALETTERGB (240,255,255)},
1283 {"alice blue" , PALETTERGB (240,248,255)},
1284 {"AliceBlue" , PALETTERGB (240,248,255)},
1285 {"lavender" , PALETTERGB (230,230,250)},
1286 {"lavender blush" , PALETTERGB (255,240,245)},
1287 {"LavenderBlush" , PALETTERGB (255,240,245)},
1288 {"misty rose" , PALETTERGB (255,228,225)},
1289 {"MistyRose" , PALETTERGB (255,228,225)},
1290 {"white" , PALETTERGB (255,255,255)},
1291 {"black" , PALETTERGB ( 0, 0, 0)},
1292 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1293 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1294 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1295 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1296 {"dim gray" , PALETTERGB (105,105,105)},
1297 {"DimGray" , PALETTERGB (105,105,105)},
1298 {"dim grey" , PALETTERGB (105,105,105)},
1299 {"DimGrey" , PALETTERGB (105,105,105)},
1300 {"slate gray" , PALETTERGB (112,128,144)},
1301 {"SlateGray" , PALETTERGB (112,128,144)},
1302 {"slate grey" , PALETTERGB (112,128,144)},
1303 {"SlateGrey" , PALETTERGB (112,128,144)},
1304 {"light slate gray" , PALETTERGB (119,136,153)},
1305 {"LightSlateGray" , PALETTERGB (119,136,153)},
1306 {"light slate grey" , PALETTERGB (119,136,153)},
1307 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1308 {"gray" , PALETTERGB (190,190,190)},
1309 {"grey" , PALETTERGB (190,190,190)},
1310 {"light grey" , PALETTERGB (211,211,211)},
1311 {"LightGrey" , PALETTERGB (211,211,211)},
1312 {"light gray" , PALETTERGB (211,211,211)},
1313 {"LightGray" , PALETTERGB (211,211,211)},
1314 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1315 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1316 {"navy" , PALETTERGB ( 0, 0,128)},
1317 {"navy blue" , PALETTERGB ( 0, 0,128)},
1318 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1319 {"cornflower blue" , PALETTERGB (100,149,237)},
1320 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1321 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1322 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1323 {"slate blue" , PALETTERGB (106, 90,205)},
1324 {"SlateBlue" , PALETTERGB (106, 90,205)},
1325 {"medium slate blue" , PALETTERGB (123,104,238)},
1326 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1327 {"light slate blue" , PALETTERGB (132,112,255)},
1328 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1329 {"medium blue" , PALETTERGB ( 0, 0,205)},
1330 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1331 {"royal blue" , PALETTERGB ( 65,105,225)},
1332 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1333 {"blue" , PALETTERGB ( 0, 0,255)},
1334 {"dodger blue" , PALETTERGB ( 30,144,255)},
1335 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1336 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1337 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1338 {"sky blue" , PALETTERGB (135,206,235)},
1339 {"SkyBlue" , PALETTERGB (135,206,235)},
1340 {"light sky blue" , PALETTERGB (135,206,250)},
1341 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1342 {"steel blue" , PALETTERGB ( 70,130,180)},
1343 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1344 {"light steel blue" , PALETTERGB (176,196,222)},
1345 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1346 {"light blue" , PALETTERGB (173,216,230)},
1347 {"LightBlue" , PALETTERGB (173,216,230)},
1348 {"powder blue" , PALETTERGB (176,224,230)},
1349 {"PowderBlue" , PALETTERGB (176,224,230)},
1350 {"pale turquoise" , PALETTERGB (175,238,238)},
1351 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1352 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1353 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1354 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1355 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1356 {"turquoise" , PALETTERGB ( 64,224,208)},
1357 {"cyan" , PALETTERGB ( 0,255,255)},
1358 {"light cyan" , PALETTERGB (224,255,255)},
1359 {"LightCyan" , PALETTERGB (224,255,255)},
1360 {"cadet blue" , PALETTERGB ( 95,158,160)},
1361 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1362 {"medium aquamarine" , PALETTERGB (102,205,170)},
1363 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1364 {"aquamarine" , PALETTERGB (127,255,212)},
1365 {"dark green" , PALETTERGB ( 0,100, 0)},
1366 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1367 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1368 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1369 {"dark sea green" , PALETTERGB (143,188,143)},
1370 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1371 {"sea green" , PALETTERGB ( 46,139, 87)},
1372 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1373 {"medium sea green" , PALETTERGB ( 60,179,113)},
1374 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1375 {"light sea green" , PALETTERGB ( 32,178,170)},
1376 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1377 {"pale green" , PALETTERGB (152,251,152)},
1378 {"PaleGreen" , PALETTERGB (152,251,152)},
1379 {"spring green" , PALETTERGB ( 0,255,127)},
1380 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1381 {"lawn green" , PALETTERGB (124,252, 0)},
1382 {"LawnGreen" , PALETTERGB (124,252, 0)},
1383 {"green" , PALETTERGB ( 0,255, 0)},
1384 {"chartreuse" , PALETTERGB (127,255, 0)},
1385 {"medium spring green" , PALETTERGB ( 0,250,154)},
1386 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1387 {"green yellow" , PALETTERGB (173,255, 47)},
1388 {"GreenYellow" , PALETTERGB (173,255, 47)},
1389 {"lime green" , PALETTERGB ( 50,205, 50)},
1390 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1391 {"yellow green" , PALETTERGB (154,205, 50)},
1392 {"YellowGreen" , PALETTERGB (154,205, 50)},
1393 {"forest green" , PALETTERGB ( 34,139, 34)},
1394 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1395 {"olive drab" , PALETTERGB (107,142, 35)},
1396 {"OliveDrab" , PALETTERGB (107,142, 35)},
1397 {"dark khaki" , PALETTERGB (189,183,107)},
1398 {"DarkKhaki" , PALETTERGB (189,183,107)},
1399 {"khaki" , PALETTERGB (240,230,140)},
1400 {"pale goldenrod" , PALETTERGB (238,232,170)},
1401 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1402 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1403 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1404 {"light yellow" , PALETTERGB (255,255,224)},
1405 {"LightYellow" , PALETTERGB (255,255,224)},
1406 {"yellow" , PALETTERGB (255,255, 0)},
1407 {"gold" , PALETTERGB (255,215, 0)},
1408 {"light goldenrod" , PALETTERGB (238,221,130)},
1409 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1410 {"goldenrod" , PALETTERGB (218,165, 32)},
1411 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1412 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1413 {"rosy brown" , PALETTERGB (188,143,143)},
1414 {"RosyBrown" , PALETTERGB (188,143,143)},
1415 {"indian red" , PALETTERGB (205, 92, 92)},
1416 {"IndianRed" , PALETTERGB (205, 92, 92)},
1417 {"saddle brown" , PALETTERGB (139, 69, 19)},
1418 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1419 {"sienna" , PALETTERGB (160, 82, 45)},
1420 {"peru" , PALETTERGB (205,133, 63)},
1421 {"burlywood" , PALETTERGB (222,184,135)},
1422 {"beige" , PALETTERGB (245,245,220)},
1423 {"wheat" , PALETTERGB (245,222,179)},
1424 {"sandy brown" , PALETTERGB (244,164, 96)},
1425 {"SandyBrown" , PALETTERGB (244,164, 96)},
1426 {"tan" , PALETTERGB (210,180,140)},
1427 {"chocolate" , PALETTERGB (210,105, 30)},
1428 {"firebrick" , PALETTERGB (178,34, 34)},
1429 {"brown" , PALETTERGB (165,42, 42)},
1430 {"dark salmon" , PALETTERGB (233,150,122)},
1431 {"DarkSalmon" , PALETTERGB (233,150,122)},
1432 {"salmon" , PALETTERGB (250,128,114)},
1433 {"light salmon" , PALETTERGB (255,160,122)},
1434 {"LightSalmon" , PALETTERGB (255,160,122)},
1435 {"orange" , PALETTERGB (255,165, 0)},
1436 {"dark orange" , PALETTERGB (255,140, 0)},
1437 {"DarkOrange" , PALETTERGB (255,140, 0)},
1438 {"coral" , PALETTERGB (255,127, 80)},
1439 {"light coral" , PALETTERGB (240,128,128)},
1440 {"LightCoral" , PALETTERGB (240,128,128)},
1441 {"tomato" , PALETTERGB (255, 99, 71)},
1442 {"orange red" , PALETTERGB (255, 69, 0)},
1443 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1444 {"red" , PALETTERGB (255, 0, 0)},
1445 {"hot pink" , PALETTERGB (255,105,180)},
1446 {"HotPink" , PALETTERGB (255,105,180)},
1447 {"deep pink" , PALETTERGB (255, 20,147)},
1448 {"DeepPink" , PALETTERGB (255, 20,147)},
1449 {"pink" , PALETTERGB (255,192,203)},
1450 {"light pink" , PALETTERGB (255,182,193)},
1451 {"LightPink" , PALETTERGB (255,182,193)},
1452 {"pale violet red" , PALETTERGB (219,112,147)},
1453 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1454 {"maroon" , PALETTERGB (176, 48, 96)},
1455 {"medium violet red" , PALETTERGB (199, 21,133)},
1456 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1457 {"violet red" , PALETTERGB (208, 32,144)},
1458 {"VioletRed" , PALETTERGB (208, 32,144)},
1459 {"magenta" , PALETTERGB (255, 0,255)},
1460 {"violet" , PALETTERGB (238,130,238)},
1461 {"plum" , PALETTERGB (221,160,221)},
1462 {"orchid" , PALETTERGB (218,112,214)},
1463 {"medium orchid" , PALETTERGB (186, 85,211)},
1464 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1465 {"dark orchid" , PALETTERGB (153, 50,204)},
1466 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1467 {"dark violet" , PALETTERGB (148, 0,211)},
1468 {"DarkViolet" , PALETTERGB (148, 0,211)},
1469 {"blue violet" , PALETTERGB (138, 43,226)},
1470 {"BlueViolet" , PALETTERGB (138, 43,226)},
1471 {"purple" , PALETTERGB (160, 32,240)},
1472 {"medium purple" , PALETTERGB (147,112,219)},
1473 {"MediumPurple" , PALETTERGB (147,112,219)},
1474 {"thistle" , PALETTERGB (216,191,216)},
1475 {"gray0" , PALETTERGB ( 0, 0, 0)},
1476 {"grey0" , PALETTERGB ( 0, 0, 0)},
1477 {"dark grey" , PALETTERGB (169,169,169)},
1478 {"DarkGrey" , PALETTERGB (169,169,169)},
1479 {"dark gray" , PALETTERGB (169,169,169)},
1480 {"DarkGray" , PALETTERGB (169,169,169)},
1481 {"dark blue" , PALETTERGB ( 0, 0,139)},
1482 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1483 {"dark cyan" , PALETTERGB ( 0,139,139)},
1484 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1485 {"dark magenta" , PALETTERGB (139, 0,139)},
1486 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1487 {"dark red" , PALETTERGB (139, 0, 0)},
1488 {"DarkRed" , PALETTERGB (139, 0, 0)},
1489 {"light green" , PALETTERGB (144,238,144)},
1490 {"LightGreen" , PALETTERGB (144,238,144)},
1493 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1494 0, 0, 0, doc: /* Return the default color map. */)
1497 int i;
1498 colormap_t *pc = w32_color_map;
1499 Lisp_Object cmap;
1501 BLOCK_INPUT;
1503 cmap = Qnil;
1505 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1506 pc++, i++)
1507 cmap = Fcons (Fcons (build_string (pc->name),
1508 make_number (pc->colorref)),
1509 cmap);
1511 UNBLOCK_INPUT;
1513 return (cmap);
1516 Lisp_Object
1517 w32_to_x_color (rgb)
1518 Lisp_Object rgb;
1520 Lisp_Object color;
1522 CHECK_NUMBER (rgb);
1524 BLOCK_INPUT;
1526 color = Frassq (rgb, Vw32_color_map);
1528 UNBLOCK_INPUT;
1530 if (!NILP (color))
1531 return (Fcar (color));
1532 else
1533 return Qnil;
1536 COLORREF
1537 w32_color_map_lookup (colorname)
1538 char *colorname;
1540 Lisp_Object tail, ret = Qnil;
1542 BLOCK_INPUT;
1544 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1546 register Lisp_Object elt, tem;
1548 elt = Fcar (tail);
1549 if (!CONSP (elt)) continue;
1551 tem = Fcar (elt);
1553 if (lstrcmpi (SDATA (tem), colorname) == 0)
1555 ret = XUINT (Fcdr (elt));
1556 break;
1559 QUIT;
1563 UNBLOCK_INPUT;
1565 return ret;
1568 COLORREF
1569 x_to_w32_color (colorname)
1570 char * colorname;
1572 register Lisp_Object ret = Qnil;
1574 BLOCK_INPUT;
1576 if (colorname[0] == '#')
1578 /* Could be an old-style RGB Device specification. */
1579 char *color;
1580 int size;
1581 color = colorname + 1;
1583 size = strlen(color);
1584 if (size == 3 || size == 6 || size == 9 || size == 12)
1586 UINT colorval;
1587 int i, pos;
1588 pos = 0;
1589 size /= 3;
1590 colorval = 0;
1592 for (i = 0; i < 3; i++)
1594 char *end;
1595 char t;
1596 unsigned long value;
1598 /* The check for 'x' in the following conditional takes into
1599 account the fact that strtol allows a "0x" in front of
1600 our numbers, and we don't. */
1601 if (!isxdigit(color[0]) || color[1] == 'x')
1602 break;
1603 t = color[size];
1604 color[size] = '\0';
1605 value = strtoul(color, &end, 16);
1606 color[size] = t;
1607 if (errno == ERANGE || end - color != size)
1608 break;
1609 switch (size)
1611 case 1:
1612 value = value * 0x10;
1613 break;
1614 case 2:
1615 break;
1616 case 3:
1617 value /= 0x10;
1618 break;
1619 case 4:
1620 value /= 0x100;
1621 break;
1623 colorval |= (value << pos);
1624 pos += 0x8;
1625 if (i == 2)
1627 UNBLOCK_INPUT;
1628 return (colorval);
1630 color = end;
1634 else if (strnicmp(colorname, "rgb:", 4) == 0)
1636 char *color;
1637 UINT colorval;
1638 int i, pos;
1639 pos = 0;
1641 colorval = 0;
1642 color = colorname + 4;
1643 for (i = 0; i < 3; i++)
1645 char *end;
1646 unsigned long value;
1648 /* The check for 'x' in the following conditional takes into
1649 account the fact that strtol allows a "0x" in front of
1650 our numbers, and we don't. */
1651 if (!isxdigit(color[0]) || color[1] == 'x')
1652 break;
1653 value = strtoul(color, &end, 16);
1654 if (errno == ERANGE)
1655 break;
1656 switch (end - color)
1658 case 1:
1659 value = value * 0x10 + value;
1660 break;
1661 case 2:
1662 break;
1663 case 3:
1664 value /= 0x10;
1665 break;
1666 case 4:
1667 value /= 0x100;
1668 break;
1669 default:
1670 value = ULONG_MAX;
1672 if (value == ULONG_MAX)
1673 break;
1674 colorval |= (value << pos);
1675 pos += 0x8;
1676 if (i == 2)
1678 if (*end != '\0')
1679 break;
1680 UNBLOCK_INPUT;
1681 return (colorval);
1683 if (*end != '/')
1684 break;
1685 color = end + 1;
1688 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1690 /* This is an RGB Intensity specification. */
1691 char *color;
1692 UINT colorval;
1693 int i, pos;
1694 pos = 0;
1696 colorval = 0;
1697 color = colorname + 5;
1698 for (i = 0; i < 3; i++)
1700 char *end;
1701 double value;
1702 UINT val;
1704 value = strtod(color, &end);
1705 if (errno == ERANGE)
1706 break;
1707 if (value < 0.0 || value > 1.0)
1708 break;
1709 val = (UINT)(0x100 * value);
1710 /* We used 0x100 instead of 0xFF to give a continuous
1711 range between 0.0 and 1.0 inclusive. The next statement
1712 fixes the 1.0 case. */
1713 if (val == 0x100)
1714 val = 0xFF;
1715 colorval |= (val << pos);
1716 pos += 0x8;
1717 if (i == 2)
1719 if (*end != '\0')
1720 break;
1721 UNBLOCK_INPUT;
1722 return (colorval);
1724 if (*end != '/')
1725 break;
1726 color = end + 1;
1729 /* I am not going to attempt to handle any of the CIE color schemes
1730 or TekHVC, since I don't know the algorithms for conversion to
1731 RGB. */
1733 /* If we fail to lookup the color name in w32_color_map, then check the
1734 colorname to see if it can be crudely approximated: If the X color
1735 ends in a number (e.g., "darkseagreen2"), strip the number and
1736 return the result of looking up the base color name. */
1737 ret = w32_color_map_lookup (colorname);
1738 if (NILP (ret))
1740 int len = strlen (colorname);
1742 if (isdigit (colorname[len - 1]))
1744 char *ptr, *approx = alloca (len + 1);
1746 strcpy (approx, colorname);
1747 ptr = &approx[len - 1];
1748 while (ptr > approx && isdigit (*ptr))
1749 *ptr-- = '\0';
1751 ret = w32_color_map_lookup (approx);
1755 UNBLOCK_INPUT;
1756 return ret;
1760 void
1761 w32_regenerate_palette (FRAME_PTR f)
1763 struct w32_palette_entry * list;
1764 LOGPALETTE * log_palette;
1765 HPALETTE new_palette;
1766 int i;
1768 /* don't bother trying to create palette if not supported */
1769 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1770 return;
1772 log_palette = (LOGPALETTE *)
1773 alloca (sizeof (LOGPALETTE) +
1774 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1775 log_palette->palVersion = 0x300;
1776 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1778 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1779 for (i = 0;
1780 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1781 i++, list = list->next)
1782 log_palette->palPalEntry[i] = list->entry;
1784 new_palette = CreatePalette (log_palette);
1786 enter_crit ();
1788 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1789 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1790 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1792 /* Realize display palette and garbage all frames. */
1793 release_frame_dc (f, get_frame_dc (f));
1795 leave_crit ();
1798 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1799 #define SET_W32_COLOR(pe, color) \
1800 do \
1802 pe.peRed = GetRValue (color); \
1803 pe.peGreen = GetGValue (color); \
1804 pe.peBlue = GetBValue (color); \
1805 pe.peFlags = 0; \
1806 } while (0)
1808 #if 0
1809 /* Keep these around in case we ever want to track color usage. */
1810 void
1811 w32_map_color (FRAME_PTR f, COLORREF color)
1813 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1815 if (NILP (Vw32_enable_palette))
1816 return;
1818 /* check if color is already mapped */
1819 while (list)
1821 if (W32_COLOR (list->entry) == color)
1823 ++list->refcount;
1824 return;
1826 list = list->next;
1829 /* not already mapped, so add to list and recreate Windows palette */
1830 list = (struct w32_palette_entry *)
1831 xmalloc (sizeof (struct w32_palette_entry));
1832 SET_W32_COLOR (list->entry, color);
1833 list->refcount = 1;
1834 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1835 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1836 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1838 /* set flag that palette must be regenerated */
1839 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1842 void
1843 w32_unmap_color (FRAME_PTR f, COLORREF color)
1845 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1846 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1848 if (NILP (Vw32_enable_palette))
1849 return;
1851 /* check if color is already mapped */
1852 while (list)
1854 if (W32_COLOR (list->entry) == color)
1856 if (--list->refcount == 0)
1858 *prev = list->next;
1859 xfree (list);
1860 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1861 break;
1863 else
1864 return;
1866 prev = &list->next;
1867 list = list->next;
1870 /* set flag that palette must be regenerated */
1871 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1873 #endif
1876 /* Gamma-correct COLOR on frame F. */
1878 void
1879 gamma_correct (f, color)
1880 struct frame *f;
1881 COLORREF *color;
1883 if (f->gamma)
1885 *color = PALETTERGB (
1886 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1887 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1888 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1893 /* Decide if color named COLOR is valid for the display associated with
1894 the selected frame; if so, return the rgb values in COLOR_DEF.
1895 If ALLOC is nonzero, allocate a new colormap cell. */
1898 w32_defined_color (f, color, color_def, alloc)
1899 FRAME_PTR f;
1900 char *color;
1901 XColor *color_def;
1902 int alloc;
1904 register Lisp_Object tem;
1905 COLORREF w32_color_ref;
1907 tem = x_to_w32_color (color);
1909 if (!NILP (tem))
1911 if (f)
1913 /* Apply gamma correction. */
1914 w32_color_ref = XUINT (tem);
1915 gamma_correct (f, &w32_color_ref);
1916 XSETINT (tem, w32_color_ref);
1919 /* Map this color to the palette if it is enabled. */
1920 if (!NILP (Vw32_enable_palette))
1922 struct w32_palette_entry * entry =
1923 one_w32_display_info.color_list;
1924 struct w32_palette_entry ** prev =
1925 &one_w32_display_info.color_list;
1927 /* check if color is already mapped */
1928 while (entry)
1930 if (W32_COLOR (entry->entry) == XUINT (tem))
1931 break;
1932 prev = &entry->next;
1933 entry = entry->next;
1936 if (entry == NULL && alloc)
1938 /* not already mapped, so add to list */
1939 entry = (struct w32_palette_entry *)
1940 xmalloc (sizeof (struct w32_palette_entry));
1941 SET_W32_COLOR (entry->entry, XUINT (tem));
1942 entry->next = NULL;
1943 *prev = entry;
1944 one_w32_display_info.num_colors++;
1946 /* set flag that palette must be regenerated */
1947 one_w32_display_info.regen_palette = TRUE;
1950 /* Ensure COLORREF value is snapped to nearest color in (default)
1951 palette by simulating the PALETTERGB macro. This works whether
1952 or not the display device has a palette. */
1953 w32_color_ref = XUINT (tem) | 0x2000000;
1955 color_def->pixel = w32_color_ref;
1956 color_def->red = GetRValue (w32_color_ref) * 256;
1957 color_def->green = GetGValue (w32_color_ref) * 256;
1958 color_def->blue = GetBValue (w32_color_ref) * 256;
1960 return 1;
1962 else
1964 return 0;
1968 /* Given a string ARG naming a color, compute a pixel value from it
1969 suitable for screen F.
1970 If F is not a color screen, return DEF (default) regardless of what
1971 ARG says. */
1974 x_decode_color (f, arg, def)
1975 FRAME_PTR f;
1976 Lisp_Object arg;
1977 int def;
1979 XColor cdef;
1981 CHECK_STRING (arg);
1983 if (strcmp (SDATA (arg), "black") == 0)
1984 return BLACK_PIX_DEFAULT (f);
1985 else if (strcmp (SDATA (arg), "white") == 0)
1986 return WHITE_PIX_DEFAULT (f);
1988 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1989 return def;
1991 /* w32_defined_color is responsible for coping with failures
1992 by looking for a near-miss. */
1993 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1994 return cdef.pixel;
1996 /* defined_color failed; return an ultimate default. */
1997 return def;
2000 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
2001 the previous value of that parameter, NEW_VALUE is the new value. */
2003 static void
2004 x_set_line_spacing (f, new_value, old_value)
2005 struct frame *f;
2006 Lisp_Object new_value, old_value;
2008 if (NILP (new_value))
2009 f->extra_line_spacing = 0;
2010 else if (NATNUMP (new_value))
2011 f->extra_line_spacing = XFASTINT (new_value);
2012 else
2013 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
2014 Fcons (new_value, Qnil)));
2015 if (FRAME_VISIBLE_P (f))
2016 redraw_frame (f);
2020 /* Change the `fullscreen' frame parameter of frame F. OLD_VALUE is
2021 the previous value of that parameter, NEW_VALUE is the new value. */
2023 static void
2024 x_set_fullscreen (f, new_value, old_value)
2025 struct frame *f;
2026 Lisp_Object new_value, old_value;
2028 if (NILP (new_value))
2029 f->output_data.w32->want_fullscreen = FULLSCREEN_NONE;
2030 else if (EQ (new_value, Qfullboth))
2031 f->output_data.w32->want_fullscreen = FULLSCREEN_BOTH;
2032 else if (EQ (new_value, Qfullwidth))
2033 f->output_data.w32->want_fullscreen = FULLSCREEN_WIDTH;
2034 else if (EQ (new_value, Qfullheight))
2035 f->output_data.w32->want_fullscreen = FULLSCREEN_HEIGHT;
2039 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
2040 the previous value of that parameter, NEW_VALUE is the new value. */
2042 static void
2043 x_set_screen_gamma (f, new_value, old_value)
2044 struct frame *f;
2045 Lisp_Object new_value, old_value;
2047 if (NILP (new_value))
2048 f->gamma = 0;
2049 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
2050 /* The value 0.4545 is the normal viewing gamma. */
2051 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
2052 else
2053 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
2054 Fcons (new_value, Qnil)));
2056 clear_face_cache (0);
2060 /* Functions called only from `x_set_frame_param'
2061 to set individual parameters.
2063 If FRAME_W32_WINDOW (f) is 0,
2064 the frame is being created and its window does not exist yet.
2065 In that case, just record the parameter's new value
2066 in the standard place; do not attempt to change the window. */
2068 void
2069 x_set_foreground_color (f, arg, oldval)
2070 struct frame *f;
2071 Lisp_Object arg, oldval;
2073 struct w32_output *x = f->output_data.w32;
2074 PIX_TYPE fg, old_fg;
2076 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2077 old_fg = FRAME_FOREGROUND_PIXEL (f);
2078 FRAME_FOREGROUND_PIXEL (f) = fg;
2080 if (FRAME_W32_WINDOW (f) != 0)
2082 if (x->cursor_pixel == old_fg)
2083 x->cursor_pixel = fg;
2085 update_face_from_frame_parameter (f, Qforeground_color, arg);
2086 if (FRAME_VISIBLE_P (f))
2087 redraw_frame (f);
2091 void
2092 x_set_background_color (f, arg, oldval)
2093 struct frame *f;
2094 Lisp_Object arg, oldval;
2096 FRAME_BACKGROUND_PIXEL (f)
2097 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2099 if (FRAME_W32_WINDOW (f) != 0)
2101 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2102 FRAME_BACKGROUND_PIXEL (f));
2104 update_face_from_frame_parameter (f, Qbackground_color, arg);
2106 if (FRAME_VISIBLE_P (f))
2107 redraw_frame (f);
2111 void
2112 x_set_mouse_color (f, arg, oldval)
2113 struct frame *f;
2114 Lisp_Object arg, oldval;
2116 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2117 int count;
2118 int mask_color;
2120 if (!EQ (Qnil, arg))
2121 f->output_data.w32->mouse_pixel
2122 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2123 mask_color = FRAME_BACKGROUND_PIXEL (f);
2125 /* Don't let pointers be invisible. */
2126 if (mask_color == f->output_data.w32->mouse_pixel
2127 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2128 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2130 #if 0 /* TODO : cursor changes */
2131 BLOCK_INPUT;
2133 /* It's not okay to crash if the user selects a screwy cursor. */
2134 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2136 if (!EQ (Qnil, Vx_pointer_shape))
2138 CHECK_NUMBER (Vx_pointer_shape);
2139 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2141 else
2142 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2143 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2145 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2147 CHECK_NUMBER (Vx_nontext_pointer_shape);
2148 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2149 XINT (Vx_nontext_pointer_shape));
2151 else
2152 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2153 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2155 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
2157 CHECK_NUMBER (Vx_hourglass_pointer_shape);
2158 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2159 XINT (Vx_hourglass_pointer_shape));
2161 else
2162 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2163 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2165 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2166 if (!EQ (Qnil, Vx_mode_pointer_shape))
2168 CHECK_NUMBER (Vx_mode_pointer_shape);
2169 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2170 XINT (Vx_mode_pointer_shape));
2172 else
2173 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2174 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2176 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2178 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
2179 cross_cursor
2180 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2181 XINT (Vx_sensitive_text_pointer_shape));
2183 else
2184 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2186 if (!NILP (Vx_window_horizontal_drag_shape))
2188 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
2189 horizontal_drag_cursor
2190 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2191 XINT (Vx_window_horizontal_drag_shape));
2193 else
2194 horizontal_drag_cursor
2195 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2197 /* Check and report errors with the above calls. */
2198 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2199 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2202 XColor fore_color, back_color;
2204 fore_color.pixel = f->output_data.w32->mouse_pixel;
2205 back_color.pixel = mask_color;
2206 XQueryColor (FRAME_W32_DISPLAY (f),
2207 DefaultColormap (FRAME_W32_DISPLAY (f),
2208 DefaultScreen (FRAME_W32_DISPLAY (f))),
2209 &fore_color);
2210 XQueryColor (FRAME_W32_DISPLAY (f),
2211 DefaultColormap (FRAME_W32_DISPLAY (f),
2212 DefaultScreen (FRAME_W32_DISPLAY (f))),
2213 &back_color);
2214 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2215 &fore_color, &back_color);
2216 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2217 &fore_color, &back_color);
2218 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2219 &fore_color, &back_color);
2220 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2221 &fore_color, &back_color);
2222 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
2223 &fore_color, &back_color);
2226 if (FRAME_W32_WINDOW (f) != 0)
2227 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2229 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2230 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2231 f->output_data.w32->text_cursor = cursor;
2233 if (nontext_cursor != f->output_data.w32->nontext_cursor
2234 && f->output_data.w32->nontext_cursor != 0)
2235 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2236 f->output_data.w32->nontext_cursor = nontext_cursor;
2238 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
2239 && f->output_data.w32->hourglass_cursor != 0)
2240 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
2241 f->output_data.w32->hourglass_cursor = hourglass_cursor;
2243 if (mode_cursor != f->output_data.w32->modeline_cursor
2244 && f->output_data.w32->modeline_cursor != 0)
2245 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2246 f->output_data.w32->modeline_cursor = mode_cursor;
2248 if (cross_cursor != f->output_data.w32->cross_cursor
2249 && f->output_data.w32->cross_cursor != 0)
2250 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2251 f->output_data.w32->cross_cursor = cross_cursor;
2253 XFlush (FRAME_W32_DISPLAY (f));
2254 UNBLOCK_INPUT;
2256 update_face_from_frame_parameter (f, Qmouse_color, arg);
2257 #endif /* TODO */
2260 /* Defined in w32term.c. */
2261 void x_update_cursor (struct frame *f, int on_p);
2263 void
2264 x_set_cursor_color (f, arg, oldval)
2265 struct frame *f;
2266 Lisp_Object arg, oldval;
2268 unsigned long fore_pixel, pixel;
2270 if (!NILP (Vx_cursor_fore_pixel))
2271 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2272 WHITE_PIX_DEFAULT (f));
2273 else
2274 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2276 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2278 /* Make sure that the cursor color differs from the background color. */
2279 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2281 pixel = f->output_data.w32->mouse_pixel;
2282 if (pixel == fore_pixel)
2283 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2286 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
2287 f->output_data.w32->cursor_pixel = pixel;
2289 if (FRAME_W32_WINDOW (f) != 0)
2291 BLOCK_INPUT;
2292 /* Update frame's cursor_gc. */
2293 f->output_data.w32->cursor_gc->foreground = fore_pixel;
2294 f->output_data.w32->cursor_gc->background = pixel;
2296 UNBLOCK_INPUT;
2298 if (FRAME_VISIBLE_P (f))
2300 x_update_cursor (f, 0);
2301 x_update_cursor (f, 1);
2305 update_face_from_frame_parameter (f, Qcursor_color, arg);
2308 /* Set the border-color of frame F to pixel value PIX.
2309 Note that this does not fully take effect if done before
2310 F has a window. */
2311 void
2312 x_set_border_pixel (f, pix)
2313 struct frame *f;
2314 int pix;
2316 f->output_data.w32->border_pixel = pix;
2318 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2320 if (FRAME_VISIBLE_P (f))
2321 redraw_frame (f);
2325 /* Set the border-color of frame F to value described by ARG.
2326 ARG can be a string naming a color.
2327 The border-color is used for the border that is drawn by the server.
2328 Note that this does not fully take effect if done before
2329 F has a window; it must be redone when the window is created. */
2331 void
2332 x_set_border_color (f, arg, oldval)
2333 struct frame *f;
2334 Lisp_Object arg, oldval;
2336 int pix;
2338 CHECK_STRING (arg);
2339 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2340 x_set_border_pixel (f, pix);
2341 update_face_from_frame_parameter (f, Qborder_color, arg);
2345 void
2346 x_set_cursor_type (f, arg, oldval)
2347 FRAME_PTR f;
2348 Lisp_Object arg, oldval;
2350 set_frame_cursor_types (f, arg);
2352 /* Make sure the cursor gets redrawn. This is overkill, but how
2353 often do people change cursor types? */
2354 update_mode_lines++;
2357 void
2358 x_set_icon_type (f, arg, oldval)
2359 struct frame *f;
2360 Lisp_Object arg, oldval;
2362 int result;
2364 if (NILP (arg) && NILP (oldval))
2365 return;
2367 if (STRINGP (arg) && STRINGP (oldval)
2368 && EQ (Fstring_equal (oldval, arg), Qt))
2369 return;
2371 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2372 return;
2374 BLOCK_INPUT;
2376 result = x_bitmap_icon (f, arg);
2377 if (result)
2379 UNBLOCK_INPUT;
2380 error ("No icon window available");
2383 UNBLOCK_INPUT;
2386 /* Return non-nil if frame F wants a bitmap icon. */
2388 Lisp_Object
2389 x_icon_type (f)
2390 FRAME_PTR f;
2392 Lisp_Object tem;
2394 tem = assq_no_quit (Qicon_type, f->param_alist);
2395 if (CONSP (tem))
2396 return XCDR (tem);
2397 else
2398 return Qnil;
2401 void
2402 x_set_icon_name (f, arg, oldval)
2403 struct frame *f;
2404 Lisp_Object arg, oldval;
2406 if (STRINGP (arg))
2408 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2409 return;
2411 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2412 return;
2414 f->icon_name = arg;
2416 #if 0
2417 if (f->output_data.w32->icon_bitmap != 0)
2418 return;
2420 BLOCK_INPUT;
2422 result = x_text_icon (f,
2423 (char *) SDATA ((!NILP (f->icon_name)
2424 ? f->icon_name
2425 : !NILP (f->title)
2426 ? f->title
2427 : f->name)));
2429 if (result)
2431 UNBLOCK_INPUT;
2432 error ("No icon window available");
2435 /* If the window was unmapped (and its icon was mapped),
2436 the new icon is not mapped, so map the window in its stead. */
2437 if (FRAME_VISIBLE_P (f))
2439 #ifdef USE_X_TOOLKIT
2440 XtPopup (f->output_data.w32->widget, XtGrabNone);
2441 #endif
2442 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2445 XFlush (FRAME_W32_DISPLAY (f));
2446 UNBLOCK_INPUT;
2447 #endif
2450 extern Lisp_Object x_new_font ();
2451 extern Lisp_Object x_new_fontset();
2453 void
2454 x_set_font (f, arg, oldval)
2455 struct frame *f;
2456 Lisp_Object arg, oldval;
2458 Lisp_Object result;
2459 Lisp_Object fontset_name;
2460 Lisp_Object frame;
2461 int old_fontset = FRAME_FONTSET(f);
2463 CHECK_STRING (arg);
2465 fontset_name = Fquery_fontset (arg, Qnil);
2467 BLOCK_INPUT;
2468 result = (STRINGP (fontset_name)
2469 ? x_new_fontset (f, SDATA (fontset_name))
2470 : x_new_font (f, SDATA (arg)));
2471 UNBLOCK_INPUT;
2473 if (EQ (result, Qnil))
2474 error ("Font `%s' is not defined", SDATA (arg));
2475 else if (EQ (result, Qt))
2476 error ("The characters of the given font have varying widths");
2477 else if (STRINGP (result))
2479 if (STRINGP (fontset_name))
2481 /* Fontset names are built from ASCII font names, so the
2482 names may be equal despite there was a change. */
2483 if (old_fontset == FRAME_FONTSET (f))
2484 return;
2486 else if (!NILP (Fequal (result, oldval)))
2487 return;
2489 store_frame_param (f, Qfont, result);
2490 recompute_basic_faces (f);
2492 else
2493 abort ();
2495 do_pending_window_change (0);
2497 /* Don't call `face-set-after-frame-default' when faces haven't been
2498 initialized yet. This is the case when called from
2499 Fx_create_frame. In that case, the X widget or window doesn't
2500 exist either, and we can end up in x_report_frame_params with a
2501 null widget which gives a segfault. */
2502 if (FRAME_FACE_CACHE (f))
2504 XSETFRAME (frame, f);
2505 call1 (Qface_set_after_frame_default, frame);
2509 static void
2510 x_set_fringe_width (f, new_value, old_value)
2511 struct frame *f;
2512 Lisp_Object new_value, old_value;
2514 x_compute_fringe_widths (f, 1);
2517 void
2518 x_set_border_width (f, arg, oldval)
2519 struct frame *f;
2520 Lisp_Object arg, oldval;
2522 CHECK_NUMBER (arg);
2524 if (XINT (arg) == f->output_data.w32->border_width)
2525 return;
2527 if (FRAME_W32_WINDOW (f) != 0)
2528 error ("Cannot change the border width of a window");
2530 f->output_data.w32->border_width = XINT (arg);
2533 void
2534 x_set_internal_border_width (f, arg, oldval)
2535 struct frame *f;
2536 Lisp_Object arg, oldval;
2538 int old = f->output_data.w32->internal_border_width;
2540 CHECK_NUMBER (arg);
2541 f->output_data.w32->internal_border_width = XINT (arg);
2542 if (f->output_data.w32->internal_border_width < 0)
2543 f->output_data.w32->internal_border_width = 0;
2545 if (f->output_data.w32->internal_border_width == old)
2546 return;
2548 if (FRAME_W32_WINDOW (f) != 0)
2550 x_set_window_size (f, 0, f->width, f->height);
2551 SET_FRAME_GARBAGED (f);
2552 do_pending_window_change (0);
2554 else
2555 SET_FRAME_GARBAGED (f);
2558 void
2559 x_set_visibility (f, value, oldval)
2560 struct frame *f;
2561 Lisp_Object value, oldval;
2563 Lisp_Object frame;
2564 XSETFRAME (frame, f);
2566 if (NILP (value))
2567 Fmake_frame_invisible (frame, Qt);
2568 else if (EQ (value, Qicon))
2569 Ficonify_frame (frame);
2570 else
2571 Fmake_frame_visible (frame);
2575 /* Change window heights in windows rooted in WINDOW by N lines. */
2577 static void
2578 x_change_window_heights (window, n)
2579 Lisp_Object window;
2580 int n;
2582 struct window *w = XWINDOW (window);
2584 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2585 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2587 if (INTEGERP (w->orig_top))
2588 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2589 if (INTEGERP (w->orig_height))
2590 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2592 /* Handle just the top child in a vertical split. */
2593 if (!NILP (w->vchild))
2594 x_change_window_heights (w->vchild, n);
2596 /* Adjust all children in a horizontal split. */
2597 for (window = w->hchild; !NILP (window); window = w->next)
2599 w = XWINDOW (window);
2600 x_change_window_heights (window, n);
2604 void
2605 x_set_menu_bar_lines (f, value, oldval)
2606 struct frame *f;
2607 Lisp_Object value, oldval;
2609 int nlines;
2610 int olines = FRAME_MENU_BAR_LINES (f);
2612 /* Right now, menu bars don't work properly in minibuf-only frames;
2613 most of the commands try to apply themselves to the minibuffer
2614 frame itself, and get an error because you can't switch buffers
2615 in or split the minibuffer window. */
2616 if (FRAME_MINIBUF_ONLY_P (f))
2617 return;
2619 if (INTEGERP (value))
2620 nlines = XINT (value);
2621 else
2622 nlines = 0;
2624 FRAME_MENU_BAR_LINES (f) = 0;
2625 if (nlines)
2626 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2627 else
2629 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2630 free_frame_menubar (f);
2631 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2633 /* Adjust the frame size so that the client (text) dimensions
2634 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2635 set correctly. */
2636 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2637 do_pending_window_change (0);
2639 adjust_glyphs (f);
2643 /* Set the number of lines used for the tool bar of frame F to VALUE.
2644 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2645 is the old number of tool bar lines. This function changes the
2646 height of all windows on frame F to match the new tool bar height.
2647 The frame's height doesn't change. */
2649 void
2650 x_set_tool_bar_lines (f, value, oldval)
2651 struct frame *f;
2652 Lisp_Object value, oldval;
2654 int delta, nlines, root_height;
2655 Lisp_Object root_window;
2657 /* Treat tool bars like menu bars. */
2658 if (FRAME_MINIBUF_ONLY_P (f))
2659 return;
2661 /* Use VALUE only if an integer >= 0. */
2662 if (INTEGERP (value) && XINT (value) >= 0)
2663 nlines = XFASTINT (value);
2664 else
2665 nlines = 0;
2667 /* Make sure we redisplay all windows in this frame. */
2668 ++windows_or_buffers_changed;
2670 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2672 /* Don't resize the tool-bar to more than we have room for. */
2673 root_window = FRAME_ROOT_WINDOW (f);
2674 root_height = XINT (XWINDOW (root_window)->height);
2675 if (root_height - delta < 1)
2677 delta = root_height - 1;
2678 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2681 FRAME_TOOL_BAR_LINES (f) = nlines;
2682 x_change_window_heights (root_window, delta);
2683 adjust_glyphs (f);
2685 /* We also have to make sure that the internal border at the top of
2686 the frame, below the menu bar or tool bar, is redrawn when the
2687 tool bar disappears. This is so because the internal border is
2688 below the tool bar if one is displayed, but is below the menu bar
2689 if there isn't a tool bar. The tool bar draws into the area
2690 below the menu bar. */
2691 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2693 updating_frame = f;
2694 clear_frame ();
2695 clear_current_matrices (f);
2696 updating_frame = NULL;
2699 /* If the tool bar gets smaller, the internal border below it
2700 has to be cleared. It was formerly part of the display
2701 of the larger tool bar, and updating windows won't clear it. */
2702 if (delta < 0)
2704 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2705 int width = PIXEL_WIDTH (f);
2706 int y = nlines * CANON_Y_UNIT (f);
2708 BLOCK_INPUT;
2710 HDC hdc = get_frame_dc (f);
2711 w32_clear_area (f, hdc, 0, y, width, height);
2712 release_frame_dc (f, hdc);
2714 UNBLOCK_INPUT;
2716 if (WINDOWP (f->tool_bar_window))
2717 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
2722 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2723 w32_id_name.
2725 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2726 name; if NAME is a string, set F's name to NAME and set
2727 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2729 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2730 suggesting a new name, which lisp code should override; if
2731 F->explicit_name is set, ignore the new name; otherwise, set it. */
2733 void
2734 x_set_name (f, name, explicit)
2735 struct frame *f;
2736 Lisp_Object name;
2737 int explicit;
2739 /* Make sure that requests from lisp code override requests from
2740 Emacs redisplay code. */
2741 if (explicit)
2743 /* If we're switching from explicit to implicit, we had better
2744 update the mode lines and thereby update the title. */
2745 if (f->explicit_name && NILP (name))
2746 update_mode_lines = 1;
2748 f->explicit_name = ! NILP (name);
2750 else if (f->explicit_name)
2751 return;
2753 /* If NAME is nil, set the name to the w32_id_name. */
2754 if (NILP (name))
2756 /* Check for no change needed in this very common case
2757 before we do any consing. */
2758 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2759 SDATA (f->name)))
2760 return;
2761 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2763 else
2764 CHECK_STRING (name);
2766 /* Don't change the name if it's already NAME. */
2767 if (! NILP (Fstring_equal (name, f->name)))
2768 return;
2770 f->name = name;
2772 /* For setting the frame title, the title parameter should override
2773 the name parameter. */
2774 if (! NILP (f->title))
2775 name = f->title;
2777 if (FRAME_W32_WINDOW (f))
2779 if (STRING_MULTIBYTE (name))
2780 name = ENCODE_SYSTEM (name);
2782 BLOCK_INPUT;
2783 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2784 UNBLOCK_INPUT;
2788 /* This function should be called when the user's lisp code has
2789 specified a name for the frame; the name will override any set by the
2790 redisplay code. */
2791 void
2792 x_explicitly_set_name (f, arg, oldval)
2793 FRAME_PTR f;
2794 Lisp_Object arg, oldval;
2796 x_set_name (f, arg, 1);
2799 /* This function should be called by Emacs redisplay code to set the
2800 name; names set this way will never override names set by the user's
2801 lisp code. */
2802 void
2803 x_implicitly_set_name (f, arg, oldval)
2804 FRAME_PTR f;
2805 Lisp_Object arg, oldval;
2807 x_set_name (f, arg, 0);
2810 /* Change the title of frame F to NAME.
2811 If NAME is nil, use the frame name as the title.
2813 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2814 name; if NAME is a string, set F's name to NAME and set
2815 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2817 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2818 suggesting a new name, which lisp code should override; if
2819 F->explicit_name is set, ignore the new name; otherwise, set it. */
2821 void
2822 x_set_title (f, name, old_name)
2823 struct frame *f;
2824 Lisp_Object name, old_name;
2826 /* Don't change the title if it's already NAME. */
2827 if (EQ (name, f->title))
2828 return;
2830 update_mode_lines = 1;
2832 f->title = name;
2834 if (NILP (name))
2835 name = f->name;
2837 if (FRAME_W32_WINDOW (f))
2839 if (STRING_MULTIBYTE (name))
2840 name = ENCODE_SYSTEM (name);
2842 BLOCK_INPUT;
2843 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2844 UNBLOCK_INPUT;
2848 void
2849 x_set_autoraise (f, arg, oldval)
2850 struct frame *f;
2851 Lisp_Object arg, oldval;
2853 f->auto_raise = !EQ (Qnil, arg);
2856 void
2857 x_set_autolower (f, arg, oldval)
2858 struct frame *f;
2859 Lisp_Object arg, oldval;
2861 f->auto_lower = !EQ (Qnil, arg);
2864 void
2865 x_set_unsplittable (f, arg, oldval)
2866 struct frame *f;
2867 Lisp_Object arg, oldval;
2869 f->no_split = !NILP (arg);
2872 void
2873 x_set_vertical_scroll_bars (f, arg, oldval)
2874 struct frame *f;
2875 Lisp_Object arg, oldval;
2877 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2878 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2879 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2880 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2882 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2883 vertical_scroll_bar_none :
2884 /* Put scroll bars on the right by default, as is conventional
2885 on MS-Windows. */
2886 EQ (Qleft, arg)
2887 ? vertical_scroll_bar_left
2888 : vertical_scroll_bar_right;
2890 /* We set this parameter before creating the window for the
2891 frame, so we can get the geometry right from the start.
2892 However, if the window hasn't been created yet, we shouldn't
2893 call x_set_window_size. */
2894 if (FRAME_W32_WINDOW (f))
2895 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2896 do_pending_window_change (0);
2900 void
2901 x_set_scroll_bar_width (f, arg, oldval)
2902 struct frame *f;
2903 Lisp_Object arg, oldval;
2905 int wid = FONT_WIDTH (f->output_data.w32->font);
2907 if (NILP (arg))
2909 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2910 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2911 wid - 1) / wid;
2912 if (FRAME_W32_WINDOW (f))
2913 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2914 do_pending_window_change (0);
2916 else if (INTEGERP (arg) && XINT (arg) > 0
2917 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2919 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2920 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2921 + wid-1) / wid;
2922 if (FRAME_W32_WINDOW (f))
2923 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2924 do_pending_window_change (0);
2926 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2927 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2928 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2931 /* Subroutines of creating a frame. */
2933 /* Make sure that Vx_resource_name is set to a reasonable value.
2934 Fix it up, or set it to `emacs' if it is too hopeless. */
2936 static void
2937 validate_x_resource_name ()
2939 int len = 0;
2940 /* Number of valid characters in the resource name. */
2941 int good_count = 0;
2942 /* Number of invalid characters in the resource name. */
2943 int bad_count = 0;
2944 Lisp_Object new;
2945 int i;
2947 if (STRINGP (Vx_resource_name))
2949 unsigned char *p = SDATA (Vx_resource_name);
2950 int i;
2952 len = SBYTES (Vx_resource_name);
2954 /* Only letters, digits, - and _ are valid in resource names.
2955 Count the valid characters and count the invalid ones. */
2956 for (i = 0; i < len; i++)
2958 int c = p[i];
2959 if (! ((c >= 'a' && c <= 'z')
2960 || (c >= 'A' && c <= 'Z')
2961 || (c >= '0' && c <= '9')
2962 || c == '-' || c == '_'))
2963 bad_count++;
2964 else
2965 good_count++;
2968 else
2969 /* Not a string => completely invalid. */
2970 bad_count = 5, good_count = 0;
2972 /* If name is valid already, return. */
2973 if (bad_count == 0)
2974 return;
2976 /* If name is entirely invalid, or nearly so, use `emacs'. */
2977 if (good_count == 0
2978 || (good_count == 1 && bad_count > 0))
2980 Vx_resource_name = build_string ("emacs");
2981 return;
2984 /* Name is partly valid. Copy it and replace the invalid characters
2985 with underscores. */
2987 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2989 for (i = 0; i < len; i++)
2991 int c = SREF (new, i);
2992 if (! ((c >= 'a' && c <= 'z')
2993 || (c >= 'A' && c <= 'Z')
2994 || (c >= '0' && c <= '9')
2995 || c == '-' || c == '_'))
2996 SSET (new, i, '_');
3001 extern char *x_get_string_resource ();
3003 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
3004 doc: /* Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.
3005 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the
3006 class, where INSTANCE is the name under which Emacs was invoked, or
3007 the name specified by the `-name' or `-rn' command-line arguments.
3009 The optional arguments COMPONENT and SUBCLASS add to the key and the
3010 class, respectively. You must specify both of them or neither.
3011 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'
3012 and the class is `Emacs.CLASS.SUBCLASS'. */)
3013 (attribute, class, component, subclass)
3014 Lisp_Object attribute, class, component, subclass;
3016 register char *value;
3017 char *name_key;
3018 char *class_key;
3020 CHECK_STRING (attribute);
3021 CHECK_STRING (class);
3023 if (!NILP (component))
3024 CHECK_STRING (component);
3025 if (!NILP (subclass))
3026 CHECK_STRING (subclass);
3027 if (NILP (component) != NILP (subclass))
3028 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
3030 validate_x_resource_name ();
3032 /* Allocate space for the components, the dots which separate them,
3033 and the final '\0'. Make them big enough for the worst case. */
3034 name_key = (char *) alloca (SBYTES (Vx_resource_name)
3035 + (STRINGP (component)
3036 ? SBYTES (component) : 0)
3037 + SBYTES (attribute)
3038 + 3);
3040 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3041 + SBYTES (class)
3042 + (STRINGP (subclass)
3043 ? SBYTES (subclass) : 0)
3044 + 3);
3046 /* Start with emacs.FRAMENAME for the name (the specific one)
3047 and with `Emacs' for the class key (the general one). */
3048 strcpy (name_key, SDATA (Vx_resource_name));
3049 strcpy (class_key, EMACS_CLASS);
3051 strcat (class_key, ".");
3052 strcat (class_key, SDATA (class));
3054 if (!NILP (component))
3056 strcat (class_key, ".");
3057 strcat (class_key, SDATA (subclass));
3059 strcat (name_key, ".");
3060 strcat (name_key, SDATA (component));
3063 strcat (name_key, ".");
3064 strcat (name_key, SDATA (attribute));
3066 value = x_get_string_resource (Qnil,
3067 name_key, class_key);
3069 if (value != (char *) 0)
3070 return build_string (value);
3071 else
3072 return Qnil;
3075 /* Used when C code wants a resource value. */
3077 char *
3078 x_get_resource_string (attribute, class)
3079 char *attribute, *class;
3081 char *name_key;
3082 char *class_key;
3083 struct frame *sf = SELECTED_FRAME ();
3085 /* Allocate space for the components, the dots which separate them,
3086 and the final '\0'. */
3087 name_key = (char *) alloca (SBYTES (Vinvocation_name)
3088 + strlen (attribute) + 2);
3089 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3090 + strlen (class) + 2);
3092 sprintf (name_key, "%s.%s",
3093 SDATA (Vinvocation_name),
3094 attribute);
3095 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
3097 return x_get_string_resource (sf, name_key, class_key);
3100 /* Types we might convert a resource string into. */
3101 enum resource_types
3103 RES_TYPE_NUMBER,
3104 RES_TYPE_FLOAT,
3105 RES_TYPE_BOOLEAN,
3106 RES_TYPE_STRING,
3107 RES_TYPE_SYMBOL
3110 /* Return the value of parameter PARAM.
3112 First search ALIST, then Vdefault_frame_alist, then the X defaults
3113 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3115 Convert the resource to the type specified by desired_type.
3117 If no default is specified, return Qunbound. If you call
3118 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3119 and don't let it get stored in any Lisp-visible variables! */
3121 static Lisp_Object
3122 w32_get_arg (alist, param, attribute, class, type)
3123 Lisp_Object alist, param;
3124 char *attribute;
3125 char *class;
3126 enum resource_types type;
3128 register Lisp_Object tem;
3130 tem = Fassq (param, alist);
3131 if (EQ (tem, Qnil))
3132 tem = Fassq (param, Vdefault_frame_alist);
3133 if (EQ (tem, Qnil))
3136 if (attribute)
3138 tem = Fx_get_resource (build_string (attribute),
3139 build_string (class),
3140 Qnil, Qnil);
3142 if (NILP (tem))
3143 return Qunbound;
3145 switch (type)
3147 case RES_TYPE_NUMBER:
3148 return make_number (atoi (SDATA (tem)));
3150 case RES_TYPE_FLOAT:
3151 return make_float (atof (SDATA (tem)));
3153 case RES_TYPE_BOOLEAN:
3154 tem = Fdowncase (tem);
3155 if (!strcmp (SDATA (tem), "on")
3156 || !strcmp (SDATA (tem), "true"))
3157 return Qt;
3158 else
3159 return Qnil;
3161 case RES_TYPE_STRING:
3162 return tem;
3164 case RES_TYPE_SYMBOL:
3165 /* As a special case, we map the values `true' and `on'
3166 to Qt, and `false' and `off' to Qnil. */
3168 Lisp_Object lower;
3169 lower = Fdowncase (tem);
3170 if (!strcmp (SDATA (lower), "on")
3171 || !strcmp (SDATA (lower), "true"))
3172 return Qt;
3173 else if (!strcmp (SDATA (lower), "off")
3174 || !strcmp (SDATA (lower), "false"))
3175 return Qnil;
3176 else
3177 return Fintern (tem, Qnil);
3180 default:
3181 abort ();
3184 else
3185 return Qunbound;
3187 return Fcdr (tem);
3190 /* Record in frame F the specified or default value according to ALIST
3191 of the parameter named PROP (a Lisp symbol).
3192 If no value is specified for PROP, look for an X default for XPROP
3193 on the frame named NAME.
3194 If that is not found either, use the value DEFLT. */
3196 static Lisp_Object
3197 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3198 struct frame *f;
3199 Lisp_Object alist;
3200 Lisp_Object prop;
3201 Lisp_Object deflt;
3202 char *xprop;
3203 char *xclass;
3204 enum resource_types type;
3206 Lisp_Object tem;
3208 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3209 if (EQ (tem, Qunbound))
3210 tem = deflt;
3211 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3212 return tem;
3215 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3216 doc: /* Parse an X-style geometry string STRING.
3217 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).
3218 The properties returned may include `top', `left', `height', and `width'.
3219 The value of `left' or `top' may be an integer,
3220 or a list (+ N) meaning N pixels relative to top/left corner,
3221 or a list (- N) meaning -N pixels relative to bottom/right corner. */)
3222 (string)
3223 Lisp_Object string;
3225 int geometry, x, y;
3226 unsigned int width, height;
3227 Lisp_Object result;
3229 CHECK_STRING (string);
3231 geometry = XParseGeometry ((char *) SDATA (string),
3232 &x, &y, &width, &height);
3234 result = Qnil;
3235 if (geometry & XValue)
3237 Lisp_Object element;
3239 if (x >= 0 && (geometry & XNegative))
3240 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3241 else if (x < 0 && ! (geometry & XNegative))
3242 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3243 else
3244 element = Fcons (Qleft, make_number (x));
3245 result = Fcons (element, result);
3248 if (geometry & YValue)
3250 Lisp_Object element;
3252 if (y >= 0 && (geometry & YNegative))
3253 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3254 else if (y < 0 && ! (geometry & YNegative))
3255 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3256 else
3257 element = Fcons (Qtop, make_number (y));
3258 result = Fcons (element, result);
3261 if (geometry & WidthValue)
3262 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3263 if (geometry & HeightValue)
3264 result = Fcons (Fcons (Qheight, make_number (height)), result);
3266 return result;
3269 /* Calculate the desired size and position of this window,
3270 and return the flags saying which aspects were specified.
3272 This function does not make the coordinates positive. */
3274 #define DEFAULT_ROWS 40
3275 #define DEFAULT_COLS 80
3277 static int
3278 x_figure_window_size (f, parms)
3279 struct frame *f;
3280 Lisp_Object parms;
3282 register Lisp_Object tem0, tem1, tem2;
3283 long window_prompting = 0;
3285 /* Default values if we fall through.
3286 Actually, if that happens we should get
3287 window manager prompting. */
3288 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3289 f->height = DEFAULT_ROWS;
3290 /* Window managers expect that if program-specified
3291 positions are not (0,0), they're intentional, not defaults. */
3292 f->output_data.w32->top_pos = 0;
3293 f->output_data.w32->left_pos = 0;
3295 /* Ensure that old new_width and new_height will not override the
3296 values set here. */
3297 FRAME_NEW_WIDTH (f) = 0;
3298 FRAME_NEW_HEIGHT (f) = 0;
3300 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3301 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3302 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3303 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3305 if (!EQ (tem0, Qunbound))
3307 CHECK_NUMBER (tem0);
3308 f->height = XINT (tem0);
3310 if (!EQ (tem1, Qunbound))
3312 CHECK_NUMBER (tem1);
3313 SET_FRAME_WIDTH (f, XINT (tem1));
3315 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3316 window_prompting |= USSize;
3317 else
3318 window_prompting |= PSize;
3321 f->output_data.w32->vertical_scroll_bar_extra
3322 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3324 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3325 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3326 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3328 x_compute_fringe_widths (f, 0);
3330 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3331 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3333 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3334 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3335 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3336 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3338 if (EQ (tem0, Qminus))
3340 f->output_data.w32->top_pos = 0;
3341 window_prompting |= YNegative;
3343 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3344 && CONSP (XCDR (tem0))
3345 && INTEGERP (XCAR (XCDR (tem0))))
3347 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3348 window_prompting |= YNegative;
3350 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3351 && CONSP (XCDR (tem0))
3352 && INTEGERP (XCAR (XCDR (tem0))))
3354 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3356 else if (EQ (tem0, Qunbound))
3357 f->output_data.w32->top_pos = 0;
3358 else
3360 CHECK_NUMBER (tem0);
3361 f->output_data.w32->top_pos = XINT (tem0);
3362 if (f->output_data.w32->top_pos < 0)
3363 window_prompting |= YNegative;
3366 if (EQ (tem1, Qminus))
3368 f->output_data.w32->left_pos = 0;
3369 window_prompting |= XNegative;
3371 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3372 && CONSP (XCDR (tem1))
3373 && INTEGERP (XCAR (XCDR (tem1))))
3375 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3376 window_prompting |= XNegative;
3378 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3379 && CONSP (XCDR (tem1))
3380 && INTEGERP (XCAR (XCDR (tem1))))
3382 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3384 else if (EQ (tem1, Qunbound))
3385 f->output_data.w32->left_pos = 0;
3386 else
3388 CHECK_NUMBER (tem1);
3389 f->output_data.w32->left_pos = XINT (tem1);
3390 if (f->output_data.w32->left_pos < 0)
3391 window_prompting |= XNegative;
3394 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3395 window_prompting |= USPosition;
3396 else
3397 window_prompting |= PPosition;
3400 if (f->output_data.w32->want_fullscreen != FULLSCREEN_NONE)
3402 int left, top;
3403 int width, height;
3405 /* It takes both for some WM:s to place it where we want */
3406 window_prompting = USPosition | PPosition;
3407 x_fullscreen_adjust (f, &width, &height, &top, &left);
3408 f->width = width;
3409 f->height = height;
3410 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3411 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3412 f->output_data.w32->left_pos = left;
3413 f->output_data.w32->top_pos = top;
3416 return window_prompting;
3421 extern LRESULT CALLBACK w32_wnd_proc ();
3423 BOOL
3424 w32_init_class (hinst)
3425 HINSTANCE hinst;
3427 WNDCLASS wc;
3429 wc.style = CS_HREDRAW | CS_VREDRAW;
3430 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3431 wc.cbClsExtra = 0;
3432 wc.cbWndExtra = WND_EXTRA_BYTES;
3433 wc.hInstance = hinst;
3434 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3435 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3436 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3437 wc.lpszMenuName = NULL;
3438 wc.lpszClassName = EMACS_CLASS;
3440 return (RegisterClass (&wc));
3443 HWND
3444 w32_createscrollbar (f, bar)
3445 struct frame *f;
3446 struct scroll_bar * bar;
3448 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3449 /* Position and size of scroll bar. */
3450 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3451 XINT(bar->top),
3452 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3453 XINT(bar->height),
3454 FRAME_W32_WINDOW (f),
3455 NULL,
3456 hinst,
3457 NULL));
3460 void
3461 w32_createwindow (f)
3462 struct frame *f;
3464 HWND hwnd;
3465 RECT rect;
3467 rect.left = rect.top = 0;
3468 rect.right = PIXEL_WIDTH (f);
3469 rect.bottom = PIXEL_HEIGHT (f);
3471 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3472 FRAME_EXTERNAL_MENU_BAR (f));
3474 /* Do first time app init */
3476 if (!hprevinst)
3478 w32_init_class (hinst);
3481 FRAME_W32_WINDOW (f) = hwnd
3482 = CreateWindow (EMACS_CLASS,
3483 f->namebuf,
3484 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3485 f->output_data.w32->left_pos,
3486 f->output_data.w32->top_pos,
3487 rect.right - rect.left,
3488 rect.bottom - rect.top,
3489 NULL,
3490 NULL,
3491 hinst,
3492 NULL);
3494 if (hwnd)
3496 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3497 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3498 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3499 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3500 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3502 /* Enable drag-n-drop. */
3503 DragAcceptFiles (hwnd, TRUE);
3505 /* Do this to discard the default setting specified by our parent. */
3506 ShowWindow (hwnd, SW_HIDE);
3510 void
3511 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3512 W32Msg * wmsg;
3513 HWND hwnd;
3514 UINT msg;
3515 WPARAM wParam;
3516 LPARAM lParam;
3518 wmsg->msg.hwnd = hwnd;
3519 wmsg->msg.message = msg;
3520 wmsg->msg.wParam = wParam;
3521 wmsg->msg.lParam = lParam;
3522 wmsg->msg.time = GetMessageTime ();
3524 post_msg (wmsg);
3527 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3528 between left and right keys as advertised. We test for this
3529 support dynamically, and set a flag when the support is absent. If
3530 absent, we keep track of the left and right control and alt keys
3531 ourselves. This is particularly necessary on keyboards that rely
3532 upon the AltGr key, which is represented as having the left control
3533 and right alt keys pressed. For these keyboards, we need to know
3534 when the left alt key has been pressed in addition to the AltGr key
3535 so that we can properly support M-AltGr-key sequences (such as M-@
3536 on Swedish keyboards). */
3538 #define EMACS_LCONTROL 0
3539 #define EMACS_RCONTROL 1
3540 #define EMACS_LMENU 2
3541 #define EMACS_RMENU 3
3543 static int modifiers[4];
3544 static int modifiers_recorded;
3545 static int modifier_key_support_tested;
3547 static void
3548 test_modifier_support (unsigned int wparam)
3550 unsigned int l, r;
3552 if (wparam != VK_CONTROL && wparam != VK_MENU)
3553 return;
3554 if (wparam == VK_CONTROL)
3556 l = VK_LCONTROL;
3557 r = VK_RCONTROL;
3559 else
3561 l = VK_LMENU;
3562 r = VK_RMENU;
3564 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3565 modifiers_recorded = 1;
3566 else
3567 modifiers_recorded = 0;
3568 modifier_key_support_tested = 1;
3571 static void
3572 record_keydown (unsigned int wparam, unsigned int lparam)
3574 int i;
3576 if (!modifier_key_support_tested)
3577 test_modifier_support (wparam);
3579 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3580 return;
3582 if (wparam == VK_CONTROL)
3583 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3584 else
3585 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3587 modifiers[i] = 1;
3590 static void
3591 record_keyup (unsigned int wparam, unsigned int lparam)
3593 int i;
3595 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3596 return;
3598 if (wparam == VK_CONTROL)
3599 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3600 else
3601 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3603 modifiers[i] = 0;
3606 /* Emacs can lose focus while a modifier key has been pressed. When
3607 it regains focus, be conservative and clear all modifiers since
3608 we cannot reconstruct the left and right modifier state. */
3609 static void
3610 reset_modifiers ()
3612 SHORT ctrl, alt;
3614 if (GetFocus () == NULL)
3615 /* Emacs doesn't have keyboard focus. Do nothing. */
3616 return;
3618 ctrl = GetAsyncKeyState (VK_CONTROL);
3619 alt = GetAsyncKeyState (VK_MENU);
3621 if (!(ctrl & 0x08000))
3622 /* Clear any recorded control modifier state. */
3623 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3625 if (!(alt & 0x08000))
3626 /* Clear any recorded alt modifier state. */
3627 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3629 /* Update the state of all modifier keys, because modifiers used in
3630 hot-key combinations can get stuck on if Emacs loses focus as a
3631 result of a hot-key being pressed. */
3633 BYTE keystate[256];
3635 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3637 GetKeyboardState (keystate);
3638 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3639 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3640 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3641 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3642 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3643 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3644 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3645 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3646 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3647 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3648 SetKeyboardState (keystate);
3652 /* Synchronize modifier state with what is reported with the current
3653 keystroke. Even if we cannot distinguish between left and right
3654 modifier keys, we know that, if no modifiers are set, then neither
3655 the left or right modifier should be set. */
3656 static void
3657 sync_modifiers ()
3659 if (!modifiers_recorded)
3660 return;
3662 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3663 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3665 if (!(GetKeyState (VK_MENU) & 0x8000))
3666 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3669 static int
3670 modifier_set (int vkey)
3672 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3673 return (GetKeyState (vkey) & 0x1);
3674 if (!modifiers_recorded)
3675 return (GetKeyState (vkey) & 0x8000);
3677 switch (vkey)
3679 case VK_LCONTROL:
3680 return modifiers[EMACS_LCONTROL];
3681 case VK_RCONTROL:
3682 return modifiers[EMACS_RCONTROL];
3683 case VK_LMENU:
3684 return modifiers[EMACS_LMENU];
3685 case VK_RMENU:
3686 return modifiers[EMACS_RMENU];
3688 return (GetKeyState (vkey) & 0x8000);
3691 /* Convert between the modifier bits W32 uses and the modifier bits
3692 Emacs uses. */
3694 unsigned int
3695 w32_key_to_modifier (int key)
3697 Lisp_Object key_mapping;
3699 switch (key)
3701 case VK_LWIN:
3702 key_mapping = Vw32_lwindow_modifier;
3703 break;
3704 case VK_RWIN:
3705 key_mapping = Vw32_rwindow_modifier;
3706 break;
3707 case VK_APPS:
3708 key_mapping = Vw32_apps_modifier;
3709 break;
3710 case VK_SCROLL:
3711 key_mapping = Vw32_scroll_lock_modifier;
3712 break;
3713 default:
3714 key_mapping = Qnil;
3717 /* NB. This code runs in the input thread, asychronously to the lisp
3718 thread, so we must be careful to ensure access to lisp data is
3719 thread-safe. The following code is safe because the modifier
3720 variable values are updated atomically from lisp and symbols are
3721 not relocated by GC. Also, we don't have to worry about seeing GC
3722 markbits here. */
3723 if (EQ (key_mapping, Qhyper))
3724 return hyper_modifier;
3725 if (EQ (key_mapping, Qsuper))
3726 return super_modifier;
3727 if (EQ (key_mapping, Qmeta))
3728 return meta_modifier;
3729 if (EQ (key_mapping, Qalt))
3730 return alt_modifier;
3731 if (EQ (key_mapping, Qctrl))
3732 return ctrl_modifier;
3733 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3734 return ctrl_modifier;
3735 if (EQ (key_mapping, Qshift))
3736 return shift_modifier;
3738 /* Don't generate any modifier if not explicitly requested. */
3739 return 0;
3742 unsigned int
3743 w32_get_modifiers ()
3745 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3746 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3747 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3748 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3749 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3750 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3751 (modifier_set (VK_MENU) ?
3752 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3755 /* We map the VK_* modifiers into console modifier constants
3756 so that we can use the same routines to handle both console
3757 and window input. */
3759 static int
3760 construct_console_modifiers ()
3762 int mods;
3764 mods = 0;
3765 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3766 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3767 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3768 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3769 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3770 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3771 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3772 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3773 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3774 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3775 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3777 return mods;
3780 static int
3781 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3783 int mods;
3785 /* Convert to emacs modifiers. */
3786 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3788 return mods;
3791 unsigned int
3792 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3794 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3795 return virt_key;
3797 if (virt_key == VK_RETURN)
3798 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3800 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3801 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3803 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3804 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3806 if (virt_key == VK_CLEAR)
3807 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3809 return virt_key;
3812 /* List of special key combinations which w32 would normally capture,
3813 but emacs should grab instead. Not directly visible to lisp, to
3814 simplify synchronization. Each item is an integer encoding a virtual
3815 key code and modifier combination to capture. */
3816 Lisp_Object w32_grabbed_keys;
3818 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3819 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3820 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3821 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3823 /* Register hot-keys for reserved key combinations when Emacs has
3824 keyboard focus, since this is the only way Emacs can receive key
3825 combinations like Alt-Tab which are used by the system. */
3827 static void
3828 register_hot_keys (hwnd)
3829 HWND hwnd;
3831 Lisp_Object keylist;
3833 /* Use GC_CONSP, since we are called asynchronously. */
3834 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3836 Lisp_Object key = XCAR (keylist);
3838 /* Deleted entries get set to nil. */
3839 if (!INTEGERP (key))
3840 continue;
3842 RegisterHotKey (hwnd, HOTKEY_ID (key),
3843 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3847 static void
3848 unregister_hot_keys (hwnd)
3849 HWND hwnd;
3851 Lisp_Object keylist;
3853 /* Use GC_CONSP, since we are called asynchronously. */
3854 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3856 Lisp_Object key = XCAR (keylist);
3858 if (!INTEGERP (key))
3859 continue;
3861 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3865 /* Main message dispatch loop. */
3867 static void
3868 w32_msg_pump (deferred_msg * msg_buf)
3870 MSG msg;
3871 int result;
3872 HWND focus_window;
3874 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3876 while (GetMessage (&msg, NULL, 0, 0))
3878 if (msg.hwnd == NULL)
3880 switch (msg.message)
3882 case WM_NULL:
3883 /* Produced by complete_deferred_msg; just ignore. */
3884 break;
3885 case WM_EMACS_CREATEWINDOW:
3886 w32_createwindow ((struct frame *) msg.wParam);
3887 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3888 abort ();
3889 break;
3890 case WM_EMACS_SETLOCALE:
3891 SetThreadLocale (msg.wParam);
3892 /* Reply is not expected. */
3893 break;
3894 case WM_EMACS_SETKEYBOARDLAYOUT:
3895 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3896 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3897 result, 0))
3898 abort ();
3899 break;
3900 case WM_EMACS_REGISTER_HOT_KEY:
3901 focus_window = GetFocus ();
3902 if (focus_window != NULL)
3903 RegisterHotKey (focus_window,
3904 HOTKEY_ID (msg.wParam),
3905 HOTKEY_MODIFIERS (msg.wParam),
3906 HOTKEY_VK_CODE (msg.wParam));
3907 /* Reply is not expected. */
3908 break;
3909 case WM_EMACS_UNREGISTER_HOT_KEY:
3910 focus_window = GetFocus ();
3911 if (focus_window != NULL)
3912 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3913 /* Mark item as erased. NB: this code must be
3914 thread-safe. The next line is okay because the cons
3915 cell is never made into garbage and is not relocated by
3916 GC. */
3917 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
3918 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3919 abort ();
3920 break;
3921 case WM_EMACS_TOGGLE_LOCK_KEY:
3923 int vk_code = (int) msg.wParam;
3924 int cur_state = (GetKeyState (vk_code) & 1);
3925 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3927 /* NB: This code must be thread-safe. It is safe to
3928 call NILP because symbols are not relocated by GC,
3929 and pointer here is not touched by GC (so the markbit
3930 can't be set). Numbers are safe because they are
3931 immediate values. */
3932 if (NILP (new_state)
3933 || (NUMBERP (new_state)
3934 && ((XUINT (new_state)) & 1) != cur_state))
3936 one_w32_display_info.faked_key = vk_code;
3938 keybd_event ((BYTE) vk_code,
3939 (BYTE) MapVirtualKey (vk_code, 0),
3940 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3941 keybd_event ((BYTE) vk_code,
3942 (BYTE) MapVirtualKey (vk_code, 0),
3943 KEYEVENTF_EXTENDEDKEY | 0, 0);
3944 keybd_event ((BYTE) vk_code,
3945 (BYTE) MapVirtualKey (vk_code, 0),
3946 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3947 cur_state = !cur_state;
3949 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3950 cur_state, 0))
3951 abort ();
3953 break;
3954 default:
3955 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3958 else
3960 DispatchMessage (&msg);
3963 /* Exit nested loop when our deferred message has completed. */
3964 if (msg_buf->completed)
3965 break;
3969 deferred_msg * deferred_msg_head;
3971 static deferred_msg *
3972 find_deferred_msg (HWND hwnd, UINT msg)
3974 deferred_msg * item;
3976 /* Don't actually need synchronization for read access, since
3977 modification of single pointer is always atomic. */
3978 /* enter_crit (); */
3980 for (item = deferred_msg_head; item != NULL; item = item->next)
3981 if (item->w32msg.msg.hwnd == hwnd
3982 && item->w32msg.msg.message == msg)
3983 break;
3985 /* leave_crit (); */
3987 return item;
3990 static LRESULT
3991 send_deferred_msg (deferred_msg * msg_buf,
3992 HWND hwnd,
3993 UINT msg,
3994 WPARAM wParam,
3995 LPARAM lParam)
3997 /* Only input thread can send deferred messages. */
3998 if (GetCurrentThreadId () != dwWindowsThreadId)
3999 abort ();
4001 /* It is an error to send a message that is already deferred. */
4002 if (find_deferred_msg (hwnd, msg) != NULL)
4003 abort ();
4005 /* Enforced synchronization is not needed because this is the only
4006 function that alters deferred_msg_head, and the following critical
4007 section is guaranteed to only be serially reentered (since only the
4008 input thread can call us). */
4010 /* enter_crit (); */
4012 msg_buf->completed = 0;
4013 msg_buf->next = deferred_msg_head;
4014 deferred_msg_head = msg_buf;
4015 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
4017 /* leave_crit (); */
4019 /* Start a new nested message loop to process other messages until
4020 this one is completed. */
4021 w32_msg_pump (msg_buf);
4023 deferred_msg_head = msg_buf->next;
4025 return msg_buf->result;
4028 void
4029 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
4031 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
4033 if (msg_buf == NULL)
4034 /* Message may have been cancelled, so don't abort(). */
4035 return;
4037 msg_buf->result = result;
4038 msg_buf->completed = 1;
4040 /* Ensure input thread is woken so it notices the completion. */
4041 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4044 void
4045 cancel_all_deferred_msgs ()
4047 deferred_msg * item;
4049 /* Don't actually need synchronization for read access, since
4050 modification of single pointer is always atomic. */
4051 /* enter_crit (); */
4053 for (item = deferred_msg_head; item != NULL; item = item->next)
4055 item->result = 0;
4056 item->completed = 1;
4059 /* leave_crit (); */
4061 /* Ensure input thread is woken so it notices the completion. */
4062 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4065 DWORD
4066 w32_msg_worker (dw)
4067 DWORD dw;
4069 MSG msg;
4070 deferred_msg dummy_buf;
4072 /* Ensure our message queue is created */
4074 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
4076 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
4077 abort ();
4079 memset (&dummy_buf, 0, sizeof (dummy_buf));
4080 dummy_buf.w32msg.msg.hwnd = NULL;
4081 dummy_buf.w32msg.msg.message = WM_NULL;
4083 /* This is the inital message loop which should only exit when the
4084 application quits. */
4085 w32_msg_pump (&dummy_buf);
4087 return 0;
4090 static void
4091 post_character_message (hwnd, msg, wParam, lParam, modifiers)
4092 HWND hwnd;
4093 UINT msg;
4094 WPARAM wParam;
4095 LPARAM lParam;
4096 DWORD modifiers;
4099 W32Msg wmsg;
4101 wmsg.dwModifiers = modifiers;
4103 /* Detect quit_char and set quit-flag directly. Note that we
4104 still need to post a message to ensure the main thread will be
4105 woken up if blocked in sys_select(), but we do NOT want to post
4106 the quit_char message itself (because it will usually be as if
4107 the user had typed quit_char twice). Instead, we post a dummy
4108 message that has no particular effect. */
4110 int c = wParam;
4111 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
4112 c = make_ctrl_char (c) & 0377;
4113 if (c == quit_char
4114 || (wmsg.dwModifiers == 0 &&
4115 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
4117 Vquit_flag = Qt;
4119 /* The choice of message is somewhat arbitrary, as long as
4120 the main thread handler just ignores it. */
4121 msg = WM_NULL;
4123 /* Interrupt any blocking system calls. */
4124 signal_quit ();
4126 /* As a safety precaution, forcibly complete any deferred
4127 messages. This is a kludge, but I don't see any particularly
4128 clean way to handle the situation where a deferred message is
4129 "dropped" in the lisp thread, and will thus never be
4130 completed, eg. by the user trying to activate the menubar
4131 when the lisp thread is busy, and then typing C-g when the
4132 menubar doesn't open promptly (with the result that the
4133 menubar never responds at all because the deferred
4134 WM_INITMENU message is never completed). Another problem
4135 situation is when the lisp thread calls SendMessage (to send
4136 a window manager command) when a message has been deferred;
4137 the lisp thread gets blocked indefinitely waiting for the
4138 deferred message to be completed, which itself is waiting for
4139 the lisp thread to respond.
4141 Note that we don't want to block the input thread waiting for
4142 a reponse from the lisp thread (although that would at least
4143 solve the deadlock problem above), because we want to be able
4144 to receive C-g to interrupt the lisp thread. */
4145 cancel_all_deferred_msgs ();
4149 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4152 /* Main window procedure */
4154 LRESULT CALLBACK
4155 w32_wnd_proc (hwnd, msg, wParam, lParam)
4156 HWND hwnd;
4157 UINT msg;
4158 WPARAM wParam;
4159 LPARAM lParam;
4161 struct frame *f;
4162 struct w32_display_info *dpyinfo = &one_w32_display_info;
4163 W32Msg wmsg;
4164 int windows_translate;
4165 int key;
4167 /* Note that it is okay to call x_window_to_frame, even though we are
4168 not running in the main lisp thread, because frame deletion
4169 requires the lisp thread to synchronize with this thread. Thus, if
4170 a frame struct is returned, it can be used without concern that the
4171 lisp thread might make it disappear while we are using it.
4173 NB. Walking the frame list in this thread is safe (as long as
4174 writes of Lisp_Object slots are atomic, which they are on Windows).
4175 Although delete-frame can destructively modify the frame list while
4176 we are walking it, a garbage collection cannot occur until after
4177 delete-frame has synchronized with this thread.
4179 It is also safe to use functions that make GDI calls, such as
4180 w32_clear_rect, because these functions must obtain a DC handle
4181 from the frame struct using get_frame_dc which is thread-aware. */
4183 switch (msg)
4185 case WM_ERASEBKGND:
4186 f = x_window_to_frame (dpyinfo, hwnd);
4187 if (f)
4189 HDC hdc = get_frame_dc (f);
4190 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4191 w32_clear_rect (f, hdc, &wmsg.rect);
4192 release_frame_dc (f, hdc);
4194 #if defined (W32_DEBUG_DISPLAY)
4195 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
4197 wmsg.rect.left, wmsg.rect.top,
4198 wmsg.rect.right, wmsg.rect.bottom));
4199 #endif /* W32_DEBUG_DISPLAY */
4201 return 1;
4202 case WM_PALETTECHANGED:
4203 /* ignore our own changes */
4204 if ((HWND)wParam != hwnd)
4206 f = x_window_to_frame (dpyinfo, hwnd);
4207 if (f)
4208 /* get_frame_dc will realize our palette and force all
4209 frames to be redrawn if needed. */
4210 release_frame_dc (f, get_frame_dc (f));
4212 return 0;
4213 case WM_PAINT:
4215 PAINTSTRUCT paintStruct;
4216 RECT update_rect;
4217 bzero (&update_rect, sizeof (update_rect));
4219 f = x_window_to_frame (dpyinfo, hwnd);
4220 if (f == 0)
4222 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
4223 return 0;
4226 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4227 fails. Apparently this can happen under some
4228 circumstances. */
4229 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
4231 enter_crit ();
4232 BeginPaint (hwnd, &paintStruct);
4234 /* The rectangles returned by GetUpdateRect and BeginPaint
4235 do not always match. Play it safe by assuming both areas
4236 are invalid. */
4237 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
4239 #if defined (W32_DEBUG_DISPLAY)
4240 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
4242 wmsg.rect.left, wmsg.rect.top,
4243 wmsg.rect.right, wmsg.rect.bottom));
4244 DebPrint ((" [update region is %d,%d-%d,%d]\n",
4245 update_rect.left, update_rect.top,
4246 update_rect.right, update_rect.bottom));
4247 #endif
4248 EndPaint (hwnd, &paintStruct);
4249 leave_crit ();
4251 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4253 return 0;
4256 /* If GetUpdateRect returns 0 (meaning there is no update
4257 region), assume the whole window needs to be repainted. */
4258 GetClientRect(hwnd, &wmsg.rect);
4259 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4260 return 0;
4263 case WM_INPUTLANGCHANGE:
4264 /* Inform lisp thread of keyboard layout changes. */
4265 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4267 /* Clear dead keys in the keyboard state; for simplicity only
4268 preserve modifier key states. */
4270 int i;
4271 BYTE keystate[256];
4273 GetKeyboardState (keystate);
4274 for (i = 0; i < 256; i++)
4275 if (1
4276 && i != VK_SHIFT
4277 && i != VK_LSHIFT
4278 && i != VK_RSHIFT
4279 && i != VK_CAPITAL
4280 && i != VK_NUMLOCK
4281 && i != VK_SCROLL
4282 && i != VK_CONTROL
4283 && i != VK_LCONTROL
4284 && i != VK_RCONTROL
4285 && i != VK_MENU
4286 && i != VK_LMENU
4287 && i != VK_RMENU
4288 && i != VK_LWIN
4289 && i != VK_RWIN)
4290 keystate[i] = 0;
4291 SetKeyboardState (keystate);
4293 goto dflt;
4295 case WM_HOTKEY:
4296 /* Synchronize hot keys with normal input. */
4297 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4298 return (0);
4300 case WM_KEYUP:
4301 case WM_SYSKEYUP:
4302 record_keyup (wParam, lParam);
4303 goto dflt;
4305 case WM_KEYDOWN:
4306 case WM_SYSKEYDOWN:
4307 /* Ignore keystrokes we fake ourself; see below. */
4308 if (dpyinfo->faked_key == wParam)
4310 dpyinfo->faked_key = 0;
4311 /* Make sure TranslateMessage sees them though (as long as
4312 they don't produce WM_CHAR messages). This ensures that
4313 indicator lights are toggled promptly on Windows 9x, for
4314 example. */
4315 if (lispy_function_keys[wParam] != 0)
4317 windows_translate = 1;
4318 goto translate;
4320 return 0;
4323 /* Synchronize modifiers with current keystroke. */
4324 sync_modifiers ();
4325 record_keydown (wParam, lParam);
4326 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4328 windows_translate = 0;
4330 switch (wParam)
4332 case VK_LWIN:
4333 if (NILP (Vw32_pass_lwindow_to_system))
4335 /* Prevent system from acting on keyup (which opens the
4336 Start menu if no other key was pressed) by simulating a
4337 press of Space which we will ignore. */
4338 if (GetAsyncKeyState (wParam) & 1)
4340 if (NUMBERP (Vw32_phantom_key_code))
4341 key = XUINT (Vw32_phantom_key_code) & 255;
4342 else
4343 key = VK_SPACE;
4344 dpyinfo->faked_key = key;
4345 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4348 if (!NILP (Vw32_lwindow_modifier))
4349 return 0;
4350 break;
4351 case VK_RWIN:
4352 if (NILP (Vw32_pass_rwindow_to_system))
4354 if (GetAsyncKeyState (wParam) & 1)
4356 if (NUMBERP (Vw32_phantom_key_code))
4357 key = XUINT (Vw32_phantom_key_code) & 255;
4358 else
4359 key = VK_SPACE;
4360 dpyinfo->faked_key = key;
4361 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4364 if (!NILP (Vw32_rwindow_modifier))
4365 return 0;
4366 break;
4367 case VK_APPS:
4368 if (!NILP (Vw32_apps_modifier))
4369 return 0;
4370 break;
4371 case VK_MENU:
4372 if (NILP (Vw32_pass_alt_to_system))
4373 /* Prevent DefWindowProc from activating the menu bar if an
4374 Alt key is pressed and released by itself. */
4375 return 0;
4376 windows_translate = 1;
4377 break;
4378 case VK_CAPITAL:
4379 /* Decide whether to treat as modifier or function key. */
4380 if (NILP (Vw32_enable_caps_lock))
4381 goto disable_lock_key;
4382 windows_translate = 1;
4383 break;
4384 case VK_NUMLOCK:
4385 /* Decide whether to treat as modifier or function key. */
4386 if (NILP (Vw32_enable_num_lock))
4387 goto disable_lock_key;
4388 windows_translate = 1;
4389 break;
4390 case VK_SCROLL:
4391 /* Decide whether to treat as modifier or function key. */
4392 if (NILP (Vw32_scroll_lock_modifier))
4393 goto disable_lock_key;
4394 windows_translate = 1;
4395 break;
4396 disable_lock_key:
4397 /* Ensure the appropriate lock key state (and indicator light)
4398 remains in the same state. We do this by faking another
4399 press of the relevant key. Apparently, this really is the
4400 only way to toggle the state of the indicator lights. */
4401 dpyinfo->faked_key = wParam;
4402 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4403 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4404 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4405 KEYEVENTF_EXTENDEDKEY | 0, 0);
4406 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4407 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4408 /* Ensure indicator lights are updated promptly on Windows 9x
4409 (TranslateMessage apparently does this), after forwarding
4410 input event. */
4411 post_character_message (hwnd, msg, wParam, lParam,
4412 w32_get_key_modifiers (wParam, lParam));
4413 windows_translate = 1;
4414 break;
4415 case VK_CONTROL:
4416 case VK_SHIFT:
4417 case VK_PROCESSKEY: /* Generated by IME. */
4418 windows_translate = 1;
4419 break;
4420 case VK_CANCEL:
4421 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4422 which is confusing for purposes of key binding; convert
4423 VK_CANCEL events into VK_PAUSE events. */
4424 wParam = VK_PAUSE;
4425 break;
4426 case VK_PAUSE:
4427 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4428 for purposes of key binding; convert these back into
4429 VK_NUMLOCK events, at least when we want to see NumLock key
4430 presses. (Note that there is never any possibility that
4431 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4432 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4433 wParam = VK_NUMLOCK;
4434 break;
4435 default:
4436 /* If not defined as a function key, change it to a WM_CHAR message. */
4437 if (lispy_function_keys[wParam] == 0)
4439 DWORD modifiers = construct_console_modifiers ();
4441 if (!NILP (Vw32_recognize_altgr)
4442 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4444 /* Always let TranslateMessage handle AltGr key chords;
4445 for some reason, ToAscii doesn't always process AltGr
4446 chords correctly. */
4447 windows_translate = 1;
4449 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4451 /* Handle key chords including any modifiers other
4452 than shift directly, in order to preserve as much
4453 modifier information as possible. */
4454 if ('A' <= wParam && wParam <= 'Z')
4456 /* Don't translate modified alphabetic keystrokes,
4457 so the user doesn't need to constantly switch
4458 layout to type control or meta keystrokes when
4459 the normal layout translates alphabetic
4460 characters to non-ascii characters. */
4461 if (!modifier_set (VK_SHIFT))
4462 wParam += ('a' - 'A');
4463 msg = WM_CHAR;
4465 else
4467 /* Try to handle other keystrokes by determining the
4468 base character (ie. translating the base key plus
4469 shift modifier). */
4470 int add;
4471 int isdead = 0;
4472 KEY_EVENT_RECORD key;
4474 key.bKeyDown = TRUE;
4475 key.wRepeatCount = 1;
4476 key.wVirtualKeyCode = wParam;
4477 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4478 key.uChar.AsciiChar = 0;
4479 key.dwControlKeyState = modifiers;
4481 add = w32_kbd_patch_key (&key);
4482 /* 0 means an unrecognised keycode, negative means
4483 dead key. Ignore both. */
4484 while (--add >= 0)
4486 /* Forward asciified character sequence. */
4487 post_character_message
4488 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4489 w32_get_key_modifiers (wParam, lParam));
4490 w32_kbd_patch_key (&key);
4492 return 0;
4495 else
4497 /* Let TranslateMessage handle everything else. */
4498 windows_translate = 1;
4503 translate:
4504 if (windows_translate)
4506 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4508 windows_msg.time = GetMessageTime ();
4509 TranslateMessage (&windows_msg);
4510 goto dflt;
4513 /* Fall through */
4515 case WM_SYSCHAR:
4516 case WM_CHAR:
4517 post_character_message (hwnd, msg, wParam, lParam,
4518 w32_get_key_modifiers (wParam, lParam));
4519 break;
4521 /* Simulate middle mouse button events when left and right buttons
4522 are used together, but only if user has two button mouse. */
4523 case WM_LBUTTONDOWN:
4524 case WM_RBUTTONDOWN:
4525 if (XINT (Vw32_num_mouse_buttons) > 2)
4526 goto handle_plain_button;
4529 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4530 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4532 if (button_state & this)
4533 return 0;
4535 if (button_state == 0)
4536 SetCapture (hwnd);
4538 button_state |= this;
4540 if (button_state & other)
4542 if (mouse_button_timer)
4544 KillTimer (hwnd, mouse_button_timer);
4545 mouse_button_timer = 0;
4547 /* Generate middle mouse event instead. */
4548 msg = WM_MBUTTONDOWN;
4549 button_state |= MMOUSE;
4551 else if (button_state & MMOUSE)
4553 /* Ignore button event if we've already generated a
4554 middle mouse down event. This happens if the
4555 user releases and press one of the two buttons
4556 after we've faked a middle mouse event. */
4557 return 0;
4559 else
4561 /* Flush out saved message. */
4562 post_msg (&saved_mouse_button_msg);
4564 wmsg.dwModifiers = w32_get_modifiers ();
4565 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4567 /* Clear message buffer. */
4568 saved_mouse_button_msg.msg.hwnd = 0;
4570 else
4572 /* Hold onto message for now. */
4573 mouse_button_timer =
4574 SetTimer (hwnd, MOUSE_BUTTON_ID,
4575 XINT (Vw32_mouse_button_tolerance), NULL);
4576 saved_mouse_button_msg.msg.hwnd = hwnd;
4577 saved_mouse_button_msg.msg.message = msg;
4578 saved_mouse_button_msg.msg.wParam = wParam;
4579 saved_mouse_button_msg.msg.lParam = lParam;
4580 saved_mouse_button_msg.msg.time = GetMessageTime ();
4581 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4584 return 0;
4586 case WM_LBUTTONUP:
4587 case WM_RBUTTONUP:
4588 if (XINT (Vw32_num_mouse_buttons) > 2)
4589 goto handle_plain_button;
4592 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4593 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4595 if ((button_state & this) == 0)
4596 return 0;
4598 button_state &= ~this;
4600 if (button_state & MMOUSE)
4602 /* Only generate event when second button is released. */
4603 if ((button_state & other) == 0)
4605 msg = WM_MBUTTONUP;
4606 button_state &= ~MMOUSE;
4608 if (button_state) abort ();
4610 else
4611 return 0;
4613 else
4615 /* Flush out saved message if necessary. */
4616 if (saved_mouse_button_msg.msg.hwnd)
4618 post_msg (&saved_mouse_button_msg);
4621 wmsg.dwModifiers = w32_get_modifiers ();
4622 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4624 /* Always clear message buffer and cancel timer. */
4625 saved_mouse_button_msg.msg.hwnd = 0;
4626 KillTimer (hwnd, mouse_button_timer);
4627 mouse_button_timer = 0;
4629 if (button_state == 0)
4630 ReleaseCapture ();
4632 return 0;
4634 case WM_XBUTTONDOWN:
4635 case WM_XBUTTONUP:
4636 if (w32_pass_extra_mouse_buttons_to_system)
4637 goto dflt;
4638 /* else fall through and process them. */
4639 case WM_MBUTTONDOWN:
4640 case WM_MBUTTONUP:
4641 handle_plain_button:
4643 BOOL up;
4644 int button;
4646 if (parse_button (msg, HIWORD (wParam), &button, &up))
4648 if (up) ReleaseCapture ();
4649 else SetCapture (hwnd);
4650 button = (button == 0) ? LMOUSE :
4651 ((button == 1) ? MMOUSE : RMOUSE);
4652 if (up)
4653 button_state &= ~button;
4654 else
4655 button_state |= button;
4659 wmsg.dwModifiers = w32_get_modifiers ();
4660 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4662 /* Need to return true for XBUTTON messages, false for others,
4663 to indicate that we processed the message. */
4664 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4666 case WM_MOUSEMOVE:
4667 /* If the mouse has just moved into the frame, start tracking
4668 it, so we will be notified when it leaves the frame. Mouse
4669 tracking only works under W98 and NT4 and later. On earlier
4670 versions, there is no way of telling when the mouse leaves the
4671 frame, so we just have to put up with help-echo and mouse
4672 highlighting remaining while the frame is not active. */
4673 if (track_mouse_event_fn && !track_mouse_window)
4675 TRACKMOUSEEVENT tme;
4676 tme.cbSize = sizeof (tme);
4677 tme.dwFlags = TME_LEAVE;
4678 tme.hwndTrack = hwnd;
4680 track_mouse_event_fn (&tme);
4681 track_mouse_window = hwnd;
4683 case WM_VSCROLL:
4684 if (XINT (Vw32_mouse_move_interval) <= 0
4685 || (msg == WM_MOUSEMOVE && button_state == 0))
4687 wmsg.dwModifiers = w32_get_modifiers ();
4688 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4689 return 0;
4692 /* Hang onto mouse move and scroll messages for a bit, to avoid
4693 sending such events to Emacs faster than it can process them.
4694 If we get more events before the timer from the first message
4695 expires, we just replace the first message. */
4697 if (saved_mouse_move_msg.msg.hwnd == 0)
4698 mouse_move_timer =
4699 SetTimer (hwnd, MOUSE_MOVE_ID,
4700 XINT (Vw32_mouse_move_interval), NULL);
4702 /* Hold onto message for now. */
4703 saved_mouse_move_msg.msg.hwnd = hwnd;
4704 saved_mouse_move_msg.msg.message = msg;
4705 saved_mouse_move_msg.msg.wParam = wParam;
4706 saved_mouse_move_msg.msg.lParam = lParam;
4707 saved_mouse_move_msg.msg.time = GetMessageTime ();
4708 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4710 return 0;
4712 case WM_MOUSEWHEEL:
4713 wmsg.dwModifiers = w32_get_modifiers ();
4714 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4715 return 0;
4717 case WM_DROPFILES:
4718 wmsg.dwModifiers = w32_get_modifiers ();
4719 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4720 return 0;
4722 case WM_TIMER:
4723 /* Flush out saved messages if necessary. */
4724 if (wParam == mouse_button_timer)
4726 if (saved_mouse_button_msg.msg.hwnd)
4728 post_msg (&saved_mouse_button_msg);
4729 saved_mouse_button_msg.msg.hwnd = 0;
4731 KillTimer (hwnd, mouse_button_timer);
4732 mouse_button_timer = 0;
4734 else if (wParam == mouse_move_timer)
4736 if (saved_mouse_move_msg.msg.hwnd)
4738 post_msg (&saved_mouse_move_msg);
4739 saved_mouse_move_msg.msg.hwnd = 0;
4741 KillTimer (hwnd, mouse_move_timer);
4742 mouse_move_timer = 0;
4744 else if (wParam == menu_free_timer)
4746 KillTimer (hwnd, menu_free_timer);
4747 menu_free_timer = 0;
4748 f = x_window_to_frame (dpyinfo, hwnd);
4749 if (!f->output_data.w32->menu_command_in_progress)
4751 /* Free memory used by owner-drawn and help-echo strings. */
4752 w32_free_menu_strings (hwnd);
4753 f->output_data.w32->menubar_active = 0;
4756 return 0;
4758 case WM_NCACTIVATE:
4759 /* Windows doesn't send us focus messages when putting up and
4760 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4761 The only indication we get that something happened is receiving
4762 this message afterwards. So this is a good time to reset our
4763 keyboard modifiers' state. */
4764 reset_modifiers ();
4765 goto dflt;
4767 case WM_INITMENU:
4768 button_state = 0;
4769 ReleaseCapture ();
4770 /* We must ensure menu bar is fully constructed and up to date
4771 before allowing user interaction with it. To achieve this
4772 we send this message to the lisp thread and wait for a
4773 reply (whose value is not actually needed) to indicate that
4774 the menu bar is now ready for use, so we can now return.
4776 To remain responsive in the meantime, we enter a nested message
4777 loop that can process all other messages.
4779 However, we skip all this if the message results from calling
4780 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4781 thread a message because it is blocked on us at this point. We
4782 set menubar_active before calling TrackPopupMenu to indicate
4783 this (there is no possibility of confusion with real menubar
4784 being active). */
4786 f = x_window_to_frame (dpyinfo, hwnd);
4787 if (f
4788 && (f->output_data.w32->menubar_active
4789 /* We can receive this message even in the absence of a
4790 menubar (ie. when the system menu is activated) - in this
4791 case we do NOT want to forward the message, otherwise it
4792 will cause the menubar to suddenly appear when the user
4793 had requested it to be turned off! */
4794 || f->output_data.w32->menubar_widget == NULL))
4795 return 0;
4798 deferred_msg msg_buf;
4800 /* Detect if message has already been deferred; in this case
4801 we cannot return any sensible value to ignore this. */
4802 if (find_deferred_msg (hwnd, msg) != NULL)
4803 abort ();
4805 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4808 case WM_EXITMENULOOP:
4809 f = x_window_to_frame (dpyinfo, hwnd);
4811 /* If a menu command is not already in progress, check again
4812 after a short delay, since Windows often (always?) sends the
4813 WM_EXITMENULOOP before the corresponding WM_COMMAND message. */
4814 if (f && !f->output_data.w32->menu_command_in_progress)
4815 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4816 goto dflt;
4818 case WM_MENUSELECT:
4819 /* Direct handling of help_echo in menus. Should be safe now
4820 that we generate the help_echo by placing a help event in the
4821 keyboard buffer. */
4823 HMENU menu = (HMENU) lParam;
4824 UINT menu_item = (UINT) LOWORD (wParam);
4825 UINT flags = (UINT) HIWORD (wParam);
4827 w32_menu_display_help (hwnd, menu, menu_item, flags);
4829 return 0;
4831 case WM_MEASUREITEM:
4832 f = x_window_to_frame (dpyinfo, hwnd);
4833 if (f)
4835 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4837 if (pMis->CtlType == ODT_MENU)
4839 /* Work out dimensions for popup menu titles. */
4840 char * title = (char *) pMis->itemData;
4841 HDC hdc = GetDC (hwnd);
4842 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4843 LOGFONT menu_logfont;
4844 HFONT old_font;
4845 SIZE size;
4847 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4848 menu_logfont.lfWeight = FW_BOLD;
4849 menu_font = CreateFontIndirect (&menu_logfont);
4850 old_font = SelectObject (hdc, menu_font);
4852 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4853 if (title)
4855 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4856 pMis->itemWidth = size.cx;
4857 if (pMis->itemHeight < size.cy)
4858 pMis->itemHeight = size.cy;
4860 else
4861 pMis->itemWidth = 0;
4863 SelectObject (hdc, old_font);
4864 DeleteObject (menu_font);
4865 ReleaseDC (hwnd, hdc);
4866 return TRUE;
4869 return 0;
4871 case WM_DRAWITEM:
4872 f = x_window_to_frame (dpyinfo, hwnd);
4873 if (f)
4875 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4877 if (pDis->CtlType == ODT_MENU)
4879 /* Draw popup menu title. */
4880 char * title = (char *) pDis->itemData;
4881 if (title)
4883 HDC hdc = pDis->hDC;
4884 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4885 LOGFONT menu_logfont;
4886 HFONT old_font;
4888 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4889 menu_logfont.lfWeight = FW_BOLD;
4890 menu_font = CreateFontIndirect (&menu_logfont);
4891 old_font = SelectObject (hdc, menu_font);
4893 /* Always draw title as if not selected. */
4894 ExtTextOut (hdc,
4895 pDis->rcItem.left
4896 + GetSystemMetrics (SM_CXMENUCHECK),
4897 pDis->rcItem.top,
4898 ETO_OPAQUE, &pDis->rcItem,
4899 title, strlen (title), NULL);
4901 SelectObject (hdc, old_font);
4902 DeleteObject (menu_font);
4904 return TRUE;
4907 return 0;
4909 #if 0
4910 /* Still not right - can't distinguish between clicks in the
4911 client area of the frame from clicks forwarded from the scroll
4912 bars - may have to hook WM_NCHITTEST to remember the mouse
4913 position and then check if it is in the client area ourselves. */
4914 case WM_MOUSEACTIVATE:
4915 /* Discard the mouse click that activates a frame, allowing the
4916 user to click anywhere without changing point (or worse!).
4917 Don't eat mouse clicks on scrollbars though!! */
4918 if (LOWORD (lParam) == HTCLIENT )
4919 return MA_ACTIVATEANDEAT;
4920 goto dflt;
4921 #endif
4923 case WM_MOUSELEAVE:
4924 /* No longer tracking mouse. */
4925 track_mouse_window = NULL;
4927 case WM_ACTIVATEAPP:
4928 case WM_ACTIVATE:
4929 case WM_WINDOWPOSCHANGED:
4930 case WM_SHOWWINDOW:
4931 /* Inform lisp thread that a frame might have just been obscured
4932 or exposed, so should recheck visibility of all frames. */
4933 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4934 goto dflt;
4936 case WM_SETFOCUS:
4938 Reinitialize the function pointer track_mouse_event_fn here.
4939 This is required even though it is initialized in syms_of_w32fns
4940 which is called in main (emacs.c).
4941 Reinitialize the function pointer track_mouse_event_fn here.
4942 Even though this function pointer is initialized in
4943 syms_of_w32fns which is called from main (emacs.c),
4944 we need to initialize it again here in order to prevent
4945 a crash that occurs in Windows 9x (possibly only when Emacs
4946 was built on Windows NT / 2000 / XP?) when handling the
4947 WM_MOUSEMOVE message.
4948 The crash occurs when attempting to call the Win32 API
4949 function TrackMouseEvent through the function pointer.
4950 It appears as if the function pointer that is obtained when
4951 syms_of_w32fns is called from main is no longer valid
4952 (possibly due to DLL relocation?).
4953 To resolve this issue, I have placed a call to reinitialize
4954 this function pointer here because this message gets received
4955 when the Emacs window gains focus.
4957 track_mouse_event_fn =
4958 (TrackMouseEvent_Proc) GetProcAddress (
4959 GetModuleHandle ("user32.dll"),
4960 "TrackMouseEvent");
4961 dpyinfo->faked_key = 0;
4962 reset_modifiers ();
4963 register_hot_keys (hwnd);
4964 goto command;
4965 case WM_KILLFOCUS:
4966 unregister_hot_keys (hwnd);
4967 button_state = 0;
4968 ReleaseCapture ();
4969 /* Relinquish the system caret. */
4970 if (w32_system_caret_hwnd)
4972 w32_visible_system_caret_hwnd = NULL;
4973 w32_system_caret_hwnd = NULL;
4974 DestroyCaret ();
4976 goto command;
4977 case WM_COMMAND:
4978 f = x_window_to_frame (dpyinfo, hwnd);
4979 if (f && HIWORD (wParam) == 0)
4981 f->output_data.w32->menu_command_in_progress = 1;
4982 if (menu_free_timer)
4984 KillTimer (hwnd, menu_free_timer);
4985 menu_free_timer = 0;
4988 case WM_MOVE:
4989 case WM_SIZE:
4990 command:
4991 wmsg.dwModifiers = w32_get_modifiers ();
4992 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4993 goto dflt;
4995 case WM_CLOSE:
4996 wmsg.dwModifiers = w32_get_modifiers ();
4997 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4998 return 0;
5000 case WM_WINDOWPOSCHANGING:
5001 /* Don't restrict the sizing of tip frames. */
5002 if (hwnd == tip_window)
5003 return 0;
5005 WINDOWPLACEMENT wp;
5006 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
5008 wp.length = sizeof (WINDOWPLACEMENT);
5009 GetWindowPlacement (hwnd, &wp);
5011 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
5013 RECT rect;
5014 int wdiff;
5015 int hdiff;
5016 DWORD font_width;
5017 DWORD line_height;
5018 DWORD internal_border;
5019 DWORD scrollbar_extra;
5020 RECT wr;
5022 wp.length = sizeof(wp);
5023 GetWindowRect (hwnd, &wr);
5025 enter_crit ();
5027 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
5028 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
5029 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
5030 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
5032 leave_crit ();
5034 memset (&rect, 0, sizeof (rect));
5035 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
5036 GetMenu (hwnd) != NULL);
5038 /* Force width and height of client area to be exact
5039 multiples of the character cell dimensions. */
5040 wdiff = (lppos->cx - (rect.right - rect.left)
5041 - 2 * internal_border - scrollbar_extra)
5042 % font_width;
5043 hdiff = (lppos->cy - (rect.bottom - rect.top)
5044 - 2 * internal_border)
5045 % line_height;
5047 if (wdiff || hdiff)
5049 /* For right/bottom sizing we can just fix the sizes.
5050 However for top/left sizing we will need to fix the X
5051 and Y positions as well. */
5053 lppos->cx -= wdiff;
5054 lppos->cy -= hdiff;
5056 if (wp.showCmd != SW_SHOWMAXIMIZED
5057 && (lppos->flags & SWP_NOMOVE) == 0)
5059 if (lppos->x != wr.left || lppos->y != wr.top)
5061 lppos->x += wdiff;
5062 lppos->y += hdiff;
5064 else
5066 lppos->flags |= SWP_NOMOVE;
5070 return 0;
5075 goto dflt;
5077 case WM_GETMINMAXINFO:
5078 /* Hack to correct bug that allows Emacs frames to be resized
5079 below the Minimum Tracking Size. */
5080 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
5081 /* Hack to allow resizing the Emacs frame above the screen size.
5082 Note that Windows 9x limits coordinates to 16-bits. */
5083 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
5084 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
5085 return 0;
5087 case WM_EMACS_CREATESCROLLBAR:
5088 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
5089 (struct scroll_bar *) lParam);
5091 case WM_EMACS_SHOWWINDOW:
5092 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
5094 case WM_EMACS_SETFOREGROUND:
5096 HWND foreground_window;
5097 DWORD foreground_thread, retval;
5099 /* On NT 5.0, and apparently Windows 98, it is necessary to
5100 attach to the thread that currently has focus in order to
5101 pull the focus away from it. */
5102 foreground_window = GetForegroundWindow ();
5103 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
5104 if (!foreground_window
5105 || foreground_thread == GetCurrentThreadId ()
5106 || !AttachThreadInput (GetCurrentThreadId (),
5107 foreground_thread, TRUE))
5108 foreground_thread = 0;
5110 retval = SetForegroundWindow ((HWND) wParam);
5112 /* Detach from the previous foreground thread. */
5113 if (foreground_thread)
5114 AttachThreadInput (GetCurrentThreadId (),
5115 foreground_thread, FALSE);
5117 return retval;
5120 case WM_EMACS_SETWINDOWPOS:
5122 WINDOWPOS * pos = (WINDOWPOS *) wParam;
5123 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5124 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
5127 case WM_EMACS_DESTROYWINDOW:
5128 DragAcceptFiles ((HWND) wParam, FALSE);
5129 return DestroyWindow ((HWND) wParam);
5131 case WM_EMACS_HIDE_CARET:
5132 return HideCaret (hwnd);
5134 case WM_EMACS_SHOW_CARET:
5135 return ShowCaret (hwnd);
5137 case WM_EMACS_DESTROY_CARET:
5138 w32_system_caret_hwnd = NULL;
5139 w32_visible_system_caret_hwnd = NULL;
5140 return DestroyCaret ();
5142 case WM_EMACS_TRACK_CARET:
5143 /* If there is currently no system caret, create one. */
5144 if (w32_system_caret_hwnd == NULL)
5146 /* Use the default caret width, and avoid changing it
5147 unneccesarily, as it confuses screen reader software. */
5148 w32_system_caret_hwnd = hwnd;
5149 CreateCaret (hwnd, NULL, 0,
5150 w32_system_caret_height);
5153 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
5154 return 0;
5155 /* Ensure visible caret gets turned on when requested. */
5156 else if (w32_use_visible_system_caret
5157 && w32_visible_system_caret_hwnd != hwnd)
5159 w32_visible_system_caret_hwnd = hwnd;
5160 return ShowCaret (hwnd);
5162 /* Ensure visible caret gets turned off when requested. */
5163 else if (!w32_use_visible_system_caret
5164 && w32_visible_system_caret_hwnd)
5166 w32_visible_system_caret_hwnd = NULL;
5167 return HideCaret (hwnd);
5169 else
5170 return 1;
5172 case WM_EMACS_TRACKPOPUPMENU:
5174 UINT flags;
5175 POINT *pos;
5176 int retval;
5177 pos = (POINT *)lParam;
5178 flags = TPM_CENTERALIGN;
5179 if (button_state & LMOUSE)
5180 flags |= TPM_LEFTBUTTON;
5181 else if (button_state & RMOUSE)
5182 flags |= TPM_RIGHTBUTTON;
5184 /* Remember we did a SetCapture on the initial mouse down event,
5185 so for safety, we make sure the capture is cancelled now. */
5186 ReleaseCapture ();
5187 button_state = 0;
5189 /* Use menubar_active to indicate that WM_INITMENU is from
5190 TrackPopupMenu below, and should be ignored. */
5191 f = x_window_to_frame (dpyinfo, hwnd);
5192 if (f)
5193 f->output_data.w32->menubar_active = 1;
5195 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
5196 0, hwnd, NULL))
5198 MSG amsg;
5199 /* Eat any mouse messages during popupmenu */
5200 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
5201 PM_REMOVE));
5202 /* Get the menu selection, if any */
5203 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
5205 retval = LOWORD (amsg.wParam);
5207 else
5209 retval = 0;
5212 else
5214 retval = -1;
5217 return retval;
5220 default:
5221 /* Check for messages registered at runtime. */
5222 if (msg == msh_mousewheel)
5224 wmsg.dwModifiers = w32_get_modifiers ();
5225 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5226 return 0;
5229 dflt:
5230 return DefWindowProc (hwnd, msg, wParam, lParam);
5234 /* The most common default return code for handled messages is 0. */
5235 return 0;
5238 void
5239 my_create_window (f)
5240 struct frame * f;
5242 MSG msg;
5244 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
5245 abort ();
5246 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5250 /* Create a tooltip window. Unlike my_create_window, we do not do this
5251 indirectly via the Window thread, as we do not need to process Window
5252 messages for the tooltip. Creating tooltips indirectly also creates
5253 deadlocks when tooltips are created for menu items. */
5254 void
5255 my_create_tip_window (f)
5256 struct frame *f;
5258 RECT rect;
5260 rect.left = rect.top = 0;
5261 rect.right = PIXEL_WIDTH (f);
5262 rect.bottom = PIXEL_HEIGHT (f);
5264 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
5265 FRAME_EXTERNAL_MENU_BAR (f));
5267 tip_window = FRAME_W32_WINDOW (f)
5268 = CreateWindow (EMACS_CLASS,
5269 f->namebuf,
5270 f->output_data.w32->dwStyle,
5271 f->output_data.w32->left_pos,
5272 f->output_data.w32->top_pos,
5273 rect.right - rect.left,
5274 rect.bottom - rect.top,
5275 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5276 NULL,
5277 hinst,
5278 NULL);
5280 if (tip_window)
5282 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
5283 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
5284 SetWindowLong (tip_window, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
5285 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5287 /* Tip frames have no scrollbars. */
5288 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
5290 /* Do this to discard the default setting specified by our parent. */
5291 ShowWindow (tip_window, SW_HIDE);
5296 /* Create and set up the w32 window for frame F. */
5298 static void
5299 w32_window (f, window_prompting, minibuffer_only)
5300 struct frame *f;
5301 long window_prompting;
5302 int minibuffer_only;
5304 BLOCK_INPUT;
5306 /* Use the resource name as the top-level window name
5307 for looking up resources. Make a non-Lisp copy
5308 for the window manager, so GC relocation won't bother it.
5310 Elsewhere we specify the window name for the window manager. */
5313 char *str = (char *) SDATA (Vx_resource_name);
5314 f->namebuf = (char *) xmalloc (strlen (str) + 1);
5315 strcpy (f->namebuf, str);
5318 my_create_window (f);
5320 validate_x_resource_name ();
5322 /* x_set_name normally ignores requests to set the name if the
5323 requested name is the same as the current name. This is the one
5324 place where that assumption isn't correct; f->name is set, but
5325 the server hasn't been told. */
5327 Lisp_Object name;
5328 int explicit = f->explicit_name;
5330 f->explicit_name = 0;
5331 name = f->name;
5332 f->name = Qnil;
5333 x_set_name (f, name, explicit);
5336 UNBLOCK_INPUT;
5338 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5339 initialize_frame_menubar (f);
5341 if (FRAME_W32_WINDOW (f) == 0)
5342 error ("Unable to create window");
5345 /* Handle the icon stuff for this window. Perhaps later we might
5346 want an x_set_icon_position which can be called interactively as
5347 well. */
5349 static void
5350 x_icon (f, parms)
5351 struct frame *f;
5352 Lisp_Object parms;
5354 Lisp_Object icon_x, icon_y;
5356 /* Set the position of the icon. Note that Windows 95 groups all
5357 icons in the tray. */
5358 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5359 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5360 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5362 CHECK_NUMBER (icon_x);
5363 CHECK_NUMBER (icon_y);
5365 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5366 error ("Both left and top icon corners of icon must be specified");
5368 BLOCK_INPUT;
5370 if (! EQ (icon_x, Qunbound))
5371 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5373 #if 0 /* TODO */
5374 /* Start up iconic or window? */
5375 x_wm_set_window_state
5376 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5377 ? IconicState
5378 : NormalState));
5380 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
5381 ? f->icon_name
5382 : f->name)));
5383 #endif
5385 UNBLOCK_INPUT;
5389 static void
5390 x_make_gc (f)
5391 struct frame *f;
5393 XGCValues gc_values;
5395 BLOCK_INPUT;
5397 /* Create the GC's of this frame.
5398 Note that many default values are used. */
5400 /* Normal video */
5401 gc_values.font = f->output_data.w32->font;
5403 /* Cursor has cursor-color background, background-color foreground. */
5404 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5405 gc_values.background = f->output_data.w32->cursor_pixel;
5406 f->output_data.w32->cursor_gc
5407 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5408 (GCFont | GCForeground | GCBackground),
5409 &gc_values);
5411 /* Reliefs. */
5412 f->output_data.w32->white_relief.gc = 0;
5413 f->output_data.w32->black_relief.gc = 0;
5415 UNBLOCK_INPUT;
5419 /* Handler for signals raised during x_create_frame and
5420 x_create_top_frame. FRAME is the frame which is partially
5421 constructed. */
5423 static Lisp_Object
5424 unwind_create_frame (frame)
5425 Lisp_Object frame;
5427 struct frame *f = XFRAME (frame);
5429 /* If frame is ``official'', nothing to do. */
5430 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
5432 #ifdef GLYPH_DEBUG
5433 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5434 #endif
5436 x_free_frame_resources (f);
5438 /* Check that reference counts are indeed correct. */
5439 xassert (dpyinfo->reference_count == dpyinfo_refcount);
5440 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
5442 return Qt;
5445 return Qnil;
5449 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5450 1, 1, 0,
5451 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5452 Returns an Emacs frame object.
5453 ALIST is an alist of frame parameters.
5454 If the parameters specify that the frame should not have a minibuffer,
5455 and do not specify a specific minibuffer window to use,
5456 then `default-minibuffer-frame' must be a frame whose minibuffer can
5457 be shared by the new frame.
5459 This function is an internal primitive--use `make-frame' instead. */)
5460 (parms)
5461 Lisp_Object parms;
5463 struct frame *f;
5464 Lisp_Object frame, tem;
5465 Lisp_Object name;
5466 int minibuffer_only = 0;
5467 long window_prompting = 0;
5468 int width, height;
5469 int count = SPECPDL_INDEX ();
5470 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5471 Lisp_Object display;
5472 struct w32_display_info *dpyinfo = NULL;
5473 Lisp_Object parent;
5474 struct kboard *kb;
5476 check_w32 ();
5478 /* Use this general default value to start with
5479 until we know if this frame has a specified name. */
5480 Vx_resource_name = Vinvocation_name;
5482 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5483 if (EQ (display, Qunbound))
5484 display = Qnil;
5485 dpyinfo = check_x_display_info (display);
5486 #ifdef MULTI_KBOARD
5487 kb = dpyinfo->kboard;
5488 #else
5489 kb = &the_only_kboard;
5490 #endif
5492 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5493 if (!STRINGP (name)
5494 && ! EQ (name, Qunbound)
5495 && ! NILP (name))
5496 error ("Invalid frame name--not a string or nil");
5498 if (STRINGP (name))
5499 Vx_resource_name = name;
5501 /* See if parent window is specified. */
5502 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5503 if (EQ (parent, Qunbound))
5504 parent = Qnil;
5505 if (! NILP (parent))
5506 CHECK_NUMBER (parent);
5508 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5509 /* No need to protect DISPLAY because that's not used after passing
5510 it to make_frame_without_minibuffer. */
5511 frame = Qnil;
5512 GCPRO4 (parms, parent, name, frame);
5513 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5514 RES_TYPE_SYMBOL);
5515 if (EQ (tem, Qnone) || NILP (tem))
5516 f = make_frame_without_minibuffer (Qnil, kb, display);
5517 else if (EQ (tem, Qonly))
5519 f = make_minibuffer_frame ();
5520 minibuffer_only = 1;
5522 else if (WINDOWP (tem))
5523 f = make_frame_without_minibuffer (tem, kb, display);
5524 else
5525 f = make_frame (1);
5527 XSETFRAME (frame, f);
5529 /* Note that Windows does support scroll bars. */
5530 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5531 /* By default, make scrollbars the system standard width. */
5532 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5534 f->output_method = output_w32;
5535 f->output_data.w32 =
5536 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5537 bzero (f->output_data.w32, sizeof (struct w32_output));
5538 FRAME_FONTSET (f) = -1;
5539 record_unwind_protect (unwind_create_frame, frame);
5541 f->icon_name
5542 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5543 if (! STRINGP (f->icon_name))
5544 f->icon_name = Qnil;
5546 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5547 #ifdef MULTI_KBOARD
5548 FRAME_KBOARD (f) = kb;
5549 #endif
5551 /* Specify the parent under which to make this window. */
5553 if (!NILP (parent))
5555 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5556 f->output_data.w32->explicit_parent = 1;
5558 else
5560 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5561 f->output_data.w32->explicit_parent = 0;
5564 /* Set the name; the functions to which we pass f expect the name to
5565 be set. */
5566 if (EQ (name, Qunbound) || NILP (name))
5568 f->name = build_string (dpyinfo->w32_id_name);
5569 f->explicit_name = 0;
5571 else
5573 f->name = name;
5574 f->explicit_name = 1;
5575 /* use the frame's title when getting resources for this frame. */
5576 specbind (Qx_resource_name, name);
5579 /* Extract the window parameters from the supplied values
5580 that are needed to determine window geometry. */
5582 Lisp_Object font;
5584 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5586 BLOCK_INPUT;
5587 /* First, try whatever font the caller has specified. */
5588 if (STRINGP (font))
5590 tem = Fquery_fontset (font, Qnil);
5591 if (STRINGP (tem))
5592 font = x_new_fontset (f, SDATA (tem));
5593 else
5594 font = x_new_font (f, SDATA (font));
5596 /* Try out a font which we hope has bold and italic variations. */
5597 if (!STRINGP (font))
5598 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5599 if (! STRINGP (font))
5600 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5601 /* If those didn't work, look for something which will at least work. */
5602 if (! STRINGP (font))
5603 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5604 UNBLOCK_INPUT;
5605 if (! STRINGP (font))
5606 font = build_string ("Fixedsys");
5608 x_default_parameter (f, parms, Qfont, font,
5609 "font", "Font", RES_TYPE_STRING);
5612 x_default_parameter (f, parms, Qborder_width, make_number (2),
5613 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5614 /* This defaults to 2 in order to match xterm. We recognize either
5615 internalBorderWidth or internalBorder (which is what xterm calls
5616 it). */
5617 if (NILP (Fassq (Qinternal_border_width, parms)))
5619 Lisp_Object value;
5621 value = w32_get_arg (parms, Qinternal_border_width,
5622 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5623 if (! EQ (value, Qunbound))
5624 parms = Fcons (Fcons (Qinternal_border_width, value),
5625 parms);
5627 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5628 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5629 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5630 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5631 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5633 /* Also do the stuff which must be set before the window exists. */
5634 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5635 "foreground", "Foreground", RES_TYPE_STRING);
5636 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5637 "background", "Background", RES_TYPE_STRING);
5638 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5639 "pointerColor", "Foreground", RES_TYPE_STRING);
5640 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5641 "cursorColor", "Foreground", RES_TYPE_STRING);
5642 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5643 "borderColor", "BorderColor", RES_TYPE_STRING);
5644 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5645 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5646 x_default_parameter (f, parms, Qline_spacing, Qnil,
5647 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5648 x_default_parameter (f, parms, Qleft_fringe, Qnil,
5649 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5650 x_default_parameter (f, parms, Qright_fringe, Qnil,
5651 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5654 /* Init faces before x_default_parameter is called for scroll-bar
5655 parameters because that function calls x_set_scroll_bar_width,
5656 which calls change_frame_size, which calls Fset_window_buffer,
5657 which runs hooks, which call Fvertical_motion. At the end, we
5658 end up in init_iterator with a null face cache, which should not
5659 happen. */
5660 init_frame_faces (f);
5662 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5663 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5664 x_default_parameter (f, parms, Qtool_bar_lines, make_number (1),
5665 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5667 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5668 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5669 x_default_parameter (f, parms, Qtitle, Qnil,
5670 "title", "Title", RES_TYPE_STRING);
5671 x_default_parameter (f, parms, Qfullscreen, Qnil,
5672 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5674 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5675 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5677 /* Add the tool-bar height to the initial frame height so that the
5678 user gets a text display area of the size he specified with -g or
5679 via .Xdefaults. Later changes of the tool-bar height don't
5680 change the frame size. This is done so that users can create
5681 tall Emacs frames without having to guess how tall the tool-bar
5682 will get. */
5683 if (FRAME_TOOL_BAR_LINES (f))
5685 int margin, relief, bar_height;
5687 relief = (tool_bar_button_relief >= 0
5688 ? tool_bar_button_relief
5689 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
5691 if (INTEGERP (Vtool_bar_button_margin)
5692 && XINT (Vtool_bar_button_margin) > 0)
5693 margin = XFASTINT (Vtool_bar_button_margin);
5694 else if (CONSP (Vtool_bar_button_margin)
5695 && INTEGERP (XCDR (Vtool_bar_button_margin))
5696 && XINT (XCDR (Vtool_bar_button_margin)) > 0)
5697 margin = XFASTINT (XCDR (Vtool_bar_button_margin));
5698 else
5699 margin = 0;
5701 bar_height = DEFAULT_TOOL_BAR_IMAGE_HEIGHT + 2 * margin + 2 * relief;
5702 f->height += (bar_height + CANON_Y_UNIT (f) - 1) / CANON_Y_UNIT (f);
5705 window_prompting = x_figure_window_size (f, parms);
5707 if (window_prompting & XNegative)
5709 if (window_prompting & YNegative)
5710 f->output_data.w32->win_gravity = SouthEastGravity;
5711 else
5712 f->output_data.w32->win_gravity = NorthEastGravity;
5714 else
5716 if (window_prompting & YNegative)
5717 f->output_data.w32->win_gravity = SouthWestGravity;
5718 else
5719 f->output_data.w32->win_gravity = NorthWestGravity;
5722 f->output_data.w32->size_hint_flags = window_prompting;
5724 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5725 f->no_split = minibuffer_only || EQ (tem, Qt);
5727 w32_window (f, window_prompting, minibuffer_only);
5728 x_icon (f, parms);
5730 x_make_gc (f);
5732 /* Now consider the frame official. */
5733 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5734 Vframe_list = Fcons (frame, Vframe_list);
5736 /* We need to do this after creating the window, so that the
5737 icon-creation functions can say whose icon they're describing. */
5738 x_default_parameter (f, parms, Qicon_type, Qnil,
5739 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5741 x_default_parameter (f, parms, Qauto_raise, Qnil,
5742 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5743 x_default_parameter (f, parms, Qauto_lower, Qnil,
5744 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5745 x_default_parameter (f, parms, Qcursor_type, Qbox,
5746 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5747 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5748 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5750 /* Dimensions, especially f->height, must be done via change_frame_size.
5751 Change will not be effected unless different from the current
5752 f->height. */
5753 width = f->width;
5754 height = f->height;
5756 f->height = 0;
5757 SET_FRAME_WIDTH (f, 0);
5758 change_frame_size (f, height, width, 1, 0, 0);
5760 /* Tell the server what size and position, etc, we want, and how
5761 badly we want them. This should be done after we have the menu
5762 bar so that its size can be taken into account. */
5763 BLOCK_INPUT;
5764 x_wm_set_size_hint (f, window_prompting, 0);
5765 UNBLOCK_INPUT;
5767 /* Avoid a bug that causes the new frame to never become visible if
5768 an echo area message is displayed during the following call1. */
5769 specbind(Qredisplay_dont_pause, Qt);
5771 /* Set up faces after all frame parameters are known. This call
5772 also merges in face attributes specified for new frames. If we
5773 don't do this, the `menu' face for instance won't have the right
5774 colors, and the menu bar won't appear in the specified colors for
5775 new frames. */
5776 call1 (Qface_set_after_frame_default, frame);
5778 /* Make the window appear on the frame and enable display, unless
5779 the caller says not to. However, with explicit parent, Emacs
5780 cannot control visibility, so don't try. */
5781 if (! f->output_data.w32->explicit_parent)
5783 Lisp_Object visibility;
5785 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5786 if (EQ (visibility, Qunbound))
5787 visibility = Qt;
5789 if (EQ (visibility, Qicon))
5790 x_iconify_frame (f);
5791 else if (! NILP (visibility))
5792 x_make_frame_visible (f);
5793 else
5794 /* Must have been Qnil. */
5797 UNGCPRO;
5799 /* Make sure windows on this frame appear in calls to next-window
5800 and similar functions. */
5801 Vwindow_list = Qnil;
5803 return unbind_to (count, frame);
5806 /* FRAME is used only to get a handle on the X display. We don't pass the
5807 display info directly because we're called from frame.c, which doesn't
5808 know about that structure. */
5809 Lisp_Object
5810 x_get_focus_frame (frame)
5811 struct frame *frame;
5813 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5814 Lisp_Object xfocus;
5815 if (! dpyinfo->w32_focus_frame)
5816 return Qnil;
5818 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5819 return xfocus;
5822 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5823 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
5824 (frame)
5825 Lisp_Object frame;
5827 x_focus_on_frame (check_x_frame (frame));
5828 return Qnil;
5832 /* Return the charset portion of a font name. */
5833 char * xlfd_charset_of_font (char * fontname)
5835 char *charset, *encoding;
5837 encoding = strrchr(fontname, '-');
5838 if (!encoding || encoding == fontname)
5839 return NULL;
5841 for (charset = encoding - 1; charset >= fontname; charset--)
5842 if (*charset == '-')
5843 break;
5845 if (charset == fontname || strcmp(charset, "-*-*") == 0)
5846 return NULL;
5848 return charset + 1;
5851 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5852 int size, char* filename);
5853 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
5854 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
5855 char * charset);
5856 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
5858 static struct font_info *
5859 w32_load_system_font (f,fontname,size)
5860 struct frame *f;
5861 char * fontname;
5862 int size;
5864 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5865 Lisp_Object font_names;
5867 /* Get a list of all the fonts that match this name. Once we
5868 have a list of matching fonts, we compare them against the fonts
5869 we already have loaded by comparing names. */
5870 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5872 if (!NILP (font_names))
5874 Lisp_Object tail;
5875 int i;
5877 /* First check if any are already loaded, as that is cheaper
5878 than loading another one. */
5879 for (i = 0; i < dpyinfo->n_fonts; i++)
5880 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5881 if (dpyinfo->font_table[i].name
5882 && (!strcmp (dpyinfo->font_table[i].name,
5883 SDATA (XCAR (tail)))
5884 || !strcmp (dpyinfo->font_table[i].full_name,
5885 SDATA (XCAR (tail)))))
5886 return (dpyinfo->font_table + i);
5888 fontname = (char *) SDATA (XCAR (font_names));
5890 else if (w32_strict_fontnames)
5892 /* If EnumFontFamiliesEx was available, we got a full list of
5893 fonts back so stop now to avoid the possibility of loading a
5894 random font. If we had to fall back to EnumFontFamilies, the
5895 list is incomplete, so continue whether the font we want was
5896 listed or not. */
5897 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5898 FARPROC enum_font_families_ex
5899 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5900 if (enum_font_families_ex)
5901 return NULL;
5904 /* Load the font and add it to the table. */
5906 char *full_name, *encoding, *charset;
5907 XFontStruct *font;
5908 struct font_info *fontp;
5909 LOGFONT lf;
5910 BOOL ok;
5911 int codepage;
5912 int i;
5914 if (!fontname || !x_to_w32_font (fontname, &lf))
5915 return (NULL);
5917 if (!*lf.lfFaceName)
5918 /* If no name was specified for the font, we get a random font
5919 from CreateFontIndirect - this is not particularly
5920 desirable, especially since CreateFontIndirect does not
5921 fill out the missing name in lf, so we never know what we
5922 ended up with. */
5923 return NULL;
5925 lf.lfQuality = DEFAULT_QUALITY;
5927 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5928 bzero (font, sizeof (*font));
5930 /* Set bdf to NULL to indicate that this is a Windows font. */
5931 font->bdf = NULL;
5933 BLOCK_INPUT;
5935 font->hfont = CreateFontIndirect (&lf);
5937 if (font->hfont == NULL)
5939 ok = FALSE;
5941 else
5943 HDC hdc;
5944 HANDLE oldobj;
5946 codepage = w32_codepage_for_font (fontname);
5948 hdc = GetDC (dpyinfo->root_window);
5949 oldobj = SelectObject (hdc, font->hfont);
5951 ok = GetTextMetrics (hdc, &font->tm);
5952 if (codepage == CP_UNICODE)
5953 font->double_byte_p = 1;
5954 else
5956 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
5957 don't report themselves as double byte fonts, when
5958 patently they are. So instead of trusting
5959 GetFontLanguageInfo, we check the properties of the
5960 codepage directly, since that is ultimately what we are
5961 working from anyway. */
5962 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
5963 CPINFO cpi = {0};
5964 GetCPInfo (codepage, &cpi);
5965 font->double_byte_p = cpi.MaxCharSize > 1;
5968 SelectObject (hdc, oldobj);
5969 ReleaseDC (dpyinfo->root_window, hdc);
5970 /* Fill out details in lf according to the font that was
5971 actually loaded. */
5972 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5973 lf.lfWidth = font->tm.tmAveCharWidth;
5974 lf.lfWeight = font->tm.tmWeight;
5975 lf.lfItalic = font->tm.tmItalic;
5976 lf.lfCharSet = font->tm.tmCharSet;
5977 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5978 ? VARIABLE_PITCH : FIXED_PITCH);
5979 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5980 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5982 w32_cache_char_metrics (font);
5985 UNBLOCK_INPUT;
5987 if (!ok)
5989 w32_unload_font (dpyinfo, font);
5990 return (NULL);
5993 /* Find a free slot in the font table. */
5994 for (i = 0; i < dpyinfo->n_fonts; ++i)
5995 if (dpyinfo->font_table[i].name == NULL)
5996 break;
5998 /* If no free slot found, maybe enlarge the font table. */
5999 if (i == dpyinfo->n_fonts
6000 && dpyinfo->n_fonts == dpyinfo->font_table_size)
6002 int sz;
6003 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
6004 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
6005 dpyinfo->font_table
6006 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
6009 fontp = dpyinfo->font_table + i;
6010 if (i == dpyinfo->n_fonts)
6011 ++dpyinfo->n_fonts;
6013 /* Now fill in the slots of *FONTP. */
6014 BLOCK_INPUT;
6015 fontp->font = font;
6016 fontp->font_idx = i;
6017 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
6018 bcopy (fontname, fontp->name, strlen (fontname) + 1);
6020 charset = xlfd_charset_of_font (fontname);
6022 /* Cache the W32 codepage for a font. This makes w32_encode_char
6023 (called for every glyph during redisplay) much faster. */
6024 fontp->codepage = codepage;
6026 /* Work out the font's full name. */
6027 full_name = (char *)xmalloc (100);
6028 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
6029 fontp->full_name = full_name;
6030 else
6032 /* If all else fails - just use the name we used to load it. */
6033 xfree (full_name);
6034 fontp->full_name = fontp->name;
6037 fontp->size = FONT_WIDTH (font);
6038 fontp->height = FONT_HEIGHT (font);
6040 /* The slot `encoding' specifies how to map a character
6041 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
6042 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
6043 (0:0x20..0x7F, 1:0xA0..0xFF,
6044 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
6045 2:0xA020..0xFF7F). For the moment, we don't know which charset
6046 uses this font. So, we set information in fontp->encoding[1]
6047 which is never used by any charset. If mapping can't be
6048 decided, set FONT_ENCODING_NOT_DECIDED. */
6050 /* SJIS fonts need to be set to type 4, all others seem to work as
6051 type FONT_ENCODING_NOT_DECIDED. */
6052 encoding = strrchr (fontp->name, '-');
6053 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
6054 fontp->encoding[1] = 4;
6055 else
6056 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
6058 /* The following three values are set to 0 under W32, which is
6059 what they get set to if XGetFontProperty fails under X. */
6060 fontp->baseline_offset = 0;
6061 fontp->relative_compose = 0;
6062 fontp->default_ascent = 0;
6064 /* Set global flag fonts_changed_p to non-zero if the font loaded
6065 has a character with a smaller width than any other character
6066 before, or if the font loaded has a smaller height than any
6067 other font loaded before. If this happens, it will make a
6068 glyph matrix reallocation necessary. */
6069 fonts_changed_p |= x_compute_min_glyph_bounds (f);
6070 UNBLOCK_INPUT;
6071 return fontp;
6075 /* Load font named FONTNAME of size SIZE for frame F, and return a
6076 pointer to the structure font_info while allocating it dynamically.
6077 If loading fails, return NULL. */
6078 struct font_info *
6079 w32_load_font (f,fontname,size)
6080 struct frame *f;
6081 char * fontname;
6082 int size;
6084 Lisp_Object bdf_fonts;
6085 struct font_info *retval = NULL;
6087 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
6089 while (!retval && CONSP (bdf_fonts))
6091 char *bdf_name, *bdf_file;
6092 Lisp_Object bdf_pair;
6094 bdf_name = SDATA (XCAR (bdf_fonts));
6095 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
6096 bdf_file = SDATA (XCDR (bdf_pair));
6098 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
6100 bdf_fonts = XCDR (bdf_fonts);
6103 if (retval)
6104 return retval;
6106 return w32_load_system_font(f, fontname, size);
6110 void
6111 w32_unload_font (dpyinfo, font)
6112 struct w32_display_info *dpyinfo;
6113 XFontStruct * font;
6115 if (font)
6117 if (font->per_char) xfree (font->per_char);
6118 if (font->bdf) w32_free_bdf_font (font->bdf);
6120 if (font->hfont) DeleteObject(font->hfont);
6121 xfree (font);
6125 /* The font conversion stuff between x and w32 */
6127 /* X font string is as follows (from faces.el)
6128 * (let ((- "[-?]")
6129 * (foundry "[^-]+")
6130 * (family "[^-]+")
6131 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
6132 * (weight\? "\\([^-]*\\)") ; 1
6133 * (slant "\\([ior]\\)") ; 2
6134 * (slant\? "\\([^-]?\\)") ; 2
6135 * (swidth "\\([^-]*\\)") ; 3
6136 * (adstyle "[^-]*") ; 4
6137 * (pixelsize "[0-9]+")
6138 * (pointsize "[0-9][0-9]+")
6139 * (resx "[0-9][0-9]+")
6140 * (resy "[0-9][0-9]+")
6141 * (spacing "[cmp?*]")
6142 * (avgwidth "[0-9]+")
6143 * (registry "[^-]+")
6144 * (encoding "[^-]+")
6148 static LONG
6149 x_to_w32_weight (lpw)
6150 char * lpw;
6152 if (!lpw) return (FW_DONTCARE);
6154 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
6155 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
6156 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
6157 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
6158 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
6159 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
6160 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
6161 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
6162 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
6163 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
6164 else
6165 return FW_DONTCARE;
6169 static char *
6170 w32_to_x_weight (fnweight)
6171 int fnweight;
6173 if (fnweight >= FW_HEAVY) return "heavy";
6174 if (fnweight >= FW_EXTRABOLD) return "extrabold";
6175 if (fnweight >= FW_BOLD) return "bold";
6176 if (fnweight >= FW_SEMIBOLD) return "demibold";
6177 if (fnweight >= FW_MEDIUM) return "medium";
6178 if (fnweight >= FW_NORMAL) return "normal";
6179 if (fnweight >= FW_LIGHT) return "light";
6180 if (fnweight >= FW_EXTRALIGHT) return "extralight";
6181 if (fnweight >= FW_THIN) return "thin";
6182 else
6183 return "*";
6186 static LONG
6187 x_to_w32_charset (lpcs)
6188 char * lpcs;
6190 Lisp_Object this_entry, w32_charset;
6191 char *charset;
6192 int len = strlen (lpcs);
6194 /* Support "*-#nnn" format for unknown charsets. */
6195 if (strncmp (lpcs, "*-#", 3) == 0)
6196 return atoi (lpcs + 3);
6198 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
6199 charset = alloca (len + 1);
6200 strcpy (charset, lpcs);
6201 lpcs = strchr (charset, '*');
6202 if (lpcs)
6203 *lpcs = 0;
6205 /* Look through w32-charset-info-alist for the character set.
6206 Format of each entry is
6207 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6209 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6211 if (NILP(this_entry))
6213 /* At startup, we want iso8859-1 fonts to come up properly. */
6214 if (stricmp(charset, "iso8859-1") == 0)
6215 return ANSI_CHARSET;
6216 else
6217 return DEFAULT_CHARSET;
6220 w32_charset = Fcar (Fcdr (this_entry));
6222 /* Translate Lisp symbol to number. */
6223 if (w32_charset == Qw32_charset_ansi)
6224 return ANSI_CHARSET;
6225 if (w32_charset == Qw32_charset_symbol)
6226 return SYMBOL_CHARSET;
6227 if (w32_charset == Qw32_charset_shiftjis)
6228 return SHIFTJIS_CHARSET;
6229 if (w32_charset == Qw32_charset_hangeul)
6230 return HANGEUL_CHARSET;
6231 if (w32_charset == Qw32_charset_chinesebig5)
6232 return CHINESEBIG5_CHARSET;
6233 if (w32_charset == Qw32_charset_gb2312)
6234 return GB2312_CHARSET;
6235 if (w32_charset == Qw32_charset_oem)
6236 return OEM_CHARSET;
6237 #ifdef JOHAB_CHARSET
6238 if (w32_charset == Qw32_charset_johab)
6239 return JOHAB_CHARSET;
6240 if (w32_charset == Qw32_charset_easteurope)
6241 return EASTEUROPE_CHARSET;
6242 if (w32_charset == Qw32_charset_turkish)
6243 return TURKISH_CHARSET;
6244 if (w32_charset == Qw32_charset_baltic)
6245 return BALTIC_CHARSET;
6246 if (w32_charset == Qw32_charset_russian)
6247 return RUSSIAN_CHARSET;
6248 if (w32_charset == Qw32_charset_arabic)
6249 return ARABIC_CHARSET;
6250 if (w32_charset == Qw32_charset_greek)
6251 return GREEK_CHARSET;
6252 if (w32_charset == Qw32_charset_hebrew)
6253 return HEBREW_CHARSET;
6254 if (w32_charset == Qw32_charset_vietnamese)
6255 return VIETNAMESE_CHARSET;
6256 if (w32_charset == Qw32_charset_thai)
6257 return THAI_CHARSET;
6258 if (w32_charset == Qw32_charset_mac)
6259 return MAC_CHARSET;
6260 #endif /* JOHAB_CHARSET */
6261 #ifdef UNICODE_CHARSET
6262 if (w32_charset == Qw32_charset_unicode)
6263 return UNICODE_CHARSET;
6264 #endif
6266 return DEFAULT_CHARSET;
6270 static char *
6271 w32_to_x_charset (fncharset)
6272 int fncharset;
6274 static char buf[32];
6275 Lisp_Object charset_type;
6277 switch (fncharset)
6279 case ANSI_CHARSET:
6280 /* Handle startup case of w32-charset-info-alist not
6281 being set up yet. */
6282 if (NILP(Vw32_charset_info_alist))
6283 return "iso8859-1";
6284 charset_type = Qw32_charset_ansi;
6285 break;
6286 case DEFAULT_CHARSET:
6287 charset_type = Qw32_charset_default;
6288 break;
6289 case SYMBOL_CHARSET:
6290 charset_type = Qw32_charset_symbol;
6291 break;
6292 case SHIFTJIS_CHARSET:
6293 charset_type = Qw32_charset_shiftjis;
6294 break;
6295 case HANGEUL_CHARSET:
6296 charset_type = Qw32_charset_hangeul;
6297 break;
6298 case GB2312_CHARSET:
6299 charset_type = Qw32_charset_gb2312;
6300 break;
6301 case CHINESEBIG5_CHARSET:
6302 charset_type = Qw32_charset_chinesebig5;
6303 break;
6304 case OEM_CHARSET:
6305 charset_type = Qw32_charset_oem;
6306 break;
6308 /* More recent versions of Windows (95 and NT4.0) define more
6309 character sets. */
6310 #ifdef EASTEUROPE_CHARSET
6311 case EASTEUROPE_CHARSET:
6312 charset_type = Qw32_charset_easteurope;
6313 break;
6314 case TURKISH_CHARSET:
6315 charset_type = Qw32_charset_turkish;
6316 break;
6317 case BALTIC_CHARSET:
6318 charset_type = Qw32_charset_baltic;
6319 break;
6320 case RUSSIAN_CHARSET:
6321 charset_type = Qw32_charset_russian;
6322 break;
6323 case ARABIC_CHARSET:
6324 charset_type = Qw32_charset_arabic;
6325 break;
6326 case GREEK_CHARSET:
6327 charset_type = Qw32_charset_greek;
6328 break;
6329 case HEBREW_CHARSET:
6330 charset_type = Qw32_charset_hebrew;
6331 break;
6332 case VIETNAMESE_CHARSET:
6333 charset_type = Qw32_charset_vietnamese;
6334 break;
6335 case THAI_CHARSET:
6336 charset_type = Qw32_charset_thai;
6337 break;
6338 case MAC_CHARSET:
6339 charset_type = Qw32_charset_mac;
6340 break;
6341 case JOHAB_CHARSET:
6342 charset_type = Qw32_charset_johab;
6343 break;
6344 #endif
6346 #ifdef UNICODE_CHARSET
6347 case UNICODE_CHARSET:
6348 charset_type = Qw32_charset_unicode;
6349 break;
6350 #endif
6351 default:
6352 /* Encode numerical value of unknown charset. */
6353 sprintf (buf, "*-#%u", fncharset);
6354 return buf;
6358 Lisp_Object rest;
6359 char * best_match = NULL;
6361 /* Look through w32-charset-info-alist for the character set.
6362 Prefer ISO codepages, and prefer lower numbers in the ISO
6363 range. Only return charsets for codepages which are installed.
6365 Format of each entry is
6366 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6368 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6370 char * x_charset;
6371 Lisp_Object w32_charset;
6372 Lisp_Object codepage;
6374 Lisp_Object this_entry = XCAR (rest);
6376 /* Skip invalid entries in alist. */
6377 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6378 || !CONSP (XCDR (this_entry))
6379 || !SYMBOLP (XCAR (XCDR (this_entry))))
6380 continue;
6382 x_charset = SDATA (XCAR (this_entry));
6383 w32_charset = XCAR (XCDR (this_entry));
6384 codepage = XCDR (XCDR (this_entry));
6386 /* Look for Same charset and a valid codepage (or non-int
6387 which means ignore). */
6388 if (w32_charset == charset_type
6389 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6390 || IsValidCodePage (XINT (codepage))))
6392 /* If we don't have a match already, then this is the
6393 best. */
6394 if (!best_match)
6395 best_match = x_charset;
6396 /* If this is an ISO codepage, and the best so far isn't,
6397 then this is better. */
6398 else if (strnicmp (best_match, "iso", 3) != 0
6399 && strnicmp (x_charset, "iso", 3) == 0)
6400 best_match = x_charset;
6401 /* If both are ISO8859 codepages, choose the one with the
6402 lowest number in the encoding field. */
6403 else if (strnicmp (best_match, "iso8859-", 8) == 0
6404 && strnicmp (x_charset, "iso8859-", 8) == 0)
6406 int best_enc = atoi (best_match + 8);
6407 int this_enc = atoi (x_charset + 8);
6408 if (this_enc > 0 && this_enc < best_enc)
6409 best_match = x_charset;
6414 /* If no match, encode the numeric value. */
6415 if (!best_match)
6417 sprintf (buf, "*-#%u", fncharset);
6418 return buf;
6421 strncpy(buf, best_match, 31);
6422 buf[31] = '\0';
6423 return buf;
6428 /* Return all the X charsets that map to a font. */
6429 static Lisp_Object
6430 w32_to_all_x_charsets (fncharset)
6431 int fncharset;
6433 static char buf[32];
6434 Lisp_Object charset_type;
6435 Lisp_Object retval = Qnil;
6437 switch (fncharset)
6439 case ANSI_CHARSET:
6440 /* Handle startup case of w32-charset-info-alist not
6441 being set up yet. */
6442 if (NILP(Vw32_charset_info_alist))
6443 return Fcons (build_string ("iso8859-1"), Qnil);
6445 charset_type = Qw32_charset_ansi;
6446 break;
6447 case DEFAULT_CHARSET:
6448 charset_type = Qw32_charset_default;
6449 break;
6450 case SYMBOL_CHARSET:
6451 charset_type = Qw32_charset_symbol;
6452 break;
6453 case SHIFTJIS_CHARSET:
6454 charset_type = Qw32_charset_shiftjis;
6455 break;
6456 case HANGEUL_CHARSET:
6457 charset_type = Qw32_charset_hangeul;
6458 break;
6459 case GB2312_CHARSET:
6460 charset_type = Qw32_charset_gb2312;
6461 break;
6462 case CHINESEBIG5_CHARSET:
6463 charset_type = Qw32_charset_chinesebig5;
6464 break;
6465 case OEM_CHARSET:
6466 charset_type = Qw32_charset_oem;
6467 break;
6469 /* More recent versions of Windows (95 and NT4.0) define more
6470 character sets. */
6471 #ifdef EASTEUROPE_CHARSET
6472 case EASTEUROPE_CHARSET:
6473 charset_type = Qw32_charset_easteurope;
6474 break;
6475 case TURKISH_CHARSET:
6476 charset_type = Qw32_charset_turkish;
6477 break;
6478 case BALTIC_CHARSET:
6479 charset_type = Qw32_charset_baltic;
6480 break;
6481 case RUSSIAN_CHARSET:
6482 charset_type = Qw32_charset_russian;
6483 break;
6484 case ARABIC_CHARSET:
6485 charset_type = Qw32_charset_arabic;
6486 break;
6487 case GREEK_CHARSET:
6488 charset_type = Qw32_charset_greek;
6489 break;
6490 case HEBREW_CHARSET:
6491 charset_type = Qw32_charset_hebrew;
6492 break;
6493 case VIETNAMESE_CHARSET:
6494 charset_type = Qw32_charset_vietnamese;
6495 break;
6496 case THAI_CHARSET:
6497 charset_type = Qw32_charset_thai;
6498 break;
6499 case MAC_CHARSET:
6500 charset_type = Qw32_charset_mac;
6501 break;
6502 case JOHAB_CHARSET:
6503 charset_type = Qw32_charset_johab;
6504 break;
6505 #endif
6507 #ifdef UNICODE_CHARSET
6508 case UNICODE_CHARSET:
6509 charset_type = Qw32_charset_unicode;
6510 break;
6511 #endif
6512 default:
6513 /* Encode numerical value of unknown charset. */
6514 sprintf (buf, "*-#%u", fncharset);
6515 return Fcons (build_string (buf), Qnil);
6519 Lisp_Object rest;
6520 /* Look through w32-charset-info-alist for the character set.
6521 Only return charsets for codepages which are installed.
6523 Format of each entry in Vw32_charset_info_alist is
6524 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6526 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6528 Lisp_Object x_charset;
6529 Lisp_Object w32_charset;
6530 Lisp_Object codepage;
6532 Lisp_Object this_entry = XCAR (rest);
6534 /* Skip invalid entries in alist. */
6535 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6536 || !CONSP (XCDR (this_entry))
6537 || !SYMBOLP (XCAR (XCDR (this_entry))))
6538 continue;
6540 x_charset = XCAR (this_entry);
6541 w32_charset = XCAR (XCDR (this_entry));
6542 codepage = XCDR (XCDR (this_entry));
6544 /* Look for Same charset and a valid codepage (or non-int
6545 which means ignore). */
6546 if (w32_charset == charset_type
6547 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6548 || IsValidCodePage (XINT (codepage))))
6550 retval = Fcons (x_charset, retval);
6554 /* If no match, encode the numeric value. */
6555 if (NILP (retval))
6557 sprintf (buf, "*-#%u", fncharset);
6558 return Fcons (build_string (buf), Qnil);
6561 return retval;
6565 /* Get the Windows codepage corresponding to the specified font. The
6566 charset info in the font name is used to look up
6567 w32-charset-to-codepage-alist. */
6569 w32_codepage_for_font (char *fontname)
6571 Lisp_Object codepage, entry;
6572 char *charset_str, *charset, *end;
6574 if (NILP (Vw32_charset_info_alist))
6575 return CP_DEFAULT;
6577 /* Extract charset part of font string. */
6578 charset = xlfd_charset_of_font (fontname);
6580 if (!charset)
6581 return CP_UNKNOWN;
6583 charset_str = (char *) alloca (strlen (charset) + 1);
6584 strcpy (charset_str, charset);
6586 #if 0
6587 /* Remove leading "*-". */
6588 if (strncmp ("*-", charset_str, 2) == 0)
6589 charset = charset_str + 2;
6590 else
6591 #endif
6592 charset = charset_str;
6594 /* Stop match at wildcard (including preceding '-'). */
6595 if (end = strchr (charset, '*'))
6597 if (end > charset && *(end-1) == '-')
6598 end--;
6599 *end = '\0';
6602 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6603 if (NILP (entry))
6604 return CP_UNKNOWN;
6606 codepage = Fcdr (Fcdr (entry));
6608 if (NILP (codepage))
6609 return CP_8BIT;
6610 else if (XFASTINT (codepage) == XFASTINT (Qt))
6611 return CP_UNICODE;
6612 else if (INTEGERP (codepage))
6613 return XINT (codepage);
6614 else
6615 return CP_UNKNOWN;
6619 static BOOL
6620 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6621 LOGFONT * lplogfont;
6622 char * lpxstr;
6623 int len;
6624 char * specific_charset;
6626 char* fonttype;
6627 char *fontname;
6628 char height_pixels[8];
6629 char height_dpi[8];
6630 char width_pixels[8];
6631 char *fontname_dash;
6632 int display_resy = (int) one_w32_display_info.resy;
6633 int display_resx = (int) one_w32_display_info.resx;
6634 int bufsz;
6635 struct coding_system coding;
6637 if (!lpxstr) abort ();
6639 if (!lplogfont)
6640 return FALSE;
6642 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6643 fonttype = "raster";
6644 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6645 fonttype = "outline";
6646 else
6647 fonttype = "unknown";
6649 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
6650 &coding);
6651 coding.src_multibyte = 0;
6652 coding.dst_multibyte = 1;
6653 coding.mode |= CODING_MODE_LAST_BLOCK;
6654 /* We explicitely disable composition handling because selection
6655 data should not contain any composition sequence. */
6656 coding.composing = COMPOSITION_DISABLED;
6657 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6659 fontname = alloca(sizeof(*fontname) * bufsz);
6660 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6661 strlen(lplogfont->lfFaceName), bufsz - 1);
6662 *(fontname + coding.produced) = '\0';
6664 /* Replace dashes with underscores so the dashes are not
6665 misinterpreted. */
6666 fontname_dash = fontname;
6667 while (fontname_dash = strchr (fontname_dash, '-'))
6668 *fontname_dash = '_';
6670 if (lplogfont->lfHeight)
6672 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6673 sprintf (height_dpi, "%u",
6674 abs (lplogfont->lfHeight) * 720 / display_resy);
6676 else
6678 strcpy (height_pixels, "*");
6679 strcpy (height_dpi, "*");
6681 if (lplogfont->lfWidth)
6682 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6683 else
6684 strcpy (width_pixels, "*");
6686 _snprintf (lpxstr, len - 1,
6687 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6688 fonttype, /* foundry */
6689 fontname, /* family */
6690 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6691 lplogfont->lfItalic?'i':'r', /* slant */
6692 /* setwidth name */
6693 /* add style name */
6694 height_pixels, /* pixel size */
6695 height_dpi, /* point size */
6696 display_resx, /* resx */
6697 display_resy, /* resy */
6698 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6699 ? 'p' : 'c', /* spacing */
6700 width_pixels, /* avg width */
6701 specific_charset ? specific_charset
6702 : w32_to_x_charset (lplogfont->lfCharSet)
6703 /* charset registry and encoding */
6706 lpxstr[len - 1] = 0; /* just to be sure */
6707 return (TRUE);
6710 static BOOL
6711 x_to_w32_font (lpxstr, lplogfont)
6712 char * lpxstr;
6713 LOGFONT * lplogfont;
6715 struct coding_system coding;
6717 if (!lplogfont) return (FALSE);
6719 memset (lplogfont, 0, sizeof (*lplogfont));
6721 /* Set default value for each field. */
6722 #if 1
6723 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6724 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6725 lplogfont->lfQuality = DEFAULT_QUALITY;
6726 #else
6727 /* go for maximum quality */
6728 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6729 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6730 lplogfont->lfQuality = PROOF_QUALITY;
6731 #endif
6733 lplogfont->lfCharSet = DEFAULT_CHARSET;
6734 lplogfont->lfWeight = FW_DONTCARE;
6735 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6737 if (!lpxstr)
6738 return FALSE;
6740 /* Provide a simple escape mechanism for specifying Windows font names
6741 * directly -- if font spec does not beginning with '-', assume this
6742 * format:
6743 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6746 if (*lpxstr == '-')
6748 int fields, tem;
6749 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6750 width[10], resy[10], remainder[50];
6751 char * encoding;
6752 int dpi = (int) one_w32_display_info.resy;
6754 fields = sscanf (lpxstr,
6755 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
6756 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6757 if (fields == EOF)
6758 return (FALSE);
6760 /* In the general case when wildcards cover more than one field,
6761 we don't know which field is which, so don't fill any in.
6762 However, we need to cope with this particular form, which is
6763 generated by font_list_1 (invoked by try_font_list):
6764 "-raster-6x10-*-gb2312*-*"
6765 and make sure to correctly parse the charset field. */
6766 if (fields == 3)
6768 fields = sscanf (lpxstr,
6769 "-%*[^-]-%49[^-]-*-%49s",
6770 name, remainder);
6772 else if (fields < 9)
6774 fields = 0;
6775 remainder[0] = 0;
6778 if (fields > 0 && name[0] != '*')
6780 int bufsize;
6781 unsigned char *buf;
6783 setup_coding_system
6784 (Fcheck_coding_system (Vlocale_coding_system), &coding);
6785 coding.src_multibyte = 1;
6786 coding.dst_multibyte = 1;
6787 bufsize = encoding_buffer_size (&coding, strlen (name));
6788 buf = (unsigned char *) alloca (bufsize);
6789 coding.mode |= CODING_MODE_LAST_BLOCK;
6790 encode_coding (&coding, name, buf, strlen (name), bufsize);
6791 if (coding.produced >= LF_FACESIZE)
6792 coding.produced = LF_FACESIZE - 1;
6793 buf[coding.produced] = 0;
6794 strcpy (lplogfont->lfFaceName, buf);
6796 else
6798 lplogfont->lfFaceName[0] = '\0';
6801 fields--;
6803 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6805 fields--;
6807 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6809 fields--;
6811 if (fields > 0 && pixels[0] != '*')
6812 lplogfont->lfHeight = atoi (pixels);
6814 fields--;
6815 fields--;
6816 if (fields > 0 && resy[0] != '*')
6818 tem = atoi (resy);
6819 if (tem > 0) dpi = tem;
6822 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6823 lplogfont->lfHeight = atoi (height) * dpi / 720;
6825 if (fields > 0)
6826 lplogfont->lfPitchAndFamily =
6827 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6829 fields--;
6831 if (fields > 0 && width[0] != '*')
6832 lplogfont->lfWidth = atoi (width) / 10;
6834 fields--;
6836 /* Strip the trailing '-' if present. (it shouldn't be, as it
6837 fails the test against xlfd-tight-regexp in fontset.el). */
6839 int len = strlen (remainder);
6840 if (len > 0 && remainder[len-1] == '-')
6841 remainder[len-1] = 0;
6843 encoding = remainder;
6844 #if 0
6845 if (strncmp (encoding, "*-", 2) == 0)
6846 encoding += 2;
6847 #endif
6848 lplogfont->lfCharSet = x_to_w32_charset (encoding);
6850 else
6852 int fields;
6853 char name[100], height[10], width[10], weight[20];
6855 fields = sscanf (lpxstr,
6856 "%99[^:]:%9[^:]:%9[^:]:%19s",
6857 name, height, width, weight);
6859 if (fields == EOF) return (FALSE);
6861 if (fields > 0)
6863 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6864 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6866 else
6868 lplogfont->lfFaceName[0] = 0;
6871 fields--;
6873 if (fields > 0)
6874 lplogfont->lfHeight = atoi (height);
6876 fields--;
6878 if (fields > 0)
6879 lplogfont->lfWidth = atoi (width);
6881 fields--;
6883 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6886 /* This makes TrueType fonts work better. */
6887 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6889 return (TRUE);
6892 /* Strip the pixel height and point height from the given xlfd, and
6893 return the pixel height. If no pixel height is specified, calculate
6894 one from the point height, or if that isn't defined either, return
6895 0 (which usually signifies a scalable font).
6897 static int
6898 xlfd_strip_height (char *fontname)
6900 int pixel_height, field_number;
6901 char *read_from, *write_to;
6903 xassert (fontname);
6905 pixel_height = field_number = 0;
6906 write_to = NULL;
6908 /* Look for height fields. */
6909 for (read_from = fontname; *read_from; read_from++)
6911 if (*read_from == '-')
6913 field_number++;
6914 if (field_number == 7) /* Pixel height. */
6916 read_from++;
6917 write_to = read_from;
6919 /* Find end of field. */
6920 for (;*read_from && *read_from != '-'; read_from++)
6923 /* Split the fontname at end of field. */
6924 if (*read_from)
6926 *read_from = '\0';
6927 read_from++;
6929 pixel_height = atoi (write_to);
6930 /* Blank out field. */
6931 if (read_from > write_to)
6933 *write_to = '-';
6934 write_to++;
6936 /* If the pixel height field is at the end (partial xlfd),
6937 return now. */
6938 else
6939 return pixel_height;
6941 /* If we got a pixel height, the point height can be
6942 ignored. Just blank it out and break now. */
6943 if (pixel_height)
6945 /* Find end of point size field. */
6946 for (; *read_from && *read_from != '-'; read_from++)
6949 if (*read_from)
6950 read_from++;
6952 /* Blank out the point size field. */
6953 if (read_from > write_to)
6955 *write_to = '-';
6956 write_to++;
6958 else
6959 return pixel_height;
6961 break;
6963 /* If the point height is already blank, break now. */
6964 if (*read_from == '-')
6966 read_from++;
6967 break;
6970 else if (field_number == 8)
6972 /* If we didn't get a pixel height, try to get the point
6973 height and convert that. */
6974 int point_size;
6975 char *point_size_start = read_from++;
6977 /* Find end of field. */
6978 for (; *read_from && *read_from != '-'; read_from++)
6981 if (*read_from)
6983 *read_from = '\0';
6984 read_from++;
6987 point_size = atoi (point_size_start);
6989 /* Convert to pixel height. */
6990 pixel_height = point_size
6991 * one_w32_display_info.height_in / 720;
6993 /* Blank out this field and break. */
6994 *write_to = '-';
6995 write_to++;
6996 break;
7001 /* Shift the rest of the font spec into place. */
7002 if (write_to && read_from > write_to)
7004 for (; *read_from; read_from++, write_to++)
7005 *write_to = *read_from;
7006 *write_to = '\0';
7009 return pixel_height;
7012 /* Assume parameter 1 is fully qualified, no wildcards. */
7013 static BOOL
7014 w32_font_match (fontname, pattern)
7015 char * fontname;
7016 char * pattern;
7018 char *regex = alloca (strlen (pattern) * 2 + 3);
7019 char *font_name_copy = alloca (strlen (fontname) + 1);
7020 char *ptr;
7022 /* Copy fontname so we can modify it during comparison. */
7023 strcpy (font_name_copy, fontname);
7025 ptr = regex;
7026 *ptr++ = '^';
7028 /* Turn pattern into a regexp and do a regexp match. */
7029 for (; *pattern; pattern++)
7031 if (*pattern == '?')
7032 *ptr++ = '.';
7033 else if (*pattern == '*')
7035 *ptr++ = '.';
7036 *ptr++ = '*';
7038 else
7039 *ptr++ = *pattern;
7041 *ptr = '$';
7042 *(ptr + 1) = '\0';
7044 /* Strip out font heights and compare them seperately, since
7045 rounding error can cause mismatches. This also allows a
7046 comparison between a font that declares only a pixel height and a
7047 pattern that declares the point height.
7050 int font_height, pattern_height;
7052 font_height = xlfd_strip_height (font_name_copy);
7053 pattern_height = xlfd_strip_height (regex);
7055 /* Compare now, and don't bother doing expensive regexp matching
7056 if the heights differ. */
7057 if (font_height && pattern_height && (font_height != pattern_height))
7058 return FALSE;
7061 return (fast_c_string_match_ignore_case (build_string (regex),
7062 font_name_copy) >= 0);
7065 /* Callback functions, and a structure holding info they need, for
7066 listing system fonts on W32. We need one set of functions to do the
7067 job properly, but these don't work on NT 3.51 and earlier, so we
7068 have a second set which don't handle character sets properly to
7069 fall back on.
7071 In both cases, there are two passes made. The first pass gets one
7072 font from each family, the second pass lists all the fonts from
7073 each family. */
7075 typedef struct enumfont_t
7077 HDC hdc;
7078 int numFonts;
7079 LOGFONT logfont;
7080 XFontStruct *size_ref;
7081 Lisp_Object pattern;
7082 Lisp_Object list;
7083 } enumfont_t;
7086 static void
7087 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
7090 static int CALLBACK
7091 enum_font_cb2 (lplf, lptm, FontType, lpef)
7092 ENUMLOGFONT * lplf;
7093 NEWTEXTMETRIC * lptm;
7094 int FontType;
7095 enumfont_t * lpef;
7097 /* Ignore struck out and underlined versions of fonts. */
7098 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
7099 return 1;
7101 /* Only return fonts with names starting with @ if they were
7102 explicitly specified, since Microsoft uses an initial @ to
7103 denote fonts for vertical writing, without providing a more
7104 convenient way of identifying them. */
7105 if (lplf->elfLogFont.lfFaceName[0] == '@'
7106 && lpef->logfont.lfFaceName[0] != '@')
7107 return 1;
7109 /* Check that the character set matches if it was specified */
7110 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
7111 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
7112 return 1;
7114 if (FontType == RASTER_FONTTYPE)
7116 /* DBCS raster fonts have problems displaying, so skip them. */
7117 int charset = lplf->elfLogFont.lfCharSet;
7118 if (charset == SHIFTJIS_CHARSET
7119 || charset == HANGEUL_CHARSET
7120 || charset == CHINESEBIG5_CHARSET
7121 || charset == GB2312_CHARSET
7122 #ifdef JOHAB_CHARSET
7123 || charset == JOHAB_CHARSET
7124 #endif
7126 return 1;
7130 char buf[100];
7131 Lisp_Object width = Qnil;
7132 Lisp_Object charset_list = Qnil;
7133 char *charset = NULL;
7135 /* Truetype fonts do not report their true metrics until loaded */
7136 if (FontType != RASTER_FONTTYPE)
7138 if (!NILP (lpef->pattern))
7140 /* Scalable fonts are as big as you want them to be. */
7141 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
7142 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
7143 width = make_number (lpef->logfont.lfWidth);
7145 else
7147 lplf->elfLogFont.lfHeight = 0;
7148 lplf->elfLogFont.lfWidth = 0;
7152 /* Make sure the height used here is the same as everywhere
7153 else (ie character height, not cell height). */
7154 if (lplf->elfLogFont.lfHeight > 0)
7156 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
7157 if (FontType == RASTER_FONTTYPE)
7158 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
7159 else
7160 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
7163 if (!NILP (lpef->pattern))
7165 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
7167 /* We already checked charsets above, but DEFAULT_CHARSET
7168 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
7169 if (charset
7170 && strncmp (charset, "*-*", 3) != 0
7171 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
7172 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
7173 return 1;
7176 if (charset)
7177 charset_list = Fcons (build_string (charset), Qnil);
7178 else
7179 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
7181 /* Loop through the charsets. */
7182 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
7184 Lisp_Object this_charset = Fcar (charset_list);
7185 charset = SDATA (this_charset);
7187 /* List bold and italic variations if w32-enable-synthesized-fonts
7188 is non-nil and this is a plain font. */
7189 if (w32_enable_synthesized_fonts
7190 && lplf->elfLogFont.lfWeight == FW_NORMAL
7191 && lplf->elfLogFont.lfItalic == FALSE)
7193 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7194 charset, width);
7195 /* bold. */
7196 lplf->elfLogFont.lfWeight = FW_BOLD;
7197 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7198 charset, width);
7199 /* bold italic. */
7200 lplf->elfLogFont.lfItalic = TRUE;
7201 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7202 charset, width);
7203 /* italic. */
7204 lplf->elfLogFont.lfWeight = FW_NORMAL;
7205 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7206 charset, width);
7208 else
7209 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7210 charset, width);
7214 return 1;
7217 static void
7218 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
7219 enumfont_t * lpef;
7220 LOGFONT * logfont;
7221 char * match_charset;
7222 Lisp_Object width;
7224 char buf[100];
7226 if (!w32_to_x_font (logfont, buf, 100, match_charset))
7227 return;
7229 if (NILP (lpef->pattern)
7230 || w32_font_match (buf, SDATA (lpef->pattern)))
7232 /* Check if we already listed this font. This may happen if
7233 w32_enable_synthesized_fonts is non-nil, and there are real
7234 bold and italic versions of the font. */
7235 Lisp_Object font_name = build_string (buf);
7236 if (NILP (Fmember (font_name, lpef->list)))
7238 Lisp_Object entry = Fcons (font_name, width);
7239 lpef->list = Fcons (entry, lpef->list);
7240 lpef->numFonts++;
7246 static int CALLBACK
7247 enum_font_cb1 (lplf, lptm, FontType, lpef)
7248 ENUMLOGFONT * lplf;
7249 NEWTEXTMETRIC * lptm;
7250 int FontType;
7251 enumfont_t * lpef;
7253 return EnumFontFamilies (lpef->hdc,
7254 lplf->elfLogFont.lfFaceName,
7255 (FONTENUMPROC) enum_font_cb2,
7256 (LPARAM) lpef);
7260 static int CALLBACK
7261 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
7262 ENUMLOGFONTEX * lplf;
7263 NEWTEXTMETRICEX * lptm;
7264 int font_type;
7265 enumfont_t * lpef;
7267 /* We are not interested in the extra info we get back from the 'Ex
7268 version - only the fact that we get character set variations
7269 enumerated seperately. */
7270 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
7271 font_type, lpef);
7274 static int CALLBACK
7275 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
7276 ENUMLOGFONTEX * lplf;
7277 NEWTEXTMETRICEX * lptm;
7278 int font_type;
7279 enumfont_t * lpef;
7281 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7282 FARPROC enum_font_families_ex
7283 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7284 /* We don't really expect EnumFontFamiliesEx to disappear once we
7285 get here, so don't bother handling it gracefully. */
7286 if (enum_font_families_ex == NULL)
7287 error ("gdi32.dll has disappeared!");
7288 return enum_font_families_ex (lpef->hdc,
7289 &lplf->elfLogFont,
7290 (FONTENUMPROC) enum_fontex_cb2,
7291 (LPARAM) lpef, 0);
7294 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
7295 and xterm.c in Emacs 20.3) */
7297 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
7299 char *fontname, *ptnstr;
7300 Lisp_Object list, tem, newlist = Qnil;
7301 int n_fonts = 0;
7303 list = Vw32_bdf_filename_alist;
7304 ptnstr = SDATA (pattern);
7306 for ( ; CONSP (list); list = XCDR (list))
7308 tem = XCAR (list);
7309 if (CONSP (tem))
7310 fontname = SDATA (XCAR (tem));
7311 else if (STRINGP (tem))
7312 fontname = SDATA (tem);
7313 else
7314 continue;
7316 if (w32_font_match (fontname, ptnstr))
7318 newlist = Fcons (XCAR (tem), newlist);
7319 n_fonts++;
7320 if (n_fonts >= max_names)
7321 break;
7325 return newlist;
7329 /* Return a list of names of available fonts matching PATTERN on frame
7330 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
7331 to be listed. Frame F NULL means we have not yet created any
7332 frame, which means we can't get proper size info, as we don't have
7333 a device context to use for GetTextMetrics.
7334 MAXNAMES sets a limit on how many fonts to match. */
7336 Lisp_Object
7337 w32_list_fonts (f, pattern, size, maxnames)
7338 struct frame *f;
7339 Lisp_Object pattern;
7340 int size;
7341 int maxnames;
7343 Lisp_Object patterns, key = Qnil, tem, tpat;
7344 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
7345 struct w32_display_info *dpyinfo = &one_w32_display_info;
7346 int n_fonts = 0;
7348 patterns = Fassoc (pattern, Valternate_fontname_alist);
7349 if (NILP (patterns))
7350 patterns = Fcons (pattern, Qnil);
7352 for (; CONSP (patterns); patterns = XCDR (patterns))
7354 enumfont_t ef;
7355 int codepage;
7357 tpat = XCAR (patterns);
7359 if (!STRINGP (tpat))
7360 continue;
7362 /* Avoid expensive EnumFontFamilies functions if we are not
7363 going to be able to output one of these anyway. */
7364 codepage = w32_codepage_for_font (SDATA (tpat));
7365 if (codepage != CP_8BIT && codepage != CP_UNICODE
7366 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
7367 && !IsValidCodePage(codepage))
7368 continue;
7370 /* See if we cached the result for this particular query.
7371 The cache is an alist of the form:
7372 ((PATTERN (FONTNAME . WIDTH) ...) ...)
7374 if (tem = XCDR (dpyinfo->name_list_element),
7375 !NILP (list = Fassoc (tpat, tem)))
7377 list = Fcdr_safe (list);
7378 /* We have a cached list. Don't have to get the list again. */
7379 goto label_cached;
7382 BLOCK_INPUT;
7383 /* At first, put PATTERN in the cache. */
7384 ef.pattern = tpat;
7385 ef.list = Qnil;
7386 ef.numFonts = 0;
7388 /* Use EnumFontFamiliesEx where it is available, as it knows
7389 about character sets. Fall back to EnumFontFamilies for
7390 older versions of NT that don't support the 'Ex function. */
7391 x_to_w32_font (SDATA (tpat), &ef.logfont);
7393 LOGFONT font_match_pattern;
7394 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7395 FARPROC enum_font_families_ex
7396 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7398 /* We do our own pattern matching so we can handle wildcards. */
7399 font_match_pattern.lfFaceName[0] = 0;
7400 font_match_pattern.lfPitchAndFamily = 0;
7401 /* We can use the charset, because if it is a wildcard it will
7402 be DEFAULT_CHARSET anyway. */
7403 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
7405 ef.hdc = GetDC (dpyinfo->root_window);
7407 if (enum_font_families_ex)
7408 enum_font_families_ex (ef.hdc,
7409 &font_match_pattern,
7410 (FONTENUMPROC) enum_fontex_cb1,
7411 (LPARAM) &ef, 0);
7412 else
7413 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
7414 (LPARAM)&ef);
7416 ReleaseDC (dpyinfo->root_window, ef.hdc);
7419 UNBLOCK_INPUT;
7420 list = ef.list;
7422 /* Make a list of the fonts we got back.
7423 Store that in the font cache for the display. */
7424 XSETCDR (dpyinfo->name_list_element,
7425 Fcons (Fcons (tpat, list),
7426 XCDR (dpyinfo->name_list_element)));
7428 label_cached:
7429 if (NILP (list)) continue; /* Try the remaining alternatives. */
7431 newlist = second_best = Qnil;
7433 /* Make a list of the fonts that have the right width. */
7434 for (; CONSP (list); list = XCDR (list))
7436 int found_size;
7437 tem = XCAR (list);
7439 if (!CONSP (tem))
7440 continue;
7441 if (NILP (XCAR (tem)))
7442 continue;
7443 if (!size)
7445 newlist = Fcons (XCAR (tem), newlist);
7446 n_fonts++;
7447 if (n_fonts >= maxnames)
7448 break;
7449 else
7450 continue;
7452 if (!INTEGERP (XCDR (tem)))
7454 /* Since we don't yet know the size of the font, we must
7455 load it and try GetTextMetrics. */
7456 W32FontStruct thisinfo;
7457 LOGFONT lf;
7458 HDC hdc;
7459 HANDLE oldobj;
7461 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
7462 continue;
7464 BLOCK_INPUT;
7465 thisinfo.bdf = NULL;
7466 thisinfo.hfont = CreateFontIndirect (&lf);
7467 if (thisinfo.hfont == NULL)
7468 continue;
7470 hdc = GetDC (dpyinfo->root_window);
7471 oldobj = SelectObject (hdc, thisinfo.hfont);
7472 if (GetTextMetrics (hdc, &thisinfo.tm))
7473 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
7474 else
7475 XSETCDR (tem, make_number (0));
7476 SelectObject (hdc, oldobj);
7477 ReleaseDC (dpyinfo->root_window, hdc);
7478 DeleteObject(thisinfo.hfont);
7479 UNBLOCK_INPUT;
7481 found_size = XINT (XCDR (tem));
7482 if (found_size == size)
7484 newlist = Fcons (XCAR (tem), newlist);
7485 n_fonts++;
7486 if (n_fonts >= maxnames)
7487 break;
7489 /* keep track of the closest matching size in case
7490 no exact match is found. */
7491 else if (found_size > 0)
7493 if (NILP (second_best))
7494 second_best = tem;
7496 else if (found_size < size)
7498 if (XINT (XCDR (second_best)) > size
7499 || XINT (XCDR (second_best)) < found_size)
7500 second_best = tem;
7502 else
7504 if (XINT (XCDR (second_best)) > size
7505 && XINT (XCDR (second_best)) >
7506 found_size)
7507 second_best = tem;
7512 if (!NILP (newlist))
7513 break;
7514 else if (!NILP (second_best))
7516 newlist = Fcons (XCAR (second_best), Qnil);
7517 break;
7521 /* Include any bdf fonts. */
7522 if (n_fonts < maxnames)
7524 Lisp_Object combined[2];
7525 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
7526 combined[1] = newlist;
7527 newlist = Fnconc(2, combined);
7530 return newlist;
7534 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
7535 struct font_info *
7536 w32_get_font_info (f, font_idx)
7537 FRAME_PTR f;
7538 int font_idx;
7540 return (FRAME_W32_FONT_TABLE (f) + font_idx);
7544 struct font_info*
7545 w32_query_font (struct frame *f, char *fontname)
7547 int i;
7548 struct font_info *pfi;
7550 pfi = FRAME_W32_FONT_TABLE (f);
7552 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
7554 if (strcmp(pfi->name, fontname) == 0) return pfi;
7557 return NULL;
7560 /* Find a CCL program for a font specified by FONTP, and set the member
7561 `encoder' of the structure. */
7563 void
7564 w32_find_ccl_program (fontp)
7565 struct font_info *fontp;
7567 Lisp_Object list, elt;
7569 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7571 elt = XCAR (list);
7572 if (CONSP (elt)
7573 && STRINGP (XCAR (elt))
7574 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7575 >= 0))
7576 break;
7578 if (! NILP (list))
7580 struct ccl_program *ccl
7581 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7583 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7584 xfree (ccl);
7585 else
7586 fontp->font_encoder = ccl;
7591 /* Find BDF files in a specified directory. (use GCPRO when calling,
7592 as this calls lisp to get a directory listing). */
7593 static Lisp_Object
7594 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
7596 Lisp_Object filelist, list = Qnil;
7597 char fontname[100];
7599 if (!STRINGP(directory))
7600 return Qnil;
7602 filelist = Fdirectory_files (directory, Qt,
7603 build_string (".*\\.[bB][dD][fF]"), Qt);
7605 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7607 Lisp_Object filename = XCAR (filelist);
7608 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
7609 store_in_alist (&list, build_string (fontname), filename);
7611 return list;
7614 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
7615 1, 1, 0,
7616 doc: /* Return a list of BDF fonts in DIR.
7617 The list is suitable for appending to w32-bdf-filename-alist. Fonts
7618 which do not contain an xlfd description will not be included in the
7619 list. DIR may be a list of directories. */)
7620 (directory)
7621 Lisp_Object directory;
7623 Lisp_Object list = Qnil;
7624 struct gcpro gcpro1, gcpro2;
7626 if (!CONSP (directory))
7627 return w32_find_bdf_fonts_in_dir (directory);
7629 for ( ; CONSP (directory); directory = XCDR (directory))
7631 Lisp_Object pair[2];
7632 pair[0] = list;
7633 pair[1] = Qnil;
7634 GCPRO2 (directory, list);
7635 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7636 list = Fnconc( 2, pair );
7637 UNGCPRO;
7639 return list;
7643 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7644 doc: /* Internal function called by `color-defined-p', which see. */)
7645 (color, frame)
7646 Lisp_Object color, frame;
7648 XColor foo;
7649 FRAME_PTR f = check_x_frame (frame);
7651 CHECK_STRING (color);
7653 if (w32_defined_color (f, SDATA (color), &foo, 0))
7654 return Qt;
7655 else
7656 return Qnil;
7659 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7660 doc: /* Internal function called by `color-values', which see. */)
7661 (color, frame)
7662 Lisp_Object color, frame;
7664 XColor foo;
7665 FRAME_PTR f = check_x_frame (frame);
7667 CHECK_STRING (color);
7669 if (w32_defined_color (f, SDATA (color), &foo, 0))
7671 Lisp_Object rgb[3];
7673 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7674 | GetRValue (foo.pixel));
7675 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7676 | GetGValue (foo.pixel));
7677 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7678 | GetBValue (foo.pixel));
7679 return Flist (3, rgb);
7681 else
7682 return Qnil;
7685 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7686 doc: /* Internal function called by `display-color-p', which see. */)
7687 (display)
7688 Lisp_Object display;
7690 struct w32_display_info *dpyinfo = check_x_display_info (display);
7692 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7693 return Qnil;
7695 return Qt;
7698 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
7699 Sx_display_grayscale_p, 0, 1, 0,
7700 doc: /* Return t if the X display supports shades of gray.
7701 Note that color displays do support shades of gray.
7702 The optional argument DISPLAY specifies which display to ask about.
7703 DISPLAY should be either a frame or a display name (a string).
7704 If omitted or nil, that stands for the selected frame's display. */)
7705 (display)
7706 Lisp_Object display;
7708 struct w32_display_info *dpyinfo = check_x_display_info (display);
7710 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7711 return Qnil;
7713 return Qt;
7716 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
7717 Sx_display_pixel_width, 0, 1, 0,
7718 doc: /* Returns the width in pixels of DISPLAY.
7719 The optional argument DISPLAY specifies which display to ask about.
7720 DISPLAY should be either a frame or a display name (a string).
7721 If omitted or nil, that stands for the selected frame's display. */)
7722 (display)
7723 Lisp_Object display;
7725 struct w32_display_info *dpyinfo = check_x_display_info (display);
7727 return make_number (dpyinfo->width);
7730 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7731 Sx_display_pixel_height, 0, 1, 0,
7732 doc: /* Returns the height in pixels of DISPLAY.
7733 The optional argument DISPLAY specifies which display to ask about.
7734 DISPLAY should be either a frame or a display name (a string).
7735 If omitted or nil, that stands for the selected frame's display. */)
7736 (display)
7737 Lisp_Object display;
7739 struct w32_display_info *dpyinfo = check_x_display_info (display);
7741 return make_number (dpyinfo->height);
7744 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7745 0, 1, 0,
7746 doc: /* Returns the number of bitplanes of DISPLAY.
7747 The optional argument DISPLAY specifies which display to ask about.
7748 DISPLAY should be either a frame or a display name (a string).
7749 If omitted or nil, that stands for the selected frame's display. */)
7750 (display)
7751 Lisp_Object display;
7753 struct w32_display_info *dpyinfo = check_x_display_info (display);
7755 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7758 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7759 0, 1, 0,
7760 doc: /* Returns the number of color cells of DISPLAY.
7761 The optional argument DISPLAY specifies which display to ask about.
7762 DISPLAY should be either a frame or a display name (a string).
7763 If omitted or nil, that stands for the selected frame's display. */)
7764 (display)
7765 Lisp_Object display;
7767 struct w32_display_info *dpyinfo = check_x_display_info (display);
7768 HDC hdc;
7769 int cap;
7771 hdc = GetDC (dpyinfo->root_window);
7772 if (dpyinfo->has_palette)
7773 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7774 else
7775 cap = GetDeviceCaps (hdc,NUMCOLORS);
7777 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
7778 and because probably is more meaningful on Windows anyway */
7779 if (cap < 0)
7780 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
7782 ReleaseDC (dpyinfo->root_window, hdc);
7784 return make_number (cap);
7787 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7788 Sx_server_max_request_size,
7789 0, 1, 0,
7790 doc: /* Returns the maximum request size of the server of DISPLAY.
7791 The optional argument DISPLAY specifies which display to ask about.
7792 DISPLAY should be either a frame or a display name (a string).
7793 If omitted or nil, that stands for the selected frame's display. */)
7794 (display)
7795 Lisp_Object display;
7797 struct w32_display_info *dpyinfo = check_x_display_info (display);
7799 return make_number (1);
7802 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7803 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
7804 The optional argument DISPLAY specifies which display to ask about.
7805 DISPLAY should be either a frame or a display name (a string).
7806 If omitted or nil, that stands for the selected frame's display. */)
7807 (display)
7808 Lisp_Object display;
7810 return build_string ("Microsoft Corp.");
7813 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7814 doc: /* Returns the version numbers of the server of DISPLAY.
7815 The value is a list of three integers: the major and minor
7816 version numbers, and the vendor-specific release
7817 number. See also the function `x-server-vendor'.
7819 The optional argument DISPLAY specifies which display to ask about.
7820 DISPLAY should be either a frame or a display name (a string).
7821 If omitted or nil, that stands for the selected frame's display. */)
7822 (display)
7823 Lisp_Object display;
7825 return Fcons (make_number (w32_major_version),
7826 Fcons (make_number (w32_minor_version),
7827 Fcons (make_number (w32_build_number), Qnil)));
7830 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7831 doc: /* Returns the number of screens on the server of DISPLAY.
7832 The optional argument DISPLAY specifies which display to ask about.
7833 DISPLAY should be either a frame or a display name (a string).
7834 If omitted or nil, that stands for the selected frame's display. */)
7835 (display)
7836 Lisp_Object display;
7838 return make_number (1);
7841 DEFUN ("x-display-mm-height", Fx_display_mm_height,
7842 Sx_display_mm_height, 0, 1, 0,
7843 doc: /* Returns the height in millimeters of DISPLAY.
7844 The optional argument DISPLAY specifies which display to ask about.
7845 DISPLAY should be either a frame or a display name (a string).
7846 If omitted or nil, that stands for the selected frame's display. */)
7847 (display)
7848 Lisp_Object display;
7850 struct w32_display_info *dpyinfo = check_x_display_info (display);
7851 HDC hdc;
7852 int cap;
7854 hdc = GetDC (dpyinfo->root_window);
7856 cap = GetDeviceCaps (hdc, VERTSIZE);
7858 ReleaseDC (dpyinfo->root_window, hdc);
7860 return make_number (cap);
7863 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7864 doc: /* Returns the width in millimeters of DISPLAY.
7865 The optional argument DISPLAY specifies which display to ask about.
7866 DISPLAY should be either a frame or a display name (a string).
7867 If omitted or nil, that stands for the selected frame's display. */)
7868 (display)
7869 Lisp_Object display;
7871 struct w32_display_info *dpyinfo = check_x_display_info (display);
7873 HDC hdc;
7874 int cap;
7876 hdc = GetDC (dpyinfo->root_window);
7878 cap = GetDeviceCaps (hdc, HORZSIZE);
7880 ReleaseDC (dpyinfo->root_window, hdc);
7882 return make_number (cap);
7885 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7886 Sx_display_backing_store, 0, 1, 0,
7887 doc: /* Returns an indication of whether DISPLAY does backing store.
7888 The value may be `always', `when-mapped', or `not-useful'.
7889 The optional argument DISPLAY specifies which display to ask about.
7890 DISPLAY should be either a frame or a display name (a string).
7891 If omitted or nil, that stands for the selected frame's display. */)
7892 (display)
7893 Lisp_Object display;
7895 return intern ("not-useful");
7898 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7899 Sx_display_visual_class, 0, 1, 0,
7900 doc: /* Returns the visual class of DISPLAY.
7901 The value is one of the symbols `static-gray', `gray-scale',
7902 `static-color', `pseudo-color', `true-color', or `direct-color'.
7904 The optional argument DISPLAY specifies which display to ask about.
7905 DISPLAY should be either a frame or a display name (a string).
7906 If omitted or nil, that stands for the selected frame's display. */)
7907 (display)
7908 Lisp_Object display;
7910 struct w32_display_info *dpyinfo = check_x_display_info (display);
7911 Lisp_Object result = Qnil;
7913 if (dpyinfo->has_palette)
7914 result = intern ("pseudo-color");
7915 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
7916 result = intern ("static-grey");
7917 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
7918 result = intern ("static-color");
7919 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
7920 result = intern ("true-color");
7922 return result;
7925 DEFUN ("x-display-save-under", Fx_display_save_under,
7926 Sx_display_save_under, 0, 1, 0,
7927 doc: /* Returns t if DISPLAY supports the save-under feature.
7928 The optional argument DISPLAY specifies which display to ask about.
7929 DISPLAY should be either a frame or a display name (a string).
7930 If omitted or nil, that stands for the selected frame's display. */)
7931 (display)
7932 Lisp_Object display;
7934 return Qnil;
7938 x_pixel_width (f)
7939 register struct frame *f;
7941 return PIXEL_WIDTH (f);
7945 x_pixel_height (f)
7946 register struct frame *f;
7948 return PIXEL_HEIGHT (f);
7952 x_char_width (f)
7953 register struct frame *f;
7955 return FONT_WIDTH (f->output_data.w32->font);
7959 x_char_height (f)
7960 register struct frame *f;
7962 return f->output_data.w32->line_height;
7966 x_screen_planes (f)
7967 register struct frame *f;
7969 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7972 /* Return the display structure for the display named NAME.
7973 Open a new connection if necessary. */
7975 struct w32_display_info *
7976 x_display_info_for_name (name)
7977 Lisp_Object name;
7979 Lisp_Object names;
7980 struct w32_display_info *dpyinfo;
7982 CHECK_STRING (name);
7984 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7985 dpyinfo;
7986 dpyinfo = dpyinfo->next, names = XCDR (names))
7988 Lisp_Object tem;
7989 tem = Fstring_equal (XCAR (XCAR (names)), name);
7990 if (!NILP (tem))
7991 return dpyinfo;
7994 /* Use this general default value to start with. */
7995 Vx_resource_name = Vinvocation_name;
7997 validate_x_resource_name ();
7999 dpyinfo = w32_term_init (name, (unsigned char *)0,
8000 (char *) SDATA (Vx_resource_name));
8002 if (dpyinfo == 0)
8003 error ("Cannot connect to server %s", SDATA (name));
8005 w32_in_use = 1;
8006 XSETFASTINT (Vwindow_system_version, 3);
8008 return dpyinfo;
8011 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
8012 1, 3, 0, doc: /* Open a connection to a server.
8013 DISPLAY is the name of the display to connect to.
8014 Optional second arg XRM-STRING is a string of resources in xrdb format.
8015 If the optional third arg MUST-SUCCEED is non-nil,
8016 terminate Emacs if we can't open the connection. */)
8017 (display, xrm_string, must_succeed)
8018 Lisp_Object display, xrm_string, must_succeed;
8020 unsigned char *xrm_option;
8021 struct w32_display_info *dpyinfo;
8023 /* If initialization has already been done, return now to avoid
8024 overwriting critical parts of one_w32_display_info. */
8025 if (w32_in_use)
8026 return Qnil;
8028 CHECK_STRING (display);
8029 if (! NILP (xrm_string))
8030 CHECK_STRING (xrm_string);
8032 if (! EQ (Vwindow_system, intern ("w32")))
8033 error ("Not using Microsoft Windows");
8035 /* Allow color mapping to be defined externally; first look in user's
8036 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
8038 Lisp_Object color_file;
8039 struct gcpro gcpro1;
8041 color_file = build_string("~/rgb.txt");
8043 GCPRO1 (color_file);
8045 if (NILP (Ffile_readable_p (color_file)))
8046 color_file =
8047 Fexpand_file_name (build_string ("rgb.txt"),
8048 Fsymbol_value (intern ("data-directory")));
8050 Vw32_color_map = Fw32_load_color_file (color_file);
8052 UNGCPRO;
8054 if (NILP (Vw32_color_map))
8055 Vw32_color_map = Fw32_default_color_map ();
8057 if (! NILP (xrm_string))
8058 xrm_option = (unsigned char *) SDATA (xrm_string);
8059 else
8060 xrm_option = (unsigned char *) 0;
8062 /* Use this general default value to start with. */
8063 /* First remove .exe suffix from invocation-name - it looks ugly. */
8065 char basename[ MAX_PATH ], *str;
8067 strcpy (basename, SDATA (Vinvocation_name));
8068 str = strrchr (basename, '.');
8069 if (str) *str = 0;
8070 Vinvocation_name = build_string (basename);
8072 Vx_resource_name = Vinvocation_name;
8074 validate_x_resource_name ();
8076 /* This is what opens the connection and sets x_current_display.
8077 This also initializes many symbols, such as those used for input. */
8078 dpyinfo = w32_term_init (display, xrm_option,
8079 (char *) SDATA (Vx_resource_name));
8081 if (dpyinfo == 0)
8083 if (!NILP (must_succeed))
8084 fatal ("Cannot connect to server %s.\n",
8085 SDATA (display));
8086 else
8087 error ("Cannot connect to server %s", SDATA (display));
8090 w32_in_use = 1;
8092 XSETFASTINT (Vwindow_system_version, 3);
8093 return Qnil;
8096 DEFUN ("x-close-connection", Fx_close_connection,
8097 Sx_close_connection, 1, 1, 0,
8098 doc: /* Close the connection to DISPLAY's server.
8099 For DISPLAY, specify either a frame or a display name (a string).
8100 If DISPLAY is nil, that stands for the selected frame's display. */)
8101 (display)
8102 Lisp_Object display;
8104 struct w32_display_info *dpyinfo = check_x_display_info (display);
8105 int i;
8107 if (dpyinfo->reference_count > 0)
8108 error ("Display still has frames on it");
8110 BLOCK_INPUT;
8111 /* Free the fonts in the font table. */
8112 for (i = 0; i < dpyinfo->n_fonts; i++)
8113 if (dpyinfo->font_table[i].name)
8115 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
8116 xfree (dpyinfo->font_table[i].full_name);
8117 xfree (dpyinfo->font_table[i].name);
8118 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
8120 x_destroy_all_bitmaps (dpyinfo);
8122 x_delete_display (dpyinfo);
8123 UNBLOCK_INPUT;
8125 return Qnil;
8128 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
8129 doc: /* Return the list of display names that Emacs has connections to. */)
8132 Lisp_Object tail, result;
8134 result = Qnil;
8135 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
8136 result = Fcons (XCAR (XCAR (tail)), result);
8138 return result;
8141 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
8142 doc: /* This is a noop on W32 systems. */)
8143 (on, display)
8144 Lisp_Object display, on;
8146 return Qnil;
8150 /***********************************************************************
8151 Image types
8152 ***********************************************************************/
8154 /* Value is the number of elements of vector VECTOR. */
8156 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
8158 /* List of supported image types. Use define_image_type to add new
8159 types. Use lookup_image_type to find a type for a given symbol. */
8161 static struct image_type *image_types;
8163 /* The symbol `image' which is the car of the lists used to represent
8164 images in Lisp. */
8166 extern Lisp_Object Qimage;
8168 /* The symbol `xbm' which is used as the type symbol for XBM images. */
8170 Lisp_Object Qxbm;
8172 /* Keywords. */
8174 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
8175 extern Lisp_Object QCdata, QCtype;
8176 Lisp_Object QCascent, QCmargin, QCrelief;
8177 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
8178 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
8180 /* Other symbols. */
8182 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
8184 /* Time in seconds after which images should be removed from the cache
8185 if not displayed. */
8187 Lisp_Object Vimage_cache_eviction_delay;
8189 /* Function prototypes. */
8191 static void define_image_type P_ ((struct image_type *type));
8192 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
8193 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
8194 static void x_laplace P_ ((struct frame *, struct image *));
8195 static void x_emboss P_ ((struct frame *, struct image *));
8196 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
8197 Lisp_Object));
8200 /* Define a new image type from TYPE. This adds a copy of TYPE to
8201 image_types and adds the symbol *TYPE->type to Vimage_types. */
8203 static void
8204 define_image_type (type)
8205 struct image_type *type;
8207 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
8208 The initialized data segment is read-only. */
8209 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
8210 bcopy (type, p, sizeof *p);
8211 p->next = image_types;
8212 image_types = p;
8213 Vimage_types = Fcons (*p->type, Vimage_types);
8217 /* Look up image type SYMBOL, and return a pointer to its image_type
8218 structure. Value is null if SYMBOL is not a known image type. */
8220 static INLINE struct image_type *
8221 lookup_image_type (symbol)
8222 Lisp_Object symbol;
8224 struct image_type *type;
8226 for (type = image_types; type; type = type->next)
8227 if (EQ (symbol, *type->type))
8228 break;
8230 return type;
8234 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
8235 valid image specification is a list whose car is the symbol
8236 `image', and whose rest is a property list. The property list must
8237 contain a value for key `:type'. That value must be the name of a
8238 supported image type. The rest of the property list depends on the
8239 image type. */
8242 valid_image_p (object)
8243 Lisp_Object object;
8245 int valid_p = 0;
8247 if (CONSP (object) && EQ (XCAR (object), Qimage))
8249 Lisp_Object tem;
8251 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
8252 if (EQ (XCAR (tem), QCtype))
8254 tem = XCDR (tem);
8255 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
8257 struct image_type *type;
8258 type = lookup_image_type (XCAR (tem));
8259 if (type)
8260 valid_p = type->valid_p (object);
8263 break;
8267 return valid_p;
8271 /* Log error message with format string FORMAT and argument ARG.
8272 Signaling an error, e.g. when an image cannot be loaded, is not a
8273 good idea because this would interrupt redisplay, and the error
8274 message display would lead to another redisplay. This function
8275 therefore simply displays a message. */
8277 static void
8278 image_error (format, arg1, arg2)
8279 char *format;
8280 Lisp_Object arg1, arg2;
8282 add_to_log (format, arg1, arg2);
8287 /***********************************************************************
8288 Image specifications
8289 ***********************************************************************/
8291 enum image_value_type
8293 IMAGE_DONT_CHECK_VALUE_TYPE,
8294 IMAGE_STRING_VALUE,
8295 IMAGE_STRING_OR_NIL_VALUE,
8296 IMAGE_SYMBOL_VALUE,
8297 IMAGE_POSITIVE_INTEGER_VALUE,
8298 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
8299 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
8300 IMAGE_ASCENT_VALUE,
8301 IMAGE_INTEGER_VALUE,
8302 IMAGE_FUNCTION_VALUE,
8303 IMAGE_NUMBER_VALUE,
8304 IMAGE_BOOL_VALUE
8307 /* Structure used when parsing image specifications. */
8309 struct image_keyword
8311 /* Name of keyword. */
8312 char *name;
8314 /* The type of value allowed. */
8315 enum image_value_type type;
8317 /* Non-zero means key must be present. */
8318 int mandatory_p;
8320 /* Used to recognize duplicate keywords in a property list. */
8321 int count;
8323 /* The value that was found. */
8324 Lisp_Object value;
8328 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
8329 int, Lisp_Object));
8330 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
8333 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
8334 has the format (image KEYWORD VALUE ...). One of the keyword/
8335 value pairs must be `:type TYPE'. KEYWORDS is a vector of
8336 image_keywords structures of size NKEYWORDS describing other
8337 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
8339 static int
8340 parse_image_spec (spec, keywords, nkeywords, type)
8341 Lisp_Object spec;
8342 struct image_keyword *keywords;
8343 int nkeywords;
8344 Lisp_Object type;
8346 int i;
8347 Lisp_Object plist;
8349 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
8350 return 0;
8352 plist = XCDR (spec);
8353 while (CONSP (plist))
8355 Lisp_Object key, value;
8357 /* First element of a pair must be a symbol. */
8358 key = XCAR (plist);
8359 plist = XCDR (plist);
8360 if (!SYMBOLP (key))
8361 return 0;
8363 /* There must follow a value. */
8364 if (!CONSP (plist))
8365 return 0;
8366 value = XCAR (plist);
8367 plist = XCDR (plist);
8369 /* Find key in KEYWORDS. Error if not found. */
8370 for (i = 0; i < nkeywords; ++i)
8371 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
8372 break;
8374 if (i == nkeywords)
8375 continue;
8377 /* Record that we recognized the keyword. If a keywords
8378 was found more than once, it's an error. */
8379 keywords[i].value = value;
8380 ++keywords[i].count;
8382 if (keywords[i].count > 1)
8383 return 0;
8385 /* Check type of value against allowed type. */
8386 switch (keywords[i].type)
8388 case IMAGE_STRING_VALUE:
8389 if (!STRINGP (value))
8390 return 0;
8391 break;
8393 case IMAGE_STRING_OR_NIL_VALUE:
8394 if (!STRINGP (value) && !NILP (value))
8395 return 0;
8396 break;
8398 case IMAGE_SYMBOL_VALUE:
8399 if (!SYMBOLP (value))
8400 return 0;
8401 break;
8403 case IMAGE_POSITIVE_INTEGER_VALUE:
8404 if (!INTEGERP (value) || XINT (value) <= 0)
8405 return 0;
8406 break;
8408 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
8409 if (INTEGERP (value) && XINT (value) >= 0)
8410 break;
8411 if (CONSP (value)
8412 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
8413 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
8414 break;
8415 return 0;
8417 case IMAGE_ASCENT_VALUE:
8418 if (SYMBOLP (value) && EQ (value, Qcenter))
8419 break;
8420 else if (INTEGERP (value)
8421 && XINT (value) >= 0
8422 && XINT (value) <= 100)
8423 break;
8424 return 0;
8426 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
8427 if (!INTEGERP (value) || XINT (value) < 0)
8428 return 0;
8429 break;
8431 case IMAGE_DONT_CHECK_VALUE_TYPE:
8432 break;
8434 case IMAGE_FUNCTION_VALUE:
8435 value = indirect_function (value);
8436 if (SUBRP (value)
8437 || COMPILEDP (value)
8438 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
8439 break;
8440 return 0;
8442 case IMAGE_NUMBER_VALUE:
8443 if (!INTEGERP (value) && !FLOATP (value))
8444 return 0;
8445 break;
8447 case IMAGE_INTEGER_VALUE:
8448 if (!INTEGERP (value))
8449 return 0;
8450 break;
8452 case IMAGE_BOOL_VALUE:
8453 if (!NILP (value) && !EQ (value, Qt))
8454 return 0;
8455 break;
8457 default:
8458 abort ();
8459 break;
8462 if (EQ (key, QCtype) && !EQ (type, value))
8463 return 0;
8466 /* Check that all mandatory fields are present. */
8467 for (i = 0; i < nkeywords; ++i)
8468 if (keywords[i].mandatory_p && keywords[i].count == 0)
8469 return 0;
8471 return NILP (plist);
8475 /* Return the value of KEY in image specification SPEC. Value is nil
8476 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
8477 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
8479 static Lisp_Object
8480 image_spec_value (spec, key, found)
8481 Lisp_Object spec, key;
8482 int *found;
8484 Lisp_Object tail;
8486 xassert (valid_image_p (spec));
8488 for (tail = XCDR (spec);
8489 CONSP (tail) && CONSP (XCDR (tail));
8490 tail = XCDR (XCDR (tail)))
8492 if (EQ (XCAR (tail), key))
8494 if (found)
8495 *found = 1;
8496 return XCAR (XCDR (tail));
8500 if (found)
8501 *found = 0;
8502 return Qnil;
8506 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
8507 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
8508 PIXELS non-nil means return the size in pixels, otherwise return the
8509 size in canonical character units.
8510 FRAME is the frame on which the image will be displayed. FRAME nil
8511 or omitted means use the selected frame. */)
8512 (spec, pixels, frame)
8513 Lisp_Object spec, pixels, frame;
8515 Lisp_Object size;
8517 size = Qnil;
8518 if (valid_image_p (spec))
8520 struct frame *f = check_x_frame (frame);
8521 int id = lookup_image (f, spec);
8522 struct image *img = IMAGE_FROM_ID (f, id);
8523 int width = img->width + 2 * img->hmargin;
8524 int height = img->height + 2 * img->vmargin;
8526 if (NILP (pixels))
8527 size = Fcons (make_float ((double) width / CANON_X_UNIT (f)),
8528 make_float ((double) height / CANON_Y_UNIT (f)));
8529 else
8530 size = Fcons (make_number (width), make_number (height));
8532 else
8533 error ("Invalid image specification");
8535 return size;
8539 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
8540 doc: /* Return t if image SPEC has a mask bitmap.
8541 FRAME is the frame on which the image will be displayed. FRAME nil
8542 or omitted means use the selected frame. */)
8543 (spec, frame)
8544 Lisp_Object spec, frame;
8546 Lisp_Object mask;
8548 mask = Qnil;
8549 if (valid_image_p (spec))
8551 struct frame *f = check_x_frame (frame);
8552 int id = lookup_image (f, spec);
8553 struct image *img = IMAGE_FROM_ID (f, id);
8554 if (img->mask)
8555 mask = Qt;
8557 else
8558 error ("Invalid image specification");
8560 return mask;
8564 /***********************************************************************
8565 Image type independent image structures
8566 ***********************************************************************/
8568 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
8569 static void free_image P_ ((struct frame *f, struct image *img));
8570 static void x_destroy_x_image P_ ((XImage *));
8573 /* Allocate and return a new image structure for image specification
8574 SPEC. SPEC has a hash value of HASH. */
8576 static struct image *
8577 make_image (spec, hash)
8578 Lisp_Object spec;
8579 unsigned hash;
8581 struct image *img = (struct image *) xmalloc (sizeof *img);
8583 xassert (valid_image_p (spec));
8584 bzero (img, sizeof *img);
8585 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
8586 xassert (img->type != NULL);
8587 img->spec = spec;
8588 img->data.lisp_val = Qnil;
8589 img->ascent = DEFAULT_IMAGE_ASCENT;
8590 img->hash = hash;
8591 return img;
8595 /* Free image IMG which was used on frame F, including its resources. */
8597 static void
8598 free_image (f, img)
8599 struct frame *f;
8600 struct image *img;
8602 if (img)
8604 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8606 /* Remove IMG from the hash table of its cache. */
8607 if (img->prev)
8608 img->prev->next = img->next;
8609 else
8610 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
8612 if (img->next)
8613 img->next->prev = img->prev;
8615 c->images[img->id] = NULL;
8617 /* Free resources, then free IMG. */
8618 img->type->free (f, img);
8619 xfree (img);
8624 /* Prepare image IMG for display on frame F. Must be called before
8625 drawing an image. */
8627 void
8628 prepare_image_for_display (f, img)
8629 struct frame *f;
8630 struct image *img;
8632 EMACS_TIME t;
8634 /* We're about to display IMG, so set its timestamp to `now'. */
8635 EMACS_GET_TIME (t);
8636 img->timestamp = EMACS_SECS (t);
8638 /* If IMG doesn't have a pixmap yet, load it now, using the image
8639 type dependent loader function. */
8640 if (img->pixmap == 0 && !img->load_failed_p)
8641 img->load_failed_p = img->type->load (f, img) == 0;
8645 /* Value is the number of pixels for the ascent of image IMG when
8646 drawn in face FACE. */
8649 image_ascent (img, face)
8650 struct image *img;
8651 struct face *face;
8653 int height = img->height + img->vmargin;
8654 int ascent;
8656 if (img->ascent == CENTERED_IMAGE_ASCENT)
8658 if (face->font)
8659 ascent = height / 2 - (FONT_DESCENT(face->font)
8660 - FONT_BASE(face->font)) / 2;
8661 else
8662 ascent = height / 2;
8664 else
8665 ascent = (int) (height * img->ascent / 100.0);
8667 return ascent;
8672 /* Image background colors. */
8674 /* Find the "best" corner color of a bitmap. XIMG is assumed to a device
8675 context with the bitmap selected. */
8676 static COLORREF
8677 four_corners_best (img_dc, width, height)
8678 HDC img_dc;
8679 unsigned long width, height;
8681 COLORREF corners[4], best;
8682 int i, best_count;
8684 /* Get the colors at the corners of img_dc. */
8685 corners[0] = GetPixel (img_dc, 0, 0);
8686 corners[1] = GetPixel (img_dc, width - 1, 0);
8687 corners[2] = GetPixel (img_dc, width - 1, height - 1);
8688 corners[3] = GetPixel (img_dc, 0, height - 1);
8690 /* Choose the most frequently found color as background. */
8691 for (i = best_count = 0; i < 4; ++i)
8693 int j, n;
8695 for (j = n = 0; j < 4; ++j)
8696 if (corners[i] == corners[j])
8697 ++n;
8699 if (n > best_count)
8700 best = corners[i], best_count = n;
8703 return best;
8706 /* Return the `background' field of IMG. If IMG doesn't have one yet,
8707 it is guessed heuristically. If non-zero, IMG_DC is an existing
8708 device context with the image selected to use for the heuristic. */
8710 unsigned long
8711 image_background (img, f, img_dc)
8712 struct image *img;
8713 struct frame *f;
8714 HDC img_dc;
8716 if (! img->background_valid)
8717 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8719 int free_ximg = !img_dc;
8720 HGDIOBJ prev;
8722 if (free_ximg)
8724 HDC frame_dc = get_frame_dc (f);
8725 img_dc = CreateCompatibleDC (frame_dc);
8726 release_frame_dc (f, frame_dc);
8728 prev = SelectObject (img_dc, img->pixmap);
8731 img->background = four_corners_best (img_dc, img->width, img->height);
8733 if (free_ximg)
8735 SelectObject (img_dc, prev);
8736 DeleteDC (img_dc);
8739 img->background_valid = 1;
8742 return img->background;
8745 /* Return the `background_transparent' field of IMG. If IMG doesn't
8746 have one yet, it is guessed heuristically. If non-zero, MASK is an
8747 existing XImage object to use for the heuristic. */
8750 image_background_transparent (img, f, mask)
8751 struct image *img;
8752 struct frame *f;
8753 HDC mask;
8755 if (! img->background_transparent_valid)
8756 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8758 if (img->mask)
8760 int free_mask = !mask;
8761 HGDIOBJ prev;
8763 if (free_mask)
8765 HDC frame_dc = get_frame_dc (f);
8766 mask = CreateCompatibleDC (frame_dc);
8767 release_frame_dc (f, frame_dc);
8769 prev = SelectObject (mask, img->mask);
8772 img->background_transparent
8773 = !four_corners_best (mask, img->width, img->height);
8775 if (free_mask)
8777 SelectObject (mask, prev);
8778 DeleteDC (mask);
8781 else
8782 img->background_transparent = 0;
8784 img->background_transparent_valid = 1;
8787 return img->background_transparent;
8791 /***********************************************************************
8792 Helper functions for X image types
8793 ***********************************************************************/
8795 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
8796 int, int));
8797 static void x_clear_image P_ ((struct frame *f, struct image *img));
8798 static unsigned long x_alloc_image_color P_ ((struct frame *f,
8799 struct image *img,
8800 Lisp_Object color_name,
8801 unsigned long dflt));
8804 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
8805 free the pixmap if any. MASK_P non-zero means clear the mask
8806 pixmap if any. COLORS_P non-zero means free colors allocated for
8807 the image, if any. */
8809 static void
8810 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
8811 struct frame *f;
8812 struct image *img;
8813 int pixmap_p, mask_p, colors_p;
8815 if (pixmap_p && img->pixmap)
8817 DeleteObject (img->pixmap);
8818 img->pixmap = NULL;
8819 img->background_valid = 0;
8822 if (mask_p && img->mask)
8824 DeleteObject (img->mask);
8825 img->mask = NULL;
8826 img->background_transparent_valid = 0;
8829 if (colors_p && img->ncolors)
8831 #if 0 /* TODO: color table support. */
8832 x_free_colors (f, img->colors, img->ncolors);
8833 #endif
8834 xfree (img->colors);
8835 img->colors = NULL;
8836 img->ncolors = 0;
8840 /* Free X resources of image IMG which is used on frame F. */
8842 static void
8843 x_clear_image (f, img)
8844 struct frame *f;
8845 struct image *img;
8847 if (img->pixmap)
8849 BLOCK_INPUT;
8850 DeleteObject (img->pixmap);
8851 img->pixmap = 0;
8852 UNBLOCK_INPUT;
8855 if (img->ncolors)
8857 #if 0 /* TODO: color table support */
8859 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8861 /* If display has an immutable color map, freeing colors is not
8862 necessary and some servers don't allow it. So don't do it. */
8863 if (class != StaticColor
8864 && class != StaticGray
8865 && class != TrueColor)
8867 Colormap cmap;
8868 BLOCK_INPUT;
8869 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8870 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8871 img->ncolors, 0);
8872 UNBLOCK_INPUT;
8874 #endif
8876 xfree (img->colors);
8877 img->colors = NULL;
8878 img->ncolors = 0;
8883 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8884 cannot be allocated, use DFLT. Add a newly allocated color to
8885 IMG->colors, so that it can be freed again. Value is the pixel
8886 color. */
8888 static unsigned long
8889 x_alloc_image_color (f, img, color_name, dflt)
8890 struct frame *f;
8891 struct image *img;
8892 Lisp_Object color_name;
8893 unsigned long dflt;
8895 XColor color;
8896 unsigned long result;
8898 xassert (STRINGP (color_name));
8900 if (w32_defined_color (f, SDATA (color_name), &color, 1))
8902 /* This isn't called frequently so we get away with simply
8903 reallocating the color vector to the needed size, here. */
8904 ++img->ncolors;
8905 img->colors =
8906 (unsigned long *) xrealloc (img->colors,
8907 img->ncolors * sizeof *img->colors);
8908 img->colors[img->ncolors - 1] = color.pixel;
8909 result = color.pixel;
8911 else
8912 result = dflt;
8913 return result;
8918 /***********************************************************************
8919 Image Cache
8920 ***********************************************************************/
8922 static void cache_image P_ ((struct frame *f, struct image *img));
8923 static void postprocess_image P_ ((struct frame *, struct image *));
8924 static void x_disable_image P_ ((struct frame *, struct image *));
8927 /* Return a new, initialized image cache that is allocated from the
8928 heap. Call free_image_cache to free an image cache. */
8930 struct image_cache *
8931 make_image_cache ()
8933 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8934 int size;
8936 bzero (c, sizeof *c);
8937 c->size = 50;
8938 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8939 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8940 c->buckets = (struct image **) xmalloc (size);
8941 bzero (c->buckets, size);
8942 return c;
8946 /* Free image cache of frame F. Be aware that X frames share images
8947 caches. */
8949 void
8950 free_image_cache (f)
8951 struct frame *f;
8953 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8954 if (c)
8956 int i;
8958 /* Cache should not be referenced by any frame when freed. */
8959 xassert (c->refcount == 0);
8961 for (i = 0; i < c->used; ++i)
8962 free_image (f, c->images[i]);
8963 xfree (c->images);
8964 xfree (c);
8965 xfree (c->buckets);
8966 FRAME_X_IMAGE_CACHE (f) = NULL;
8971 /* Clear image cache of frame F. FORCE_P non-zero means free all
8972 images. FORCE_P zero means clear only images that haven't been
8973 displayed for some time. Should be called from time to time to
8974 reduce the number of loaded images. If image-eviction-seconds is
8975 non-nil, this frees images in the cache which weren't displayed for
8976 at least that many seconds. */
8978 void
8979 clear_image_cache (f, force_p)
8980 struct frame *f;
8981 int force_p;
8983 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8985 if (c && INTEGERP (Vimage_cache_eviction_delay))
8987 EMACS_TIME t;
8988 unsigned long old;
8989 int i, nfreed;
8991 EMACS_GET_TIME (t);
8992 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8994 /* Block input so that we won't be interrupted by a SIGIO
8995 while being in an inconsistent state. */
8996 BLOCK_INPUT;
8998 for (i = nfreed = 0; i < c->used; ++i)
9000 struct image *img = c->images[i];
9001 if (img != NULL
9002 && (force_p || (img->timestamp < old)))
9004 free_image (f, img);
9005 ++nfreed;
9009 /* We may be clearing the image cache because, for example,
9010 Emacs was iconified for a longer period of time. In that
9011 case, current matrices may still contain references to
9012 images freed above. So, clear these matrices. */
9013 if (nfreed)
9015 Lisp_Object tail, frame;
9017 FOR_EACH_FRAME (tail, frame)
9019 struct frame *f = XFRAME (frame);
9020 if (FRAME_W32_P (f)
9021 && FRAME_X_IMAGE_CACHE (f) == c)
9022 clear_current_matrices (f);
9025 ++windows_or_buffers_changed;
9028 UNBLOCK_INPUT;
9033 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
9034 0, 1, 0,
9035 doc: /* Clear the image cache of FRAME.
9036 FRAME nil or omitted means use the selected frame.
9037 FRAME t means clear the image caches of all frames. */)
9038 (frame)
9039 Lisp_Object frame;
9041 if (EQ (frame, Qt))
9043 Lisp_Object tail;
9045 FOR_EACH_FRAME (tail, frame)
9046 if (FRAME_W32_P (XFRAME (frame)))
9047 clear_image_cache (XFRAME (frame), 1);
9049 else
9050 clear_image_cache (check_x_frame (frame), 1);
9052 return Qnil;
9056 /* Compute masks and transform image IMG on frame F, as specified
9057 by the image's specification, */
9059 static void
9060 postprocess_image (f, img)
9061 struct frame *f;
9062 struct image *img;
9064 /* Manipulation of the image's mask. */
9065 if (img->pixmap)
9067 Lisp_Object conversion, spec;
9068 Lisp_Object mask;
9070 spec = img->spec;
9072 /* `:heuristic-mask t'
9073 `:mask heuristic'
9074 means build a mask heuristically.
9075 `:heuristic-mask (R G B)'
9076 `:mask (heuristic (R G B))'
9077 means build a mask from color (R G B) in the
9078 image.
9079 `:mask nil'
9080 means remove a mask, if any. */
9082 mask = image_spec_value (spec, QCheuristic_mask, NULL);
9083 if (!NILP (mask))
9084 x_build_heuristic_mask (f, img, mask);
9085 else
9087 int found_p;
9089 mask = image_spec_value (spec, QCmask, &found_p);
9091 if (EQ (mask, Qheuristic))
9092 x_build_heuristic_mask (f, img, Qt);
9093 else if (CONSP (mask)
9094 && EQ (XCAR (mask), Qheuristic))
9096 if (CONSP (XCDR (mask)))
9097 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
9098 else
9099 x_build_heuristic_mask (f, img, XCDR (mask));
9101 else if (NILP (mask) && found_p && img->mask)
9103 DeleteObject (img->mask);
9104 img->mask = NULL;
9109 /* Should we apply an image transformation algorithm? */
9110 conversion = image_spec_value (spec, QCconversion, NULL);
9111 if (EQ (conversion, Qdisabled))
9112 x_disable_image (f, img);
9113 else if (EQ (conversion, Qlaplace))
9114 x_laplace (f, img);
9115 else if (EQ (conversion, Qemboss))
9116 x_emboss (f, img);
9117 else if (CONSP (conversion)
9118 && EQ (XCAR (conversion), Qedge_detection))
9120 Lisp_Object tem;
9121 tem = XCDR (conversion);
9122 if (CONSP (tem))
9123 x_edge_detection (f, img,
9124 Fplist_get (tem, QCmatrix),
9125 Fplist_get (tem, QCcolor_adjustment));
9131 /* Return the id of image with Lisp specification SPEC on frame F.
9132 SPEC must be a valid Lisp image specification (see valid_image_p). */
9135 lookup_image (f, spec)
9136 struct frame *f;
9137 Lisp_Object spec;
9139 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9140 struct image *img;
9141 int i;
9142 unsigned hash;
9143 struct gcpro gcpro1;
9144 EMACS_TIME now;
9146 /* F must be a window-system frame, and SPEC must be a valid image
9147 specification. */
9148 xassert (FRAME_WINDOW_P (f));
9149 xassert (valid_image_p (spec));
9151 GCPRO1 (spec);
9153 /* Look up SPEC in the hash table of the image cache. */
9154 hash = sxhash (spec, 0);
9155 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
9157 for (img = c->buckets[i]; img; img = img->next)
9158 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
9159 break;
9161 /* If not found, create a new image and cache it. */
9162 if (img == NULL)
9164 extern Lisp_Object Qpostscript;
9166 BLOCK_INPUT;
9167 img = make_image (spec, hash);
9168 cache_image (f, img);
9169 img->load_failed_p = img->type->load (f, img) == 0;
9171 /* If we can't load the image, and we don't have a width and
9172 height, use some arbitrary width and height so that we can
9173 draw a rectangle for it. */
9174 if (img->load_failed_p)
9176 Lisp_Object value;
9178 value = image_spec_value (spec, QCwidth, NULL);
9179 img->width = (INTEGERP (value)
9180 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
9181 value = image_spec_value (spec, QCheight, NULL);
9182 img->height = (INTEGERP (value)
9183 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
9185 else
9187 /* Handle image type independent image attributes
9188 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
9189 `:background COLOR'. */
9190 Lisp_Object ascent, margin, relief, bg;
9192 ascent = image_spec_value (spec, QCascent, NULL);
9193 if (INTEGERP (ascent))
9194 img->ascent = XFASTINT (ascent);
9195 else if (EQ (ascent, Qcenter))
9196 img->ascent = CENTERED_IMAGE_ASCENT;
9198 margin = image_spec_value (spec, QCmargin, NULL);
9199 if (INTEGERP (margin) && XINT (margin) >= 0)
9200 img->vmargin = img->hmargin = XFASTINT (margin);
9201 else if (CONSP (margin) && INTEGERP (XCAR (margin))
9202 && INTEGERP (XCDR (margin)))
9204 if (XINT (XCAR (margin)) > 0)
9205 img->hmargin = XFASTINT (XCAR (margin));
9206 if (XINT (XCDR (margin)) > 0)
9207 img->vmargin = XFASTINT (XCDR (margin));
9210 relief = image_spec_value (spec, QCrelief, NULL);
9211 if (INTEGERP (relief))
9213 img->relief = XINT (relief);
9214 img->hmargin += abs (img->relief);
9215 img->vmargin += abs (img->relief);
9218 if (! img->background_valid)
9220 bg = image_spec_value (img->spec, QCbackground, NULL);
9221 if (!NILP (bg))
9223 img->background
9224 = x_alloc_image_color (f, img, bg,
9225 FRAME_BACKGROUND_PIXEL (f));
9226 img->background_valid = 1;
9230 /* Do image transformations and compute masks, unless we
9231 don't have the image yet. */
9232 if (!EQ (*img->type->type, Qpostscript))
9233 postprocess_image (f, img);
9236 UNBLOCK_INPUT;
9237 xassert (!interrupt_input_blocked);
9240 /* We're using IMG, so set its timestamp to `now'. */
9241 EMACS_GET_TIME (now);
9242 img->timestamp = EMACS_SECS (now);
9244 UNGCPRO;
9246 /* Value is the image id. */
9247 return img->id;
9251 /* Cache image IMG in the image cache of frame F. */
9253 static void
9254 cache_image (f, img)
9255 struct frame *f;
9256 struct image *img;
9258 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9259 int i;
9261 /* Find a free slot in c->images. */
9262 for (i = 0; i < c->used; ++i)
9263 if (c->images[i] == NULL)
9264 break;
9266 /* If no free slot found, maybe enlarge c->images. */
9267 if (i == c->used && c->used == c->size)
9269 c->size *= 2;
9270 c->images = (struct image **) xrealloc (c->images,
9271 c->size * sizeof *c->images);
9274 /* Add IMG to c->images, and assign IMG an id. */
9275 c->images[i] = img;
9276 img->id = i;
9277 if (i == c->used)
9278 ++c->used;
9280 /* Add IMG to the cache's hash table. */
9281 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
9282 img->next = c->buckets[i];
9283 if (img->next)
9284 img->next->prev = img;
9285 img->prev = NULL;
9286 c->buckets[i] = img;
9290 /* Call FN on every image in the image cache of frame F. Used to mark
9291 Lisp Objects in the image cache. */
9293 void
9294 forall_images_in_image_cache (f, fn)
9295 struct frame *f;
9296 void (*fn) P_ ((struct image *img));
9298 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
9300 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9301 if (c)
9303 int i;
9304 for (i = 0; i < c->used; ++i)
9305 if (c->images[i])
9306 fn (c->images[i]);
9313 /***********************************************************************
9314 W32 support code
9315 ***********************************************************************/
9317 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
9318 XImage **, Pixmap *));
9319 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
9322 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
9323 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
9324 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
9325 via xmalloc. DEPTH of zero signifies a 24 bit image, otherwise
9326 DEPTH should indicate the bit depth of the image. Print error
9327 messages via image_error if an error occurs. Value is non-zero if
9328 successful. */
9330 static int
9331 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
9332 struct frame *f;
9333 int width, height, depth;
9334 XImage **ximg;
9335 Pixmap *pixmap;
9337 BITMAPINFOHEADER *header;
9338 HDC hdc;
9339 int scanline_width_bits;
9340 int remainder;
9341 int palette_colors = 0;
9343 if (depth == 0)
9344 depth = 24;
9346 if (depth != 1 && depth != 4 && depth != 8
9347 && depth != 16 && depth != 24 && depth != 32)
9349 image_error ("Invalid image bit depth specified", Qnil, Qnil);
9350 return 0;
9353 scanline_width_bits = width * depth;
9354 remainder = scanline_width_bits % 32;
9356 if (remainder)
9357 scanline_width_bits += 32 - remainder;
9359 /* Bitmaps with a depth less than 16 need a palette. */
9360 /* BITMAPINFO structure already contains the first RGBQUAD. */
9361 if (depth < 16)
9362 palette_colors = 1 << depth - 1;
9364 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
9365 if (*ximg == NULL)
9367 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
9368 return 0;
9371 header = &((*ximg)->info.bmiHeader);
9372 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
9373 header->biSize = sizeof (*header);
9374 header->biWidth = width;
9375 header->biHeight = -height; /* negative indicates a top-down bitmap. */
9376 header->biPlanes = 1;
9377 header->biBitCount = depth;
9378 header->biCompression = BI_RGB;
9379 header->biClrUsed = palette_colors;
9381 /* TODO: fill in palette. */
9382 if (depth == 1)
9384 (*ximg)->info.bmiColors[0].rgbBlue = 0;
9385 (*ximg)->info.bmiColors[0].rgbGreen = 0;
9386 (*ximg)->info.bmiColors[0].rgbRed = 0;
9387 (*ximg)->info.bmiColors[0].rgbReserved = 0;
9388 (*ximg)->info.bmiColors[1].rgbBlue = 255;
9389 (*ximg)->info.bmiColors[1].rgbGreen = 255;
9390 (*ximg)->info.bmiColors[1].rgbRed = 255;
9391 (*ximg)->info.bmiColors[1].rgbReserved = 0;
9394 hdc = get_frame_dc (f);
9396 /* Create a DIBSection and raster array for the bitmap,
9397 and store its handle in *pixmap. */
9398 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
9399 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
9400 &((*ximg)->data), NULL, 0);
9402 /* Realize display palette and garbage all frames. */
9403 release_frame_dc (f, hdc);
9405 if (*pixmap == NULL)
9407 DWORD err = GetLastError();
9408 Lisp_Object errcode;
9409 /* All system errors are < 10000, so the following is safe. */
9410 XSETINT (errcode, (int) err);
9411 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
9412 x_destroy_x_image (*ximg);
9413 return 0;
9416 return 1;
9420 /* Destroy XImage XIMG. Free XIMG->data. */
9422 static void
9423 x_destroy_x_image (ximg)
9424 XImage *ximg;
9426 xassert (interrupt_input_blocked);
9427 if (ximg)
9429 /* Data will be freed by DestroyObject. */
9430 ximg->data = NULL;
9431 xfree (ximg);
9436 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
9437 are width and height of both the image and pixmap. */
9439 static void
9440 x_put_x_image (f, ximg, pixmap, width, height)
9441 struct frame *f;
9442 XImage *ximg;
9443 Pixmap pixmap;
9445 #if 0 /* I don't think this is necessary looking at where it is used. */
9446 HDC hdc = get_frame_dc (f);
9447 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
9448 release_frame_dc (f, hdc);
9449 #endif
9453 /***********************************************************************
9454 File Handling
9455 ***********************************************************************/
9457 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
9458 static char *slurp_file P_ ((char *, int *));
9461 /* Find image file FILE. Look in data-directory, then
9462 x-bitmap-file-path. Value is the full name of the file found, or
9463 nil if not found. */
9465 static Lisp_Object
9466 x_find_image_file (file)
9467 Lisp_Object file;
9469 Lisp_Object file_found, search_path;
9470 struct gcpro gcpro1, gcpro2;
9471 int fd;
9473 file_found = Qnil;
9474 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
9475 GCPRO2 (file_found, search_path);
9477 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
9478 fd = openp (search_path, file, Qnil, &file_found, Qnil);
9480 if (fd == -1)
9481 file_found = Qnil;
9482 else
9483 close (fd);
9485 UNGCPRO;
9486 return file_found;
9490 /* Read FILE into memory. Value is a pointer to a buffer allocated
9491 with xmalloc holding FILE's contents. Value is null if an error
9492 occurred. *SIZE is set to the size of the file. */
9494 static char *
9495 slurp_file (file, size)
9496 char *file;
9497 int *size;
9499 FILE *fp = NULL;
9500 char *buf = NULL;
9501 struct stat st;
9503 if (stat (file, &st) == 0
9504 && (fp = fopen (file, "r")) != NULL
9505 && (buf = (char *) xmalloc (st.st_size),
9506 fread (buf, 1, st.st_size, fp) == st.st_size))
9508 *size = st.st_size;
9509 fclose (fp);
9511 else
9513 if (fp)
9514 fclose (fp);
9515 if (buf)
9517 xfree (buf);
9518 buf = NULL;
9522 return buf;
9527 /***********************************************************************
9528 XBM images
9529 ***********************************************************************/
9531 static int xbm_scan P_ ((char **, char *, char *, int *));
9532 static int xbm_load P_ ((struct frame *f, struct image *img));
9533 static int xbm_load_image P_ ((struct frame *f, struct image *img,
9534 char *, char *));
9535 static int xbm_image_p P_ ((Lisp_Object object));
9536 static int xbm_read_bitmap_data P_ ((char *, char *, int *, int *,
9537 unsigned char **));
9538 static int xbm_file_p P_ ((Lisp_Object));
9541 /* Indices of image specification fields in xbm_format, below. */
9543 enum xbm_keyword_index
9545 XBM_TYPE,
9546 XBM_FILE,
9547 XBM_WIDTH,
9548 XBM_HEIGHT,
9549 XBM_DATA,
9550 XBM_FOREGROUND,
9551 XBM_BACKGROUND,
9552 XBM_ASCENT,
9553 XBM_MARGIN,
9554 XBM_RELIEF,
9555 XBM_ALGORITHM,
9556 XBM_HEURISTIC_MASK,
9557 XBM_MASK,
9558 XBM_LAST
9561 /* Vector of image_keyword structures describing the format
9562 of valid XBM image specifications. */
9564 static struct image_keyword xbm_format[XBM_LAST] =
9566 {":type", IMAGE_SYMBOL_VALUE, 1},
9567 {":file", IMAGE_STRING_VALUE, 0},
9568 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9569 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9570 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9571 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
9572 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
9573 {":ascent", IMAGE_ASCENT_VALUE, 0},
9574 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9575 {":relief", IMAGE_INTEGER_VALUE, 0},
9576 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9577 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9578 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9581 /* Structure describing the image type XBM. */
9583 static struct image_type xbm_type =
9585 &Qxbm,
9586 xbm_image_p,
9587 xbm_load,
9588 x_clear_image,
9589 NULL
9592 /* Tokens returned from xbm_scan. */
9594 enum xbm_token
9596 XBM_TK_IDENT = 256,
9597 XBM_TK_NUMBER
9601 /* Return non-zero if OBJECT is a valid XBM-type image specification.
9602 A valid specification is a list starting with the symbol `image'
9603 The rest of the list is a property list which must contain an
9604 entry `:type xbm..
9606 If the specification specifies a file to load, it must contain
9607 an entry `:file FILENAME' where FILENAME is a string.
9609 If the specification is for a bitmap loaded from memory it must
9610 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
9611 WIDTH and HEIGHT are integers > 0. DATA may be:
9613 1. a string large enough to hold the bitmap data, i.e. it must
9614 have a size >= (WIDTH + 7) / 8 * HEIGHT
9616 2. a bool-vector of size >= WIDTH * HEIGHT
9618 3. a vector of strings or bool-vectors, one for each line of the
9619 bitmap.
9621 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
9622 may not be specified in this case because they are defined in the
9623 XBM file.
9625 Both the file and data forms may contain the additional entries
9626 `:background COLOR' and `:foreground COLOR'. If not present,
9627 foreground and background of the frame on which the image is
9628 displayed is used. */
9630 static int
9631 xbm_image_p (object)
9632 Lisp_Object object;
9634 struct image_keyword kw[XBM_LAST];
9636 bcopy (xbm_format, kw, sizeof kw);
9637 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
9638 return 0;
9640 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
9642 if (kw[XBM_FILE].count)
9644 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
9645 return 0;
9647 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
9649 /* In-memory XBM file. */
9650 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
9651 return 0;
9653 else
9655 Lisp_Object data;
9656 int width, height;
9658 /* Entries for `:width', `:height' and `:data' must be present. */
9659 if (!kw[XBM_WIDTH].count
9660 || !kw[XBM_HEIGHT].count
9661 || !kw[XBM_DATA].count)
9662 return 0;
9664 data = kw[XBM_DATA].value;
9665 width = XFASTINT (kw[XBM_WIDTH].value);
9666 height = XFASTINT (kw[XBM_HEIGHT].value);
9668 /* Check type of data, and width and height against contents of
9669 data. */
9670 if (VECTORP (data))
9672 int i;
9674 /* Number of elements of the vector must be >= height. */
9675 if (XVECTOR (data)->size < height)
9676 return 0;
9678 /* Each string or bool-vector in data must be large enough
9679 for one line of the image. */
9680 for (i = 0; i < height; ++i)
9682 Lisp_Object elt = XVECTOR (data)->contents[i];
9684 if (STRINGP (elt))
9686 if (SCHARS (elt)
9687 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
9688 return 0;
9690 else if (BOOL_VECTOR_P (elt))
9692 if (XBOOL_VECTOR (elt)->size < width)
9693 return 0;
9695 else
9696 return 0;
9699 else if (STRINGP (data))
9701 if (SCHARS (data)
9702 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
9703 return 0;
9705 else if (BOOL_VECTOR_P (data))
9707 if (XBOOL_VECTOR (data)->size < width * height)
9708 return 0;
9710 else
9711 return 0;
9714 return 1;
9718 /* Scan a bitmap file. FP is the stream to read from. Value is
9719 either an enumerator from enum xbm_token, or a character for a
9720 single-character token, or 0 at end of file. If scanning an
9721 identifier, store the lexeme of the identifier in SVAL. If
9722 scanning a number, store its value in *IVAL. */
9724 static int
9725 xbm_scan (s, end, sval, ival)
9726 char **s, *end;
9727 char *sval;
9728 int *ival;
9730 int c;
9732 loop:
9734 /* Skip white space. */
9735 while (*s < end && (c = *(*s)++, isspace (c)))
9738 if (*s >= end)
9739 c = 0;
9740 else if (isdigit (c))
9742 int value = 0, digit;
9744 if (c == '0' && *s < end)
9746 c = *(*s)++;
9747 if (c == 'x' || c == 'X')
9749 while (*s < end)
9751 c = *(*s)++;
9752 if (isdigit (c))
9753 digit = c - '0';
9754 else if (c >= 'a' && c <= 'f')
9755 digit = c - 'a' + 10;
9756 else if (c >= 'A' && c <= 'F')
9757 digit = c - 'A' + 10;
9758 else
9759 break;
9760 value = 16 * value + digit;
9763 else if (isdigit (c))
9765 value = c - '0';
9766 while (*s < end
9767 && (c = *(*s)++, isdigit (c)))
9768 value = 8 * value + c - '0';
9771 else
9773 value = c - '0';
9774 while (*s < end
9775 && (c = *(*s)++, isdigit (c)))
9776 value = 10 * value + c - '0';
9779 if (*s < end)
9780 *s = *s - 1;
9781 *ival = value;
9782 c = XBM_TK_NUMBER;
9784 else if (isalpha (c) || c == '_')
9786 *sval++ = c;
9787 while (*s < end
9788 && (c = *(*s)++, (isalnum (c) || c == '_')))
9789 *sval++ = c;
9790 *sval = 0;
9791 if (*s < end)
9792 *s = *s - 1;
9793 c = XBM_TK_IDENT;
9795 else if (c == '/' && **s == '*')
9797 /* C-style comment. */
9798 ++*s;
9799 while (**s && (**s != '*' || *(*s + 1) != '/'))
9800 ++*s;
9801 if (**s)
9803 *s += 2;
9804 goto loop;
9808 return c;
9812 /* XBM bits seem to be backward within bytes compared with how
9813 Windows does things. */
9814 static unsigned char reflect_byte (unsigned char orig)
9816 int i;
9817 unsigned char reflected = 0x00;
9818 for (i = 0; i < 8; i++)
9820 if (orig & (0x01 << i))
9821 reflected |= 0x80 >> i;
9823 return reflected;
9827 /* Create a Windows bitmap from X bitmap data. */
9828 static HBITMAP
9829 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
9831 int i, j, w1, w2;
9832 char *bits, *p;
9833 HBITMAP bmp;
9835 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
9836 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
9837 bits = (char *) xmalloc (height * w2);
9838 bzero (bits, height * w2);
9839 for (i = 0; i < height; i++)
9841 p = bits + i*w2;
9842 for (j = 0; j < w1; j++)
9843 *p++ = reflect_byte(*data++);
9845 bmp = CreateBitmap (width, height, 1, 1, bits);
9846 xfree (bits);
9848 return bmp;
9852 /* Replacement for XReadBitmapFileData which isn't available under old
9853 X versions. CONTENTS is a pointer to a buffer to parse; END is the
9854 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
9855 the image. Return in *DATA the bitmap data allocated with xmalloc.
9856 Value is non-zero if successful. DATA null means just test if
9857 CONTENTS looks like an in-memory XBM file. */
9859 static int
9860 xbm_read_bitmap_data (contents, end, width, height, data)
9861 char *contents, *end;
9862 int *width, *height;
9863 unsigned char **data;
9865 char *s = contents;
9866 char buffer[BUFSIZ];
9867 int padding_p = 0;
9868 int v10 = 0;
9869 int bytes_per_line, i, nbytes;
9870 unsigned char *p;
9871 int value;
9872 int LA1;
9874 #define match() \
9875 LA1 = xbm_scan (&s, end, buffer, &value)
9877 #define expect(TOKEN) \
9878 if (LA1 != (TOKEN)) \
9879 goto failure; \
9880 else \
9881 match ()
9883 #define expect_ident(IDENT) \
9884 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
9885 match (); \
9886 else \
9887 goto failure
9889 *width = *height = -1;
9890 if (data)
9891 *data = NULL;
9892 LA1 = xbm_scan (&s, end, buffer, &value);
9894 /* Parse defines for width, height and hot-spots. */
9895 while (LA1 == '#')
9897 match ();
9898 expect_ident ("define");
9899 expect (XBM_TK_IDENT);
9901 if (LA1 == XBM_TK_NUMBER);
9903 char *p = strrchr (buffer, '_');
9904 p = p ? p + 1 : buffer;
9905 if (strcmp (p, "width") == 0)
9906 *width = value;
9907 else if (strcmp (p, "height") == 0)
9908 *height = value;
9910 expect (XBM_TK_NUMBER);
9913 if (*width < 0 || *height < 0)
9914 goto failure;
9915 else if (data == NULL)
9916 goto success;
9918 /* Parse bits. Must start with `static'. */
9919 expect_ident ("static");
9920 if (LA1 == XBM_TK_IDENT)
9922 if (strcmp (buffer, "unsigned") == 0)
9924 match ();
9925 expect_ident ("char");
9927 else if (strcmp (buffer, "short") == 0)
9929 match ();
9930 v10 = 1;
9931 if (*width % 16 && *width % 16 < 9)
9932 padding_p = 1;
9934 else if (strcmp (buffer, "char") == 0)
9935 match ();
9936 else
9937 goto failure;
9939 else
9940 goto failure;
9942 expect (XBM_TK_IDENT);
9943 expect ('[');
9944 expect (']');
9945 expect ('=');
9946 expect ('{');
9948 bytes_per_line = (*width + 7) / 8 + padding_p;
9949 nbytes = bytes_per_line * *height;
9950 p = *data = (char *) xmalloc (nbytes);
9952 if (v10)
9954 for (i = 0; i < nbytes; i += 2)
9956 int val = value;
9957 expect (XBM_TK_NUMBER);
9959 *p++ = ~ val;
9960 if (!padding_p || ((i + 2) % bytes_per_line))
9961 *p++ = ~ (value >> 8);
9963 if (LA1 == ',' || LA1 == '}')
9964 match ();
9965 else
9966 goto failure;
9969 else
9971 for (i = 0; i < nbytes; ++i)
9973 int val = value;
9974 expect (XBM_TK_NUMBER);
9976 *p++ = ~ val;
9978 if (LA1 == ',' || LA1 == '}')
9979 match ();
9980 else
9981 goto failure;
9985 success:
9986 return 1;
9988 failure:
9990 if (data && *data)
9992 xfree (*data);
9993 *data = NULL;
9995 return 0;
9997 #undef match
9998 #undef expect
9999 #undef expect_ident
10002 static void convert_mono_to_color_image (f, img, foreground, background)
10003 struct frame *f;
10004 struct image *img;
10005 COLORREF foreground, background;
10007 HDC hdc, old_img_dc, new_img_dc;
10008 HGDIOBJ old_prev, new_prev;
10009 HBITMAP new_pixmap;
10011 hdc = get_frame_dc (f);
10012 old_img_dc = CreateCompatibleDC (hdc);
10013 new_img_dc = CreateCompatibleDC (hdc);
10014 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
10015 release_frame_dc (f, hdc);
10016 old_prev = SelectObject (old_img_dc, img->pixmap);
10017 new_prev = SelectObject (new_img_dc, new_pixmap);
10018 SetTextColor (new_img_dc, foreground);
10019 SetBkColor (new_img_dc, background);
10021 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
10022 0, 0, SRCCOPY);
10024 SelectObject (old_img_dc, old_prev);
10025 SelectObject (new_img_dc, new_prev);
10026 DeleteDC (old_img_dc);
10027 DeleteDC (new_img_dc);
10028 DeleteObject (img->pixmap);
10029 if (new_pixmap == 0)
10030 fprintf (stderr, "Failed to convert image to color.\n");
10031 else
10032 img->pixmap = new_pixmap;
10035 /* Load XBM image IMG which will be displayed on frame F from buffer
10036 CONTENTS. END is the end of the buffer. Value is non-zero if
10037 successful. */
10039 static int
10040 xbm_load_image (f, img, contents, end)
10041 struct frame *f;
10042 struct image *img;
10043 char *contents, *end;
10045 int rc;
10046 unsigned char *data;
10047 int success_p = 0;
10049 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
10050 if (rc)
10052 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
10053 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
10054 int non_default_colors = 0;
10055 Lisp_Object value;
10057 xassert (img->width > 0 && img->height > 0);
10059 /* Get foreground and background colors, maybe allocate colors. */
10060 value = image_spec_value (img->spec, QCforeground, NULL);
10061 if (!NILP (value))
10063 foreground = x_alloc_image_color (f, img, value, foreground);
10064 non_default_colors = 1;
10066 value = image_spec_value (img->spec, QCbackground, NULL);
10067 if (!NILP (value))
10069 background = x_alloc_image_color (f, img, value, background);
10070 img->background = background;
10071 img->background_valid = 1;
10072 non_default_colors = 1;
10074 img->pixmap
10075 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
10077 /* If colors were specified, transfer the bitmap to a color one. */
10078 if (non_default_colors)
10079 convert_mono_to_color_image (f, img, foreground, background);
10081 xfree (data);
10083 if (img->pixmap == 0)
10085 x_clear_image (f, img);
10086 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
10088 else
10089 success_p = 1;
10091 else
10092 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10094 return success_p;
10098 /* Value is non-zero if DATA looks like an in-memory XBM file. */
10100 static int
10101 xbm_file_p (data)
10102 Lisp_Object data;
10104 int w, h;
10105 return (STRINGP (data)
10106 && xbm_read_bitmap_data (SDATA (data),
10107 (SDATA (data)
10108 + SBYTES (data)),
10109 &w, &h, NULL));
10113 /* Fill image IMG which is used on frame F with pixmap data. Value is
10114 non-zero if successful. */
10116 static int
10117 xbm_load (f, img)
10118 struct frame *f;
10119 struct image *img;
10121 int success_p = 0;
10122 Lisp_Object file_name;
10124 xassert (xbm_image_p (img->spec));
10126 /* If IMG->spec specifies a file name, create a non-file spec from it. */
10127 file_name = image_spec_value (img->spec, QCfile, NULL);
10128 if (STRINGP (file_name))
10130 Lisp_Object file;
10131 char *contents;
10132 int size;
10133 struct gcpro gcpro1;
10135 file = x_find_image_file (file_name);
10136 GCPRO1 (file);
10137 if (!STRINGP (file))
10139 image_error ("Cannot find image file `%s'", file_name, Qnil);
10140 UNGCPRO;
10141 return 0;
10144 contents = slurp_file (SDATA (file), &size);
10145 if (contents == NULL)
10147 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10148 UNGCPRO;
10149 return 0;
10152 success_p = xbm_load_image (f, img, contents, contents + size);
10153 UNGCPRO;
10155 else
10157 struct image_keyword fmt[XBM_LAST];
10158 Lisp_Object data;
10159 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
10160 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
10161 int non_default_colors = 0;
10162 char *bits;
10163 int parsed_p;
10164 int in_memory_file_p = 0;
10166 /* See if data looks like an in-memory XBM file. */
10167 data = image_spec_value (img->spec, QCdata, NULL);
10168 in_memory_file_p = xbm_file_p (data);
10170 /* Parse the image specification. */
10171 bcopy (xbm_format, fmt, sizeof fmt);
10172 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
10173 xassert (parsed_p);
10175 /* Get specified width, and height. */
10176 if (!in_memory_file_p)
10178 img->width = XFASTINT (fmt[XBM_WIDTH].value);
10179 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
10180 xassert (img->width > 0 && img->height > 0);
10183 /* Get foreground and background colors, maybe allocate colors. */
10184 if (fmt[XBM_FOREGROUND].count
10185 && STRINGP (fmt[XBM_FOREGROUND].value))
10187 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
10188 foreground);
10189 non_default_colors = 1;
10192 if (fmt[XBM_BACKGROUND].count
10193 && STRINGP (fmt[XBM_BACKGROUND].value))
10195 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
10196 background);
10197 non_default_colors = 1;
10200 if (in_memory_file_p)
10201 success_p = xbm_load_image (f, img, SDATA (data),
10202 (SDATA (data)
10203 + SBYTES (data)));
10204 else
10206 if (VECTORP (data))
10208 int i;
10209 char *p;
10210 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
10212 p = bits = (char *) alloca (nbytes * img->height);
10213 for (i = 0; i < img->height; ++i, p += nbytes)
10215 Lisp_Object line = XVECTOR (data)->contents[i];
10216 if (STRINGP (line))
10217 bcopy (SDATA (line), p, nbytes);
10218 else
10219 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
10222 else if (STRINGP (data))
10223 bits = SDATA (data);
10224 else
10225 bits = XBOOL_VECTOR (data)->data;
10227 /* Create the pixmap. */
10228 img->pixmap
10229 = w32_create_pixmap_from_bitmap_data (img->width, img->height,
10230 bits);
10232 /* If colors were specified, transfer the bitmap to a color one. */
10233 if (non_default_colors)
10234 convert_mono_to_color_image (f, img, foreground, background);
10236 if (img->pixmap)
10237 success_p = 1;
10238 else
10240 image_error ("Unable to create pixmap for XBM image `%s'",
10241 img->spec, Qnil);
10242 x_clear_image (f, img);
10247 return success_p;
10252 /***********************************************************************
10253 XPM images
10254 ***********************************************************************/
10256 #if HAVE_XPM
10258 static int xpm_image_p P_ ((Lisp_Object object));
10259 static int xpm_load P_ ((struct frame *f, struct image *img));
10260 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
10262 #include "X11/xpm.h"
10264 /* The symbol `xpm' identifying XPM-format images. */
10266 Lisp_Object Qxpm;
10268 /* Indices of image specification fields in xpm_format, below. */
10270 enum xpm_keyword_index
10272 XPM_TYPE,
10273 XPM_FILE,
10274 XPM_DATA,
10275 XPM_ASCENT,
10276 XPM_MARGIN,
10277 XPM_RELIEF,
10278 XPM_ALGORITHM,
10279 XPM_HEURISTIC_MASK,
10280 XPM_MASK,
10281 XPM_COLOR_SYMBOLS,
10282 XPM_BACKGROUND,
10283 XPM_LAST
10286 /* Vector of image_keyword structures describing the format
10287 of valid XPM image specifications. */
10289 static struct image_keyword xpm_format[XPM_LAST] =
10291 {":type", IMAGE_SYMBOL_VALUE, 1},
10292 {":file", IMAGE_STRING_VALUE, 0},
10293 {":data", IMAGE_STRING_VALUE, 0},
10294 {":ascent", IMAGE_ASCENT_VALUE, 0},
10295 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10296 {":relief", IMAGE_INTEGER_VALUE, 0},
10297 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10298 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10299 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10300 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10301 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
10304 /* Structure describing the image type XPM. */
10306 static struct image_type xpm_type =
10308 &Qxpm,
10309 xpm_image_p,
10310 xpm_load,
10311 x_clear_image,
10312 NULL
10316 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
10317 for XPM images. Such a list must consist of conses whose car and
10318 cdr are strings. */
10320 static int
10321 xpm_valid_color_symbols_p (color_symbols)
10322 Lisp_Object color_symbols;
10324 while (CONSP (color_symbols))
10326 Lisp_Object sym = XCAR (color_symbols);
10327 if (!CONSP (sym)
10328 || !STRINGP (XCAR (sym))
10329 || !STRINGP (XCDR (sym)))
10330 break;
10331 color_symbols = XCDR (color_symbols);
10334 return NILP (color_symbols);
10338 /* Value is non-zero if OBJECT is a valid XPM image specification. */
10340 static int
10341 xpm_image_p (object)
10342 Lisp_Object object;
10344 struct image_keyword fmt[XPM_LAST];
10345 bcopy (xpm_format, fmt, sizeof fmt);
10346 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
10347 /* Either `:file' or `:data' must be present. */
10348 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
10349 /* Either no `:color-symbols' or it's a list of conses
10350 whose car and cdr are strings. */
10351 && (fmt[XPM_COLOR_SYMBOLS].count == 0
10352 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
10356 /* Load image IMG which will be displayed on frame F. Value is
10357 non-zero if successful. */
10359 static int
10360 xpm_load (f, img)
10361 struct frame *f;
10362 struct image *img;
10364 int rc, i;
10365 XpmAttributes attrs;
10366 Lisp_Object specified_file, color_symbols;
10368 /* Configure the XPM lib. Use the visual of frame F. Allocate
10369 close colors. Return colors allocated. */
10370 bzero (&attrs, sizeof attrs);
10371 attrs.visual = FRAME_X_VISUAL (f);
10372 attrs.colormap = FRAME_X_COLORMAP (f);
10373 attrs.valuemask |= XpmVisual;
10374 attrs.valuemask |= XpmColormap;
10375 attrs.valuemask |= XpmReturnAllocPixels;
10376 #ifdef XpmAllocCloseColors
10377 attrs.alloc_close_colors = 1;
10378 attrs.valuemask |= XpmAllocCloseColors;
10379 #else
10380 attrs.closeness = 600;
10381 attrs.valuemask |= XpmCloseness;
10382 #endif
10384 /* If image specification contains symbolic color definitions, add
10385 these to `attrs'. */
10386 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
10387 if (CONSP (color_symbols))
10389 Lisp_Object tail;
10390 XpmColorSymbol *xpm_syms;
10391 int i, size;
10393 attrs.valuemask |= XpmColorSymbols;
10395 /* Count number of symbols. */
10396 attrs.numsymbols = 0;
10397 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
10398 ++attrs.numsymbols;
10400 /* Allocate an XpmColorSymbol array. */
10401 size = attrs.numsymbols * sizeof *xpm_syms;
10402 xpm_syms = (XpmColorSymbol *) alloca (size);
10403 bzero (xpm_syms, size);
10404 attrs.colorsymbols = xpm_syms;
10406 /* Fill the color symbol array. */
10407 for (tail = color_symbols, i = 0;
10408 CONSP (tail);
10409 ++i, tail = XCDR (tail))
10411 Lisp_Object name = XCAR (XCAR (tail));
10412 Lisp_Object color = XCDR (XCAR (tail));
10413 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
10414 strcpy (xpm_syms[i].name, SDATA (name));
10415 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
10416 strcpy (xpm_syms[i].value, SDATA (color));
10420 /* Create a pixmap for the image, either from a file, or from a
10421 string buffer containing data in the same format as an XPM file. */
10422 BLOCK_INPUT;
10423 specified_file = image_spec_value (img->spec, QCfile, NULL);
10424 if (STRINGP (specified_file))
10426 Lisp_Object file = x_find_image_file (specified_file);
10427 if (!STRINGP (file))
10429 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10430 UNBLOCK_INPUT;
10431 return 0;
10434 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
10435 SDATA (file), &img->pixmap, &img->mask,
10436 &attrs);
10438 else
10440 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
10441 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
10442 SDATA (buffer),
10443 &img->pixmap, &img->mask,
10444 &attrs);
10446 UNBLOCK_INPUT;
10448 if (rc == XpmSuccess)
10450 /* Remember allocated colors. */
10451 img->ncolors = attrs.nalloc_pixels;
10452 img->colors = (unsigned long *) xmalloc (img->ncolors
10453 * sizeof *img->colors);
10454 for (i = 0; i < attrs.nalloc_pixels; ++i)
10455 img->colors[i] = attrs.alloc_pixels[i];
10457 img->width = attrs.width;
10458 img->height = attrs.height;
10459 xassert (img->width > 0 && img->height > 0);
10461 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
10462 BLOCK_INPUT;
10463 XpmFreeAttributes (&attrs);
10464 UNBLOCK_INPUT;
10466 else
10468 switch (rc)
10470 case XpmOpenFailed:
10471 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
10472 break;
10474 case XpmFileInvalid:
10475 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
10476 break;
10478 case XpmNoMemory:
10479 image_error ("Out of memory (%s)", img->spec, Qnil);
10480 break;
10482 case XpmColorFailed:
10483 image_error ("Color allocation error (%s)", img->spec, Qnil);
10484 break;
10486 default:
10487 image_error ("Unknown error (%s)", img->spec, Qnil);
10488 break;
10492 return rc == XpmSuccess;
10495 #endif /* HAVE_XPM != 0 */
10498 #if 0 /* TODO : Color tables on W32. */
10499 /***********************************************************************
10500 Color table
10501 ***********************************************************************/
10503 /* An entry in the color table mapping an RGB color to a pixel color. */
10505 struct ct_color
10507 int r, g, b;
10508 unsigned long pixel;
10510 /* Next in color table collision list. */
10511 struct ct_color *next;
10514 /* The bucket vector size to use. Must be prime. */
10516 #define CT_SIZE 101
10518 /* Value is a hash of the RGB color given by R, G, and B. */
10520 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
10522 /* The color hash table. */
10524 struct ct_color **ct_table;
10526 /* Number of entries in the color table. */
10528 int ct_colors_allocated;
10530 /* Function prototypes. */
10532 static void init_color_table P_ ((void));
10533 static void free_color_table P_ ((void));
10534 static unsigned long *colors_in_color_table P_ ((int *n));
10535 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
10536 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
10539 /* Initialize the color table. */
10541 static void
10542 init_color_table ()
10544 int size = CT_SIZE * sizeof (*ct_table);
10545 ct_table = (struct ct_color **) xmalloc (size);
10546 bzero (ct_table, size);
10547 ct_colors_allocated = 0;
10551 /* Free memory associated with the color table. */
10553 static void
10554 free_color_table ()
10556 int i;
10557 struct ct_color *p, *next;
10559 for (i = 0; i < CT_SIZE; ++i)
10560 for (p = ct_table[i]; p; p = next)
10562 next = p->next;
10563 xfree (p);
10566 xfree (ct_table);
10567 ct_table = NULL;
10571 /* Value is a pixel color for RGB color R, G, B on frame F. If an
10572 entry for that color already is in the color table, return the
10573 pixel color of that entry. Otherwise, allocate a new color for R,
10574 G, B, and make an entry in the color table. */
10576 static unsigned long
10577 lookup_rgb_color (f, r, g, b)
10578 struct frame *f;
10579 int r, g, b;
10581 unsigned hash = CT_HASH_RGB (r, g, b);
10582 int i = hash % CT_SIZE;
10583 struct ct_color *p;
10585 for (p = ct_table[i]; p; p = p->next)
10586 if (p->r == r && p->g == g && p->b == b)
10587 break;
10589 if (p == NULL)
10591 COLORREF color;
10592 Colormap cmap;
10593 int rc;
10595 color = PALETTERGB (r, g, b);
10597 ++ct_colors_allocated;
10599 p = (struct ct_color *) xmalloc (sizeof *p);
10600 p->r = r;
10601 p->g = g;
10602 p->b = b;
10603 p->pixel = color;
10604 p->next = ct_table[i];
10605 ct_table[i] = p;
10608 return p->pixel;
10612 /* Look up pixel color PIXEL which is used on frame F in the color
10613 table. If not already present, allocate it. Value is PIXEL. */
10615 static unsigned long
10616 lookup_pixel_color (f, pixel)
10617 struct frame *f;
10618 unsigned long pixel;
10620 int i = pixel % CT_SIZE;
10621 struct ct_color *p;
10623 for (p = ct_table[i]; p; p = p->next)
10624 if (p->pixel == pixel)
10625 break;
10627 if (p == NULL)
10629 XColor color;
10630 Colormap cmap;
10631 int rc;
10633 BLOCK_INPUT;
10635 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10636 color.pixel = pixel;
10637 XQueryColor (NULL, cmap, &color);
10638 rc = x_alloc_nearest_color (f, cmap, &color);
10639 UNBLOCK_INPUT;
10641 if (rc)
10643 ++ct_colors_allocated;
10645 p = (struct ct_color *) xmalloc (sizeof *p);
10646 p->r = color.red;
10647 p->g = color.green;
10648 p->b = color.blue;
10649 p->pixel = pixel;
10650 p->next = ct_table[i];
10651 ct_table[i] = p;
10653 else
10654 return FRAME_FOREGROUND_PIXEL (f);
10656 return p->pixel;
10660 /* Value is a vector of all pixel colors contained in the color table,
10661 allocated via xmalloc. Set *N to the number of colors. */
10663 static unsigned long *
10664 colors_in_color_table (n)
10665 int *n;
10667 int i, j;
10668 struct ct_color *p;
10669 unsigned long *colors;
10671 if (ct_colors_allocated == 0)
10673 *n = 0;
10674 colors = NULL;
10676 else
10678 colors = (unsigned long *) xmalloc (ct_colors_allocated
10679 * sizeof *colors);
10680 *n = ct_colors_allocated;
10682 for (i = j = 0; i < CT_SIZE; ++i)
10683 for (p = ct_table[i]; p; p = p->next)
10684 colors[j++] = p->pixel;
10687 return colors;
10690 #endif /* TODO */
10693 /***********************************************************************
10694 Algorithms
10695 ***********************************************************************/
10696 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
10697 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
10698 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
10699 static void XPutPixel (XImage *, int, int, COLORREF);
10701 /* Non-zero means draw a cross on images having `:conversion
10702 disabled'. */
10704 int cross_disabled_images;
10706 /* Edge detection matrices for different edge-detection
10707 strategies. */
10709 static int emboss_matrix[9] = {
10710 /* x - 1 x x + 1 */
10711 2, -1, 0, /* y - 1 */
10712 -1, 0, 1, /* y */
10713 0, 1, -2 /* y + 1 */
10716 static int laplace_matrix[9] = {
10717 /* x - 1 x x + 1 */
10718 1, 0, 0, /* y - 1 */
10719 0, 0, 0, /* y */
10720 0, 0, -1 /* y + 1 */
10723 /* Value is the intensity of the color whose red/green/blue values
10724 are R, G, and B. */
10726 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
10729 /* On frame F, return an array of XColor structures describing image
10730 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
10731 non-zero means also fill the red/green/blue members of the XColor
10732 structures. Value is a pointer to the array of XColors structures,
10733 allocated with xmalloc; it must be freed by the caller. */
10735 static XColor *
10736 x_to_xcolors (f, img, rgb_p)
10737 struct frame *f;
10738 struct image *img;
10739 int rgb_p;
10741 int x, y;
10742 XColor *colors, *p;
10743 HDC hdc, bmpdc;
10744 HGDIOBJ prev;
10746 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
10748 /* Load the image into a memory device context. */
10749 hdc = get_frame_dc (f);
10750 bmpdc = CreateCompatibleDC (hdc);
10751 release_frame_dc (f, hdc);
10752 prev = SelectObject (bmpdc, img->pixmap);
10754 /* Fill the `pixel' members of the XColor array. I wished there
10755 were an easy and portable way to circumvent XGetPixel. */
10756 p = colors;
10757 for (y = 0; y < img->height; ++y)
10759 XColor *row = p;
10761 for (x = 0; x < img->width; ++x, ++p)
10763 /* TODO: palette support needed here? */
10764 p->pixel = GetPixel (bmpdc, x, y);
10766 if (rgb_p)
10768 p->red = 256 * GetRValue (p->pixel);
10769 p->green = 256 * GetGValue (p->pixel);
10770 p->blue = 256 * GetBValue (p->pixel);
10775 SelectObject (bmpdc, prev);
10776 DeleteDC (bmpdc);
10778 return colors;
10781 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
10782 created with CreateDIBSection, with the pointer to the bit values
10783 stored in ximg->data. */
10785 static void XPutPixel (ximg, x, y, color)
10786 XImage * ximg;
10787 int x, y;
10788 COLORREF color;
10790 int width = ximg->info.bmiHeader.biWidth;
10791 int height = ximg->info.bmiHeader.biHeight;
10792 int rowbytes = width * 3;
10793 unsigned char * pixel;
10795 /* Don't support putting pixels in images with palettes. */
10796 xassert (ximg->info.bmiHeader.biBitCount == 24);
10798 /* Ensure scanlines are aligned on 4 byte boundaries. */
10799 if (rowbytes % 4)
10800 rowbytes += 4 - (rowbytes % 4);
10802 pixel = ximg->data + y * rowbytes + x * 3;
10803 /* Windows bitmaps are in BGR order. */
10804 *pixel = GetBValue (color);
10805 *(pixel + 1) = GetGValue (color);
10806 *(pixel + 2) = GetRValue (color);
10810 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
10811 RGB members are set. F is the frame on which this all happens.
10812 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
10814 static void
10815 x_from_xcolors (f, img, colors)
10816 struct frame *f;
10817 struct image *img;
10818 XColor *colors;
10820 int x, y;
10821 XImage *oimg;
10822 Pixmap pixmap;
10823 XColor *p;
10824 #if 0 /* TODO: color tables. */
10825 init_color_table ();
10826 #endif
10827 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
10828 &oimg, &pixmap);
10829 p = colors;
10830 for (y = 0; y < img->height; ++y)
10831 for (x = 0; x < img->width; ++x, ++p)
10833 unsigned long pixel;
10834 #if 0 /* TODO: color tables. */
10835 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
10836 #else
10837 pixel = PALETTERGB (p->red / 256, p->green / 256, p->blue / 256);
10838 #endif
10839 XPutPixel (oimg, x, y, pixel);
10842 xfree (colors);
10843 x_clear_image_1 (f, img, 1, 0, 1);
10845 x_put_x_image (f, oimg, pixmap, img->width, img->height);
10846 x_destroy_x_image (oimg);
10847 img->pixmap = pixmap;
10848 #if 0 /* TODO: color tables. */
10849 img->colors = colors_in_color_table (&img->ncolors);
10850 free_color_table ();
10851 #endif
10855 /* On frame F, perform edge-detection on image IMG.
10857 MATRIX is a nine-element array specifying the transformation
10858 matrix. See emboss_matrix for an example.
10860 COLOR_ADJUST is a color adjustment added to each pixel of the
10861 outgoing image. */
10863 static void
10864 x_detect_edges (f, img, matrix, color_adjust)
10865 struct frame *f;
10866 struct image *img;
10867 int matrix[9], color_adjust;
10869 XColor *colors = x_to_xcolors (f, img, 1);
10870 XColor *new, *p;
10871 int x, y, i, sum;
10873 for (i = sum = 0; i < 9; ++i)
10874 sum += abs (matrix[i]);
10876 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
10878 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
10880 for (y = 0; y < img->height; ++y)
10882 p = COLOR (new, 0, y);
10883 p->red = p->green = p->blue = 0xffff/2;
10884 p = COLOR (new, img->width - 1, y);
10885 p->red = p->green = p->blue = 0xffff/2;
10888 for (x = 1; x < img->width - 1; ++x)
10890 p = COLOR (new, x, 0);
10891 p->red = p->green = p->blue = 0xffff/2;
10892 p = COLOR (new, x, img->height - 1);
10893 p->red = p->green = p->blue = 0xffff/2;
10896 for (y = 1; y < img->height - 1; ++y)
10898 p = COLOR (new, 1, y);
10900 for (x = 1; x < img->width - 1; ++x, ++p)
10902 int r, g, b, y1, x1;
10904 r = g = b = i = 0;
10905 for (y1 = y - 1; y1 < y + 2; ++y1)
10906 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
10907 if (matrix[i])
10909 XColor *t = COLOR (colors, x1, y1);
10910 r += matrix[i] * t->red;
10911 g += matrix[i] * t->green;
10912 b += matrix[i] * t->blue;
10915 r = (r / sum + color_adjust) & 0xffff;
10916 g = (g / sum + color_adjust) & 0xffff;
10917 b = (b / sum + color_adjust) & 0xffff;
10918 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
10922 xfree (colors);
10923 x_from_xcolors (f, img, new);
10925 #undef COLOR
10929 /* Perform the pre-defined `emboss' edge-detection on image IMG
10930 on frame F. */
10932 static void
10933 x_emboss (f, img)
10934 struct frame *f;
10935 struct image *img;
10937 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
10941 /* Transform image IMG which is used on frame F with a Laplace
10942 edge-detection algorithm. The result is an image that can be used
10943 to draw disabled buttons, for example. */
10945 static void
10946 x_laplace (f, img)
10947 struct frame *f;
10948 struct image *img;
10950 x_detect_edges (f, img, laplace_matrix, 45000);
10954 /* Perform edge-detection on image IMG on frame F, with specified
10955 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
10957 MATRIX must be either
10959 - a list of at least 9 numbers in row-major form
10960 - a vector of at least 9 numbers
10962 COLOR_ADJUST nil means use a default; otherwise it must be a
10963 number. */
10965 static void
10966 x_edge_detection (f, img, matrix, color_adjust)
10967 struct frame *f;
10968 struct image *img;
10969 Lisp_Object matrix, color_adjust;
10971 int i = 0;
10972 int trans[9];
10974 if (CONSP (matrix))
10976 for (i = 0;
10977 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
10978 ++i, matrix = XCDR (matrix))
10979 trans[i] = XFLOATINT (XCAR (matrix));
10981 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
10983 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
10984 trans[i] = XFLOATINT (AREF (matrix, i));
10987 if (NILP (color_adjust))
10988 color_adjust = make_number (0xffff / 2);
10990 if (i == 9 && NUMBERP (color_adjust))
10991 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
10995 /* Transform image IMG on frame F so that it looks disabled. */
10997 static void
10998 x_disable_image (f, img)
10999 struct frame *f;
11000 struct image *img;
11002 struct w32_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
11004 if (dpyinfo->n_planes * dpyinfo->n_cbits >= 2)
11006 /* Color (or grayscale). Convert to gray, and equalize. Just
11007 drawing such images with a stipple can look very odd, so
11008 we're using this method instead. */
11009 XColor *colors = x_to_xcolors (f, img, 1);
11010 XColor *p, *end;
11011 const int h = 15000;
11012 const int l = 30000;
11014 for (p = colors, end = colors + img->width * img->height;
11015 p < end;
11016 ++p)
11018 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
11019 int i2 = (0xffff - h - l) * i / 0xffff + l;
11020 p->red = p->green = p->blue = i2;
11023 x_from_xcolors (f, img, colors);
11026 /* Draw a cross over the disabled image, if we must or if we
11027 should. */
11028 if (dpyinfo->n_planes * dpyinfo->n_cbits < 2 || cross_disabled_images)
11030 HDC hdc, bmpdc;
11031 HGDIOBJ prev;
11033 hdc = get_frame_dc (f);
11034 bmpdc = CreateCompatibleDC (hdc);
11035 release_frame_dc (f, hdc);
11037 prev = SelectObject (bmpdc, img->pixmap);
11039 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
11040 MoveToEx (bmpdc, 0, 0, NULL);
11041 LineTo (bmpdc, img->width - 1, img->height - 1);
11042 MoveToEx (bmpdc, 0, img->height - 1, NULL);
11043 LineTo (bmpdc, img->width - 1, 0);
11045 if (img->mask)
11047 SelectObject (bmpdc, img->mask);
11048 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
11049 MoveToEx (bmpdc, 0, 0, NULL);
11050 LineTo (bmpdc, img->width - 1, img->height - 1);
11051 MoveToEx (bmpdc, 0, img->height - 1, NULL);
11052 LineTo (bmpdc, img->width - 1, 0);
11054 SelectObject (bmpdc, prev);
11055 DeleteDC (bmpdc);
11060 /* Build a mask for image IMG which is used on frame F. FILE is the
11061 name of an image file, for error messages. HOW determines how to
11062 determine the background color of IMG. If it is a list '(R G B)',
11063 with R, G, and B being integers >= 0, take that as the color of the
11064 background. Otherwise, determine the background color of IMG
11065 heuristically. Value is non-zero if successful. */
11067 static int
11068 x_build_heuristic_mask (f, img, how)
11069 struct frame *f;
11070 struct image *img;
11071 Lisp_Object how;
11073 HDC img_dc, frame_dc;
11074 HGDIOBJ prev;
11075 char *mask_img;
11076 int x, y, rc, use_img_background;
11077 unsigned long bg = 0;
11078 int row_width;
11080 if (img->mask)
11082 DeleteObject (img->mask);
11083 img->mask = NULL;
11084 img->background_transparent_valid = 0;
11087 /* Create the bit array serving as mask. */
11088 row_width = (img->width + 7) / 8;
11089 mask_img = xmalloc (row_width * img->height);
11090 bzero (mask_img, row_width * img->height);
11092 /* Create a memory device context for IMG->pixmap. */
11093 frame_dc = get_frame_dc (f);
11094 img_dc = CreateCompatibleDC (frame_dc);
11095 release_frame_dc (f, frame_dc);
11096 prev = SelectObject (img_dc, img->pixmap);
11098 /* Determine the background color of img_dc. If HOW is `(R G B)'
11099 take that as color. Otherwise, use the image's background color. */
11100 use_img_background = 1;
11102 if (CONSP (how))
11104 int rgb[3], i;
11106 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
11108 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
11109 how = XCDR (how);
11112 if (i == 3 && NILP (how))
11114 char color_name[30];
11115 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
11116 bg = x_alloc_image_color (f, img, build_string (color_name), 0)
11117 & 0x00ffffff; /* Filter out palette info. */
11118 use_img_background = 0;
11122 if (use_img_background)
11123 bg = four_corners_best (img_dc, img->width, img->height);
11125 /* Set all bits in mask_img to 1 whose color in ximg is different
11126 from the background color bg. */
11127 for (y = 0; y < img->height; ++y)
11128 for (x = 0; x < img->width; ++x)
11130 COLORREF p = GetPixel (img_dc, x, y);
11131 if (p != bg)
11132 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
11135 /* Create the mask image. */
11136 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
11137 mask_img);
11139 /* Fill in the background_transparent field while we have the mask handy. */
11140 SelectObject (img_dc, img->mask);
11142 image_background_transparent (img, f, img_dc);
11144 /* Put mask_img into img->mask. */
11145 x_destroy_x_image (mask_img);
11146 SelectObject (img_dc, prev);
11147 DeleteDC (img_dc);
11149 return 1;
11153 /***********************************************************************
11154 PBM (mono, gray, color)
11155 ***********************************************************************/
11157 static int pbm_image_p P_ ((Lisp_Object object));
11158 static int pbm_load P_ ((struct frame *f, struct image *img));
11159 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
11161 /* The symbol `pbm' identifying images of this type. */
11163 Lisp_Object Qpbm;
11165 /* Indices of image specification fields in gs_format, below. */
11167 enum pbm_keyword_index
11169 PBM_TYPE,
11170 PBM_FILE,
11171 PBM_DATA,
11172 PBM_ASCENT,
11173 PBM_MARGIN,
11174 PBM_RELIEF,
11175 PBM_ALGORITHM,
11176 PBM_HEURISTIC_MASK,
11177 PBM_MASK,
11178 PBM_FOREGROUND,
11179 PBM_BACKGROUND,
11180 PBM_LAST
11183 /* Vector of image_keyword structures describing the format
11184 of valid user-defined image specifications. */
11186 static struct image_keyword pbm_format[PBM_LAST] =
11188 {":type", IMAGE_SYMBOL_VALUE, 1},
11189 {":file", IMAGE_STRING_VALUE, 0},
11190 {":data", IMAGE_STRING_VALUE, 0},
11191 {":ascent", IMAGE_ASCENT_VALUE, 0},
11192 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11193 {":relief", IMAGE_INTEGER_VALUE, 0},
11194 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11195 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11196 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11197 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
11198 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11201 /* Structure describing the image type `pbm'. */
11203 static struct image_type pbm_type =
11205 &Qpbm,
11206 pbm_image_p,
11207 pbm_load,
11208 x_clear_image,
11209 NULL
11213 /* Return non-zero if OBJECT is a valid PBM image specification. */
11215 static int
11216 pbm_image_p (object)
11217 Lisp_Object object;
11219 struct image_keyword fmt[PBM_LAST];
11221 bcopy (pbm_format, fmt, sizeof fmt);
11223 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
11224 return 0;
11226 /* Must specify either :data or :file. */
11227 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
11231 /* Scan a decimal number from *S and return it. Advance *S while
11232 reading the number. END is the end of the string. Value is -1 at
11233 end of input. */
11235 static int
11236 pbm_scan_number (s, end)
11237 unsigned char **s, *end;
11239 int c, val = -1;
11241 while (*s < end)
11243 /* Skip white-space. */
11244 while (*s < end && (c = *(*s)++, isspace (c)))
11247 if (c == '#')
11249 /* Skip comment to end of line. */
11250 while (*s < end && (c = *(*s)++, c != '\n'))
11253 else if (isdigit (c))
11255 /* Read decimal number. */
11256 val = c - '0';
11257 while (*s < end && (c = *(*s)++, isdigit (c)))
11258 val = 10 * val + c - '0';
11259 break;
11261 else
11262 break;
11265 return val;
11269 /* Read FILE into memory. Value is a pointer to a buffer allocated
11270 with xmalloc holding FILE's contents. Value is null if an error
11271 occurred. *SIZE is set to the size of the file. */
11273 static char *
11274 pbm_read_file (file, size)
11275 Lisp_Object file;
11276 int *size;
11278 FILE *fp = NULL;
11279 char *buf = NULL;
11280 struct stat st;
11282 if (stat (SDATA (file), &st) == 0
11283 && (fp = fopen (SDATA (file), "r")) != NULL
11284 && (buf = (char *) xmalloc (st.st_size),
11285 fread (buf, 1, st.st_size, fp) == st.st_size))
11287 *size = st.st_size;
11288 fclose (fp);
11290 else
11292 if (fp)
11293 fclose (fp);
11294 if (buf)
11296 xfree (buf);
11297 buf = NULL;
11301 return buf;
11305 /* Load PBM image IMG for use on frame F. */
11307 static int
11308 pbm_load (f, img)
11309 struct frame *f;
11310 struct image *img;
11312 int raw_p, x, y;
11313 int width, height, max_color_idx = 0;
11314 XImage *ximg;
11315 Lisp_Object file, specified_file;
11316 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
11317 struct gcpro gcpro1;
11318 unsigned char *contents = NULL;
11319 unsigned char *end, *p;
11320 int size;
11322 specified_file = image_spec_value (img->spec, QCfile, NULL);
11323 file = Qnil;
11324 GCPRO1 (file);
11326 if (STRINGP (specified_file))
11328 file = x_find_image_file (specified_file);
11329 if (!STRINGP (file))
11331 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11332 UNGCPRO;
11333 return 0;
11336 contents = slurp_file (SDATA (file), &size);
11337 if (contents == NULL)
11339 image_error ("Error reading `%s'", file, Qnil);
11340 UNGCPRO;
11341 return 0;
11344 p = contents;
11345 end = contents + size;
11347 else
11349 Lisp_Object data;
11350 data = image_spec_value (img->spec, QCdata, NULL);
11351 p = SDATA (data);
11352 end = p + SBYTES (data);
11355 /* Check magic number. */
11356 if (end - p < 2 || *p++ != 'P')
11358 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11359 error:
11360 xfree (contents);
11361 UNGCPRO;
11362 return 0;
11365 switch (*p++)
11367 case '1':
11368 raw_p = 0, type = PBM_MONO;
11369 break;
11371 case '2':
11372 raw_p = 0, type = PBM_GRAY;
11373 break;
11375 case '3':
11376 raw_p = 0, type = PBM_COLOR;
11377 break;
11379 case '4':
11380 raw_p = 1, type = PBM_MONO;
11381 break;
11383 case '5':
11384 raw_p = 1, type = PBM_GRAY;
11385 break;
11387 case '6':
11388 raw_p = 1, type = PBM_COLOR;
11389 break;
11391 default:
11392 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11393 goto error;
11396 /* Read width, height, maximum color-component. Characters
11397 starting with `#' up to the end of a line are ignored. */
11398 width = pbm_scan_number (&p, end);
11399 height = pbm_scan_number (&p, end);
11401 if (type != PBM_MONO)
11403 max_color_idx = pbm_scan_number (&p, end);
11404 if (raw_p && max_color_idx > 255)
11405 max_color_idx = 255;
11408 if (width < 0
11409 || height < 0
11410 || (type != PBM_MONO && max_color_idx < 0))
11411 goto error;
11413 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11414 goto error;
11416 #if 0 /* TODO: color tables. */
11417 /* Initialize the color hash table. */
11418 init_color_table ();
11419 #endif
11421 if (type == PBM_MONO)
11423 int c = 0, g;
11424 struct image_keyword fmt[PBM_LAST];
11425 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
11426 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
11428 /* Parse the image specification. */
11429 bcopy (pbm_format, fmt, sizeof fmt);
11430 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
11432 /* Get foreground and background colors, maybe allocate colors. */
11433 if (fmt[PBM_FOREGROUND].count
11434 && STRINGP (fmt[PBM_FOREGROUND].value))
11435 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
11436 if (fmt[PBM_BACKGROUND].count
11437 && STRINGP (fmt[PBM_BACKGROUND].value))
11439 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
11440 img->background = bg;
11441 img->background_valid = 1;
11444 for (y = 0; y < height; ++y)
11445 for (x = 0; x < width; ++x)
11447 if (raw_p)
11449 if ((x & 7) == 0)
11450 c = *p++;
11451 g = c & 0x80;
11452 c <<= 1;
11454 else
11455 g = pbm_scan_number (&p, end);
11457 XPutPixel (ximg, x, y, g ? fg : bg);
11460 else
11462 for (y = 0; y < height; ++y)
11463 for (x = 0; x < width; ++x)
11465 int r, g, b;
11467 if (type == PBM_GRAY)
11468 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
11469 else if (raw_p)
11471 r = *p++;
11472 g = *p++;
11473 b = *p++;
11475 else
11477 r = pbm_scan_number (&p, end);
11478 g = pbm_scan_number (&p, end);
11479 b = pbm_scan_number (&p, end);
11482 if (r < 0 || g < 0 || b < 0)
11484 x_destroy_x_image (ximg);
11485 image_error ("Invalid pixel value in image `%s'",
11486 img->spec, Qnil);
11487 goto error;
11490 /* RGB values are now in the range 0..max_color_idx.
11491 Scale this to the range 0..0xff supported by W32. */
11492 r = (int) ((double) r * 255 / max_color_idx);
11493 g = (int) ((double) g * 255 / max_color_idx);
11494 b = (int) ((double) b * 255 / max_color_idx);
11495 XPutPixel (ximg, x, y,
11496 #if 0 /* TODO: color tables. */
11497 lookup_rgb_color (f, r, g, b));
11498 #else
11499 PALETTERGB (r, g, b));
11500 #endif
11504 #if 0 /* TODO: color tables. */
11505 /* Store in IMG->colors the colors allocated for the image, and
11506 free the color table. */
11507 img->colors = colors_in_color_table (&img->ncolors);
11508 free_color_table ();
11509 #endif
11510 /* Maybe fill in the background field while we have ximg handy. */
11511 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11512 IMAGE_BACKGROUND (img, f, ximg);
11514 /* Put the image into a pixmap. */
11515 x_put_x_image (f, ximg, img->pixmap, width, height);
11516 x_destroy_x_image (ximg);
11518 img->width = width;
11519 img->height = height;
11521 UNGCPRO;
11522 xfree (contents);
11523 return 1;
11527 /***********************************************************************
11529 ***********************************************************************/
11531 #if HAVE_PNG
11533 #include <png.h>
11535 /* Function prototypes. */
11537 static int png_image_p P_ ((Lisp_Object object));
11538 static int png_load P_ ((struct frame *f, struct image *img));
11540 /* The symbol `png' identifying images of this type. */
11542 Lisp_Object Qpng;
11544 /* Indices of image specification fields in png_format, below. */
11546 enum png_keyword_index
11548 PNG_TYPE,
11549 PNG_DATA,
11550 PNG_FILE,
11551 PNG_ASCENT,
11552 PNG_MARGIN,
11553 PNG_RELIEF,
11554 PNG_ALGORITHM,
11555 PNG_HEURISTIC_MASK,
11556 PNG_MASK,
11557 PNG_BACKGROUND,
11558 PNG_LAST
11561 /* Vector of image_keyword structures describing the format
11562 of valid user-defined image specifications. */
11564 static struct image_keyword png_format[PNG_LAST] =
11566 {":type", IMAGE_SYMBOL_VALUE, 1},
11567 {":data", IMAGE_STRING_VALUE, 0},
11568 {":file", IMAGE_STRING_VALUE, 0},
11569 {":ascent", IMAGE_ASCENT_VALUE, 0},
11570 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11571 {":relief", IMAGE_INTEGER_VALUE, 0},
11572 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11573 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11574 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11575 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11578 /* Structure describing the image type `png'. */
11580 static struct image_type png_type =
11582 &Qpng,
11583 png_image_p,
11584 png_load,
11585 x_clear_image,
11586 NULL
11590 /* Return non-zero if OBJECT is a valid PNG image specification. */
11592 static int
11593 png_image_p (object)
11594 Lisp_Object object;
11596 struct image_keyword fmt[PNG_LAST];
11597 bcopy (png_format, fmt, sizeof fmt);
11599 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
11600 return 0;
11602 /* Must specify either the :data or :file keyword. */
11603 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
11607 /* Error and warning handlers installed when the PNG library
11608 is initialized. */
11610 static void
11611 my_png_error (png_ptr, msg)
11612 png_struct *png_ptr;
11613 char *msg;
11615 xassert (png_ptr != NULL);
11616 image_error ("PNG error: %s", build_string (msg), Qnil);
11617 longjmp (png_ptr->jmpbuf, 1);
11621 static void
11622 my_png_warning (png_ptr, msg)
11623 png_struct *png_ptr;
11624 char *msg;
11626 xassert (png_ptr != NULL);
11627 image_error ("PNG warning: %s", build_string (msg), Qnil);
11630 /* Memory source for PNG decoding. */
11632 struct png_memory_storage
11634 unsigned char *bytes; /* The data */
11635 size_t len; /* How big is it? */
11636 int index; /* Where are we? */
11640 /* Function set as reader function when reading PNG image from memory.
11641 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
11642 bytes from the input to DATA. */
11644 static void
11645 png_read_from_memory (png_ptr, data, length)
11646 png_structp png_ptr;
11647 png_bytep data;
11648 png_size_t length;
11650 struct png_memory_storage *tbr
11651 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
11653 if (length > tbr->len - tbr->index)
11654 png_error (png_ptr, "Read error");
11656 bcopy (tbr->bytes + tbr->index, data, length);
11657 tbr->index = tbr->index + length;
11660 /* Load PNG image IMG for use on frame F. Value is non-zero if
11661 successful. */
11663 static int
11664 png_load (f, img)
11665 struct frame *f;
11666 struct image *img;
11668 Lisp_Object file, specified_file;
11669 Lisp_Object specified_data;
11670 int x, y, i;
11671 XImage *ximg, *mask_img = NULL;
11672 struct gcpro gcpro1;
11673 png_struct *png_ptr = NULL;
11674 png_info *info_ptr = NULL, *end_info = NULL;
11675 FILE *volatile fp = NULL;
11676 png_byte sig[8];
11677 png_byte *volatile pixels = NULL;
11678 png_byte **volatile rows = NULL;
11679 png_uint_32 width, height;
11680 int bit_depth, color_type, interlace_type;
11681 png_byte channels;
11682 png_uint_32 row_bytes;
11683 int transparent_p;
11684 char *gamma_str;
11685 double screen_gamma, image_gamma;
11686 int intent;
11687 struct png_memory_storage tbr; /* Data to be read */
11689 /* Find out what file to load. */
11690 specified_file = image_spec_value (img->spec, QCfile, NULL);
11691 specified_data = image_spec_value (img->spec, QCdata, NULL);
11692 file = Qnil;
11693 GCPRO1 (file);
11695 if (NILP (specified_data))
11697 file = x_find_image_file (specified_file);
11698 if (!STRINGP (file))
11700 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11701 UNGCPRO;
11702 return 0;
11705 /* Open the image file. */
11706 fp = fopen (SDATA (file), "rb");
11707 if (!fp)
11709 image_error ("Cannot open image file `%s'", file, Qnil);
11710 UNGCPRO;
11711 fclose (fp);
11712 return 0;
11715 /* Check PNG signature. */
11716 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
11717 || !png_check_sig (sig, sizeof sig))
11719 image_error ("Not a PNG file:` %s'", file, Qnil);
11720 UNGCPRO;
11721 fclose (fp);
11722 return 0;
11725 else
11727 /* Read from memory. */
11728 tbr.bytes = SDATA (specified_data);
11729 tbr.len = SBYTES (specified_data);
11730 tbr.index = 0;
11732 /* Check PNG signature. */
11733 if (tbr.len < sizeof sig
11734 || !png_check_sig (tbr.bytes, sizeof sig))
11736 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
11737 UNGCPRO;
11738 return 0;
11741 /* Need to skip past the signature. */
11742 tbr.bytes += sizeof (sig);
11745 /* Initialize read and info structs for PNG lib. */
11746 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
11747 my_png_error, my_png_warning);
11748 if (!png_ptr)
11750 if (fp) fclose (fp);
11751 UNGCPRO;
11752 return 0;
11755 info_ptr = png_create_info_struct (png_ptr);
11756 if (!info_ptr)
11758 png_destroy_read_struct (&png_ptr, NULL, NULL);
11759 if (fp) fclose (fp);
11760 UNGCPRO;
11761 return 0;
11764 end_info = png_create_info_struct (png_ptr);
11765 if (!end_info)
11767 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
11768 if (fp) fclose (fp);
11769 UNGCPRO;
11770 return 0;
11773 /* Set error jump-back. We come back here when the PNG library
11774 detects an error. */
11775 if (setjmp (png_ptr->jmpbuf))
11777 error:
11778 if (png_ptr)
11779 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11780 xfree (pixels);
11781 xfree (rows);
11782 if (fp) fclose (fp);
11783 UNGCPRO;
11784 return 0;
11787 /* Read image info. */
11788 if (!NILP (specified_data))
11789 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
11790 else
11791 png_init_io (png_ptr, fp);
11793 png_set_sig_bytes (png_ptr, sizeof sig);
11794 png_read_info (png_ptr, info_ptr);
11795 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
11796 &interlace_type, NULL, NULL);
11798 /* If image contains simply transparency data, we prefer to
11799 construct a clipping mask. */
11800 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
11801 transparent_p = 1;
11802 else
11803 transparent_p = 0;
11805 /* This function is easier to write if we only have to handle
11806 one data format: RGB or RGBA with 8 bits per channel. Let's
11807 transform other formats into that format. */
11809 /* Strip more than 8 bits per channel. */
11810 if (bit_depth == 16)
11811 png_set_strip_16 (png_ptr);
11813 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
11814 if available. */
11815 png_set_expand (png_ptr);
11817 /* Convert grayscale images to RGB. */
11818 if (color_type == PNG_COLOR_TYPE_GRAY
11819 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
11820 png_set_gray_to_rgb (png_ptr);
11822 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
11823 gamma_str = getenv ("SCREEN_GAMMA");
11824 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
11826 /* Tell the PNG lib to handle gamma correction for us. */
11828 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
11829 if (png_get_sRGB (png_ptr, info_ptr, &intent))
11830 /* There is a special chunk in the image specifying the gamma. */
11831 png_set_sRGB (png_ptr, info_ptr, intent);
11832 else
11833 #endif
11834 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
11835 /* Image contains gamma information. */
11836 png_set_gamma (png_ptr, screen_gamma, image_gamma);
11837 else
11838 /* Use a default of 0.5 for the image gamma. */
11839 png_set_gamma (png_ptr, screen_gamma, 0.5);
11841 /* Handle alpha channel by combining the image with a background
11842 color. Do this only if a real alpha channel is supplied. For
11843 simple transparency, we prefer a clipping mask. */
11844 if (!transparent_p)
11846 png_color_16 *image_background;
11847 Lisp_Object specified_bg
11848 = image_spec_value (img->spec, QCbackground, NULL);
11851 if (STRINGP (specified_bg))
11852 /* The user specified `:background', use that. */
11854 COLORREF color;
11855 if (w32_defined_color (f, SDATA (specified_bg), &color, 0))
11857 png_color_16 user_bg;
11859 bzero (&user_bg, sizeof user_bg);
11860 user_bg.red = color.red;
11861 user_bg.green = color.green;
11862 user_bg.blue = color.blue;
11864 png_set_background (png_ptr, &user_bg,
11865 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11868 else if (png_get_bKGD (png_ptr, info_ptr, &image_background))
11869 /* Image contains a background color with which to
11870 combine the image. */
11871 png_set_background (png_ptr, image_background,
11872 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
11873 else
11875 /* Image does not contain a background color with which
11876 to combine the image data via an alpha channel. Use
11877 the frame's background instead. */
11878 XColor color;
11879 Colormap cmap;
11880 png_color_16 frame_background;
11882 cmap = FRAME_X_COLORMAP (f);
11883 color.pixel = FRAME_BACKGROUND_PIXEL (f);
11884 x_query_color (f, &color);
11886 bzero (&frame_background, sizeof frame_background);
11887 frame_background.red = color.red;
11888 frame_background.green = color.green;
11889 frame_background.blue = color.blue;
11891 png_set_background (png_ptr, &frame_background,
11892 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11896 /* Update info structure. */
11897 png_read_update_info (png_ptr, info_ptr);
11899 /* Get number of channels. Valid values are 1 for grayscale images
11900 and images with a palette, 2 for grayscale images with transparency
11901 information (alpha channel), 3 for RGB images, and 4 for RGB
11902 images with alpha channel, i.e. RGBA. If conversions above were
11903 sufficient we should only have 3 or 4 channels here. */
11904 channels = png_get_channels (png_ptr, info_ptr);
11905 xassert (channels == 3 || channels == 4);
11907 /* Number of bytes needed for one row of the image. */
11908 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
11910 /* Allocate memory for the image. */
11911 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
11912 rows = (png_byte **) xmalloc (height * sizeof *rows);
11913 for (i = 0; i < height; ++i)
11914 rows[i] = pixels + i * row_bytes;
11916 /* Read the entire image. */
11917 png_read_image (png_ptr, rows);
11918 png_read_end (png_ptr, info_ptr);
11919 if (fp)
11921 fclose (fp);
11922 fp = NULL;
11925 /* Create the X image and pixmap. */
11926 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11927 &img->pixmap))
11928 goto error;
11930 /* Create an image and pixmap serving as mask if the PNG image
11931 contains an alpha channel. */
11932 if (channels == 4
11933 && !transparent_p
11934 && !x_create_x_image_and_pixmap (f, width, height, 1,
11935 &mask_img, &img->mask))
11937 x_destroy_x_image (ximg);
11938 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
11939 img->pixmap = 0;
11940 goto error;
11943 /* Fill the X image and mask from PNG data. */
11944 init_color_table ();
11946 for (y = 0; y < height; ++y)
11948 png_byte *p = rows[y];
11950 for (x = 0; x < width; ++x)
11952 unsigned r, g, b;
11954 r = *p++ << 8;
11955 g = *p++ << 8;
11956 b = *p++ << 8;
11957 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
11959 /* An alpha channel, aka mask channel, associates variable
11960 transparency with an image. Where other image formats
11961 support binary transparency---fully transparent or fully
11962 opaque---PNG allows up to 254 levels of partial transparency.
11963 The PNG library implements partial transparency by combining
11964 the image with a specified background color.
11966 I'm not sure how to handle this here nicely: because the
11967 background on which the image is displayed may change, for
11968 real alpha channel support, it would be necessary to create
11969 a new image for each possible background.
11971 What I'm doing now is that a mask is created if we have
11972 boolean transparency information. Otherwise I'm using
11973 the frame's background color to combine the image with. */
11975 if (channels == 4)
11977 if (mask_img)
11978 XPutPixel (mask_img, x, y, *p > 0);
11979 ++p;
11984 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11985 /* Set IMG's background color from the PNG image, unless the user
11986 overrode it. */
11988 png_color_16 *bg;
11989 if (png_get_bKGD (png_ptr, info_ptr, &bg))
11991 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
11992 img->background_valid = 1;
11996 /* Remember colors allocated for this image. */
11997 img->colors = colors_in_color_table (&img->ncolors);
11998 free_color_table ();
12000 /* Clean up. */
12001 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
12002 xfree (rows);
12003 xfree (pixels);
12005 img->width = width;
12006 img->height = height;
12008 /* Maybe fill in the background field while we have ximg handy. */
12009 IMAGE_BACKGROUND (img, f, ximg);
12011 /* Put the image into the pixmap, then free the X image and its buffer. */
12012 x_put_x_image (f, ximg, img->pixmap, width, height);
12013 x_destroy_x_image (ximg);
12015 /* Same for the mask. */
12016 if (mask_img)
12018 /* Fill in the background_transparent field while we have the mask
12019 handy. */
12020 image_background_transparent (img, f, mask_img);
12022 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
12023 x_destroy_x_image (mask_img);
12026 UNGCPRO;
12027 return 1;
12030 #endif /* HAVE_PNG != 0 */
12034 /***********************************************************************
12035 JPEG
12036 ***********************************************************************/
12038 #if HAVE_JPEG
12040 /* Work around a warning about HAVE_STDLIB_H being redefined in
12041 jconfig.h. */
12042 #ifdef HAVE_STDLIB_H
12043 #define HAVE_STDLIB_H_1
12044 #undef HAVE_STDLIB_H
12045 #endif /* HAVE_STLIB_H */
12047 #include <jpeglib.h>
12048 #include <jerror.h>
12049 #include <setjmp.h>
12051 #ifdef HAVE_STLIB_H_1
12052 #define HAVE_STDLIB_H 1
12053 #endif
12055 static int jpeg_image_p P_ ((Lisp_Object object));
12056 static int jpeg_load P_ ((struct frame *f, struct image *img));
12058 /* The symbol `jpeg' identifying images of this type. */
12060 Lisp_Object Qjpeg;
12062 /* Indices of image specification fields in gs_format, below. */
12064 enum jpeg_keyword_index
12066 JPEG_TYPE,
12067 JPEG_DATA,
12068 JPEG_FILE,
12069 JPEG_ASCENT,
12070 JPEG_MARGIN,
12071 JPEG_RELIEF,
12072 JPEG_ALGORITHM,
12073 JPEG_HEURISTIC_MASK,
12074 JPEG_MASK,
12075 JPEG_BACKGROUND,
12076 JPEG_LAST
12079 /* Vector of image_keyword structures describing the format
12080 of valid user-defined image specifications. */
12082 static struct image_keyword jpeg_format[JPEG_LAST] =
12084 {":type", IMAGE_SYMBOL_VALUE, 1},
12085 {":data", IMAGE_STRING_VALUE, 0},
12086 {":file", IMAGE_STRING_VALUE, 0},
12087 {":ascent", IMAGE_ASCENT_VALUE, 0},
12088 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12089 {":relief", IMAGE_INTEGER_VALUE, 0},
12090 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12091 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12092 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12093 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12096 /* Structure describing the image type `jpeg'. */
12098 static struct image_type jpeg_type =
12100 &Qjpeg,
12101 jpeg_image_p,
12102 jpeg_load,
12103 x_clear_image,
12104 NULL
12108 /* Return non-zero if OBJECT is a valid JPEG image specification. */
12110 static int
12111 jpeg_image_p (object)
12112 Lisp_Object object;
12114 struct image_keyword fmt[JPEG_LAST];
12116 bcopy (jpeg_format, fmt, sizeof fmt);
12118 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
12119 return 0;
12121 /* Must specify either the :data or :file keyword. */
12122 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
12126 struct my_jpeg_error_mgr
12128 struct jpeg_error_mgr pub;
12129 jmp_buf setjmp_buffer;
12132 static void
12133 my_error_exit (cinfo)
12134 j_common_ptr cinfo;
12136 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
12137 longjmp (mgr->setjmp_buffer, 1);
12140 /* Init source method for JPEG data source manager. Called by
12141 jpeg_read_header() before any data is actually read. See
12142 libjpeg.doc from the JPEG lib distribution. */
12144 static void
12145 our_init_source (cinfo)
12146 j_decompress_ptr cinfo;
12151 /* Fill input buffer method for JPEG data source manager. Called
12152 whenever more data is needed. We read the whole image in one step,
12153 so this only adds a fake end of input marker at the end. */
12155 static boolean
12156 our_fill_input_buffer (cinfo)
12157 j_decompress_ptr cinfo;
12159 /* Insert a fake EOI marker. */
12160 struct jpeg_source_mgr *src = cinfo->src;
12161 static JOCTET buffer[2];
12163 buffer[0] = (JOCTET) 0xFF;
12164 buffer[1] = (JOCTET) JPEG_EOI;
12166 src->next_input_byte = buffer;
12167 src->bytes_in_buffer = 2;
12168 return TRUE;
12172 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
12173 is the JPEG data source manager. */
12175 static void
12176 our_skip_input_data (cinfo, num_bytes)
12177 j_decompress_ptr cinfo;
12178 long num_bytes;
12180 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
12182 if (src)
12184 if (num_bytes > src->bytes_in_buffer)
12185 ERREXIT (cinfo, JERR_INPUT_EOF);
12187 src->bytes_in_buffer -= num_bytes;
12188 src->next_input_byte += num_bytes;
12193 /* Method to terminate data source. Called by
12194 jpeg_finish_decompress() after all data has been processed. */
12196 static void
12197 our_term_source (cinfo)
12198 j_decompress_ptr cinfo;
12203 /* Set up the JPEG lib for reading an image from DATA which contains
12204 LEN bytes. CINFO is the decompression info structure created for
12205 reading the image. */
12207 static void
12208 jpeg_memory_src (cinfo, data, len)
12209 j_decompress_ptr cinfo;
12210 JOCTET *data;
12211 unsigned int len;
12213 struct jpeg_source_mgr *src;
12215 if (cinfo->src == NULL)
12217 /* First time for this JPEG object? */
12218 cinfo->src = (struct jpeg_source_mgr *)
12219 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
12220 sizeof (struct jpeg_source_mgr));
12221 src = (struct jpeg_source_mgr *) cinfo->src;
12222 src->next_input_byte = data;
12225 src = (struct jpeg_source_mgr *) cinfo->src;
12226 src->init_source = our_init_source;
12227 src->fill_input_buffer = our_fill_input_buffer;
12228 src->skip_input_data = our_skip_input_data;
12229 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
12230 src->term_source = our_term_source;
12231 src->bytes_in_buffer = len;
12232 src->next_input_byte = data;
12236 /* Load image IMG for use on frame F. Patterned after example.c
12237 from the JPEG lib. */
12239 static int
12240 jpeg_load (f, img)
12241 struct frame *f;
12242 struct image *img;
12244 struct jpeg_decompress_struct cinfo;
12245 struct my_jpeg_error_mgr mgr;
12246 Lisp_Object file, specified_file;
12247 Lisp_Object specified_data;
12248 FILE * volatile fp = NULL;
12249 JSAMPARRAY buffer;
12250 int row_stride, x, y;
12251 XImage *ximg = NULL;
12252 int rc;
12253 unsigned long *colors;
12254 int width, height;
12255 struct gcpro gcpro1;
12257 /* Open the JPEG file. */
12258 specified_file = image_spec_value (img->spec, QCfile, NULL);
12259 specified_data = image_spec_value (img->spec, QCdata, NULL);
12260 file = Qnil;
12261 GCPRO1 (file);
12263 if (NILP (specified_data))
12265 file = x_find_image_file (specified_file);
12266 if (!STRINGP (file))
12268 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12269 UNGCPRO;
12270 return 0;
12273 fp = fopen (SDATA (file), "r");
12274 if (fp == NULL)
12276 image_error ("Cannot open `%s'", file, Qnil);
12277 UNGCPRO;
12278 return 0;
12282 /* Customize libjpeg's error handling to call my_error_exit when an
12283 error is detected. This function will perform a longjmp. */
12284 cinfo.err = jpeg_std_error (&mgr.pub);
12285 mgr.pub.error_exit = my_error_exit;
12287 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
12289 if (rc == 1)
12291 /* Called from my_error_exit. Display a JPEG error. */
12292 char buffer[JMSG_LENGTH_MAX];
12293 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
12294 image_error ("Error reading JPEG image `%s': %s", img->spec,
12295 build_string (buffer));
12298 /* Close the input file and destroy the JPEG object. */
12299 if (fp)
12300 fclose (fp);
12301 jpeg_destroy_decompress (&cinfo);
12303 /* If we already have an XImage, free that. */
12304 x_destroy_x_image (ximg);
12306 /* Free pixmap and colors. */
12307 x_clear_image (f, img);
12309 UNGCPRO;
12310 return 0;
12313 /* Create the JPEG decompression object. Let it read from fp.
12314 Read the JPEG image header. */
12315 jpeg_create_decompress (&cinfo);
12317 if (NILP (specified_data))
12318 jpeg_stdio_src (&cinfo, fp);
12319 else
12320 jpeg_memory_src (&cinfo, SDATA (specified_data),
12321 SBYTES (specified_data));
12323 jpeg_read_header (&cinfo, TRUE);
12325 /* Customize decompression so that color quantization will be used.
12326 Start decompression. */
12327 cinfo.quantize_colors = TRUE;
12328 jpeg_start_decompress (&cinfo);
12329 width = img->width = cinfo.output_width;
12330 height = img->height = cinfo.output_height;
12332 /* Create X image and pixmap. */
12333 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
12334 &img->pixmap))
12335 longjmp (mgr.setjmp_buffer, 2);
12337 /* Allocate colors. When color quantization is used,
12338 cinfo.actual_number_of_colors has been set with the number of
12339 colors generated, and cinfo.colormap is a two-dimensional array
12340 of color indices in the range 0..cinfo.actual_number_of_colors.
12341 No more than 255 colors will be generated. */
12343 int i, ir, ig, ib;
12345 if (cinfo.out_color_components > 2)
12346 ir = 0, ig = 1, ib = 2;
12347 else if (cinfo.out_color_components > 1)
12348 ir = 0, ig = 1, ib = 0;
12349 else
12350 ir = 0, ig = 0, ib = 0;
12352 /* Use the color table mechanism because it handles colors that
12353 cannot be allocated nicely. Such colors will be replaced with
12354 a default color, and we don't have to care about which colors
12355 can be freed safely, and which can't. */
12356 init_color_table ();
12357 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
12358 * sizeof *colors);
12360 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
12362 /* Multiply RGB values with 255 because X expects RGB values
12363 in the range 0..0xffff. */
12364 int r = cinfo.colormap[ir][i] << 8;
12365 int g = cinfo.colormap[ig][i] << 8;
12366 int b = cinfo.colormap[ib][i] << 8;
12367 colors[i] = lookup_rgb_color (f, r, g, b);
12370 /* Remember those colors actually allocated. */
12371 img->colors = colors_in_color_table (&img->ncolors);
12372 free_color_table ();
12375 /* Read pixels. */
12376 row_stride = width * cinfo.output_components;
12377 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
12378 row_stride, 1);
12379 for (y = 0; y < height; ++y)
12381 jpeg_read_scanlines (&cinfo, buffer, 1);
12382 for (x = 0; x < cinfo.output_width; ++x)
12383 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
12386 /* Clean up. */
12387 jpeg_finish_decompress (&cinfo);
12388 jpeg_destroy_decompress (&cinfo);
12389 if (fp)
12390 fclose (fp);
12392 /* Maybe fill in the background field while we have ximg handy. */
12393 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12394 IMAGE_BACKGROUND (img, f, ximg);
12396 /* Put the image into the pixmap. */
12397 x_put_x_image (f, ximg, img->pixmap, width, height);
12398 x_destroy_x_image (ximg);
12399 UNBLOCK_INPUT;
12400 UNGCPRO;
12401 return 1;
12404 #endif /* HAVE_JPEG */
12408 /***********************************************************************
12409 TIFF
12410 ***********************************************************************/
12412 #if HAVE_TIFF
12414 #include <tiffio.h>
12416 static int tiff_image_p P_ ((Lisp_Object object));
12417 static int tiff_load P_ ((struct frame *f, struct image *img));
12419 /* The symbol `tiff' identifying images of this type. */
12421 Lisp_Object Qtiff;
12423 /* Indices of image specification fields in tiff_format, below. */
12425 enum tiff_keyword_index
12427 TIFF_TYPE,
12428 TIFF_DATA,
12429 TIFF_FILE,
12430 TIFF_ASCENT,
12431 TIFF_MARGIN,
12432 TIFF_RELIEF,
12433 TIFF_ALGORITHM,
12434 TIFF_HEURISTIC_MASK,
12435 TIFF_MASK,
12436 TIFF_BACKGROUND,
12437 TIFF_LAST
12440 /* Vector of image_keyword structures describing the format
12441 of valid user-defined image specifications. */
12443 static struct image_keyword tiff_format[TIFF_LAST] =
12445 {":type", IMAGE_SYMBOL_VALUE, 1},
12446 {":data", IMAGE_STRING_VALUE, 0},
12447 {":file", IMAGE_STRING_VALUE, 0},
12448 {":ascent", IMAGE_ASCENT_VALUE, 0},
12449 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12450 {":relief", IMAGE_INTEGER_VALUE, 0},
12451 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12452 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12453 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12454 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12457 /* Structure describing the image type `tiff'. */
12459 static struct image_type tiff_type =
12461 &Qtiff,
12462 tiff_image_p,
12463 tiff_load,
12464 x_clear_image,
12465 NULL
12469 /* Return non-zero if OBJECT is a valid TIFF image specification. */
12471 static int
12472 tiff_image_p (object)
12473 Lisp_Object object;
12475 struct image_keyword fmt[TIFF_LAST];
12476 bcopy (tiff_format, fmt, sizeof fmt);
12478 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
12479 return 0;
12481 /* Must specify either the :data or :file keyword. */
12482 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
12486 /* Reading from a memory buffer for TIFF images Based on the PNG
12487 memory source, but we have to provide a lot of extra functions.
12488 Blah.
12490 We really only need to implement read and seek, but I am not
12491 convinced that the TIFF library is smart enough not to destroy
12492 itself if we only hand it the function pointers we need to
12493 override. */
12495 typedef struct
12497 unsigned char *bytes;
12498 size_t len;
12499 int index;
12501 tiff_memory_source;
12503 static size_t
12504 tiff_read_from_memory (data, buf, size)
12505 thandle_t data;
12506 tdata_t buf;
12507 tsize_t size;
12509 tiff_memory_source *src = (tiff_memory_source *) data;
12511 if (size > src->len - src->index)
12512 return (size_t) -1;
12513 bcopy (src->bytes + src->index, buf, size);
12514 src->index += size;
12515 return size;
12518 static size_t
12519 tiff_write_from_memory (data, buf, size)
12520 thandle_t data;
12521 tdata_t buf;
12522 tsize_t size;
12524 return (size_t) -1;
12527 static toff_t
12528 tiff_seek_in_memory (data, off, whence)
12529 thandle_t data;
12530 toff_t off;
12531 int whence;
12533 tiff_memory_source *src = (tiff_memory_source *) data;
12534 int idx;
12536 switch (whence)
12538 case SEEK_SET: /* Go from beginning of source. */
12539 idx = off;
12540 break;
12542 case SEEK_END: /* Go from end of source. */
12543 idx = src->len + off;
12544 break;
12546 case SEEK_CUR: /* Go from current position. */
12547 idx = src->index + off;
12548 break;
12550 default: /* Invalid `whence'. */
12551 return -1;
12554 if (idx > src->len || idx < 0)
12555 return -1;
12557 src->index = idx;
12558 return src->index;
12561 static int
12562 tiff_close_memory (data)
12563 thandle_t data;
12565 /* NOOP */
12566 return 0;
12569 static int
12570 tiff_mmap_memory (data, pbase, psize)
12571 thandle_t data;
12572 tdata_t *pbase;
12573 toff_t *psize;
12575 /* It is already _IN_ memory. */
12576 return 0;
12579 static void
12580 tiff_unmap_memory (data, base, size)
12581 thandle_t data;
12582 tdata_t base;
12583 toff_t size;
12585 /* We don't need to do this. */
12588 static toff_t
12589 tiff_size_of_memory (data)
12590 thandle_t data;
12592 return ((tiff_memory_source *) data)->len;
12596 static void
12597 tiff_error_handler (title, format, ap)
12598 const char *title, *format;
12599 va_list ap;
12601 char buf[512];
12602 int len;
12604 len = sprintf (buf, "TIFF error: %s ", title);
12605 vsprintf (buf + len, format, ap);
12606 add_to_log (buf, Qnil, Qnil);
12610 static void
12611 tiff_warning_handler (title, format, ap)
12612 const char *title, *format;
12613 va_list ap;
12615 char buf[512];
12616 int len;
12618 len = sprintf (buf, "TIFF warning: %s ", title);
12619 vsprintf (buf + len, format, ap);
12620 add_to_log (buf, Qnil, Qnil);
12624 /* Load TIFF image IMG for use on frame F. Value is non-zero if
12625 successful. */
12627 static int
12628 tiff_load (f, img)
12629 struct frame *f;
12630 struct image *img;
12632 Lisp_Object file, specified_file;
12633 Lisp_Object specified_data;
12634 TIFF *tiff;
12635 int width, height, x, y;
12636 uint32 *buf;
12637 int rc;
12638 XImage *ximg;
12639 struct gcpro gcpro1;
12640 tiff_memory_source memsrc;
12642 specified_file = image_spec_value (img->spec, QCfile, NULL);
12643 specified_data = image_spec_value (img->spec, QCdata, NULL);
12644 file = Qnil;
12645 GCPRO1 (file);
12647 TIFFSetErrorHandler (tiff_error_handler);
12648 TIFFSetWarningHandler (tiff_warning_handler);
12650 if (NILP (specified_data))
12652 /* Read from a file */
12653 file = x_find_image_file (specified_file);
12654 if (!STRINGP (file))
12656 image_error ("Cannot find image file `%s'", file, Qnil);
12657 UNGCPRO;
12658 return 0;
12661 /* Try to open the image file. */
12662 tiff = TIFFOpen (SDATA (file), "r");
12663 if (tiff == NULL)
12665 image_error ("Cannot open `%s'", file, Qnil);
12666 UNGCPRO;
12667 return 0;
12670 else
12672 /* Memory source! */
12673 memsrc.bytes = SDATA (specified_data);
12674 memsrc.len = SBYTES (specified_data);
12675 memsrc.index = 0;
12677 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
12678 (TIFFReadWriteProc) tiff_read_from_memory,
12679 (TIFFReadWriteProc) tiff_write_from_memory,
12680 tiff_seek_in_memory,
12681 tiff_close_memory,
12682 tiff_size_of_memory,
12683 tiff_mmap_memory,
12684 tiff_unmap_memory);
12686 if (!tiff)
12688 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
12689 UNGCPRO;
12690 return 0;
12694 /* Get width and height of the image, and allocate a raster buffer
12695 of width x height 32-bit values. */
12696 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
12697 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
12698 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
12700 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
12701 TIFFClose (tiff);
12702 if (!rc)
12704 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
12705 xfree (buf);
12706 UNGCPRO;
12707 return 0;
12710 /* Create the X image and pixmap. */
12711 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12713 xfree (buf);
12714 UNGCPRO;
12715 return 0;
12718 /* Initialize the color table. */
12719 init_color_table ();
12721 /* Process the pixel raster. Origin is in the lower-left corner. */
12722 for (y = 0; y < height; ++y)
12724 uint32 *row = buf + y * width;
12726 for (x = 0; x < width; ++x)
12728 uint32 abgr = row[x];
12729 int r = TIFFGetR (abgr) << 8;
12730 int g = TIFFGetG (abgr) << 8;
12731 int b = TIFFGetB (abgr) << 8;
12732 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
12736 /* Remember the colors allocated for the image. Free the color table. */
12737 img->colors = colors_in_color_table (&img->ncolors);
12738 free_color_table ();
12740 img->width = width;
12741 img->height = height;
12743 /* Maybe fill in the background field while we have ximg handy. */
12744 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12745 IMAGE_BACKGROUND (img, f, ximg);
12747 /* Put the image into the pixmap, then free the X image and its buffer. */
12748 x_put_x_image (f, ximg, img->pixmap, width, height);
12749 x_destroy_x_image (ximg);
12750 xfree (buf);
12752 UNGCPRO;
12753 return 1;
12756 #endif /* HAVE_TIFF != 0 */
12760 /***********************************************************************
12762 ***********************************************************************/
12764 #if HAVE_GIF
12766 #include <gif_lib.h>
12768 static int gif_image_p P_ ((Lisp_Object object));
12769 static int gif_load P_ ((struct frame *f, struct image *img));
12771 /* The symbol `gif' identifying images of this type. */
12773 Lisp_Object Qgif;
12775 /* Indices of image specification fields in gif_format, below. */
12777 enum gif_keyword_index
12779 GIF_TYPE,
12780 GIF_DATA,
12781 GIF_FILE,
12782 GIF_ASCENT,
12783 GIF_MARGIN,
12784 GIF_RELIEF,
12785 GIF_ALGORITHM,
12786 GIF_HEURISTIC_MASK,
12787 GIF_MASK,
12788 GIF_IMAGE,
12789 GIF_BACKGROUND,
12790 GIF_LAST
12793 /* Vector of image_keyword structures describing the format
12794 of valid user-defined image specifications. */
12796 static struct image_keyword gif_format[GIF_LAST] =
12798 {":type", IMAGE_SYMBOL_VALUE, 1},
12799 {":data", IMAGE_STRING_VALUE, 0},
12800 {":file", IMAGE_STRING_VALUE, 0},
12801 {":ascent", IMAGE_ASCENT_VALUE, 0},
12802 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12803 {":relief", IMAGE_INTEGER_VALUE, 0},
12804 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12805 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12806 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12807 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12808 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12811 /* Structure describing the image type `gif'. */
12813 static struct image_type gif_type =
12815 &Qgif,
12816 gif_image_p,
12817 gif_load,
12818 x_clear_image,
12819 NULL
12822 /* Return non-zero if OBJECT is a valid GIF image specification. */
12824 static int
12825 gif_image_p (object)
12826 Lisp_Object object;
12828 struct image_keyword fmt[GIF_LAST];
12829 bcopy (gif_format, fmt, sizeof fmt);
12831 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
12832 return 0;
12834 /* Must specify either the :data or :file keyword. */
12835 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
12838 /* Reading a GIF image from memory
12839 Based on the PNG memory stuff to a certain extent. */
12841 typedef struct
12843 unsigned char *bytes;
12844 size_t len;
12845 int index;
12847 gif_memory_source;
12849 /* Make the current memory source available to gif_read_from_memory.
12850 It's done this way because not all versions of libungif support
12851 a UserData field in the GifFileType structure. */
12852 static gif_memory_source *current_gif_memory_src;
12854 static int
12855 gif_read_from_memory (file, buf, len)
12856 GifFileType *file;
12857 GifByteType *buf;
12858 int len;
12860 gif_memory_source *src = current_gif_memory_src;
12862 if (len > src->len - src->index)
12863 return -1;
12865 bcopy (src->bytes + src->index, buf, len);
12866 src->index += len;
12867 return len;
12871 /* Load GIF image IMG for use on frame F. Value is non-zero if
12872 successful. */
12874 static int
12875 gif_load (f, img)
12876 struct frame *f;
12877 struct image *img;
12879 Lisp_Object file, specified_file;
12880 Lisp_Object specified_data;
12881 int rc, width, height, x, y, i;
12882 XImage *ximg;
12883 ColorMapObject *gif_color_map;
12884 unsigned long pixel_colors[256];
12885 GifFileType *gif;
12886 struct gcpro gcpro1;
12887 Lisp_Object image;
12888 int ino, image_left, image_top, image_width, image_height;
12889 gif_memory_source memsrc;
12890 unsigned char *raster;
12892 specified_file = image_spec_value (img->spec, QCfile, NULL);
12893 specified_data = image_spec_value (img->spec, QCdata, NULL);
12894 file = Qnil;
12895 GCPRO1 (file);
12897 if (NILP (specified_data))
12899 file = x_find_image_file (specified_file);
12900 if (!STRINGP (file))
12902 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12903 UNGCPRO;
12904 return 0;
12907 /* Open the GIF file. */
12908 gif = DGifOpenFileName (SDATA (file));
12909 if (gif == NULL)
12911 image_error ("Cannot open `%s'", file, Qnil);
12912 UNGCPRO;
12913 return 0;
12916 else
12918 /* Read from memory! */
12919 current_gif_memory_src = &memsrc;
12920 memsrc.bytes = SDATA (specified_data);
12921 memsrc.len = SBYTES (specified_data);
12922 memsrc.index = 0;
12924 gif = DGifOpen(&memsrc, gif_read_from_memory);
12925 if (!gif)
12927 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
12928 UNGCPRO;
12929 return 0;
12933 /* Read entire contents. */
12934 rc = DGifSlurp (gif);
12935 if (rc == GIF_ERROR)
12937 image_error ("Error reading `%s'", img->spec, Qnil);
12938 DGifCloseFile (gif);
12939 UNGCPRO;
12940 return 0;
12943 image = image_spec_value (img->spec, QCindex, NULL);
12944 ino = INTEGERP (image) ? XFASTINT (image) : 0;
12945 if (ino >= gif->ImageCount)
12947 image_error ("Invalid image number `%s' in image `%s'",
12948 image, img->spec);
12949 DGifCloseFile (gif);
12950 UNGCPRO;
12951 return 0;
12954 width = img->width = gif->SWidth;
12955 height = img->height = gif->SHeight;
12957 /* Create the X image and pixmap. */
12958 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12960 DGifCloseFile (gif);
12961 UNGCPRO;
12962 return 0;
12965 /* Allocate colors. */
12966 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
12967 if (!gif_color_map)
12968 gif_color_map = gif->SColorMap;
12969 init_color_table ();
12970 bzero (pixel_colors, sizeof pixel_colors);
12972 for (i = 0; i < gif_color_map->ColorCount; ++i)
12974 int r = gif_color_map->Colors[i].Red << 8;
12975 int g = gif_color_map->Colors[i].Green << 8;
12976 int b = gif_color_map->Colors[i].Blue << 8;
12977 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
12980 img->colors = colors_in_color_table (&img->ncolors);
12981 free_color_table ();
12983 /* Clear the part of the screen image that are not covered by
12984 the image from the GIF file. Full animated GIF support
12985 requires more than can be done here (see the gif89 spec,
12986 disposal methods). Let's simply assume that the part
12987 not covered by a sub-image is in the frame's background color. */
12988 image_top = gif->SavedImages[ino].ImageDesc.Top;
12989 image_left = gif->SavedImages[ino].ImageDesc.Left;
12990 image_width = gif->SavedImages[ino].ImageDesc.Width;
12991 image_height = gif->SavedImages[ino].ImageDesc.Height;
12993 for (y = 0; y < image_top; ++y)
12994 for (x = 0; x < width; ++x)
12995 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12997 for (y = image_top + image_height; y < height; ++y)
12998 for (x = 0; x < width; ++x)
12999 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
13001 for (y = image_top; y < image_top + image_height; ++y)
13003 for (x = 0; x < image_left; ++x)
13004 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
13005 for (x = image_left + image_width; x < width; ++x)
13006 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
13009 /* Read the GIF image into the X image. We use a local variable
13010 `raster' here because RasterBits below is a char *, and invites
13011 problems with bytes >= 0x80. */
13012 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
13014 if (gif->SavedImages[ino].ImageDesc.Interlace)
13016 static int interlace_start[] = {0, 4, 2, 1};
13017 static int interlace_increment[] = {8, 8, 4, 2};
13018 int pass;
13019 int row = interlace_start[0];
13021 pass = 0;
13023 for (y = 0; y < image_height; y++)
13025 if (row >= image_height)
13027 row = interlace_start[++pass];
13028 while (row >= image_height)
13029 row = interlace_start[++pass];
13032 for (x = 0; x < image_width; x++)
13034 int i = raster[(y * image_width) + x];
13035 XPutPixel (ximg, x + image_left, row + image_top,
13036 pixel_colors[i]);
13039 row += interlace_increment[pass];
13042 else
13044 for (y = 0; y < image_height; ++y)
13045 for (x = 0; x < image_width; ++x)
13047 int i = raster[y* image_width + x];
13048 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
13052 DGifCloseFile (gif);
13054 /* Maybe fill in the background field while we have ximg handy. */
13055 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
13056 IMAGE_BACKGROUND (img, f, ximg);
13058 /* Put the image into the pixmap, then free the X image and its buffer. */
13059 x_put_x_image (f, ximg, img->pixmap, width, height);
13060 x_destroy_x_image (ximg);
13062 UNGCPRO;
13063 return 1;
13066 #endif /* HAVE_GIF != 0 */
13070 /***********************************************************************
13071 Ghostscript
13072 ***********************************************************************/
13074 Lisp_Object Qpostscript;
13076 #ifdef HAVE_GHOSTSCRIPT
13077 static int gs_image_p P_ ((Lisp_Object object));
13078 static int gs_load P_ ((struct frame *f, struct image *img));
13079 static void gs_clear_image P_ ((struct frame *f, struct image *img));
13081 /* The symbol `postscript' identifying images of this type. */
13083 /* Keyword symbols. */
13085 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
13087 /* Indices of image specification fields in gs_format, below. */
13089 enum gs_keyword_index
13091 GS_TYPE,
13092 GS_PT_WIDTH,
13093 GS_PT_HEIGHT,
13094 GS_FILE,
13095 GS_LOADER,
13096 GS_BOUNDING_BOX,
13097 GS_ASCENT,
13098 GS_MARGIN,
13099 GS_RELIEF,
13100 GS_ALGORITHM,
13101 GS_HEURISTIC_MASK,
13102 GS_MASK,
13103 GS_BACKGROUND,
13104 GS_LAST
13107 /* Vector of image_keyword structures describing the format
13108 of valid user-defined image specifications. */
13110 static struct image_keyword gs_format[GS_LAST] =
13112 {":type", IMAGE_SYMBOL_VALUE, 1},
13113 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13114 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13115 {":file", IMAGE_STRING_VALUE, 1},
13116 {":loader", IMAGE_FUNCTION_VALUE, 0},
13117 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
13118 {":ascent", IMAGE_ASCENT_VALUE, 0},
13119 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
13120 {":relief", IMAGE_INTEGER_VALUE, 0},
13121 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13122 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13123 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13124 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
13127 /* Structure describing the image type `ghostscript'. */
13129 static struct image_type gs_type =
13131 &Qpostscript,
13132 gs_image_p,
13133 gs_load,
13134 gs_clear_image,
13135 NULL
13139 /* Free X resources of Ghostscript image IMG which is used on frame F. */
13141 static void
13142 gs_clear_image (f, img)
13143 struct frame *f;
13144 struct image *img;
13146 /* IMG->data.ptr_val may contain a recorded colormap. */
13147 xfree (img->data.ptr_val);
13148 x_clear_image (f, img);
13152 /* Return non-zero if OBJECT is a valid Ghostscript image
13153 specification. */
13155 static int
13156 gs_image_p (object)
13157 Lisp_Object object;
13159 struct image_keyword fmt[GS_LAST];
13160 Lisp_Object tem;
13161 int i;
13163 bcopy (gs_format, fmt, sizeof fmt);
13165 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
13166 return 0;
13168 /* Bounding box must be a list or vector containing 4 integers. */
13169 tem = fmt[GS_BOUNDING_BOX].value;
13170 if (CONSP (tem))
13172 for (i = 0; i < 4; ++i, tem = XCDR (tem))
13173 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
13174 return 0;
13175 if (!NILP (tem))
13176 return 0;
13178 else if (VECTORP (tem))
13180 if (XVECTOR (tem)->size != 4)
13181 return 0;
13182 for (i = 0; i < 4; ++i)
13183 if (!INTEGERP (XVECTOR (tem)->contents[i]))
13184 return 0;
13186 else
13187 return 0;
13189 return 1;
13193 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
13194 if successful. */
13196 static int
13197 gs_load (f, img)
13198 struct frame *f;
13199 struct image *img;
13201 char buffer[100];
13202 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
13203 struct gcpro gcpro1, gcpro2;
13204 Lisp_Object frame;
13205 double in_width, in_height;
13206 Lisp_Object pixel_colors = Qnil;
13208 /* Compute pixel size of pixmap needed from the given size in the
13209 image specification. Sizes in the specification are in pt. 1 pt
13210 = 1/72 in, xdpi and ydpi are stored in the frame's X display
13211 info. */
13212 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
13213 in_width = XFASTINT (pt_width) / 72.0;
13214 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
13215 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
13216 in_height = XFASTINT (pt_height) / 72.0;
13217 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
13219 /* Create the pixmap. */
13220 BLOCK_INPUT;
13221 xassert (img->pixmap == 0);
13222 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13223 img->width, img->height,
13224 one_w32_display_info.n_cbits);
13225 UNBLOCK_INPUT;
13227 if (!img->pixmap)
13229 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
13230 return 0;
13233 /* Call the loader to fill the pixmap. It returns a process object
13234 if successful. We do not record_unwind_protect here because
13235 other places in redisplay like calling window scroll functions
13236 don't either. Let the Lisp loader use `unwind-protect' instead. */
13237 GCPRO2 (window_and_pixmap_id, pixel_colors);
13239 sprintf (buffer, "%lu %lu",
13240 (unsigned long) FRAME_W32_WINDOW (f),
13241 (unsigned long) img->pixmap);
13242 window_and_pixmap_id = build_string (buffer);
13244 sprintf (buffer, "%lu %lu",
13245 FRAME_FOREGROUND_PIXEL (f),
13246 FRAME_BACKGROUND_PIXEL (f));
13247 pixel_colors = build_string (buffer);
13249 XSETFRAME (frame, f);
13250 loader = image_spec_value (img->spec, QCloader, NULL);
13251 if (NILP (loader))
13252 loader = intern ("gs-load-image");
13254 img->data.lisp_val = call6 (loader, frame, img->spec,
13255 make_number (img->width),
13256 make_number (img->height),
13257 window_and_pixmap_id,
13258 pixel_colors);
13259 UNGCPRO;
13260 return PROCESSP (img->data.lisp_val);
13264 /* Kill the Ghostscript process that was started to fill PIXMAP on
13265 frame F. Called from XTread_socket when receiving an event
13266 telling Emacs that Ghostscript has finished drawing. */
13268 void
13269 x_kill_gs_process (pixmap, f)
13270 Pixmap pixmap;
13271 struct frame *f;
13273 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
13274 int class, i;
13275 struct image *img;
13277 /* Find the image containing PIXMAP. */
13278 for (i = 0; i < c->used; ++i)
13279 if (c->images[i]->pixmap == pixmap)
13280 break;
13282 /* Should someone in between have cleared the image cache, for
13283 instance, give up. */
13284 if (i == c->used)
13285 return;
13287 /* Kill the GS process. We should have found PIXMAP in the image
13288 cache and its image should contain a process object. */
13289 img = c->images[i];
13290 xassert (PROCESSP (img->data.lisp_val));
13291 Fkill_process (img->data.lisp_val, Qnil);
13292 img->data.lisp_val = Qnil;
13294 /* On displays with a mutable colormap, figure out the colors
13295 allocated for the image by looking at the pixels of an XImage for
13296 img->pixmap. */
13297 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
13298 if (class != StaticColor && class != StaticGray && class != TrueColor)
13300 XImage *ximg;
13302 BLOCK_INPUT;
13304 /* Try to get an XImage for img->pixmep. */
13305 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
13306 0, 0, img->width, img->height, ~0, ZPixmap);
13307 if (ximg)
13309 int x, y;
13311 /* Initialize the color table. */
13312 init_color_table ();
13314 /* For each pixel of the image, look its color up in the
13315 color table. After having done so, the color table will
13316 contain an entry for each color used by the image. */
13317 for (y = 0; y < img->height; ++y)
13318 for (x = 0; x < img->width; ++x)
13320 unsigned long pixel = XGetPixel (ximg, x, y);
13321 lookup_pixel_color (f, pixel);
13324 /* Record colors in the image. Free color table and XImage. */
13325 img->colors = colors_in_color_table (&img->ncolors);
13326 free_color_table ();
13327 XDestroyImage (ximg);
13329 #if 0 /* This doesn't seem to be the case. If we free the colors
13330 here, we get a BadAccess later in x_clear_image when
13331 freeing the colors. */
13332 /* We have allocated colors once, but Ghostscript has also
13333 allocated colors on behalf of us. So, to get the
13334 reference counts right, free them once. */
13335 if (img->ncolors)
13336 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
13337 img->colors, img->ncolors, 0);
13338 #endif
13340 else
13341 image_error ("Cannot get X image of `%s'; colors will not be freed",
13342 img->spec, Qnil);
13344 UNBLOCK_INPUT;
13347 /* Now that we have the pixmap, compute mask and transform the
13348 image if requested. */
13349 BLOCK_INPUT;
13350 postprocess_image (f, img);
13351 UNBLOCK_INPUT;
13354 #endif /* HAVE_GHOSTSCRIPT */
13357 /***********************************************************************
13358 Window properties
13359 ***********************************************************************/
13361 DEFUN ("x-change-window-property", Fx_change_window_property,
13362 Sx_change_window_property, 2, 3, 0,
13363 doc: /* Change window property PROP to VALUE on the X window of FRAME.
13364 PROP and VALUE must be strings. FRAME nil or omitted means use the
13365 selected frame. Value is VALUE. */)
13366 (prop, value, frame)
13367 Lisp_Object frame, prop, value;
13369 #if 0 /* TODO : port window properties to W32 */
13370 struct frame *f = check_x_frame (frame);
13371 Atom prop_atom;
13373 CHECK_STRING (prop);
13374 CHECK_STRING (value);
13376 BLOCK_INPUT;
13377 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13378 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13379 prop_atom, XA_STRING, 8, PropModeReplace,
13380 SDATA (value), SCHARS (value));
13382 /* Make sure the property is set when we return. */
13383 XFlush (FRAME_W32_DISPLAY (f));
13384 UNBLOCK_INPUT;
13386 #endif /* TODO */
13388 return value;
13392 DEFUN ("x-delete-window-property", Fx_delete_window_property,
13393 Sx_delete_window_property, 1, 2, 0,
13394 doc: /* Remove window property PROP from X window of FRAME.
13395 FRAME nil or omitted means use the selected frame. Value is PROP. */)
13396 (prop, frame)
13397 Lisp_Object prop, frame;
13399 #if 0 /* TODO : port window properties to W32 */
13401 struct frame *f = check_x_frame (frame);
13402 Atom prop_atom;
13404 CHECK_STRING (prop);
13405 BLOCK_INPUT;
13406 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13407 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
13409 /* Make sure the property is removed when we return. */
13410 XFlush (FRAME_W32_DISPLAY (f));
13411 UNBLOCK_INPUT;
13412 #endif /* TODO */
13414 return prop;
13418 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
13419 1, 2, 0,
13420 doc: /* Value is the value of window property PROP on FRAME.
13421 If FRAME is nil or omitted, use the selected frame. Value is nil
13422 if FRAME hasn't a property with name PROP or if PROP has no string
13423 value. */)
13424 (prop, frame)
13425 Lisp_Object prop, frame;
13427 #if 0 /* TODO : port window properties to W32 */
13429 struct frame *f = check_x_frame (frame);
13430 Atom prop_atom;
13431 int rc;
13432 Lisp_Object prop_value = Qnil;
13433 char *tmp_data = NULL;
13434 Atom actual_type;
13435 int actual_format;
13436 unsigned long actual_size, bytes_remaining;
13438 CHECK_STRING (prop);
13439 BLOCK_INPUT;
13440 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13441 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13442 prop_atom, 0, 0, False, XA_STRING,
13443 &actual_type, &actual_format, &actual_size,
13444 &bytes_remaining, (unsigned char **) &tmp_data);
13445 if (rc == Success)
13447 int size = bytes_remaining;
13449 XFree (tmp_data);
13450 tmp_data = NULL;
13452 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13453 prop_atom, 0, bytes_remaining,
13454 False, XA_STRING,
13455 &actual_type, &actual_format,
13456 &actual_size, &bytes_remaining,
13457 (unsigned char **) &tmp_data);
13458 if (rc == Success)
13459 prop_value = make_string (tmp_data, size);
13461 XFree (tmp_data);
13464 UNBLOCK_INPUT;
13466 return prop_value;
13468 #endif /* TODO */
13469 return Qnil;
13474 /***********************************************************************
13475 Busy cursor
13476 ***********************************************************************/
13478 /* If non-null, an asynchronous timer that, when it expires, displays
13479 an hourglass cursor on all frames. */
13481 static struct atimer *hourglass_atimer;
13483 /* Non-zero means an hourglass cursor is currently shown. */
13485 static int hourglass_shown_p;
13487 /* Number of seconds to wait before displaying an hourglass cursor. */
13489 static Lisp_Object Vhourglass_delay;
13491 /* Default number of seconds to wait before displaying an hourglass
13492 cursor. */
13494 #define DEFAULT_HOURGLASS_DELAY 1
13496 /* Function prototypes. */
13498 static void show_hourglass P_ ((struct atimer *));
13499 static void hide_hourglass P_ ((void));
13502 /* Cancel a currently active hourglass timer, and start a new one. */
13504 void
13505 start_hourglass ()
13507 #if 0 /* TODO: cursor shape changes. */
13508 EMACS_TIME delay;
13509 int secs, usecs = 0;
13511 cancel_hourglass ();
13513 if (INTEGERP (Vhourglass_delay)
13514 && XINT (Vhourglass_delay) > 0)
13515 secs = XFASTINT (Vhourglass_delay);
13516 else if (FLOATP (Vhourglass_delay)
13517 && XFLOAT_DATA (Vhourglass_delay) > 0)
13519 Lisp_Object tem;
13520 tem = Ftruncate (Vhourglass_delay, Qnil);
13521 secs = XFASTINT (tem);
13522 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
13524 else
13525 secs = DEFAULT_HOURGLASS_DELAY;
13527 EMACS_SET_SECS_USECS (delay, secs, usecs);
13528 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
13529 show_hourglass, NULL);
13530 #endif
13534 /* Cancel the hourglass cursor timer if active, hide an hourglass
13535 cursor if shown. */
13537 void
13538 cancel_hourglass ()
13540 if (hourglass_atimer)
13542 cancel_atimer (hourglass_atimer);
13543 hourglass_atimer = NULL;
13546 if (hourglass_shown_p)
13547 hide_hourglass ();
13551 /* Timer function of hourglass_atimer. TIMER is equal to
13552 hourglass_atimer.
13554 Display an hourglass cursor on all frames by mapping the frames'
13555 hourglass_window. Set the hourglass_p flag in the frames'
13556 output_data.x structure to indicate that an hourglass cursor is
13557 shown on the frames. */
13559 static void
13560 show_hourglass (timer)
13561 struct atimer *timer;
13563 #if 0 /* TODO: cursor shape changes. */
13564 /* The timer implementation will cancel this timer automatically
13565 after this function has run. Set hourglass_atimer to null
13566 so that we know the timer doesn't have to be canceled. */
13567 hourglass_atimer = NULL;
13569 if (!hourglass_shown_p)
13571 Lisp_Object rest, frame;
13573 BLOCK_INPUT;
13575 FOR_EACH_FRAME (rest, frame)
13576 if (FRAME_W32_P (XFRAME (frame)))
13578 struct frame *f = XFRAME (frame);
13580 f->output_data.w32->hourglass_p = 1;
13582 if (!f->output_data.w32->hourglass_window)
13584 unsigned long mask = CWCursor;
13585 XSetWindowAttributes attrs;
13587 attrs.cursor = f->output_data.w32->hourglass_cursor;
13589 f->output_data.w32->hourglass_window
13590 = XCreateWindow (FRAME_X_DISPLAY (f),
13591 FRAME_OUTER_WINDOW (f),
13592 0, 0, 32000, 32000, 0, 0,
13593 InputOnly,
13594 CopyFromParent,
13595 mask, &attrs);
13598 XMapRaised (FRAME_X_DISPLAY (f),
13599 f->output_data.w32->hourglass_window);
13600 XFlush (FRAME_X_DISPLAY (f));
13603 hourglass_shown_p = 1;
13604 UNBLOCK_INPUT;
13606 #endif
13610 /* Hide the hourglass cursor on all frames, if it is currently shown. */
13612 static void
13613 hide_hourglass ()
13615 #if 0 /* TODO: cursor shape changes. */
13616 if (hourglass_shown_p)
13618 Lisp_Object rest, frame;
13620 BLOCK_INPUT;
13621 FOR_EACH_FRAME (rest, frame)
13623 struct frame *f = XFRAME (frame);
13625 if (FRAME_W32_P (f)
13626 /* Watch out for newly created frames. */
13627 && f->output_data.x->hourglass_window)
13629 XUnmapWindow (FRAME_X_DISPLAY (f),
13630 f->output_data.x->hourglass_window);
13631 /* Sync here because XTread_socket looks at the
13632 hourglass_p flag that is reset to zero below. */
13633 XSync (FRAME_X_DISPLAY (f), False);
13634 f->output_data.x->hourglass_p = 0;
13638 hourglass_shown_p = 0;
13639 UNBLOCK_INPUT;
13641 #endif
13646 /***********************************************************************
13647 Tool tips
13648 ***********************************************************************/
13650 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
13651 Lisp_Object, Lisp_Object));
13652 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
13653 Lisp_Object, int, int, int *, int *));
13655 /* The frame of a currently visible tooltip. */
13657 Lisp_Object tip_frame;
13659 /* If non-nil, a timer started that hides the last tooltip when it
13660 fires. */
13662 Lisp_Object tip_timer;
13663 Window tip_window;
13665 /* If non-nil, a vector of 3 elements containing the last args
13666 with which x-show-tip was called. See there. */
13668 Lisp_Object last_show_tip_args;
13670 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
13672 Lisp_Object Vx_max_tooltip_size;
13675 static Lisp_Object
13676 unwind_create_tip_frame (frame)
13677 Lisp_Object frame;
13679 Lisp_Object deleted;
13681 deleted = unwind_create_frame (frame);
13682 if (EQ (deleted, Qt))
13684 tip_window = NULL;
13685 tip_frame = Qnil;
13688 return deleted;
13692 /* Create a frame for a tooltip on the display described by DPYINFO.
13693 PARMS is a list of frame parameters. TEXT is the string to
13694 display in the tip frame. Value is the frame.
13696 Note that functions called here, esp. x_default_parameter can
13697 signal errors, for instance when a specified color name is
13698 undefined. We have to make sure that we're in a consistent state
13699 when this happens. */
13701 static Lisp_Object
13702 x_create_tip_frame (dpyinfo, parms, text)
13703 struct w32_display_info *dpyinfo;
13704 Lisp_Object parms, text;
13706 struct frame *f;
13707 Lisp_Object frame, tem;
13708 Lisp_Object name;
13709 long window_prompting = 0;
13710 int width, height;
13711 int count = SPECPDL_INDEX ();
13712 struct gcpro gcpro1, gcpro2, gcpro3;
13713 struct kboard *kb;
13714 int face_change_count_before = face_change_count;
13715 Lisp_Object buffer;
13716 struct buffer *old_buffer;
13718 check_w32 ();
13720 /* Use this general default value to start with until we know if
13721 this frame has a specified name. */
13722 Vx_resource_name = Vinvocation_name;
13724 #ifdef MULTI_KBOARD
13725 kb = dpyinfo->kboard;
13726 #else
13727 kb = &the_only_kboard;
13728 #endif
13730 /* Get the name of the frame to use for resource lookup. */
13731 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
13732 if (!STRINGP (name)
13733 && !EQ (name, Qunbound)
13734 && !NILP (name))
13735 error ("Invalid frame name--not a string or nil");
13736 Vx_resource_name = name;
13738 frame = Qnil;
13739 GCPRO3 (parms, name, frame);
13740 /* Make a frame without minibuffer nor mode-line. */
13741 f = make_frame (0);
13742 f->wants_modeline = 0;
13743 XSETFRAME (frame, f);
13745 buffer = Fget_buffer_create (build_string (" *tip*"));
13746 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
13747 old_buffer = current_buffer;
13748 set_buffer_internal_1 (XBUFFER (buffer));
13749 current_buffer->truncate_lines = Qnil;
13750 Ferase_buffer ();
13751 Finsert (1, &text);
13752 set_buffer_internal_1 (old_buffer);
13754 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
13755 record_unwind_protect (unwind_create_tip_frame, frame);
13757 /* By setting the output method, we're essentially saying that
13758 the frame is live, as per FRAME_LIVE_P. If we get a signal
13759 from this point on, x_destroy_window might screw up reference
13760 counts etc. */
13761 f->output_method = output_w32;
13762 f->output_data.w32 =
13763 (struct w32_output *) xmalloc (sizeof (struct w32_output));
13764 bzero (f->output_data.w32, sizeof (struct w32_output));
13766 FRAME_FONTSET (f) = -1;
13767 f->icon_name = Qnil;
13769 #if 0 /* GLYPH_DEBUG TODO: image support. */
13770 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
13771 dpyinfo_refcount = dpyinfo->reference_count;
13772 #endif /* GLYPH_DEBUG */
13773 #ifdef MULTI_KBOARD
13774 FRAME_KBOARD (f) = kb;
13775 #endif
13776 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13777 f->output_data.w32->explicit_parent = 0;
13779 /* Set the name; the functions to which we pass f expect the name to
13780 be set. */
13781 if (EQ (name, Qunbound) || NILP (name))
13783 f->name = build_string (dpyinfo->w32_id_name);
13784 f->explicit_name = 0;
13786 else
13788 f->name = name;
13789 f->explicit_name = 1;
13790 /* use the frame's title when getting resources for this frame. */
13791 specbind (Qx_resource_name, name);
13794 /* Extract the window parameters from the supplied values
13795 that are needed to determine window geometry. */
13797 Lisp_Object font;
13799 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
13801 BLOCK_INPUT;
13802 /* First, try whatever font the caller has specified. */
13803 if (STRINGP (font))
13805 tem = Fquery_fontset (font, Qnil);
13806 if (STRINGP (tem))
13807 font = x_new_fontset (f, SDATA (tem));
13808 else
13809 font = x_new_font (f, SDATA (font));
13812 /* Try out a font which we hope has bold and italic variations. */
13813 if (!STRINGP (font))
13814 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
13815 if (! STRINGP (font))
13816 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
13817 /* If those didn't work, look for something which will at least work. */
13818 if (! STRINGP (font))
13819 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
13820 UNBLOCK_INPUT;
13821 if (! STRINGP (font))
13822 font = build_string ("Fixedsys");
13824 x_default_parameter (f, parms, Qfont, font,
13825 "font", "Font", RES_TYPE_STRING);
13828 x_default_parameter (f, parms, Qborder_width, make_number (2),
13829 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
13830 /* This defaults to 2 in order to match xterm. We recognize either
13831 internalBorderWidth or internalBorder (which is what xterm calls
13832 it). */
13833 if (NILP (Fassq (Qinternal_border_width, parms)))
13835 Lisp_Object value;
13837 value = w32_get_arg (parms, Qinternal_border_width,
13838 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
13839 if (! EQ (value, Qunbound))
13840 parms = Fcons (Fcons (Qinternal_border_width, value),
13841 parms);
13843 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
13844 "internalBorderWidth", "internalBorderWidth",
13845 RES_TYPE_NUMBER);
13847 /* Also do the stuff which must be set before the window exists. */
13848 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
13849 "foreground", "Foreground", RES_TYPE_STRING);
13850 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
13851 "background", "Background", RES_TYPE_STRING);
13852 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
13853 "pointerColor", "Foreground", RES_TYPE_STRING);
13854 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
13855 "cursorColor", "Foreground", RES_TYPE_STRING);
13856 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
13857 "borderColor", "BorderColor", RES_TYPE_STRING);
13859 /* Init faces before x_default_parameter is called for scroll-bar
13860 parameters because that function calls x_set_scroll_bar_width,
13861 which calls change_frame_size, which calls Fset_window_buffer,
13862 which runs hooks, which call Fvertical_motion. At the end, we
13863 end up in init_iterator with a null face cache, which should not
13864 happen. */
13865 init_frame_faces (f);
13867 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
13868 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13870 window_prompting = x_figure_window_size (f, parms);
13872 /* No fringes on tip frame. */
13873 f->output_data.w32->fringes_extra = 0;
13874 f->output_data.w32->fringe_cols = 0;
13875 f->output_data.w32->left_fringe_width = 0;
13876 f->output_data.w32->right_fringe_width = 0;
13878 if (window_prompting & XNegative)
13880 if (window_prompting & YNegative)
13881 f->output_data.w32->win_gravity = SouthEastGravity;
13882 else
13883 f->output_data.w32->win_gravity = NorthEastGravity;
13885 else
13887 if (window_prompting & YNegative)
13888 f->output_data.w32->win_gravity = SouthWestGravity;
13889 else
13890 f->output_data.w32->win_gravity = NorthWestGravity;
13893 f->output_data.w32->size_hint_flags = window_prompting;
13895 BLOCK_INPUT;
13896 my_create_tip_window (f);
13897 UNBLOCK_INPUT;
13899 x_make_gc (f);
13901 x_default_parameter (f, parms, Qauto_raise, Qnil,
13902 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13903 x_default_parameter (f, parms, Qauto_lower, Qnil,
13904 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13905 x_default_parameter (f, parms, Qcursor_type, Qbox,
13906 "cursorType", "CursorType", RES_TYPE_SYMBOL);
13908 /* Dimensions, especially f->height, must be done via change_frame_size.
13909 Change will not be effected unless different from the current
13910 f->height. */
13911 width = f->width;
13912 height = f->height;
13913 f->height = 0;
13914 SET_FRAME_WIDTH (f, 0);
13915 change_frame_size (f, height, width, 1, 0, 0);
13917 /* Add `tooltip' frame parameter's default value. */
13918 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
13919 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
13920 Qnil));
13922 /* Set up faces after all frame parameters are known. This call
13923 also merges in face attributes specified for new frames.
13925 Frame parameters may be changed if .Xdefaults contains
13926 specifications for the default font. For example, if there is an
13927 `Emacs.default.attributeBackground: pink', the `background-color'
13928 attribute of the frame get's set, which let's the internal border
13929 of the tooltip frame appear in pink. Prevent this. */
13931 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
13933 /* Set tip_frame here, so that */
13934 tip_frame = frame;
13935 call1 (Qface_set_after_frame_default, frame);
13937 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
13938 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
13939 Qnil));
13942 f->no_split = 1;
13944 UNGCPRO;
13946 /* It is now ok to make the frame official even if we get an error
13947 below. And the frame needs to be on Vframe_list or making it
13948 visible won't work. */
13949 Vframe_list = Fcons (frame, Vframe_list);
13951 /* Now that the frame is official, it counts as a reference to
13952 its display. */
13953 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
13955 /* Setting attributes of faces of the tooltip frame from resources
13956 and similar will increment face_change_count, which leads to the
13957 clearing of all current matrices. Since this isn't necessary
13958 here, avoid it by resetting face_change_count to the value it
13959 had before we created the tip frame. */
13960 face_change_count = face_change_count_before;
13962 /* Discard the unwind_protect. */
13963 return unbind_to (count, frame);
13967 /* Compute where to display tip frame F. PARMS is the list of frame
13968 parameters for F. DX and DY are specified offsets from the current
13969 location of the mouse. WIDTH and HEIGHT are the width and height
13970 of the tooltip. Return coordinates relative to the root window of
13971 the display in *ROOT_X, and *ROOT_Y. */
13973 static void
13974 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
13975 struct frame *f;
13976 Lisp_Object parms, dx, dy;
13977 int width, height;
13978 int *root_x, *root_y;
13980 Lisp_Object left, top;
13982 /* User-specified position? */
13983 left = Fcdr (Fassq (Qleft, parms));
13984 top = Fcdr (Fassq (Qtop, parms));
13986 /* Move the tooltip window where the mouse pointer is. Resize and
13987 show it. */
13988 if (!INTEGERP (left) || !INTEGERP (top))
13990 POINT pt;
13992 BLOCK_INPUT;
13993 GetCursorPos (&pt);
13994 *root_x = pt.x;
13995 *root_y = pt.y;
13996 UNBLOCK_INPUT;
13999 if (INTEGERP (top))
14000 *root_y = XINT (top);
14001 else if (*root_y + XINT (dy) - height < 0)
14002 *root_y -= XINT (dy);
14003 else
14005 *root_y -= height;
14006 *root_y += XINT (dy);
14009 if (INTEGERP (left))
14010 *root_x = XINT (left);
14011 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
14012 /* It fits to the right of the pointer. */
14013 *root_x += XINT (dx);
14014 else if (width + XINT (dx) <= *root_x)
14015 /* It fits to the left of the pointer. */
14016 *root_x -= width + XINT (dx);
14017 else
14018 /* Put it left justified on the screen -- it ought to fit that way. */
14019 *root_x = 0;
14023 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
14024 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
14025 A tooltip window is a small window displaying a string.
14027 FRAME nil or omitted means use the selected frame.
14029 PARMS is an optional list of frame parameters which can be
14030 used to change the tooltip's appearance.
14032 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
14033 means use the default timeout of 5 seconds.
14035 If the list of frame parameters PARAMS contains a `left' parameter,
14036 the tooltip is displayed at that x-position. Otherwise it is
14037 displayed at the mouse position, with offset DX added (default is 5 if
14038 DX isn't specified). Likewise for the y-position; if a `top' frame
14039 parameter is specified, it determines the y-position of the tooltip
14040 window, otherwise it is displayed at the mouse position, with offset
14041 DY added (default is -10).
14043 A tooltip's maximum size is specified by `x-max-tooltip-size'.
14044 Text larger than the specified size is clipped. */)
14045 (string, frame, parms, timeout, dx, dy)
14046 Lisp_Object string, frame, parms, timeout, dx, dy;
14048 struct frame *f;
14049 struct window *w;
14050 int root_x, root_y;
14051 struct buffer *old_buffer;
14052 struct text_pos pos;
14053 int i, width, height;
14054 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
14055 int old_windows_or_buffers_changed = windows_or_buffers_changed;
14056 int count = SPECPDL_INDEX ();
14058 specbind (Qinhibit_redisplay, Qt);
14060 GCPRO4 (string, parms, frame, timeout);
14062 CHECK_STRING (string);
14063 f = check_x_frame (frame);
14064 if (NILP (timeout))
14065 timeout = make_number (5);
14066 else
14067 CHECK_NATNUM (timeout);
14069 if (NILP (dx))
14070 dx = make_number (5);
14071 else
14072 CHECK_NUMBER (dx);
14074 if (NILP (dy))
14075 dy = make_number (-10);
14076 else
14077 CHECK_NUMBER (dy);
14079 if (NILP (last_show_tip_args))
14080 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
14082 if (!NILP (tip_frame))
14084 Lisp_Object last_string = AREF (last_show_tip_args, 0);
14085 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
14086 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
14088 if (EQ (frame, last_frame)
14089 && !NILP (Fequal (last_string, string))
14090 && !NILP (Fequal (last_parms, parms)))
14092 struct frame *f = XFRAME (tip_frame);
14094 /* Only DX and DY have changed. */
14095 if (!NILP (tip_timer))
14097 Lisp_Object timer = tip_timer;
14098 tip_timer = Qnil;
14099 call1 (Qcancel_timer, timer);
14102 BLOCK_INPUT;
14103 compute_tip_xy (f, parms, dx, dy, PIXEL_WIDTH (f),
14104 PIXEL_HEIGHT (f), &root_x, &root_y);
14106 /* Put tooltip in topmost group and in position. */
14107 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14108 root_x, root_y, 0, 0,
14109 SWP_NOSIZE | SWP_NOACTIVATE);
14111 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14112 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14113 0, 0, 0, 0,
14114 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14116 UNBLOCK_INPUT;
14117 goto start_timer;
14121 /* Hide a previous tip, if any. */
14122 Fx_hide_tip ();
14124 ASET (last_show_tip_args, 0, string);
14125 ASET (last_show_tip_args, 1, frame);
14126 ASET (last_show_tip_args, 2, parms);
14128 /* Add default values to frame parameters. */
14129 if (NILP (Fassq (Qname, parms)))
14130 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
14131 if (NILP (Fassq (Qinternal_border_width, parms)))
14132 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
14133 if (NILP (Fassq (Qborder_width, parms)))
14134 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
14135 if (NILP (Fassq (Qborder_color, parms)))
14136 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
14137 if (NILP (Fassq (Qbackground_color, parms)))
14138 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
14139 parms);
14141 /* Block input until the tip has been fully drawn, to avoid crashes
14142 when drawing tips in menus. */
14143 BLOCK_INPUT;
14145 /* Create a frame for the tooltip, and record it in the global
14146 variable tip_frame. */
14147 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
14148 f = XFRAME (frame);
14150 /* Set up the frame's root window. */
14151 w = XWINDOW (FRAME_ROOT_WINDOW (f));
14152 w->left = w->top = make_number (0);
14154 if (CONSP (Vx_max_tooltip_size)
14155 && INTEGERP (XCAR (Vx_max_tooltip_size))
14156 && XINT (XCAR (Vx_max_tooltip_size)) > 0
14157 && INTEGERP (XCDR (Vx_max_tooltip_size))
14158 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
14160 w->width = XCAR (Vx_max_tooltip_size);
14161 w->height = XCDR (Vx_max_tooltip_size);
14163 else
14165 w->width = make_number (80);
14166 w->height = make_number (40);
14169 f->window_width = XINT (w->width);
14170 adjust_glyphs (f);
14171 w->pseudo_window_p = 1;
14173 /* Display the tooltip text in a temporary buffer. */
14174 old_buffer = current_buffer;
14175 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
14176 current_buffer->truncate_lines = Qnil;
14177 clear_glyph_matrix (w->desired_matrix);
14178 clear_glyph_matrix (w->current_matrix);
14179 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
14180 try_window (FRAME_ROOT_WINDOW (f), pos);
14182 /* Compute width and height of the tooltip. */
14183 width = height = 0;
14184 for (i = 0; i < w->desired_matrix->nrows; ++i)
14186 struct glyph_row *row = &w->desired_matrix->rows[i];
14187 struct glyph *last;
14188 int row_width;
14190 /* Stop at the first empty row at the end. */
14191 if (!row->enabled_p || !row->displays_text_p)
14192 break;
14194 /* Let the row go over the full width of the frame. */
14195 row->full_width_p = 1;
14197 #ifdef TODO /* Investigate why some fonts need more width than is
14198 calculated for some tooltips. */
14199 /* There's a glyph at the end of rows that is use to place
14200 the cursor there. Don't include the width of this glyph. */
14201 if (row->used[TEXT_AREA])
14203 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
14204 row_width = row->pixel_width - last->pixel_width;
14206 else
14207 #endif
14208 row_width = row->pixel_width;
14210 /* TODO: find why tips do not draw along baseline as instructed. */
14211 height += row->height;
14212 width = max (width, row_width);
14215 /* Add the frame's internal border to the width and height the X
14216 window should have. */
14217 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14218 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14220 /* Move the tooltip window where the mouse pointer is. Resize and
14221 show it. */
14222 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
14225 /* Adjust Window size to take border into account. */
14226 RECT rect;
14227 rect.left = rect.top = 0;
14228 rect.right = width;
14229 rect.bottom = height;
14230 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
14231 FRAME_EXTERNAL_MENU_BAR (f));
14233 /* Position and size tooltip, and put it in the topmost group. */
14234 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14235 root_x, root_y, rect.right - rect.left,
14236 rect.bottom - rect.top, SWP_NOACTIVATE);
14238 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14239 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14240 0, 0, 0, 0,
14241 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14243 /* Let redisplay know that we have made the frame visible already. */
14244 f->async_visible = 1;
14246 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
14249 /* Draw into the window. */
14250 w->must_be_updated_p = 1;
14251 update_single_window (w, 1);
14253 UNBLOCK_INPUT;
14255 /* Restore original current buffer. */
14256 set_buffer_internal_1 (old_buffer);
14257 windows_or_buffers_changed = old_windows_or_buffers_changed;
14259 start_timer:
14260 /* Let the tip disappear after timeout seconds. */
14261 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
14262 intern ("x-hide-tip"));
14264 UNGCPRO;
14265 return unbind_to (count, Qnil);
14269 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
14270 doc: /* Hide the current tooltip window, if there is any.
14271 Value is t if tooltip was open, nil otherwise. */)
14274 int count;
14275 Lisp_Object deleted, frame, timer;
14276 struct gcpro gcpro1, gcpro2;
14278 /* Return quickly if nothing to do. */
14279 if (NILP (tip_timer) && NILP (tip_frame))
14280 return Qnil;
14282 frame = tip_frame;
14283 timer = tip_timer;
14284 GCPRO2 (frame, timer);
14285 tip_frame = tip_timer = deleted = Qnil;
14287 count = SPECPDL_INDEX ();
14288 specbind (Qinhibit_redisplay, Qt);
14289 specbind (Qinhibit_quit, Qt);
14291 if (!NILP (timer))
14292 call1 (Qcancel_timer, timer);
14294 if (FRAMEP (frame))
14296 Fdelete_frame (frame, Qnil);
14297 deleted = Qt;
14300 UNGCPRO;
14301 return unbind_to (count, deleted);
14306 /***********************************************************************
14307 File selection dialog
14308 ***********************************************************************/
14309 extern Lisp_Object Qfile_name_history;
14311 /* Callback for altering the behaviour of the Open File dialog.
14312 Makes the Filename text field contain "Current Directory" and be
14313 read-only when "Directories" is selected in the filter. This
14314 allows us to work around the fact that the standard Open File
14315 dialog does not support directories. */
14316 UINT CALLBACK
14317 file_dialog_callback (hwnd, msg, wParam, lParam)
14318 HWND hwnd;
14319 UINT msg;
14320 WPARAM wParam;
14321 LPARAM lParam;
14323 if (msg == WM_NOTIFY)
14325 OFNOTIFY * notify = (OFNOTIFY *)lParam;
14326 /* Detect when the Filter dropdown is changed. */
14327 if (notify->hdr.code == CDN_TYPECHANGE)
14329 HWND dialog = GetParent (hwnd);
14330 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
14332 /* Directories is in index 2. */
14333 if (notify->lpOFN->nFilterIndex == 2)
14335 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14336 "Current Directory");
14337 EnableWindow (edit_control, FALSE);
14339 else
14341 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14342 "");
14343 EnableWindow (edit_control, TRUE);
14347 return 0;
14350 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
14351 doc: /* Read file name, prompting with PROMPT in directory DIR.
14352 Use a file selection dialog.
14353 Select DEFAULT-FILENAME in the dialog's file selection box, if
14354 specified. Ensure that file exists if MUSTMATCH is non-nil. */)
14355 (prompt, dir, default_filename, mustmatch)
14356 Lisp_Object prompt, dir, default_filename, mustmatch;
14358 struct frame *f = SELECTED_FRAME ();
14359 Lisp_Object file = Qnil;
14360 int count = SPECPDL_INDEX ();
14361 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
14362 char filename[MAX_PATH + 1];
14363 char init_dir[MAX_PATH + 1];
14365 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
14366 CHECK_STRING (prompt);
14367 CHECK_STRING (dir);
14369 /* Create the dialog with PROMPT as title, using DIR as initial
14370 directory and using "*" as pattern. */
14371 dir = Fexpand_file_name (dir, Qnil);
14372 strncpy (init_dir, SDATA (dir), MAX_PATH);
14373 init_dir[MAX_PATH] = '\0';
14374 unixtodos_filename (init_dir);
14376 if (STRINGP (default_filename))
14378 char *file_name_only;
14379 char *full_path_name = SDATA (default_filename);
14381 unixtodos_filename (full_path_name);
14383 file_name_only = strrchr (full_path_name, '\\');
14384 if (!file_name_only)
14385 file_name_only = full_path_name;
14386 else
14388 file_name_only++;
14391 strncpy (filename, file_name_only, MAX_PATH);
14392 filename[MAX_PATH] = '\0';
14394 else
14395 filename[0] = '\0';
14398 OPENFILENAME file_details;
14400 /* Prevent redisplay. */
14401 specbind (Qinhibit_redisplay, Qt);
14402 BLOCK_INPUT;
14404 bzero (&file_details, sizeof (file_details));
14405 file_details.lStructSize = sizeof (file_details);
14406 file_details.hwndOwner = FRAME_W32_WINDOW (f);
14407 /* Undocumented Bug in Common File Dialog:
14408 If a filter is not specified, shell links are not resolved. */
14409 file_details.lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
14410 file_details.lpstrFile = filename;
14411 file_details.nMaxFile = sizeof (filename);
14412 file_details.lpstrInitialDir = init_dir;
14413 file_details.lpstrTitle = SDATA (prompt);
14414 file_details.Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
14415 | OFN_EXPLORER | OFN_ENABLEHOOK);
14416 if (!NILP (mustmatch))
14417 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
14419 file_details.lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
14421 if (GetOpenFileName (&file_details))
14423 dostounix_filename (filename);
14424 if (file_details.nFilterIndex == 2)
14426 /* "Folder Only" selected - strip dummy file name. */
14427 char * last = strrchr (filename, '/');
14428 *last = '\0';
14431 file = DECODE_FILE(build_string (filename));
14433 /* User cancelled the dialog without making a selection. */
14434 else if (!CommDlgExtendedError ())
14435 file = Qnil;
14436 /* An error occurred, fallback on reading from the mini-buffer. */
14437 else
14438 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
14439 dir, mustmatch, dir, Qfile_name_history,
14440 default_filename, Qnil);
14442 UNBLOCK_INPUT;
14443 file = unbind_to (count, file);
14446 UNGCPRO;
14448 /* Make "Cancel" equivalent to C-g. */
14449 if (NILP (file))
14450 Fsignal (Qquit, Qnil);
14452 return unbind_to (count, file);
14457 /***********************************************************************
14458 w32 specialized functions
14459 ***********************************************************************/
14461 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
14462 doc: /* Select a font using the W32 font dialog.
14463 Returns an X font string corresponding to the selection. */)
14464 (frame, include_proportional)
14465 Lisp_Object frame, include_proportional;
14467 FRAME_PTR f = check_x_frame (frame);
14468 CHOOSEFONT cf;
14469 LOGFONT lf;
14470 TEXTMETRIC tm;
14471 HDC hdc;
14472 HANDLE oldobj;
14473 char buf[100];
14475 bzero (&cf, sizeof (cf));
14476 bzero (&lf, sizeof (lf));
14478 cf.lStructSize = sizeof (cf);
14479 cf.hwndOwner = FRAME_W32_WINDOW (f);
14480 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
14482 /* Unless include_proportional is non-nil, limit the selection to
14483 monospaced fonts. */
14484 if (NILP (include_proportional))
14485 cf.Flags |= CF_FIXEDPITCHONLY;
14487 cf.lpLogFont = &lf;
14489 /* Initialize as much of the font details as we can from the current
14490 default font. */
14491 hdc = GetDC (FRAME_W32_WINDOW (f));
14492 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
14493 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
14494 if (GetTextMetrics (hdc, &tm))
14496 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
14497 lf.lfWeight = tm.tmWeight;
14498 lf.lfItalic = tm.tmItalic;
14499 lf.lfUnderline = tm.tmUnderlined;
14500 lf.lfStrikeOut = tm.tmStruckOut;
14501 lf.lfCharSet = tm.tmCharSet;
14502 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
14504 SelectObject (hdc, oldobj);
14505 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
14507 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
14508 return Qnil;
14510 return build_string (buf);
14513 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
14514 Sw32_send_sys_command, 1, 2, 0,
14515 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
14516 Some useful values for command are #xf030 to maximise frame (#xf020
14517 to minimize), #xf120 to restore frame to original size, and #xf100
14518 to activate the menubar for keyboard access. #xf140 activates the
14519 screen saver if defined.
14521 If optional parameter FRAME is not specified, use selected frame. */)
14522 (command, frame)
14523 Lisp_Object command, frame;
14525 FRAME_PTR f = check_x_frame (frame);
14527 CHECK_NUMBER (command);
14529 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
14531 return Qnil;
14534 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
14535 doc: /* Get Windows to perform OPERATION on DOCUMENT.
14536 This is a wrapper around the ShellExecute system function, which
14537 invokes the application registered to handle OPERATION for DOCUMENT.
14538 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
14539 nil for the default action), and DOCUMENT is typically the name of a
14540 document file or URL, but can also be a program executable to run or
14541 a directory to open in the Windows Explorer.
14543 If DOCUMENT is a program executable, PARAMETERS can be a string
14544 containing command line parameters, but otherwise should be nil.
14546 SHOW-FLAG can be used to control whether the invoked application is hidden
14547 or minimized. If SHOW-FLAG is nil, the application is displayed normally,
14548 otherwise it is an integer representing a ShowWindow flag:
14550 0 - start hidden
14551 1 - start normally
14552 3 - start maximized
14553 6 - start minimized */)
14554 (operation, document, parameters, show_flag)
14555 Lisp_Object operation, document, parameters, show_flag;
14557 Lisp_Object current_dir;
14559 CHECK_STRING (document);
14561 /* Encode filename and current directory. */
14562 current_dir = ENCODE_FILE (current_buffer->directory);
14563 document = ENCODE_FILE (document);
14564 if ((int) ShellExecute (NULL,
14565 (STRINGP (operation) ?
14566 SDATA (operation) : NULL),
14567 SDATA (document),
14568 (STRINGP (parameters) ?
14569 SDATA (parameters) : NULL),
14570 SDATA (current_dir),
14571 (INTEGERP (show_flag) ?
14572 XINT (show_flag) : SW_SHOWDEFAULT))
14573 > 32)
14574 return Qt;
14575 error ("ShellExecute failed: %s", w32_strerror (0));
14578 /* Lookup virtual keycode from string representing the name of a
14579 non-ascii keystroke into the corresponding virtual key, using
14580 lispy_function_keys. */
14581 static int
14582 lookup_vk_code (char *key)
14584 int i;
14586 for (i = 0; i < 256; i++)
14587 if (lispy_function_keys[i] != 0
14588 && strcmp (lispy_function_keys[i], key) == 0)
14589 return i;
14591 return -1;
14594 /* Convert a one-element vector style key sequence to a hot key
14595 definition. */
14596 static int
14597 w32_parse_hot_key (key)
14598 Lisp_Object key;
14600 /* Copied from Fdefine_key and store_in_keymap. */
14601 register Lisp_Object c;
14602 int vk_code;
14603 int lisp_modifiers;
14604 int w32_modifiers;
14605 struct gcpro gcpro1;
14607 CHECK_VECTOR (key);
14609 if (XFASTINT (Flength (key)) != 1)
14610 return Qnil;
14612 GCPRO1 (key);
14614 c = Faref (key, make_number (0));
14616 if (CONSP (c) && lucid_event_type_list_p (c))
14617 c = Fevent_convert_list (c);
14619 UNGCPRO;
14621 if (! INTEGERP (c) && ! SYMBOLP (c))
14622 error ("Key definition is invalid");
14624 /* Work out the base key and the modifiers. */
14625 if (SYMBOLP (c))
14627 c = parse_modifiers (c);
14628 lisp_modifiers = Fcar (Fcdr (c));
14629 c = Fcar (c);
14630 if (!SYMBOLP (c))
14631 abort ();
14632 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
14634 else if (INTEGERP (c))
14636 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
14637 /* Many ascii characters are their own virtual key code. */
14638 vk_code = XINT (c) & CHARACTERBITS;
14641 if (vk_code < 0 || vk_code > 255)
14642 return Qnil;
14644 if ((lisp_modifiers & meta_modifier) != 0
14645 && !NILP (Vw32_alt_is_meta))
14646 lisp_modifiers |= alt_modifier;
14648 /* Supply defs missing from mingw32. */
14649 #ifndef MOD_ALT
14650 #define MOD_ALT 0x0001
14651 #define MOD_CONTROL 0x0002
14652 #define MOD_SHIFT 0x0004
14653 #define MOD_WIN 0x0008
14654 #endif
14656 /* Convert lisp modifiers to Windows hot-key form. */
14657 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
14658 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
14659 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
14660 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
14662 return HOTKEY (vk_code, w32_modifiers);
14665 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
14666 Sw32_register_hot_key, 1, 1, 0,
14667 doc: /* Register KEY as a hot-key combination.
14668 Certain key combinations like Alt-Tab are reserved for system use on
14669 Windows, and therefore are normally intercepted by the system. However,
14670 most of these key combinations can be received by registering them as
14671 hot-keys, overriding their special meaning.
14673 KEY must be a one element key definition in vector form that would be
14674 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
14675 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
14676 is always interpreted as the Windows modifier keys.
14678 The return value is the hotkey-id if registered, otherwise nil. */)
14679 (key)
14680 Lisp_Object key;
14682 key = w32_parse_hot_key (key);
14684 if (NILP (Fmemq (key, w32_grabbed_keys)))
14686 /* Reuse an empty slot if possible. */
14687 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
14689 /* Safe to add new key to list, even if we have focus. */
14690 if (NILP (item))
14691 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
14692 else
14693 XSETCAR (item, key);
14695 /* Notify input thread about new hot-key definition, so that it
14696 takes effect without needing to switch focus. */
14697 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
14698 (WPARAM) key, 0);
14701 return key;
14704 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
14705 Sw32_unregister_hot_key, 1, 1, 0,
14706 doc: /* Unregister HOTKEY as a hot-key combination. */)
14707 (key)
14708 Lisp_Object key;
14710 Lisp_Object item;
14712 if (!INTEGERP (key))
14713 key = w32_parse_hot_key (key);
14715 item = Fmemq (key, w32_grabbed_keys);
14717 if (!NILP (item))
14719 /* Notify input thread about hot-key definition being removed, so
14720 that it takes effect without needing focus switch. */
14721 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
14722 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
14724 MSG msg;
14725 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14727 return Qt;
14729 return Qnil;
14732 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
14733 Sw32_registered_hot_keys, 0, 0, 0,
14734 doc: /* Return list of registered hot-key IDs. */)
14737 return Fcopy_sequence (w32_grabbed_keys);
14740 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
14741 Sw32_reconstruct_hot_key, 1, 1, 0,
14742 doc: /* Convert hot-key ID to a lisp key combination. */)
14743 (hotkeyid)
14744 Lisp_Object hotkeyid;
14746 int vk_code, w32_modifiers;
14747 Lisp_Object key;
14749 CHECK_NUMBER (hotkeyid);
14751 vk_code = HOTKEY_VK_CODE (hotkeyid);
14752 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
14754 if (lispy_function_keys[vk_code])
14755 key = intern (lispy_function_keys[vk_code]);
14756 else
14757 key = make_number (vk_code);
14759 key = Fcons (key, Qnil);
14760 if (w32_modifiers & MOD_SHIFT)
14761 key = Fcons (Qshift, key);
14762 if (w32_modifiers & MOD_CONTROL)
14763 key = Fcons (Qctrl, key);
14764 if (w32_modifiers & MOD_ALT)
14765 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
14766 if (w32_modifiers & MOD_WIN)
14767 key = Fcons (Qhyper, key);
14769 return key;
14772 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
14773 Sw32_toggle_lock_key, 1, 2, 0,
14774 doc: /* Toggle the state of the lock key KEY.
14775 KEY can be `capslock', `kp-numlock', or `scroll'.
14776 If the optional parameter NEW-STATE is a number, then the state of KEY
14777 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
14778 (key, new_state)
14779 Lisp_Object key, new_state;
14781 int vk_code;
14783 if (EQ (key, intern ("capslock")))
14784 vk_code = VK_CAPITAL;
14785 else if (EQ (key, intern ("kp-numlock")))
14786 vk_code = VK_NUMLOCK;
14787 else if (EQ (key, intern ("scroll")))
14788 vk_code = VK_SCROLL;
14789 else
14790 return Qnil;
14792 if (!dwWindowsThreadId)
14793 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
14795 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
14796 (WPARAM) vk_code, (LPARAM) new_state))
14798 MSG msg;
14799 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14800 return make_number (msg.wParam);
14802 return Qnil;
14805 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
14806 doc: /* Return storage information about the file system FILENAME is on.
14807 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
14808 storage of the file system, FREE is the free storage, and AVAIL is the
14809 storage available to a non-superuser. All 3 numbers are in bytes.
14810 If the underlying system call fails, value is nil. */)
14811 (filename)
14812 Lisp_Object filename;
14814 Lisp_Object encoded, value;
14816 CHECK_STRING (filename);
14817 filename = Fexpand_file_name (filename, Qnil);
14818 encoded = ENCODE_FILE (filename);
14820 value = Qnil;
14822 /* Determining the required information on Windows turns out, sadly,
14823 to be more involved than one would hope. The original Win32 api
14824 call for this will return bogus information on some systems, but we
14825 must dynamically probe for the replacement api, since that was
14826 added rather late on. */
14828 HMODULE hKernel = GetModuleHandle ("kernel32");
14829 BOOL (*pfn_GetDiskFreeSpaceEx)
14830 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
14831 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
14833 /* On Windows, we may need to specify the root directory of the
14834 volume holding FILENAME. */
14835 char rootname[MAX_PATH];
14836 char *name = SDATA (encoded);
14838 /* find the root name of the volume if given */
14839 if (isalpha (name[0]) && name[1] == ':')
14841 rootname[0] = name[0];
14842 rootname[1] = name[1];
14843 rootname[2] = '\\';
14844 rootname[3] = 0;
14846 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
14848 char *str = rootname;
14849 int slashes = 4;
14852 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
14853 break;
14854 *str++ = *name++;
14856 while ( *name );
14858 *str++ = '\\';
14859 *str = 0;
14862 if (pfn_GetDiskFreeSpaceEx)
14864 /* Unsigned large integers cannot be cast to double, so
14865 use signed ones instead. */
14866 LARGE_INTEGER availbytes;
14867 LARGE_INTEGER freebytes;
14868 LARGE_INTEGER totalbytes;
14870 if (pfn_GetDiskFreeSpaceEx(rootname,
14871 (ULARGE_INTEGER *)&availbytes,
14872 (ULARGE_INTEGER *)&totalbytes,
14873 (ULARGE_INTEGER *)&freebytes))
14874 value = list3 (make_float ((double) totalbytes.QuadPart),
14875 make_float ((double) freebytes.QuadPart),
14876 make_float ((double) availbytes.QuadPart));
14878 else
14880 DWORD sectors_per_cluster;
14881 DWORD bytes_per_sector;
14882 DWORD free_clusters;
14883 DWORD total_clusters;
14885 if (GetDiskFreeSpace(rootname,
14886 &sectors_per_cluster,
14887 &bytes_per_sector,
14888 &free_clusters,
14889 &total_clusters))
14890 value = list3 (make_float ((double) total_clusters
14891 * sectors_per_cluster * bytes_per_sector),
14892 make_float ((double) free_clusters
14893 * sectors_per_cluster * bytes_per_sector),
14894 make_float ((double) free_clusters
14895 * sectors_per_cluster * bytes_per_sector));
14899 return value;
14902 /***********************************************************************
14903 Initialization
14904 ***********************************************************************/
14906 void
14907 syms_of_w32fns ()
14909 HMODULE user32_lib = GetModuleHandle ("user32.dll");
14911 /* This is zero if not using MS-Windows. */
14912 w32_in_use = 0;
14914 /* TrackMouseEvent not available in all versions of Windows, so must load
14915 it dynamically. Do it once, here, instead of every time it is used. */
14916 track_mouse_event_fn = (TrackMouseEvent_Proc) GetProcAddress (user32_lib, "TrackMouseEvent");
14917 track_mouse_window = NULL;
14919 w32_visible_system_caret_hwnd = NULL;
14921 Qauto_raise = intern ("auto-raise");
14922 staticpro (&Qauto_raise);
14923 Qauto_lower = intern ("auto-lower");
14924 staticpro (&Qauto_lower);
14925 Qborder_color = intern ("border-color");
14926 staticpro (&Qborder_color);
14927 Qborder_width = intern ("border-width");
14928 staticpro (&Qborder_width);
14929 Qcursor_color = intern ("cursor-color");
14930 staticpro (&Qcursor_color);
14931 Qcursor_type = intern ("cursor-type");
14932 staticpro (&Qcursor_type);
14933 Qgeometry = intern ("geometry");
14934 staticpro (&Qgeometry);
14935 Qicon_left = intern ("icon-left");
14936 staticpro (&Qicon_left);
14937 Qicon_top = intern ("icon-top");
14938 staticpro (&Qicon_top);
14939 Qicon_type = intern ("icon-type");
14940 staticpro (&Qicon_type);
14941 Qicon_name = intern ("icon-name");
14942 staticpro (&Qicon_name);
14943 Qinternal_border_width = intern ("internal-border-width");
14944 staticpro (&Qinternal_border_width);
14945 Qleft = intern ("left");
14946 staticpro (&Qleft);
14947 Qright = intern ("right");
14948 staticpro (&Qright);
14949 Qmouse_color = intern ("mouse-color");
14950 staticpro (&Qmouse_color);
14951 Qnone = intern ("none");
14952 staticpro (&Qnone);
14953 Qparent_id = intern ("parent-id");
14954 staticpro (&Qparent_id);
14955 Qscroll_bar_width = intern ("scroll-bar-width");
14956 staticpro (&Qscroll_bar_width);
14957 Qsuppress_icon = intern ("suppress-icon");
14958 staticpro (&Qsuppress_icon);
14959 Qundefined_color = intern ("undefined-color");
14960 staticpro (&Qundefined_color);
14961 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
14962 staticpro (&Qvertical_scroll_bars);
14963 Qvisibility = intern ("visibility");
14964 staticpro (&Qvisibility);
14965 Qwindow_id = intern ("window-id");
14966 staticpro (&Qwindow_id);
14967 Qx_frame_parameter = intern ("x-frame-parameter");
14968 staticpro (&Qx_frame_parameter);
14969 Qx_resource_name = intern ("x-resource-name");
14970 staticpro (&Qx_resource_name);
14971 Quser_position = intern ("user-position");
14972 staticpro (&Quser_position);
14973 Quser_size = intern ("user-size");
14974 staticpro (&Quser_size);
14975 Qscreen_gamma = intern ("screen-gamma");
14976 staticpro (&Qscreen_gamma);
14977 Qline_spacing = intern ("line-spacing");
14978 staticpro (&Qline_spacing);
14979 Qcenter = intern ("center");
14980 staticpro (&Qcenter);
14981 Qcancel_timer = intern ("cancel-timer");
14982 staticpro (&Qcancel_timer);
14983 Qfullscreen = intern ("fullscreen");
14984 staticpro (&Qfullscreen);
14985 Qfullwidth = intern ("fullwidth");
14986 staticpro (&Qfullwidth);
14987 Qfullheight = intern ("fullheight");
14988 staticpro (&Qfullheight);
14989 Qfullboth = intern ("fullboth");
14990 staticpro (&Qfullboth);
14992 Qhyper = intern ("hyper");
14993 staticpro (&Qhyper);
14994 Qsuper = intern ("super");
14995 staticpro (&Qsuper);
14996 Qmeta = intern ("meta");
14997 staticpro (&Qmeta);
14998 Qalt = intern ("alt");
14999 staticpro (&Qalt);
15000 Qctrl = intern ("ctrl");
15001 staticpro (&Qctrl);
15002 Qcontrol = intern ("control");
15003 staticpro (&Qcontrol);
15004 Qshift = intern ("shift");
15005 staticpro (&Qshift);
15006 /* This is the end of symbol initialization. */
15008 /* Text property `display' should be nonsticky by default. */
15009 Vtext_property_default_nonsticky
15010 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
15013 Qlaplace = intern ("laplace");
15014 staticpro (&Qlaplace);
15015 Qemboss = intern ("emboss");
15016 staticpro (&Qemboss);
15017 Qedge_detection = intern ("edge-detection");
15018 staticpro (&Qedge_detection);
15019 Qheuristic = intern ("heuristic");
15020 staticpro (&Qheuristic);
15021 QCmatrix = intern (":matrix");
15022 staticpro (&QCmatrix);
15023 QCcolor_adjustment = intern (":color-adjustment");
15024 staticpro (&QCcolor_adjustment);
15025 QCmask = intern (":mask");
15026 staticpro (&QCmask);
15028 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
15029 staticpro (&Qface_set_after_frame_default);
15031 Fput (Qundefined_color, Qerror_conditions,
15032 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
15033 Fput (Qundefined_color, Qerror_message,
15034 build_string ("Undefined color"));
15036 staticpro (&w32_grabbed_keys);
15037 w32_grabbed_keys = Qnil;
15039 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
15040 doc: /* An array of color name mappings for windows. */);
15041 Vw32_color_map = Qnil;
15043 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
15044 doc: /* Non-nil if alt key presses are passed on to Windows.
15045 When non-nil, for example, alt pressed and released and then space will
15046 open the System menu. When nil, Emacs silently swallows alt key events. */);
15047 Vw32_pass_alt_to_system = Qnil;
15049 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
15050 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
15051 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
15052 Vw32_alt_is_meta = Qt;
15054 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
15055 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
15056 XSETINT (Vw32_quit_key, 0);
15058 DEFVAR_LISP ("w32-pass-lwindow-to-system",
15059 &Vw32_pass_lwindow_to_system,
15060 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
15061 When non-nil, the Start menu is opened by tapping the key. */);
15062 Vw32_pass_lwindow_to_system = Qt;
15064 DEFVAR_LISP ("w32-pass-rwindow-to-system",
15065 &Vw32_pass_rwindow_to_system,
15066 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
15067 When non-nil, the Start menu is opened by tapping the key. */);
15068 Vw32_pass_rwindow_to_system = Qt;
15070 DEFVAR_INT ("w32-phantom-key-code",
15071 &Vw32_phantom_key_code,
15072 doc: /* Virtual key code used to generate \"phantom\" key presses.
15073 Value is a number between 0 and 255.
15075 Phantom key presses are generated in order to stop the system from
15076 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
15077 `w32-pass-rwindow-to-system' is nil. */);
15078 /* Although 255 is technically not a valid key code, it works and
15079 means that this hack won't interfere with any real key code. */
15080 Vw32_phantom_key_code = 255;
15082 DEFVAR_LISP ("w32-enable-num-lock",
15083 &Vw32_enable_num_lock,
15084 doc: /* Non-nil if Num Lock should act normally.
15085 Set to nil to see Num Lock as the key `kp-numlock'. */);
15086 Vw32_enable_num_lock = Qt;
15088 DEFVAR_LISP ("w32-enable-caps-lock",
15089 &Vw32_enable_caps_lock,
15090 doc: /* Non-nil if Caps Lock should act normally.
15091 Set to nil to see Caps Lock as the key `capslock'. */);
15092 Vw32_enable_caps_lock = Qt;
15094 DEFVAR_LISP ("w32-scroll-lock-modifier",
15095 &Vw32_scroll_lock_modifier,
15096 doc: /* Modifier to use for the Scroll Lock on state.
15097 The value can be hyper, super, meta, alt, control or shift for the
15098 respective modifier, or nil to see Scroll Lock as the key `scroll'.
15099 Any other value will cause the key to be ignored. */);
15100 Vw32_scroll_lock_modifier = Qt;
15102 DEFVAR_LISP ("w32-lwindow-modifier",
15103 &Vw32_lwindow_modifier,
15104 doc: /* Modifier to use for the left \"Windows\" key.
15105 The value can be hyper, super, meta, alt, control or shift for the
15106 respective modifier, or nil to appear as the key `lwindow'.
15107 Any other value will cause the key to be ignored. */);
15108 Vw32_lwindow_modifier = Qnil;
15110 DEFVAR_LISP ("w32-rwindow-modifier",
15111 &Vw32_rwindow_modifier,
15112 doc: /* Modifier to use for the right \"Windows\" key.
15113 The value can be hyper, super, meta, alt, control or shift for the
15114 respective modifier, or nil to appear as the key `rwindow'.
15115 Any other value will cause the key to be ignored. */);
15116 Vw32_rwindow_modifier = Qnil;
15118 DEFVAR_LISP ("w32-apps-modifier",
15119 &Vw32_apps_modifier,
15120 doc: /* Modifier to use for the \"Apps\" key.
15121 The value can be hyper, super, meta, alt, control or shift for the
15122 respective modifier, or nil to appear as the key `apps'.
15123 Any other value will cause the key to be ignored. */);
15124 Vw32_apps_modifier = Qnil;
15126 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
15127 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
15128 w32_enable_synthesized_fonts = 0;
15130 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
15131 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
15132 Vw32_enable_palette = Qt;
15134 DEFVAR_INT ("w32-mouse-button-tolerance",
15135 &Vw32_mouse_button_tolerance,
15136 doc: /* Analogue of double click interval for faking middle mouse events.
15137 The value is the minimum time in milliseconds that must elapse between
15138 left/right button down events before they are considered distinct events.
15139 If both mouse buttons are depressed within this interval, a middle mouse
15140 button down event is generated instead. */);
15141 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
15143 DEFVAR_INT ("w32-mouse-move-interval",
15144 &Vw32_mouse_move_interval,
15145 doc: /* Minimum interval between mouse move events.
15146 The value is the minimum time in milliseconds that must elapse between
15147 successive mouse move (or scroll bar drag) events before they are
15148 reported as lisp events. */);
15149 XSETINT (Vw32_mouse_move_interval, 0);
15151 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
15152 &w32_pass_extra_mouse_buttons_to_system,
15153 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
15154 Recent versions of Windows support mice with up to five buttons.
15155 Since most applications don't support these extra buttons, most mouse
15156 drivers will allow you to map them to functions at the system level.
15157 If this variable is non-nil, Emacs will pass them on, allowing the
15158 system to handle them. */);
15159 w32_pass_extra_mouse_buttons_to_system = 0;
15161 init_x_parm_symbols ();
15163 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
15164 doc: /* List of directories to search for bitmap files for w32. */);
15165 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
15167 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
15168 doc: /* The shape of the pointer when over text.
15169 Changing the value does not affect existing frames
15170 unless you set the mouse color. */);
15171 Vx_pointer_shape = Qnil;
15173 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
15174 doc: /* The name Emacs uses to look up resources; for internal use only.
15175 `x-get-resource' uses this as the first component of the instance name
15176 when requesting resource values.
15177 Emacs initially sets `x-resource-name' to the name under which Emacs
15178 was invoked, or to the value specified with the `-name' or `-rn'
15179 switches, if present. */);
15180 Vx_resource_name = Qnil;
15182 Vx_nontext_pointer_shape = Qnil;
15184 Vx_mode_pointer_shape = Qnil;
15186 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
15187 doc: /* The shape of the pointer when Emacs is busy.
15188 This variable takes effect when you create a new frame
15189 or when you set the mouse color. */);
15190 Vx_hourglass_pointer_shape = Qnil;
15192 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
15193 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
15194 display_hourglass_p = 1;
15196 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
15197 doc: /* *Seconds to wait before displaying an hourglass pointer.
15198 Value must be an integer or float. */);
15199 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
15201 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
15202 &Vx_sensitive_text_pointer_shape,
15203 doc: /* The shape of the pointer when over mouse-sensitive text.
15204 This variable takes effect when you create a new frame
15205 or when you set the mouse color. */);
15206 Vx_sensitive_text_pointer_shape = Qnil;
15208 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
15209 &Vx_window_horizontal_drag_shape,
15210 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
15211 This variable takes effect when you create a new frame
15212 or when you set the mouse color. */);
15213 Vx_window_horizontal_drag_shape = Qnil;
15215 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
15216 doc: /* A string indicating the foreground color of the cursor box. */);
15217 Vx_cursor_fore_pixel = Qnil;
15219 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
15220 doc: /* Maximum size for tooltips.
15221 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
15222 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
15224 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
15225 doc: /* Non-nil if no window manager is in use.
15226 Emacs doesn't try to figure this out; this is always nil
15227 unless you set it to something else. */);
15228 /* We don't have any way to find this out, so set it to nil
15229 and maybe the user would like to set it to t. */
15230 Vx_no_window_manager = Qnil;
15232 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
15233 &Vx_pixel_size_width_font_regexp,
15234 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
15236 Since Emacs gets width of a font matching with this regexp from
15237 PIXEL_SIZE field of the name, font finding mechanism gets faster for
15238 such a font. This is especially effective for such large fonts as
15239 Chinese, Japanese, and Korean. */);
15240 Vx_pixel_size_width_font_regexp = Qnil;
15242 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
15243 doc: /* Time after which cached images are removed from the cache.
15244 When an image has not been displayed this many seconds, remove it
15245 from the image cache. Value must be an integer or nil with nil
15246 meaning don't clear the cache. */);
15247 Vimage_cache_eviction_delay = make_number (30 * 60);
15249 DEFVAR_LISP ("w32-bdf-filename-alist",
15250 &Vw32_bdf_filename_alist,
15251 doc: /* List of bdf fonts and their corresponding filenames. */);
15252 Vw32_bdf_filename_alist = Qnil;
15254 DEFVAR_BOOL ("w32-strict-fontnames",
15255 &w32_strict_fontnames,
15256 doc: /* Non-nil means only use fonts that are exact matches for those requested.
15257 Default is nil, which allows old fontnames that are not XLFD compliant,
15258 and allows third-party CJK display to work by specifying false charset
15259 fields to trick Emacs into translating to Big5, SJIS etc.
15260 Setting this to t will prevent wrong fonts being selected when
15261 fontsets are automatically created. */);
15262 w32_strict_fontnames = 0;
15264 DEFVAR_BOOL ("w32-strict-painting",
15265 &w32_strict_painting,
15266 doc: /* Non-nil means use strict rules for repainting frames.
15267 Set this to nil to get the old behaviour for repainting; this should
15268 only be necessary if the default setting causes problems. */);
15269 w32_strict_painting = 1;
15271 DEFVAR_LISP ("w32-charset-info-alist",
15272 &Vw32_charset_info_alist,
15273 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
15274 Each entry should be of the form:
15276 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
15278 where CHARSET_NAME is a string used in font names to identify the charset,
15279 WINDOWS_CHARSET is a symbol that can be one of:
15280 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
15281 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
15282 w32-charset-chinesebig5,
15283 #ifdef JOHAB_CHARSET
15284 w32-charset-johab, w32-charset-hebrew,
15285 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
15286 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
15287 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
15288 #endif
15289 #ifdef UNICODE_CHARSET
15290 w32-charset-unicode,
15291 #endif
15292 or w32-charset-oem.
15293 CODEPAGE should be an integer specifying the codepage that should be used
15294 to display the character set, t to do no translation and output as Unicode,
15295 or nil to do no translation and output as 8 bit (or multibyte on far-east
15296 versions of Windows) characters. */);
15297 Vw32_charset_info_alist = Qnil;
15299 staticpro (&Qw32_charset_ansi);
15300 Qw32_charset_ansi = intern ("w32-charset-ansi");
15301 staticpro (&Qw32_charset_symbol);
15302 Qw32_charset_symbol = intern ("w32-charset-symbol");
15303 staticpro (&Qw32_charset_shiftjis);
15304 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
15305 staticpro (&Qw32_charset_hangeul);
15306 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
15307 staticpro (&Qw32_charset_chinesebig5);
15308 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
15309 staticpro (&Qw32_charset_gb2312);
15310 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
15311 staticpro (&Qw32_charset_oem);
15312 Qw32_charset_oem = intern ("w32-charset-oem");
15314 #ifdef JOHAB_CHARSET
15316 static int w32_extra_charsets_defined = 1;
15317 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
15318 doc: /* Internal variable. */);
15320 staticpro (&Qw32_charset_johab);
15321 Qw32_charset_johab = intern ("w32-charset-johab");
15322 staticpro (&Qw32_charset_easteurope);
15323 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
15324 staticpro (&Qw32_charset_turkish);
15325 Qw32_charset_turkish = intern ("w32-charset-turkish");
15326 staticpro (&Qw32_charset_baltic);
15327 Qw32_charset_baltic = intern ("w32-charset-baltic");
15328 staticpro (&Qw32_charset_russian);
15329 Qw32_charset_russian = intern ("w32-charset-russian");
15330 staticpro (&Qw32_charset_arabic);
15331 Qw32_charset_arabic = intern ("w32-charset-arabic");
15332 staticpro (&Qw32_charset_greek);
15333 Qw32_charset_greek = intern ("w32-charset-greek");
15334 staticpro (&Qw32_charset_hebrew);
15335 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
15336 staticpro (&Qw32_charset_vietnamese);
15337 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
15338 staticpro (&Qw32_charset_thai);
15339 Qw32_charset_thai = intern ("w32-charset-thai");
15340 staticpro (&Qw32_charset_mac);
15341 Qw32_charset_mac = intern ("w32-charset-mac");
15343 #endif
15345 #ifdef UNICODE_CHARSET
15347 static int w32_unicode_charset_defined = 1;
15348 DEFVAR_BOOL ("w32-unicode-charset-defined",
15349 &w32_unicode_charset_defined,
15350 doc: /* Internal variable. */);
15352 staticpro (&Qw32_charset_unicode);
15353 Qw32_charset_unicode = intern ("w32-charset-unicode");
15354 #endif
15356 defsubr (&Sx_get_resource);
15357 #if 0 /* TODO: Port to W32 */
15358 defsubr (&Sx_change_window_property);
15359 defsubr (&Sx_delete_window_property);
15360 defsubr (&Sx_window_property);
15361 #endif
15362 defsubr (&Sxw_display_color_p);
15363 defsubr (&Sx_display_grayscale_p);
15364 defsubr (&Sxw_color_defined_p);
15365 defsubr (&Sxw_color_values);
15366 defsubr (&Sx_server_max_request_size);
15367 defsubr (&Sx_server_vendor);
15368 defsubr (&Sx_server_version);
15369 defsubr (&Sx_display_pixel_width);
15370 defsubr (&Sx_display_pixel_height);
15371 defsubr (&Sx_display_mm_width);
15372 defsubr (&Sx_display_mm_height);
15373 defsubr (&Sx_display_screens);
15374 defsubr (&Sx_display_planes);
15375 defsubr (&Sx_display_color_cells);
15376 defsubr (&Sx_display_visual_class);
15377 defsubr (&Sx_display_backing_store);
15378 defsubr (&Sx_display_save_under);
15379 defsubr (&Sx_parse_geometry);
15380 defsubr (&Sx_create_frame);
15381 defsubr (&Sx_open_connection);
15382 defsubr (&Sx_close_connection);
15383 defsubr (&Sx_display_list);
15384 defsubr (&Sx_synchronize);
15386 /* W32 specific functions */
15388 defsubr (&Sw32_focus_frame);
15389 defsubr (&Sw32_select_font);
15390 defsubr (&Sw32_define_rgb_color);
15391 defsubr (&Sw32_default_color_map);
15392 defsubr (&Sw32_load_color_file);
15393 defsubr (&Sw32_send_sys_command);
15394 defsubr (&Sw32_shell_execute);
15395 defsubr (&Sw32_register_hot_key);
15396 defsubr (&Sw32_unregister_hot_key);
15397 defsubr (&Sw32_registered_hot_keys);
15398 defsubr (&Sw32_reconstruct_hot_key);
15399 defsubr (&Sw32_toggle_lock_key);
15400 defsubr (&Sw32_find_bdf_fonts);
15402 defsubr (&Sfile_system_info);
15404 /* Setting callback functions for fontset handler. */
15405 get_font_info_func = w32_get_font_info;
15407 #if 0 /* This function pointer doesn't seem to be used anywhere.
15408 And the pointer assigned has the wrong type, anyway. */
15409 list_fonts_func = w32_list_fonts;
15410 #endif
15412 load_font_func = w32_load_font;
15413 find_ccl_program_func = w32_find_ccl_program;
15414 query_font_func = w32_query_font;
15415 set_frame_fontset_func = x_set_font;
15416 check_window_system_func = check_w32;
15418 /* Images. */
15419 Qxbm = intern ("xbm");
15420 staticpro (&Qxbm);
15421 QCconversion = intern (":conversion");
15422 staticpro (&QCconversion);
15423 QCheuristic_mask = intern (":heuristic-mask");
15424 staticpro (&QCheuristic_mask);
15425 QCcolor_symbols = intern (":color-symbols");
15426 staticpro (&QCcolor_symbols);
15427 QCascent = intern (":ascent");
15428 staticpro (&QCascent);
15429 QCmargin = intern (":margin");
15430 staticpro (&QCmargin);
15431 QCrelief = intern (":relief");
15432 staticpro (&QCrelief);
15433 Qpostscript = intern ("postscript");
15434 staticpro (&Qpostscript);
15435 #if 0 /* TODO: These need entries at top of file. */
15436 QCloader = intern (":loader");
15437 staticpro (&QCloader);
15438 QCbounding_box = intern (":bounding-box");
15439 staticpro (&QCbounding_box);
15440 QCpt_width = intern (":pt-width");
15441 staticpro (&QCpt_width);
15442 QCpt_height = intern (":pt-height");
15443 staticpro (&QCpt_height);
15444 #endif
15445 QCindex = intern (":index");
15446 staticpro (&QCindex);
15447 Qpbm = intern ("pbm");
15448 staticpro (&Qpbm);
15450 #if HAVE_XPM
15451 Qxpm = intern ("xpm");
15452 staticpro (&Qxpm);
15453 #endif
15455 #if HAVE_JPEG
15456 Qjpeg = intern ("jpeg");
15457 staticpro (&Qjpeg);
15458 #endif
15460 #if HAVE_TIFF
15461 Qtiff = intern ("tiff");
15462 staticpro (&Qtiff);
15463 #endif
15465 #if HAVE_GIF
15466 Qgif = intern ("gif");
15467 staticpro (&Qgif);
15468 #endif
15470 #if HAVE_PNG
15471 Qpng = intern ("png");
15472 staticpro (&Qpng);
15473 #endif
15475 defsubr (&Sclear_image_cache);
15476 defsubr (&Simage_size);
15477 defsubr (&Simage_mask_p);
15479 #if GLYPH_DEBUG
15480 defsubr (&Simagep);
15481 defsubr (&Slookup_image);
15482 #endif
15484 hourglass_atimer = NULL;
15485 hourglass_shown_p = 0;
15486 defsubr (&Sx_show_tip);
15487 defsubr (&Sx_hide_tip);
15488 tip_timer = Qnil;
15489 staticpro (&tip_timer);
15490 tip_frame = Qnil;
15491 staticpro (&tip_frame);
15493 last_show_tip_args = Qnil;
15494 staticpro (&last_show_tip_args);
15496 defsubr (&Sx_file_dialog);
15500 void
15501 init_xfns ()
15503 image_types = NULL;
15504 Vimage_types = Qnil;
15506 define_image_type (&pbm_type);
15507 define_image_type (&xbm_type);
15508 #if 0 /* TODO : Image support for W32 */
15509 define_image_type (&gs_type);
15510 #endif
15512 #if HAVE_XPM
15513 define_image_type (&xpm_type);
15514 #endif
15516 #if HAVE_JPEG
15517 define_image_type (&jpeg_type);
15518 #endif
15520 #if HAVE_TIFF
15521 define_image_type (&tiff_type);
15522 #endif
15524 #if HAVE_GIF
15525 define_image_type (&gif_type);
15526 #endif
15528 #if HAVE_PNG
15529 define_image_type (&png_type);
15530 #endif
15533 #undef abort
15535 void
15536 w32_abort()
15538 int button;
15539 button = MessageBox (NULL,
15540 "A fatal error has occurred!\n\n"
15541 "Select Abort to exit, Retry to debug, Ignore to continue",
15542 "Emacs Abort Dialog",
15543 MB_ICONEXCLAMATION | MB_TASKMODAL
15544 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
15545 switch (button)
15547 case IDRETRY:
15548 DebugBreak ();
15549 break;
15550 case IDIGNORE:
15551 break;
15552 case IDABORT:
15553 default:
15554 abort ();
15555 break;
15559 /* For convenience when debugging. */
15561 w32_last_error()
15563 return GetLastError ();