Version 2.0.25 released.
[emacs.git] / src / w32fns.c
blob2e0352ab68a9ea9aeb801b7e7da687c3f3690857
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 /* A definition of XColor for non-X frames. */
68 #ifndef HAVE_X_WINDOWS
69 typedef struct {
70 unsigned long pixel;
71 unsigned short red, green, blue;
72 char flags;
73 char pad;
74 } XColor;
75 #endif
77 extern char *lispy_function_keys[];
79 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
80 it, and including `bitmaps/gray' more than once is a problem when
81 config.h defines `static' as an empty replacement string. */
83 int gray_bitmap_width = gray_width;
84 int gray_bitmap_height = gray_height;
85 unsigned char *gray_bitmap_bits = gray_bits;
87 /* The colormap for converting color names to RGB values */
88 Lisp_Object Vw32_color_map;
90 /* Non nil if alt key presses are passed on to Windows. */
91 Lisp_Object Vw32_pass_alt_to_system;
93 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
94 to alt_modifier. */
95 Lisp_Object Vw32_alt_is_meta;
97 /* If non-zero, the windows virtual key code for an alternative quit key. */
98 Lisp_Object Vw32_quit_key;
100 /* Non nil if left window key events are passed on to Windows (this only
101 affects whether "tapping" the key opens the Start menu). */
102 Lisp_Object Vw32_pass_lwindow_to_system;
104 /* Non nil if right window key events are passed on to Windows (this
105 only affects whether "tapping" the key opens the Start menu). */
106 Lisp_Object Vw32_pass_rwindow_to_system;
108 /* Virtual key code used to generate "phantom" key presses in order
109 to stop system from acting on Windows key events. */
110 Lisp_Object Vw32_phantom_key_code;
112 /* Modifier associated with the left "Windows" key, or nil to act as a
113 normal key. */
114 Lisp_Object Vw32_lwindow_modifier;
116 /* Modifier associated with the right "Windows" key, or nil to act as a
117 normal key. */
118 Lisp_Object Vw32_rwindow_modifier;
120 /* Modifier associated with the "Apps" key, or nil to act as a normal
121 key. */
122 Lisp_Object Vw32_apps_modifier;
124 /* Value is nil if Num Lock acts as a function key. */
125 Lisp_Object Vw32_enable_num_lock;
127 /* Value is nil if Caps Lock acts as a function key. */
128 Lisp_Object Vw32_enable_caps_lock;
130 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
131 Lisp_Object Vw32_scroll_lock_modifier;
133 /* Switch to control whether we inhibit requests for synthesized bold
134 and italic versions of fonts. */
135 int w32_enable_synthesized_fonts;
137 /* Enable palette management. */
138 Lisp_Object Vw32_enable_palette;
140 /* Control how close left/right button down events must be to
141 be converted to a middle button down event. */
142 Lisp_Object Vw32_mouse_button_tolerance;
144 /* Minimum interval between mouse movement (and scroll bar drag)
145 events that are passed on to the event loop. */
146 Lisp_Object Vw32_mouse_move_interval;
148 /* Flag to indicate if XBUTTON events should be passed on to Windows. */
149 int w32_pass_extra_mouse_buttons_to_system;
151 /* The name we're using in resource queries. */
152 Lisp_Object Vx_resource_name;
154 /* Non nil if no window manager is in use. */
155 Lisp_Object Vx_no_window_manager;
157 /* Non-zero means we're allowed to display a hourglass pointer. */
159 int display_hourglass_p;
161 /* The background and shape of the mouse pointer, and shape when not
162 over text or in the modeline. */
164 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
165 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
167 /* The shape when over mouse-sensitive text. */
169 Lisp_Object Vx_sensitive_text_pointer_shape;
171 /* Color of chars displayed in cursor box. */
173 Lisp_Object Vx_cursor_fore_pixel;
175 /* Nonzero if using Windows. */
177 static int w32_in_use;
179 /* Search path for bitmap files. */
181 Lisp_Object Vx_bitmap_file_path;
183 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
185 Lisp_Object Vx_pixel_size_width_font_regexp;
187 /* Alist of bdf fonts and the files that define them. */
188 Lisp_Object Vw32_bdf_filename_alist;
190 /* A flag to control whether fonts are matched strictly or not. */
191 int w32_strict_fontnames;
193 /* A flag to control whether we should only repaint if GetUpdateRect
194 indicates there is an update region. */
195 int w32_strict_painting;
197 /* Associative list linking character set strings to Windows codepages. */
198 Lisp_Object Vw32_charset_info_alist;
200 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
201 #ifndef VIETNAMESE_CHARSET
202 #define VIETNAMESE_CHARSET 163
203 #endif
205 Lisp_Object Qauto_raise;
206 Lisp_Object Qauto_lower;
207 Lisp_Object Qborder_color;
208 Lisp_Object Qborder_width;
209 extern Lisp_Object Qbox;
210 Lisp_Object Qcursor_color;
211 Lisp_Object Qcursor_type;
212 Lisp_Object Qgeometry;
213 Lisp_Object Qicon_left;
214 Lisp_Object Qicon_top;
215 Lisp_Object Qicon_type;
216 Lisp_Object Qicon_name;
217 Lisp_Object Qinternal_border_width;
218 Lisp_Object Qleft;
219 Lisp_Object Qright;
220 Lisp_Object Qmouse_color;
221 Lisp_Object Qnone;
222 Lisp_Object Qparent_id;
223 Lisp_Object Qscroll_bar_width;
224 Lisp_Object Qsuppress_icon;
225 Lisp_Object Qundefined_color;
226 Lisp_Object Qvertical_scroll_bars;
227 Lisp_Object Qvisibility;
228 Lisp_Object Qwindow_id;
229 Lisp_Object Qx_frame_parameter;
230 Lisp_Object Qx_resource_name;
231 Lisp_Object Quser_position;
232 Lisp_Object Quser_size;
233 Lisp_Object Qscreen_gamma;
234 Lisp_Object Qline_spacing;
235 Lisp_Object Qcenter;
236 Lisp_Object Qcancel_timer;
237 Lisp_Object Qhyper;
238 Lisp_Object Qsuper;
239 Lisp_Object Qmeta;
240 Lisp_Object Qalt;
241 Lisp_Object Qctrl;
242 Lisp_Object Qcontrol;
243 Lisp_Object Qshift;
245 Lisp_Object Qw32_charset_ansi;
246 Lisp_Object Qw32_charset_default;
247 Lisp_Object Qw32_charset_symbol;
248 Lisp_Object Qw32_charset_shiftjis;
249 Lisp_Object Qw32_charset_hangeul;
250 Lisp_Object Qw32_charset_gb2312;
251 Lisp_Object Qw32_charset_chinesebig5;
252 Lisp_Object Qw32_charset_oem;
254 #ifndef JOHAB_CHARSET
255 #define JOHAB_CHARSET 130
256 #endif
257 #ifdef JOHAB_CHARSET
258 Lisp_Object Qw32_charset_easteurope;
259 Lisp_Object Qw32_charset_turkish;
260 Lisp_Object Qw32_charset_baltic;
261 Lisp_Object Qw32_charset_russian;
262 Lisp_Object Qw32_charset_arabic;
263 Lisp_Object Qw32_charset_greek;
264 Lisp_Object Qw32_charset_hebrew;
265 Lisp_Object Qw32_charset_vietnamese;
266 Lisp_Object Qw32_charset_thai;
267 Lisp_Object Qw32_charset_johab;
268 Lisp_Object Qw32_charset_mac;
269 #endif
271 #ifdef UNICODE_CHARSET
272 Lisp_Object Qw32_charset_unicode;
273 #endif
275 Lisp_Object Qfullscreen;
276 Lisp_Object Qfullwidth;
277 Lisp_Object Qfullheight;
278 Lisp_Object Qfullboth;
280 extern Lisp_Object Qtop;
281 extern Lisp_Object Qdisplay;
283 /* State variables for emulating a three button mouse. */
284 #define LMOUSE 1
285 #define MMOUSE 2
286 #define RMOUSE 4
288 static int button_state = 0;
289 static W32Msg saved_mouse_button_msg;
290 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
291 static W32Msg saved_mouse_move_msg;
292 static unsigned mouse_move_timer = 0;
294 /* Window that is tracking the mouse. */
295 static HWND track_mouse_window;
296 FARPROC track_mouse_event_fn;
298 /* W95 mousewheel handler */
299 unsigned int msh_mousewheel = 0;
301 /* Timers */
302 #define MOUSE_BUTTON_ID 1
303 #define MOUSE_MOVE_ID 2
304 #define MENU_FREE_ID 3
305 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
306 is received. */
307 #define MENU_FREE_DELAY 1000
308 static unsigned menu_free_timer = 0;
310 /* The below are defined in frame.c. */
312 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
313 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
314 extern Lisp_Object Qtool_bar_lines;
316 extern Lisp_Object Vwindow_system_version;
318 Lisp_Object Qface_set_after_frame_default;
320 #ifdef GLYPH_DEBUG
321 int image_cache_refcount, dpyinfo_refcount;
322 #endif
325 /* From w32term.c. */
326 extern Lisp_Object Vw32_num_mouse_buttons;
327 extern Lisp_Object Vw32_recognize_altgr;
329 extern HWND w32_system_caret_hwnd;
331 extern int w32_system_caret_height;
332 extern int w32_system_caret_x;
333 extern int w32_system_caret_y;
334 extern int w32_use_visible_system_caret;
336 static HWND w32_visible_system_caret_hwnd;
339 /* Error if we are not connected to MS-Windows. */
340 void
341 check_w32 ()
343 if (! w32_in_use)
344 error ("MS-Windows not in use or not initialized");
347 /* Nonzero if we can use mouse menus.
348 You should not call this unless HAVE_MENUS is defined. */
351 have_menus_p ()
353 return w32_in_use;
356 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
357 and checking validity for W32. */
359 FRAME_PTR
360 check_x_frame (frame)
361 Lisp_Object frame;
363 FRAME_PTR f;
365 if (NILP (frame))
366 frame = selected_frame;
367 CHECK_LIVE_FRAME (frame);
368 f = XFRAME (frame);
369 if (! FRAME_W32_P (f))
370 error ("non-w32 frame used");
371 return f;
374 /* Let the user specify an display with a frame.
375 nil stands for the selected frame--or, if that is not a w32 frame,
376 the first display on the list. */
378 static struct w32_display_info *
379 check_x_display_info (frame)
380 Lisp_Object frame;
382 if (NILP (frame))
384 struct frame *sf = XFRAME (selected_frame);
386 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
387 return FRAME_W32_DISPLAY_INFO (sf);
388 else
389 return &one_w32_display_info;
391 else if (STRINGP (frame))
392 return x_display_info_for_name (frame);
393 else
395 FRAME_PTR f;
397 CHECK_LIVE_FRAME (frame);
398 f = XFRAME (frame);
399 if (! FRAME_W32_P (f))
400 error ("non-w32 frame used");
401 return FRAME_W32_DISPLAY_INFO (f);
405 /* Return the Emacs frame-object corresponding to an w32 window.
406 It could be the frame's main window or an icon window. */
408 /* This function can be called during GC, so use GC_xxx type test macros. */
410 struct frame *
411 x_window_to_frame (dpyinfo, wdesc)
412 struct w32_display_info *dpyinfo;
413 HWND wdesc;
415 Lisp_Object tail, frame;
416 struct frame *f;
418 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
420 frame = XCAR (tail);
421 if (!GC_FRAMEP (frame))
422 continue;
423 f = XFRAME (frame);
424 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
425 continue;
426 if (f->output_data.w32->hourglass_window == wdesc)
427 return f;
429 if (FRAME_W32_WINDOW (f) == wdesc)
430 return f;
432 return 0;
437 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
438 id, which is just an int that this section returns. Bitmaps are
439 reference counted so they can be shared among frames.
441 Bitmap indices are guaranteed to be > 0, so a negative number can
442 be used to indicate no bitmap.
444 If you use x_create_bitmap_from_data, then you must keep track of
445 the bitmaps yourself. That is, creating a bitmap from the same
446 data more than once will not be caught. */
449 /* Functions to access the contents of a bitmap, given an id. */
452 x_bitmap_height (f, id)
453 FRAME_PTR f;
454 int id;
456 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
460 x_bitmap_width (f, id)
461 FRAME_PTR f;
462 int id;
464 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
468 x_bitmap_pixmap (f, id)
469 FRAME_PTR f;
470 int id;
472 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
476 /* Allocate a new bitmap record. Returns index of new record. */
478 static int
479 x_allocate_bitmap_record (f)
480 FRAME_PTR f;
482 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
483 int i;
485 if (dpyinfo->bitmaps == NULL)
487 dpyinfo->bitmaps_size = 10;
488 dpyinfo->bitmaps
489 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
490 dpyinfo->bitmaps_last = 1;
491 return 1;
494 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
495 return ++dpyinfo->bitmaps_last;
497 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
498 if (dpyinfo->bitmaps[i].refcount == 0)
499 return i + 1;
501 dpyinfo->bitmaps_size *= 2;
502 dpyinfo->bitmaps
503 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
504 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
505 return ++dpyinfo->bitmaps_last;
508 /* Add one reference to the reference count of the bitmap with id ID. */
510 void
511 x_reference_bitmap (f, id)
512 FRAME_PTR f;
513 int id;
515 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
518 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
521 x_create_bitmap_from_data (f, bits, width, height)
522 struct frame *f;
523 char *bits;
524 unsigned int width, height;
526 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
527 Pixmap bitmap;
528 int id;
530 bitmap = CreateBitmap (width, height,
531 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
532 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
533 bits);
535 if (! bitmap)
536 return -1;
538 id = x_allocate_bitmap_record (f);
539 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
540 dpyinfo->bitmaps[id - 1].file = NULL;
541 dpyinfo->bitmaps[id - 1].hinst = NULL;
542 dpyinfo->bitmaps[id - 1].refcount = 1;
543 dpyinfo->bitmaps[id - 1].depth = 1;
544 dpyinfo->bitmaps[id - 1].height = height;
545 dpyinfo->bitmaps[id - 1].width = width;
547 return id;
550 /* Create bitmap from file FILE for frame F. */
553 x_create_bitmap_from_file (f, file)
554 struct frame *f;
555 Lisp_Object file;
557 return -1;
558 #if 0 /* TODO : bitmap support */
559 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
560 unsigned int width, height;
561 HBITMAP bitmap;
562 int xhot, yhot, result, id;
563 Lisp_Object found;
564 int fd;
565 char *filename;
566 HINSTANCE hinst;
568 /* Look for an existing bitmap with the same name. */
569 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
571 if (dpyinfo->bitmaps[id].refcount
572 && dpyinfo->bitmaps[id].file
573 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
575 ++dpyinfo->bitmaps[id].refcount;
576 return id + 1;
580 /* Search bitmap-file-path for the file, if appropriate. */
581 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
582 if (fd < 0)
583 return -1;
584 emacs_close (fd);
586 filename = (char *) SDATA (found);
588 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
590 if (hinst == NULL)
591 return -1;
594 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
595 filename, &width, &height, &bitmap, &xhot, &yhot);
596 if (result != BitmapSuccess)
597 return -1;
599 id = x_allocate_bitmap_record (f);
600 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
601 dpyinfo->bitmaps[id - 1].refcount = 1;
602 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SCHARS (file) + 1);
603 dpyinfo->bitmaps[id - 1].depth = 1;
604 dpyinfo->bitmaps[id - 1].height = height;
605 dpyinfo->bitmaps[id - 1].width = width;
606 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
608 return id;
609 #endif /* TODO */
612 /* Remove reference to bitmap with id number ID. */
614 void
615 x_destroy_bitmap (f, id)
616 FRAME_PTR f;
617 int id;
619 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
621 if (id > 0)
623 --dpyinfo->bitmaps[id - 1].refcount;
624 if (dpyinfo->bitmaps[id - 1].refcount == 0)
626 BLOCK_INPUT;
627 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
628 if (dpyinfo->bitmaps[id - 1].file)
630 xfree (dpyinfo->bitmaps[id - 1].file);
631 dpyinfo->bitmaps[id - 1].file = NULL;
633 UNBLOCK_INPUT;
638 /* Free all the bitmaps for the display specified by DPYINFO. */
640 static void
641 x_destroy_all_bitmaps (dpyinfo)
642 struct w32_display_info *dpyinfo;
644 int i;
645 for (i = 0; i < dpyinfo->bitmaps_last; i++)
646 if (dpyinfo->bitmaps[i].refcount > 0)
648 DeleteObject (dpyinfo->bitmaps[i].pixmap);
649 if (dpyinfo->bitmaps[i].file)
650 xfree (dpyinfo->bitmaps[i].file);
652 dpyinfo->bitmaps_last = 0;
655 /* Connect the frame-parameter names for W32 frames
656 to the ways of passing the parameter values to the window system.
658 The name of a parameter, as a Lisp symbol,
659 has an `x-frame-parameter' property which is an integer in Lisp
660 but can be interpreted as an `enum x_frame_parm' in C. */
662 enum x_frame_parm
664 X_PARM_FOREGROUND_COLOR,
665 X_PARM_BACKGROUND_COLOR,
666 X_PARM_MOUSE_COLOR,
667 X_PARM_CURSOR_COLOR,
668 X_PARM_BORDER_COLOR,
669 X_PARM_ICON_TYPE,
670 X_PARM_FONT,
671 X_PARM_BORDER_WIDTH,
672 X_PARM_INTERNAL_BORDER_WIDTH,
673 X_PARM_NAME,
674 X_PARM_AUTORAISE,
675 X_PARM_AUTOLOWER,
676 X_PARM_VERT_SCROLL_BAR,
677 X_PARM_VISIBILITY,
678 X_PARM_MENU_BAR_LINES
682 struct x_frame_parm_table
684 char *name;
685 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
688 BOOL my_show_window P_ ((struct frame *, HWND, int));
689 void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
690 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
691 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
692 static void x_change_window_heights P_ ((Lisp_Object, int));
693 /* TODO: Native Input Method support; see x_create_im. */
694 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
695 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
696 static void x_set_fullscreen P_ ((struct frame *, Lisp_Object, Lisp_Object));
697 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
698 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
699 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
700 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
701 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
702 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
703 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
704 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
705 static void x_set_fringe_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
706 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
707 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
708 Lisp_Object));
709 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
710 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
711 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
712 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
713 Lisp_Object));
714 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
715 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
716 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
717 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
718 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
719 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
720 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
721 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
722 Lisp_Object));
724 static struct x_frame_parm_table x_frame_parms[] =
726 {"auto-raise", x_set_autoraise},
727 {"auto-lower", x_set_autolower},
728 {"background-color", x_set_background_color},
729 {"border-color", x_set_border_color},
730 {"border-width", x_set_border_width},
731 {"cursor-color", x_set_cursor_color},
732 {"cursor-type", x_set_cursor_type},
733 {"font", x_set_font},
734 {"foreground-color", x_set_foreground_color},
735 {"icon-name", x_set_icon_name},
736 {"icon-type", x_set_icon_type},
737 {"internal-border-width", x_set_internal_border_width},
738 {"menu-bar-lines", x_set_menu_bar_lines},
739 {"mouse-color", x_set_mouse_color},
740 {"name", x_explicitly_set_name},
741 {"scroll-bar-width", x_set_scroll_bar_width},
742 {"title", x_set_title},
743 {"unsplittable", x_set_unsplittable},
744 {"vertical-scroll-bars", x_set_vertical_scroll_bars},
745 {"visibility", x_set_visibility},
746 {"tool-bar-lines", x_set_tool_bar_lines},
747 {"screen-gamma", x_set_screen_gamma},
748 {"line-spacing", x_set_line_spacing},
749 {"left-fringe", x_set_fringe_width},
750 {"right-fringe", x_set_fringe_width},
751 {"fullscreen", x_set_fullscreen},
754 /* Attach the `x-frame-parameter' properties to
755 the Lisp symbol names of parameters relevant to W32. */
757 void
758 init_x_parm_symbols ()
760 int i;
762 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
763 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
764 make_number (i));
767 /* Really try to move where we want to be in case of fullscreen. Some WMs
768 moves the window where we tell them. Some (mwm, twm) moves the outer
769 window manager window there instead.
770 Try to compensate for those WM here. */
771 static void
772 x_fullscreen_move (f, new_top, new_left)
773 struct frame *f;
774 int new_top;
775 int new_left;
777 if (new_top != f->output_data.w32->top_pos
778 || new_left != f->output_data.w32->left_pos)
780 int move_x = new_left;
781 int move_y = new_top;
783 f->output_data.w32->want_fullscreen |= FULLSCREEN_MOVE_WAIT;
784 x_set_offset (f, move_x, move_y, 1);
788 /* Change the parameters of frame F as specified by ALIST.
789 If a parameter is not specially recognized, do nothing;
790 otherwise call the `x_set_...' function for that parameter. */
792 void
793 x_set_frame_parameters (f, alist)
794 FRAME_PTR f;
795 Lisp_Object alist;
797 Lisp_Object tail;
799 /* If both of these parameters are present, it's more efficient to
800 set them both at once. So we wait until we've looked at the
801 entire list before we set them. */
802 int width, height;
804 /* Same here. */
805 Lisp_Object left, top;
807 /* Same with these. */
808 Lisp_Object icon_left, icon_top;
810 /* Record in these vectors all the parms specified. */
811 Lisp_Object *parms;
812 Lisp_Object *values;
813 int i, p;
814 int left_no_change = 0, top_no_change = 0;
815 int icon_left_no_change = 0, icon_top_no_change = 0;
816 int fullscreen_is_being_set = 0;
818 struct gcpro gcpro1, gcpro2;
820 i = 0;
821 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
822 i++;
824 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
825 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
827 /* Extract parm names and values into those vectors. */
829 i = 0;
830 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
832 Lisp_Object elt;
834 elt = Fcar (tail);
835 parms[i] = Fcar (elt);
836 values[i] = Fcdr (elt);
837 i++;
839 /* TAIL and ALIST are not used again below here. */
840 alist = tail = Qnil;
842 GCPRO2 (*parms, *values);
843 gcpro1.nvars = i;
844 gcpro2.nvars = i;
846 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
847 because their values appear in VALUES and strings are not valid. */
848 top = left = Qunbound;
849 icon_left = icon_top = Qunbound;
851 /* Provide default values for HEIGHT and WIDTH. */
852 if (FRAME_NEW_WIDTH (f))
853 width = FRAME_NEW_WIDTH (f);
854 else
855 width = FRAME_WIDTH (f);
857 if (FRAME_NEW_HEIGHT (f))
858 height = FRAME_NEW_HEIGHT (f);
859 else
860 height = FRAME_HEIGHT (f);
862 /* Process foreground_color and background_color before anything else.
863 They are independent of other properties, but other properties (e.g.,
864 cursor_color) are dependent upon them. */
865 /* Process default font as well, since fringe widths depends on it. */
866 for (p = 0; p < i; p++)
868 Lisp_Object prop, val;
870 prop = parms[p];
871 val = values[p];
872 if (EQ (prop, Qforeground_color)
873 || EQ (prop, Qbackground_color)
874 || EQ (prop, Qfont)
875 || EQ (prop, Qfullscreen))
877 register Lisp_Object param_index, old_value;
879 old_value = get_frame_param (f, prop);
880 fullscreen_is_being_set |= EQ (prop, Qfullscreen);
882 if (NILP (Fequal (val, old_value)))
884 store_frame_param (f, prop, val);
886 param_index = Fget (prop, Qx_frame_parameter);
887 if (NATNUMP (param_index)
888 && (XFASTINT (param_index)
889 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
890 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
895 /* Now process them in reverse of specified order. */
896 for (i--; i >= 0; i--)
898 Lisp_Object prop, val;
900 prop = parms[i];
901 val = values[i];
903 if (EQ (prop, Qwidth) && NUMBERP (val))
904 width = XFASTINT (val);
905 else if (EQ (prop, Qheight) && NUMBERP (val))
906 height = XFASTINT (val);
907 else if (EQ (prop, Qtop))
908 top = val;
909 else if (EQ (prop, Qleft))
910 left = val;
911 else if (EQ (prop, Qicon_top))
912 icon_top = val;
913 else if (EQ (prop, Qicon_left))
914 icon_left = val;
915 else if (EQ (prop, Qforeground_color)
916 || EQ (prop, Qbackground_color)
917 || EQ (prop, Qfont)
918 || EQ (prop, Qfullscreen))
919 /* Processed above. */
920 continue;
921 else
923 register Lisp_Object param_index, old_value;
925 old_value = get_frame_param (f, prop);
927 store_frame_param (f, prop, val);
929 param_index = Fget (prop, Qx_frame_parameter);
930 if (NATNUMP (param_index)
931 && (XFASTINT (param_index)
932 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
933 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
937 /* Don't die if just one of these was set. */
938 if (EQ (left, Qunbound))
940 left_no_change = 1;
941 if (f->output_data.w32->left_pos < 0)
942 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
943 else
944 XSETINT (left, f->output_data.w32->left_pos);
946 if (EQ (top, Qunbound))
948 top_no_change = 1;
949 if (f->output_data.w32->top_pos < 0)
950 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
951 else
952 XSETINT (top, f->output_data.w32->top_pos);
955 /* If one of the icon positions was not set, preserve or default it. */
956 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
958 icon_left_no_change = 1;
959 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
960 if (NILP (icon_left))
961 XSETINT (icon_left, 0);
963 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
965 icon_top_no_change = 1;
966 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
967 if (NILP (icon_top))
968 XSETINT (icon_top, 0);
971 if (FRAME_VISIBLE_P (f) && fullscreen_is_being_set)
973 /* If the frame is visible already and the fullscreen parameter is
974 being set, it is too late to set WM manager hints to specify
975 size and position.
976 Here we first get the width, height and position that applies to
977 fullscreen. We then move the frame to the appropriate
978 position. Resize of the frame is taken care of in the code after
979 this if-statement. */
980 int new_left, new_top;
982 x_fullscreen_adjust (f, &width, &height, &new_top, &new_left);
983 x_fullscreen_move (f, new_top, new_left);
986 /* Don't set these parameters unless they've been explicitly
987 specified. The window might be mapped or resized while we're in
988 this function, and we don't want to override that unless the lisp
989 code has asked for it.
991 Don't set these parameters unless they actually differ from the
992 window's current parameters; the window may not actually exist
993 yet. */
995 Lisp_Object frame;
997 check_frame_size (f, &height, &width);
999 XSETFRAME (frame, f);
1001 if (width != FRAME_WIDTH (f)
1002 || height != FRAME_HEIGHT (f)
1003 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
1004 Fset_frame_size (frame, make_number (width), make_number (height));
1006 if ((!NILP (left) || !NILP (top))
1007 && ! (left_no_change && top_no_change)
1008 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
1009 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
1011 int leftpos = 0;
1012 int toppos = 0;
1014 /* Record the signs. */
1015 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
1016 if (EQ (left, Qminus))
1017 f->output_data.w32->size_hint_flags |= XNegative;
1018 else if (INTEGERP (left))
1020 leftpos = XINT (left);
1021 if (leftpos < 0)
1022 f->output_data.w32->size_hint_flags |= XNegative;
1024 else if (CONSP (left) && EQ (XCAR (left), Qminus)
1025 && CONSP (XCDR (left))
1026 && INTEGERP (XCAR (XCDR (left))))
1028 leftpos = - XINT (XCAR (XCDR (left)));
1029 f->output_data.w32->size_hint_flags |= XNegative;
1031 else if (CONSP (left) && EQ (XCAR (left), Qplus)
1032 && CONSP (XCDR (left))
1033 && INTEGERP (XCAR (XCDR (left))))
1035 leftpos = XINT (XCAR (XCDR (left)));
1038 if (EQ (top, Qminus))
1039 f->output_data.w32->size_hint_flags |= YNegative;
1040 else if (INTEGERP (top))
1042 toppos = XINT (top);
1043 if (toppos < 0)
1044 f->output_data.w32->size_hint_flags |= YNegative;
1046 else if (CONSP (top) && EQ (XCAR (top), Qminus)
1047 && CONSP (XCDR (top))
1048 && INTEGERP (XCAR (XCDR (top))))
1050 toppos = - XINT (XCAR (XCDR (top)));
1051 f->output_data.w32->size_hint_flags |= YNegative;
1053 else if (CONSP (top) && EQ (XCAR (top), Qplus)
1054 && CONSP (XCDR (top))
1055 && INTEGERP (XCAR (XCDR (top))))
1057 toppos = XINT (XCAR (XCDR (top)));
1061 /* Store the numeric value of the position. */
1062 f->output_data.w32->top_pos = toppos;
1063 f->output_data.w32->left_pos = leftpos;
1065 f->output_data.w32->win_gravity = NorthWestGravity;
1067 /* Actually set that position, and convert to absolute. */
1068 x_set_offset (f, leftpos, toppos, -1);
1071 if ((!NILP (icon_left) || !NILP (icon_top))
1072 && ! (icon_left_no_change && icon_top_no_change))
1073 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1076 UNGCPRO;
1079 /* Store the screen positions of frame F into XPTR and YPTR.
1080 These are the positions of the containing window manager window,
1081 not Emacs's own window. */
1083 void
1084 x_real_positions (f, xptr, yptr)
1085 FRAME_PTR f;
1086 int *xptr, *yptr;
1088 POINT pt;
1089 RECT rect;
1091 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1092 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1094 pt.x = rect.left;
1095 pt.y = rect.top;
1097 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1099 /* Remember x_pixels_diff and y_pixels_diff. */
1100 f->output_data.w32->x_pixels_diff = pt.x - rect.left;
1101 f->output_data.w32->y_pixels_diff = pt.y - rect.top;
1103 *xptr = pt.x;
1104 *yptr = pt.y;
1107 /* Insert a description of internally-recorded parameters of frame X
1108 into the parameter alist *ALISTPTR that is to be given to the user.
1109 Only parameters that are specific to W32
1110 and whose values are not correctly recorded in the frame's
1111 param_alist need to be considered here. */
1113 void
1114 x_report_frame_params (f, alistptr)
1115 struct frame *f;
1116 Lisp_Object *alistptr;
1118 char buf[16];
1119 Lisp_Object tem;
1121 /* Represent negative positions (off the top or left screen edge)
1122 in a way that Fmodify_frame_parameters will understand correctly. */
1123 XSETINT (tem, f->output_data.w32->left_pos);
1124 if (f->output_data.w32->left_pos >= 0)
1125 store_in_alist (alistptr, Qleft, tem);
1126 else
1127 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1129 XSETINT (tem, f->output_data.w32->top_pos);
1130 if (f->output_data.w32->top_pos >= 0)
1131 store_in_alist (alistptr, Qtop, tem);
1132 else
1133 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1135 store_in_alist (alistptr, Qborder_width,
1136 make_number (f->output_data.w32->border_width));
1137 store_in_alist (alistptr, Qinternal_border_width,
1138 make_number (f->output_data.w32->internal_border_width));
1139 store_in_alist (alistptr, Qleft_fringe,
1140 make_number (f->output_data.w32->left_fringe_width));
1141 store_in_alist (alistptr, Qright_fringe,
1142 make_number (f->output_data.w32->right_fringe_width));
1143 store_in_alist (alistptr, Qscroll_bar_width,
1144 make_number (FRAME_HAS_VERTICAL_SCROLL_BARS (f)
1145 ? FRAME_SCROLL_BAR_PIXEL_WIDTH(f)
1146 : 0));
1147 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1148 store_in_alist (alistptr, Qwindow_id,
1149 build_string (buf));
1150 store_in_alist (alistptr, Qicon_name, f->icon_name);
1151 FRAME_SAMPLE_VISIBILITY (f);
1152 store_in_alist (alistptr, Qvisibility,
1153 (FRAME_VISIBLE_P (f) ? Qt
1154 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1155 store_in_alist (alistptr, Qdisplay,
1156 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1160 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
1161 Sw32_define_rgb_color, 4, 4, 0,
1162 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
1163 This adds or updates a named color to w32-color-map, making it
1164 available for use. The original entry's RGB ref is returned, or nil
1165 if the entry is new. */)
1166 (red, green, blue, name)
1167 Lisp_Object red, green, blue, name;
1169 Lisp_Object rgb;
1170 Lisp_Object oldrgb = Qnil;
1171 Lisp_Object entry;
1173 CHECK_NUMBER (red);
1174 CHECK_NUMBER (green);
1175 CHECK_NUMBER (blue);
1176 CHECK_STRING (name);
1178 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1180 BLOCK_INPUT;
1182 /* replace existing entry in w32-color-map or add new entry. */
1183 entry = Fassoc (name, Vw32_color_map);
1184 if (NILP (entry))
1186 entry = Fcons (name, rgb);
1187 Vw32_color_map = Fcons (entry, Vw32_color_map);
1189 else
1191 oldrgb = Fcdr (entry);
1192 Fsetcdr (entry, rgb);
1195 UNBLOCK_INPUT;
1197 return (oldrgb);
1200 DEFUN ("w32-load-color-file", Fw32_load_color_file,
1201 Sw32_load_color_file, 1, 1, 0,
1202 doc: /* Create an alist of color entries from an external file.
1203 Assign this value to w32-color-map to replace the existing color map.
1205 The file should define one named RGB color per line like so:
1206 R G B name
1207 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
1208 (filename)
1209 Lisp_Object filename;
1211 FILE *fp;
1212 Lisp_Object cmap = Qnil;
1213 Lisp_Object abspath;
1215 CHECK_STRING (filename);
1216 abspath = Fexpand_file_name (filename, Qnil);
1218 fp = fopen (SDATA (filename), "rt");
1219 if (fp)
1221 char buf[512];
1222 int red, green, blue;
1223 int num;
1225 BLOCK_INPUT;
1227 while (fgets (buf, sizeof (buf), fp) != NULL) {
1228 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1230 char *name = buf + num;
1231 num = strlen (name) - 1;
1232 if (name[num] == '\n')
1233 name[num] = 0;
1234 cmap = Fcons (Fcons (build_string (name),
1235 make_number (RGB (red, green, blue))),
1236 cmap);
1239 fclose (fp);
1241 UNBLOCK_INPUT;
1244 return cmap;
1247 /* The default colors for the w32 color map */
1248 typedef struct colormap_t
1250 char *name;
1251 COLORREF colorref;
1252 } colormap_t;
1254 colormap_t w32_color_map[] =
1256 {"snow" , PALETTERGB (255,250,250)},
1257 {"ghost white" , PALETTERGB (248,248,255)},
1258 {"GhostWhite" , PALETTERGB (248,248,255)},
1259 {"white smoke" , PALETTERGB (245,245,245)},
1260 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1261 {"gainsboro" , PALETTERGB (220,220,220)},
1262 {"floral white" , PALETTERGB (255,250,240)},
1263 {"FloralWhite" , PALETTERGB (255,250,240)},
1264 {"old lace" , PALETTERGB (253,245,230)},
1265 {"OldLace" , PALETTERGB (253,245,230)},
1266 {"linen" , PALETTERGB (250,240,230)},
1267 {"antique white" , PALETTERGB (250,235,215)},
1268 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1269 {"papaya whip" , PALETTERGB (255,239,213)},
1270 {"PapayaWhip" , PALETTERGB (255,239,213)},
1271 {"blanched almond" , PALETTERGB (255,235,205)},
1272 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1273 {"bisque" , PALETTERGB (255,228,196)},
1274 {"peach puff" , PALETTERGB (255,218,185)},
1275 {"PeachPuff" , PALETTERGB (255,218,185)},
1276 {"navajo white" , PALETTERGB (255,222,173)},
1277 {"NavajoWhite" , PALETTERGB (255,222,173)},
1278 {"moccasin" , PALETTERGB (255,228,181)},
1279 {"cornsilk" , PALETTERGB (255,248,220)},
1280 {"ivory" , PALETTERGB (255,255,240)},
1281 {"lemon chiffon" , PALETTERGB (255,250,205)},
1282 {"LemonChiffon" , PALETTERGB (255,250,205)},
1283 {"seashell" , PALETTERGB (255,245,238)},
1284 {"honeydew" , PALETTERGB (240,255,240)},
1285 {"mint cream" , PALETTERGB (245,255,250)},
1286 {"MintCream" , PALETTERGB (245,255,250)},
1287 {"azure" , PALETTERGB (240,255,255)},
1288 {"alice blue" , PALETTERGB (240,248,255)},
1289 {"AliceBlue" , PALETTERGB (240,248,255)},
1290 {"lavender" , PALETTERGB (230,230,250)},
1291 {"lavender blush" , PALETTERGB (255,240,245)},
1292 {"LavenderBlush" , PALETTERGB (255,240,245)},
1293 {"misty rose" , PALETTERGB (255,228,225)},
1294 {"MistyRose" , PALETTERGB (255,228,225)},
1295 {"white" , PALETTERGB (255,255,255)},
1296 {"black" , PALETTERGB ( 0, 0, 0)},
1297 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1298 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1299 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1300 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1301 {"dim gray" , PALETTERGB (105,105,105)},
1302 {"DimGray" , PALETTERGB (105,105,105)},
1303 {"dim grey" , PALETTERGB (105,105,105)},
1304 {"DimGrey" , PALETTERGB (105,105,105)},
1305 {"slate gray" , PALETTERGB (112,128,144)},
1306 {"SlateGray" , PALETTERGB (112,128,144)},
1307 {"slate grey" , PALETTERGB (112,128,144)},
1308 {"SlateGrey" , PALETTERGB (112,128,144)},
1309 {"light slate gray" , PALETTERGB (119,136,153)},
1310 {"LightSlateGray" , PALETTERGB (119,136,153)},
1311 {"light slate grey" , PALETTERGB (119,136,153)},
1312 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1313 {"gray" , PALETTERGB (190,190,190)},
1314 {"grey" , PALETTERGB (190,190,190)},
1315 {"light grey" , PALETTERGB (211,211,211)},
1316 {"LightGrey" , PALETTERGB (211,211,211)},
1317 {"light gray" , PALETTERGB (211,211,211)},
1318 {"LightGray" , PALETTERGB (211,211,211)},
1319 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1320 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1321 {"navy" , PALETTERGB ( 0, 0,128)},
1322 {"navy blue" , PALETTERGB ( 0, 0,128)},
1323 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1324 {"cornflower blue" , PALETTERGB (100,149,237)},
1325 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1326 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1327 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1328 {"slate blue" , PALETTERGB (106, 90,205)},
1329 {"SlateBlue" , PALETTERGB (106, 90,205)},
1330 {"medium slate blue" , PALETTERGB (123,104,238)},
1331 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1332 {"light slate blue" , PALETTERGB (132,112,255)},
1333 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1334 {"medium blue" , PALETTERGB ( 0, 0,205)},
1335 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1336 {"royal blue" , PALETTERGB ( 65,105,225)},
1337 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1338 {"blue" , PALETTERGB ( 0, 0,255)},
1339 {"dodger blue" , PALETTERGB ( 30,144,255)},
1340 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1341 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1342 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1343 {"sky blue" , PALETTERGB (135,206,235)},
1344 {"SkyBlue" , PALETTERGB (135,206,235)},
1345 {"light sky blue" , PALETTERGB (135,206,250)},
1346 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1347 {"steel blue" , PALETTERGB ( 70,130,180)},
1348 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1349 {"light steel blue" , PALETTERGB (176,196,222)},
1350 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1351 {"light blue" , PALETTERGB (173,216,230)},
1352 {"LightBlue" , PALETTERGB (173,216,230)},
1353 {"powder blue" , PALETTERGB (176,224,230)},
1354 {"PowderBlue" , PALETTERGB (176,224,230)},
1355 {"pale turquoise" , PALETTERGB (175,238,238)},
1356 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1357 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1358 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1359 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1360 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1361 {"turquoise" , PALETTERGB ( 64,224,208)},
1362 {"cyan" , PALETTERGB ( 0,255,255)},
1363 {"light cyan" , PALETTERGB (224,255,255)},
1364 {"LightCyan" , PALETTERGB (224,255,255)},
1365 {"cadet blue" , PALETTERGB ( 95,158,160)},
1366 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1367 {"medium aquamarine" , PALETTERGB (102,205,170)},
1368 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1369 {"aquamarine" , PALETTERGB (127,255,212)},
1370 {"dark green" , PALETTERGB ( 0,100, 0)},
1371 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1372 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1373 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1374 {"dark sea green" , PALETTERGB (143,188,143)},
1375 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1376 {"sea green" , PALETTERGB ( 46,139, 87)},
1377 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1378 {"medium sea green" , PALETTERGB ( 60,179,113)},
1379 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1380 {"light sea green" , PALETTERGB ( 32,178,170)},
1381 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1382 {"pale green" , PALETTERGB (152,251,152)},
1383 {"PaleGreen" , PALETTERGB (152,251,152)},
1384 {"spring green" , PALETTERGB ( 0,255,127)},
1385 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1386 {"lawn green" , PALETTERGB (124,252, 0)},
1387 {"LawnGreen" , PALETTERGB (124,252, 0)},
1388 {"green" , PALETTERGB ( 0,255, 0)},
1389 {"chartreuse" , PALETTERGB (127,255, 0)},
1390 {"medium spring green" , PALETTERGB ( 0,250,154)},
1391 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1392 {"green yellow" , PALETTERGB (173,255, 47)},
1393 {"GreenYellow" , PALETTERGB (173,255, 47)},
1394 {"lime green" , PALETTERGB ( 50,205, 50)},
1395 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1396 {"yellow green" , PALETTERGB (154,205, 50)},
1397 {"YellowGreen" , PALETTERGB (154,205, 50)},
1398 {"forest green" , PALETTERGB ( 34,139, 34)},
1399 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1400 {"olive drab" , PALETTERGB (107,142, 35)},
1401 {"OliveDrab" , PALETTERGB (107,142, 35)},
1402 {"dark khaki" , PALETTERGB (189,183,107)},
1403 {"DarkKhaki" , PALETTERGB (189,183,107)},
1404 {"khaki" , PALETTERGB (240,230,140)},
1405 {"pale goldenrod" , PALETTERGB (238,232,170)},
1406 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1407 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1408 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1409 {"light yellow" , PALETTERGB (255,255,224)},
1410 {"LightYellow" , PALETTERGB (255,255,224)},
1411 {"yellow" , PALETTERGB (255,255, 0)},
1412 {"gold" , PALETTERGB (255,215, 0)},
1413 {"light goldenrod" , PALETTERGB (238,221,130)},
1414 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1415 {"goldenrod" , PALETTERGB (218,165, 32)},
1416 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1417 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1418 {"rosy brown" , PALETTERGB (188,143,143)},
1419 {"RosyBrown" , PALETTERGB (188,143,143)},
1420 {"indian red" , PALETTERGB (205, 92, 92)},
1421 {"IndianRed" , PALETTERGB (205, 92, 92)},
1422 {"saddle brown" , PALETTERGB (139, 69, 19)},
1423 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1424 {"sienna" , PALETTERGB (160, 82, 45)},
1425 {"peru" , PALETTERGB (205,133, 63)},
1426 {"burlywood" , PALETTERGB (222,184,135)},
1427 {"beige" , PALETTERGB (245,245,220)},
1428 {"wheat" , PALETTERGB (245,222,179)},
1429 {"sandy brown" , PALETTERGB (244,164, 96)},
1430 {"SandyBrown" , PALETTERGB (244,164, 96)},
1431 {"tan" , PALETTERGB (210,180,140)},
1432 {"chocolate" , PALETTERGB (210,105, 30)},
1433 {"firebrick" , PALETTERGB (178,34, 34)},
1434 {"brown" , PALETTERGB (165,42, 42)},
1435 {"dark salmon" , PALETTERGB (233,150,122)},
1436 {"DarkSalmon" , PALETTERGB (233,150,122)},
1437 {"salmon" , PALETTERGB (250,128,114)},
1438 {"light salmon" , PALETTERGB (255,160,122)},
1439 {"LightSalmon" , PALETTERGB (255,160,122)},
1440 {"orange" , PALETTERGB (255,165, 0)},
1441 {"dark orange" , PALETTERGB (255,140, 0)},
1442 {"DarkOrange" , PALETTERGB (255,140, 0)},
1443 {"coral" , PALETTERGB (255,127, 80)},
1444 {"light coral" , PALETTERGB (240,128,128)},
1445 {"LightCoral" , PALETTERGB (240,128,128)},
1446 {"tomato" , PALETTERGB (255, 99, 71)},
1447 {"orange red" , PALETTERGB (255, 69, 0)},
1448 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1449 {"red" , PALETTERGB (255, 0, 0)},
1450 {"hot pink" , PALETTERGB (255,105,180)},
1451 {"HotPink" , PALETTERGB (255,105,180)},
1452 {"deep pink" , PALETTERGB (255, 20,147)},
1453 {"DeepPink" , PALETTERGB (255, 20,147)},
1454 {"pink" , PALETTERGB (255,192,203)},
1455 {"light pink" , PALETTERGB (255,182,193)},
1456 {"LightPink" , PALETTERGB (255,182,193)},
1457 {"pale violet red" , PALETTERGB (219,112,147)},
1458 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1459 {"maroon" , PALETTERGB (176, 48, 96)},
1460 {"medium violet red" , PALETTERGB (199, 21,133)},
1461 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1462 {"violet red" , PALETTERGB (208, 32,144)},
1463 {"VioletRed" , PALETTERGB (208, 32,144)},
1464 {"magenta" , PALETTERGB (255, 0,255)},
1465 {"violet" , PALETTERGB (238,130,238)},
1466 {"plum" , PALETTERGB (221,160,221)},
1467 {"orchid" , PALETTERGB (218,112,214)},
1468 {"medium orchid" , PALETTERGB (186, 85,211)},
1469 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1470 {"dark orchid" , PALETTERGB (153, 50,204)},
1471 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1472 {"dark violet" , PALETTERGB (148, 0,211)},
1473 {"DarkViolet" , PALETTERGB (148, 0,211)},
1474 {"blue violet" , PALETTERGB (138, 43,226)},
1475 {"BlueViolet" , PALETTERGB (138, 43,226)},
1476 {"purple" , PALETTERGB (160, 32,240)},
1477 {"medium purple" , PALETTERGB (147,112,219)},
1478 {"MediumPurple" , PALETTERGB (147,112,219)},
1479 {"thistle" , PALETTERGB (216,191,216)},
1480 {"gray0" , PALETTERGB ( 0, 0, 0)},
1481 {"grey0" , PALETTERGB ( 0, 0, 0)},
1482 {"dark grey" , PALETTERGB (169,169,169)},
1483 {"DarkGrey" , PALETTERGB (169,169,169)},
1484 {"dark gray" , PALETTERGB (169,169,169)},
1485 {"DarkGray" , PALETTERGB (169,169,169)},
1486 {"dark blue" , PALETTERGB ( 0, 0,139)},
1487 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1488 {"dark cyan" , PALETTERGB ( 0,139,139)},
1489 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1490 {"dark magenta" , PALETTERGB (139, 0,139)},
1491 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1492 {"dark red" , PALETTERGB (139, 0, 0)},
1493 {"DarkRed" , PALETTERGB (139, 0, 0)},
1494 {"light green" , PALETTERGB (144,238,144)},
1495 {"LightGreen" , PALETTERGB (144,238,144)},
1498 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1499 0, 0, 0, doc: /* Return the default color map. */)
1502 int i;
1503 colormap_t *pc = w32_color_map;
1504 Lisp_Object cmap;
1506 BLOCK_INPUT;
1508 cmap = Qnil;
1510 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1511 pc++, i++)
1512 cmap = Fcons (Fcons (build_string (pc->name),
1513 make_number (pc->colorref)),
1514 cmap);
1516 UNBLOCK_INPUT;
1518 return (cmap);
1521 Lisp_Object
1522 w32_to_x_color (rgb)
1523 Lisp_Object rgb;
1525 Lisp_Object color;
1527 CHECK_NUMBER (rgb);
1529 BLOCK_INPUT;
1531 color = Frassq (rgb, Vw32_color_map);
1533 UNBLOCK_INPUT;
1535 if (!NILP (color))
1536 return (Fcar (color));
1537 else
1538 return Qnil;
1541 COLORREF
1542 w32_color_map_lookup (colorname)
1543 char *colorname;
1545 Lisp_Object tail, ret = Qnil;
1547 BLOCK_INPUT;
1549 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1551 register Lisp_Object elt, tem;
1553 elt = Fcar (tail);
1554 if (!CONSP (elt)) continue;
1556 tem = Fcar (elt);
1558 if (lstrcmpi (SDATA (tem), colorname) == 0)
1560 ret = XUINT (Fcdr (elt));
1561 break;
1564 QUIT;
1568 UNBLOCK_INPUT;
1570 return ret;
1573 COLORREF
1574 x_to_w32_color (colorname)
1575 char * colorname;
1577 register Lisp_Object ret = Qnil;
1579 BLOCK_INPUT;
1581 if (colorname[0] == '#')
1583 /* Could be an old-style RGB Device specification. */
1584 char *color;
1585 int size;
1586 color = colorname + 1;
1588 size = strlen(color);
1589 if (size == 3 || size == 6 || size == 9 || size == 12)
1591 UINT colorval;
1592 int i, pos;
1593 pos = 0;
1594 size /= 3;
1595 colorval = 0;
1597 for (i = 0; i < 3; i++)
1599 char *end;
1600 char t;
1601 unsigned long value;
1603 /* The check for 'x' in the following conditional takes into
1604 account the fact that strtol allows a "0x" in front of
1605 our numbers, and we don't. */
1606 if (!isxdigit(color[0]) || color[1] == 'x')
1607 break;
1608 t = color[size];
1609 color[size] = '\0';
1610 value = strtoul(color, &end, 16);
1611 color[size] = t;
1612 if (errno == ERANGE || end - color != size)
1613 break;
1614 switch (size)
1616 case 1:
1617 value = value * 0x10;
1618 break;
1619 case 2:
1620 break;
1621 case 3:
1622 value /= 0x10;
1623 break;
1624 case 4:
1625 value /= 0x100;
1626 break;
1628 colorval |= (value << pos);
1629 pos += 0x8;
1630 if (i == 2)
1632 UNBLOCK_INPUT;
1633 return (colorval);
1635 color = end;
1639 else if (strnicmp(colorname, "rgb:", 4) == 0)
1641 char *color;
1642 UINT colorval;
1643 int i, pos;
1644 pos = 0;
1646 colorval = 0;
1647 color = colorname + 4;
1648 for (i = 0; i < 3; i++)
1650 char *end;
1651 unsigned long value;
1653 /* The check for 'x' in the following conditional takes into
1654 account the fact that strtol allows a "0x" in front of
1655 our numbers, and we don't. */
1656 if (!isxdigit(color[0]) || color[1] == 'x')
1657 break;
1658 value = strtoul(color, &end, 16);
1659 if (errno == ERANGE)
1660 break;
1661 switch (end - color)
1663 case 1:
1664 value = value * 0x10 + value;
1665 break;
1666 case 2:
1667 break;
1668 case 3:
1669 value /= 0x10;
1670 break;
1671 case 4:
1672 value /= 0x100;
1673 break;
1674 default:
1675 value = ULONG_MAX;
1677 if (value == ULONG_MAX)
1678 break;
1679 colorval |= (value << pos);
1680 pos += 0x8;
1681 if (i == 2)
1683 if (*end != '\0')
1684 break;
1685 UNBLOCK_INPUT;
1686 return (colorval);
1688 if (*end != '/')
1689 break;
1690 color = end + 1;
1693 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1695 /* This is an RGB Intensity specification. */
1696 char *color;
1697 UINT colorval;
1698 int i, pos;
1699 pos = 0;
1701 colorval = 0;
1702 color = colorname + 5;
1703 for (i = 0; i < 3; i++)
1705 char *end;
1706 double value;
1707 UINT val;
1709 value = strtod(color, &end);
1710 if (errno == ERANGE)
1711 break;
1712 if (value < 0.0 || value > 1.0)
1713 break;
1714 val = (UINT)(0x100 * value);
1715 /* We used 0x100 instead of 0xFF to give an continuous
1716 range between 0.0 and 1.0 inclusive. The next statement
1717 fixes the 1.0 case. */
1718 if (val == 0x100)
1719 val = 0xFF;
1720 colorval |= (val << pos);
1721 pos += 0x8;
1722 if (i == 2)
1724 if (*end != '\0')
1725 break;
1726 UNBLOCK_INPUT;
1727 return (colorval);
1729 if (*end != '/')
1730 break;
1731 color = end + 1;
1734 /* I am not going to attempt to handle any of the CIE color schemes
1735 or TekHVC, since I don't know the algorithms for conversion to
1736 RGB. */
1738 /* If we fail to lookup the color name in w32_color_map, then check the
1739 colorname to see if it can be crudely approximated: If the X color
1740 ends in a number (e.g., "darkseagreen2"), strip the number and
1741 return the result of looking up the base color name. */
1742 ret = w32_color_map_lookup (colorname);
1743 if (NILP (ret))
1745 int len = strlen (colorname);
1747 if (isdigit (colorname[len - 1]))
1749 char *ptr, *approx = alloca (len + 1);
1751 strcpy (approx, colorname);
1752 ptr = &approx[len - 1];
1753 while (ptr > approx && isdigit (*ptr))
1754 *ptr-- = '\0';
1756 ret = w32_color_map_lookup (approx);
1760 UNBLOCK_INPUT;
1761 return ret;
1765 void
1766 w32_regenerate_palette (FRAME_PTR f)
1768 struct w32_palette_entry * list;
1769 LOGPALETTE * log_palette;
1770 HPALETTE new_palette;
1771 int i;
1773 /* don't bother trying to create palette if not supported */
1774 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1775 return;
1777 log_palette = (LOGPALETTE *)
1778 alloca (sizeof (LOGPALETTE) +
1779 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1780 log_palette->palVersion = 0x300;
1781 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1783 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1784 for (i = 0;
1785 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1786 i++, list = list->next)
1787 log_palette->palPalEntry[i] = list->entry;
1789 new_palette = CreatePalette (log_palette);
1791 enter_crit ();
1793 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1794 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1795 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1797 /* Realize display palette and garbage all frames. */
1798 release_frame_dc (f, get_frame_dc (f));
1800 leave_crit ();
1803 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1804 #define SET_W32_COLOR(pe, color) \
1805 do \
1807 pe.peRed = GetRValue (color); \
1808 pe.peGreen = GetGValue (color); \
1809 pe.peBlue = GetBValue (color); \
1810 pe.peFlags = 0; \
1811 } while (0)
1813 #if 0
1814 /* Keep these around in case we ever want to track color usage. */
1815 void
1816 w32_map_color (FRAME_PTR f, COLORREF color)
1818 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1820 if (NILP (Vw32_enable_palette))
1821 return;
1823 /* check if color is already mapped */
1824 while (list)
1826 if (W32_COLOR (list->entry) == color)
1828 ++list->refcount;
1829 return;
1831 list = list->next;
1834 /* not already mapped, so add to list and recreate Windows palette */
1835 list = (struct w32_palette_entry *)
1836 xmalloc (sizeof (struct w32_palette_entry));
1837 SET_W32_COLOR (list->entry, color);
1838 list->refcount = 1;
1839 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1840 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1841 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1843 /* set flag that palette must be regenerated */
1844 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1847 void
1848 w32_unmap_color (FRAME_PTR f, COLORREF color)
1850 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1851 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1853 if (NILP (Vw32_enable_palette))
1854 return;
1856 /* check if color is already mapped */
1857 while (list)
1859 if (W32_COLOR (list->entry) == color)
1861 if (--list->refcount == 0)
1863 *prev = list->next;
1864 xfree (list);
1865 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1866 break;
1868 else
1869 return;
1871 prev = &list->next;
1872 list = list->next;
1875 /* set flag that palette must be regenerated */
1876 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1878 #endif
1881 /* Gamma-correct COLOR on frame F. */
1883 void
1884 gamma_correct (f, color)
1885 struct frame *f;
1886 COLORREF *color;
1888 if (f->gamma)
1890 *color = PALETTERGB (
1891 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1892 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1893 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1898 /* Decide if color named COLOR is valid for the display associated with
1899 the selected frame; if so, return the rgb values in COLOR_DEF.
1900 If ALLOC is nonzero, allocate a new colormap cell. */
1903 w32_defined_color (f, color, color_def, alloc)
1904 FRAME_PTR f;
1905 char *color;
1906 XColor *color_def;
1907 int alloc;
1909 register Lisp_Object tem;
1910 COLORREF w32_color_ref;
1912 tem = x_to_w32_color (color);
1914 if (!NILP (tem))
1916 if (f)
1918 /* Apply gamma correction. */
1919 w32_color_ref = XUINT (tem);
1920 gamma_correct (f, &w32_color_ref);
1921 XSETINT (tem, w32_color_ref);
1924 /* Map this color to the palette if it is enabled. */
1925 if (!NILP (Vw32_enable_palette))
1927 struct w32_palette_entry * entry =
1928 one_w32_display_info.color_list;
1929 struct w32_palette_entry ** prev =
1930 &one_w32_display_info.color_list;
1932 /* check if color is already mapped */
1933 while (entry)
1935 if (W32_COLOR (entry->entry) == XUINT (tem))
1936 break;
1937 prev = &entry->next;
1938 entry = entry->next;
1941 if (entry == NULL && alloc)
1943 /* not already mapped, so add to list */
1944 entry = (struct w32_palette_entry *)
1945 xmalloc (sizeof (struct w32_palette_entry));
1946 SET_W32_COLOR (entry->entry, XUINT (tem));
1947 entry->next = NULL;
1948 *prev = entry;
1949 one_w32_display_info.num_colors++;
1951 /* set flag that palette must be regenerated */
1952 one_w32_display_info.regen_palette = TRUE;
1955 /* Ensure COLORREF value is snapped to nearest color in (default)
1956 palette by simulating the PALETTERGB macro. This works whether
1957 or not the display device has a palette. */
1958 w32_color_ref = XUINT (tem) | 0x2000000;
1960 color_def->pixel = w32_color_ref;
1961 color_def->red = GetRValue (w32_color_ref);
1962 color_def->green = GetGValue (w32_color_ref);
1963 color_def->blue = GetBValue (w32_color_ref);
1965 return 1;
1967 else
1969 return 0;
1973 /* Given a string ARG naming a color, compute a pixel value from it
1974 suitable for screen F.
1975 If F is not a color screen, return DEF (default) regardless of what
1976 ARG says. */
1979 x_decode_color (f, arg, def)
1980 FRAME_PTR f;
1981 Lisp_Object arg;
1982 int def;
1984 XColor cdef;
1986 CHECK_STRING (arg);
1988 if (strcmp (SDATA (arg), "black") == 0)
1989 return BLACK_PIX_DEFAULT (f);
1990 else if (strcmp (SDATA (arg), "white") == 0)
1991 return WHITE_PIX_DEFAULT (f);
1993 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1994 return def;
1996 /* w32_defined_color is responsible for coping with failures
1997 by looking for a near-miss. */
1998 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1999 return cdef.pixel;
2001 /* defined_color failed; return an ultimate default. */
2002 return def;
2005 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
2006 the previous value of that parameter, NEW_VALUE is the new value. */
2008 static void
2009 x_set_line_spacing (f, new_value, old_value)
2010 struct frame *f;
2011 Lisp_Object new_value, old_value;
2013 if (NILP (new_value))
2014 f->extra_line_spacing = 0;
2015 else if (NATNUMP (new_value))
2016 f->extra_line_spacing = XFASTINT (new_value);
2017 else
2018 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
2019 Fcons (new_value, Qnil)));
2020 if (FRAME_VISIBLE_P (f))
2021 redraw_frame (f);
2025 /* Change the `fullscreen' frame parameter of frame F. OLD_VALUE is
2026 the previous value of that parameter, NEW_VALUE is the new value. */
2028 static void
2029 x_set_fullscreen (f, new_value, old_value)
2030 struct frame *f;
2031 Lisp_Object new_value, old_value;
2033 if (NILP (new_value))
2034 f->output_data.w32->want_fullscreen = FULLSCREEN_NONE;
2035 else if (EQ (new_value, Qfullboth))
2036 f->output_data.w32->want_fullscreen = FULLSCREEN_BOTH;
2037 else if (EQ (new_value, Qfullwidth))
2038 f->output_data.w32->want_fullscreen = FULLSCREEN_WIDTH;
2039 else if (EQ (new_value, Qfullheight))
2040 f->output_data.w32->want_fullscreen = FULLSCREEN_HEIGHT;
2044 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
2045 the previous value of that parameter, NEW_VALUE is the new value. */
2047 static void
2048 x_set_screen_gamma (f, new_value, old_value)
2049 struct frame *f;
2050 Lisp_Object new_value, old_value;
2052 if (NILP (new_value))
2053 f->gamma = 0;
2054 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
2055 /* The value 0.4545 is the normal viewing gamma. */
2056 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
2057 else
2058 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
2059 Fcons (new_value, Qnil)));
2061 clear_face_cache (0);
2065 /* Functions called only from `x_set_frame_param'
2066 to set individual parameters.
2068 If FRAME_W32_WINDOW (f) is 0,
2069 the frame is being created and its window does not exist yet.
2070 In that case, just record the parameter's new value
2071 in the standard place; do not attempt to change the window. */
2073 void
2074 x_set_foreground_color (f, arg, oldval)
2075 struct frame *f;
2076 Lisp_Object arg, oldval;
2078 struct w32_output *x = f->output_data.w32;
2079 PIX_TYPE fg, old_fg;
2081 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2082 old_fg = FRAME_FOREGROUND_PIXEL (f);
2083 FRAME_FOREGROUND_PIXEL (f) = fg;
2085 if (FRAME_W32_WINDOW (f) != 0)
2087 if (x->cursor_pixel == old_fg)
2088 x->cursor_pixel = fg;
2090 update_face_from_frame_parameter (f, Qforeground_color, arg);
2091 if (FRAME_VISIBLE_P (f))
2092 redraw_frame (f);
2096 void
2097 x_set_background_color (f, arg, oldval)
2098 struct frame *f;
2099 Lisp_Object arg, oldval;
2101 FRAME_BACKGROUND_PIXEL (f)
2102 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2104 if (FRAME_W32_WINDOW (f) != 0)
2106 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2107 FRAME_BACKGROUND_PIXEL (f));
2109 update_face_from_frame_parameter (f, Qbackground_color, arg);
2111 if (FRAME_VISIBLE_P (f))
2112 redraw_frame (f);
2116 void
2117 x_set_mouse_color (f, arg, oldval)
2118 struct frame *f;
2119 Lisp_Object arg, oldval;
2121 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2122 int count;
2123 int mask_color;
2125 if (!EQ (Qnil, arg))
2126 f->output_data.w32->mouse_pixel
2127 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2128 mask_color = FRAME_BACKGROUND_PIXEL (f);
2130 /* Don't let pointers be invisible. */
2131 if (mask_color == f->output_data.w32->mouse_pixel
2132 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2133 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2135 #if 0 /* TODO : cursor changes */
2136 BLOCK_INPUT;
2138 /* It's not okay to crash if the user selects a screwy cursor. */
2139 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2141 if (!EQ (Qnil, Vx_pointer_shape))
2143 CHECK_NUMBER (Vx_pointer_shape);
2144 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2146 else
2147 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2148 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2150 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2152 CHECK_NUMBER (Vx_nontext_pointer_shape);
2153 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2154 XINT (Vx_nontext_pointer_shape));
2156 else
2157 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2158 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2160 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
2162 CHECK_NUMBER (Vx_hourglass_pointer_shape);
2163 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2164 XINT (Vx_hourglass_pointer_shape));
2166 else
2167 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2168 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2170 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2171 if (!EQ (Qnil, Vx_mode_pointer_shape))
2173 CHECK_NUMBER (Vx_mode_pointer_shape);
2174 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2175 XINT (Vx_mode_pointer_shape));
2177 else
2178 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2179 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2181 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2183 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
2184 cross_cursor
2185 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2186 XINT (Vx_sensitive_text_pointer_shape));
2188 else
2189 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2191 if (!NILP (Vx_window_horizontal_drag_shape))
2193 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
2194 horizontal_drag_cursor
2195 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2196 XINT (Vx_window_horizontal_drag_shape));
2198 else
2199 horizontal_drag_cursor
2200 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2202 /* Check and report errors with the above calls. */
2203 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2204 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2207 XColor fore_color, back_color;
2209 fore_color.pixel = f->output_data.w32->mouse_pixel;
2210 back_color.pixel = mask_color;
2211 XQueryColor (FRAME_W32_DISPLAY (f),
2212 DefaultColormap (FRAME_W32_DISPLAY (f),
2213 DefaultScreen (FRAME_W32_DISPLAY (f))),
2214 &fore_color);
2215 XQueryColor (FRAME_W32_DISPLAY (f),
2216 DefaultColormap (FRAME_W32_DISPLAY (f),
2217 DefaultScreen (FRAME_W32_DISPLAY (f))),
2218 &back_color);
2219 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2220 &fore_color, &back_color);
2221 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2222 &fore_color, &back_color);
2223 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2224 &fore_color, &back_color);
2225 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2226 &fore_color, &back_color);
2227 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
2228 &fore_color, &back_color);
2231 if (FRAME_W32_WINDOW (f) != 0)
2232 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2234 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2235 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2236 f->output_data.w32->text_cursor = cursor;
2238 if (nontext_cursor != f->output_data.w32->nontext_cursor
2239 && f->output_data.w32->nontext_cursor != 0)
2240 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2241 f->output_data.w32->nontext_cursor = nontext_cursor;
2243 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
2244 && f->output_data.w32->hourglass_cursor != 0)
2245 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
2246 f->output_data.w32->hourglass_cursor = hourglass_cursor;
2248 if (mode_cursor != f->output_data.w32->modeline_cursor
2249 && f->output_data.w32->modeline_cursor != 0)
2250 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2251 f->output_data.w32->modeline_cursor = mode_cursor;
2253 if (cross_cursor != f->output_data.w32->cross_cursor
2254 && f->output_data.w32->cross_cursor != 0)
2255 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2256 f->output_data.w32->cross_cursor = cross_cursor;
2258 XFlush (FRAME_W32_DISPLAY (f));
2259 UNBLOCK_INPUT;
2261 update_face_from_frame_parameter (f, Qmouse_color, arg);
2262 #endif /* TODO */
2265 /* Defined in w32term.c. */
2266 void x_update_cursor (struct frame *f, int on_p);
2268 void
2269 x_set_cursor_color (f, arg, oldval)
2270 struct frame *f;
2271 Lisp_Object arg, oldval;
2273 unsigned long fore_pixel, pixel;
2275 if (!NILP (Vx_cursor_fore_pixel))
2276 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2277 WHITE_PIX_DEFAULT (f));
2278 else
2279 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2281 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2283 /* Make sure that the cursor color differs from the background color. */
2284 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2286 pixel = f->output_data.w32->mouse_pixel;
2287 if (pixel == fore_pixel)
2288 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2291 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
2292 f->output_data.w32->cursor_pixel = pixel;
2294 if (FRAME_W32_WINDOW (f) != 0)
2296 BLOCK_INPUT;
2297 /* Update frame's cursor_gc. */
2298 f->output_data.w32->cursor_gc->foreground = fore_pixel;
2299 f->output_data.w32->cursor_gc->background = pixel;
2301 UNBLOCK_INPUT;
2303 if (FRAME_VISIBLE_P (f))
2305 x_update_cursor (f, 0);
2306 x_update_cursor (f, 1);
2310 update_face_from_frame_parameter (f, Qcursor_color, arg);
2313 /* Set the border-color of frame F to pixel value PIX.
2314 Note that this does not fully take effect if done before
2315 F has an window. */
2316 void
2317 x_set_border_pixel (f, pix)
2318 struct frame *f;
2319 int pix;
2321 f->output_data.w32->border_pixel = pix;
2323 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2325 if (FRAME_VISIBLE_P (f))
2326 redraw_frame (f);
2330 /* Set the border-color of frame F to value described by ARG.
2331 ARG can be a string naming a color.
2332 The border-color is used for the border that is drawn by the server.
2333 Note that this does not fully take effect if done before
2334 F has a window; it must be redone when the window is created. */
2336 void
2337 x_set_border_color (f, arg, oldval)
2338 struct frame *f;
2339 Lisp_Object arg, oldval;
2341 int pix;
2343 CHECK_STRING (arg);
2344 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2345 x_set_border_pixel (f, pix);
2346 update_face_from_frame_parameter (f, Qborder_color, arg);
2350 void
2351 x_set_cursor_type (f, arg, oldval)
2352 FRAME_PTR f;
2353 Lisp_Object arg, oldval;
2355 set_frame_cursor_types (f, arg);
2357 /* Make sure the cursor gets redrawn. This is overkill, but how
2358 often do people change cursor types? */
2359 update_mode_lines++;
2362 void
2363 x_set_icon_type (f, arg, oldval)
2364 struct frame *f;
2365 Lisp_Object arg, oldval;
2367 int result;
2369 if (NILP (arg) && NILP (oldval))
2370 return;
2372 if (STRINGP (arg) && STRINGP (oldval)
2373 && EQ (Fstring_equal (oldval, arg), Qt))
2374 return;
2376 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2377 return;
2379 BLOCK_INPUT;
2381 result = x_bitmap_icon (f, arg);
2382 if (result)
2384 UNBLOCK_INPUT;
2385 error ("No icon window available");
2388 UNBLOCK_INPUT;
2391 /* Return non-nil if frame F wants a bitmap icon. */
2393 Lisp_Object
2394 x_icon_type (f)
2395 FRAME_PTR f;
2397 Lisp_Object tem;
2399 tem = assq_no_quit (Qicon_type, f->param_alist);
2400 if (CONSP (tem))
2401 return XCDR (tem);
2402 else
2403 return Qnil;
2406 void
2407 x_set_icon_name (f, arg, oldval)
2408 struct frame *f;
2409 Lisp_Object arg, oldval;
2411 if (STRINGP (arg))
2413 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2414 return;
2416 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2417 return;
2419 f->icon_name = arg;
2421 #if 0
2422 if (f->output_data.w32->icon_bitmap != 0)
2423 return;
2425 BLOCK_INPUT;
2427 result = x_text_icon (f,
2428 (char *) SDATA ((!NILP (f->icon_name)
2429 ? f->icon_name
2430 : !NILP (f->title)
2431 ? f->title
2432 : f->name)));
2434 if (result)
2436 UNBLOCK_INPUT;
2437 error ("No icon window available");
2440 /* If the window was unmapped (and its icon was mapped),
2441 the new icon is not mapped, so map the window in its stead. */
2442 if (FRAME_VISIBLE_P (f))
2444 #ifdef USE_X_TOOLKIT
2445 XtPopup (f->output_data.w32->widget, XtGrabNone);
2446 #endif
2447 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2450 XFlush (FRAME_W32_DISPLAY (f));
2451 UNBLOCK_INPUT;
2452 #endif
2455 extern Lisp_Object x_new_font ();
2456 extern Lisp_Object x_new_fontset();
2458 void
2459 x_set_font (f, arg, oldval)
2460 struct frame *f;
2461 Lisp_Object arg, oldval;
2463 Lisp_Object result;
2464 Lisp_Object fontset_name;
2465 Lisp_Object frame;
2466 int old_fontset = FRAME_FONTSET(f);
2468 CHECK_STRING (arg);
2470 fontset_name = Fquery_fontset (arg, Qnil);
2472 BLOCK_INPUT;
2473 result = (STRINGP (fontset_name)
2474 ? x_new_fontset (f, SDATA (fontset_name))
2475 : x_new_font (f, SDATA (arg)));
2476 UNBLOCK_INPUT;
2478 if (EQ (result, Qnil))
2479 error ("Font `%s' is not defined", SDATA (arg));
2480 else if (EQ (result, Qt))
2481 error ("The characters of the given font have varying widths");
2482 else if (STRINGP (result))
2484 if (STRINGP (fontset_name))
2486 /* Fontset names are built from ASCII font names, so the
2487 names may be equal despite there was a change. */
2488 if (old_fontset == FRAME_FONTSET (f))
2489 return;
2491 else if (!NILP (Fequal (result, oldval)))
2492 return;
2494 store_frame_param (f, Qfont, result);
2495 recompute_basic_faces (f);
2497 else
2498 abort ();
2500 do_pending_window_change (0);
2502 /* Don't call `face-set-after-frame-default' when faces haven't been
2503 initialized yet. This is the case when called from
2504 Fx_create_frame. In that case, the X widget or window doesn't
2505 exist either, and we can end up in x_report_frame_params with a
2506 null widget which gives a segfault. */
2507 if (FRAME_FACE_CACHE (f))
2509 XSETFRAME (frame, f);
2510 call1 (Qface_set_after_frame_default, frame);
2514 static void
2515 x_set_fringe_width (f, new_value, old_value)
2516 struct frame *f;
2517 Lisp_Object new_value, old_value;
2519 x_compute_fringe_widths (f, 1);
2522 void
2523 x_set_border_width (f, arg, oldval)
2524 struct frame *f;
2525 Lisp_Object arg, oldval;
2527 CHECK_NUMBER (arg);
2529 if (XINT (arg) == f->output_data.w32->border_width)
2530 return;
2532 if (FRAME_W32_WINDOW (f) != 0)
2533 error ("Cannot change the border width of a window");
2535 f->output_data.w32->border_width = XINT (arg);
2538 void
2539 x_set_internal_border_width (f, arg, oldval)
2540 struct frame *f;
2541 Lisp_Object arg, oldval;
2543 int old = f->output_data.w32->internal_border_width;
2545 CHECK_NUMBER (arg);
2546 f->output_data.w32->internal_border_width = XINT (arg);
2547 if (f->output_data.w32->internal_border_width < 0)
2548 f->output_data.w32->internal_border_width = 0;
2550 if (f->output_data.w32->internal_border_width == old)
2551 return;
2553 if (FRAME_W32_WINDOW (f) != 0)
2555 x_set_window_size (f, 0, f->width, f->height);
2556 SET_FRAME_GARBAGED (f);
2557 do_pending_window_change (0);
2559 else
2560 SET_FRAME_GARBAGED (f);
2563 void
2564 x_set_visibility (f, value, oldval)
2565 struct frame *f;
2566 Lisp_Object value, oldval;
2568 Lisp_Object frame;
2569 XSETFRAME (frame, f);
2571 if (NILP (value))
2572 Fmake_frame_invisible (frame, Qt);
2573 else if (EQ (value, Qicon))
2574 Ficonify_frame (frame);
2575 else
2576 Fmake_frame_visible (frame);
2580 /* Change window heights in windows rooted in WINDOW by N lines. */
2582 static void
2583 x_change_window_heights (window, n)
2584 Lisp_Object window;
2585 int n;
2587 struct window *w = XWINDOW (window);
2589 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2590 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2592 if (INTEGERP (w->orig_top))
2593 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2594 if (INTEGERP (w->orig_height))
2595 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2597 /* Handle just the top child in a vertical split. */
2598 if (!NILP (w->vchild))
2599 x_change_window_heights (w->vchild, n);
2601 /* Adjust all children in a horizontal split. */
2602 for (window = w->hchild; !NILP (window); window = w->next)
2604 w = XWINDOW (window);
2605 x_change_window_heights (window, n);
2609 void
2610 x_set_menu_bar_lines (f, value, oldval)
2611 struct frame *f;
2612 Lisp_Object value, oldval;
2614 int nlines;
2615 int olines = FRAME_MENU_BAR_LINES (f);
2617 /* Right now, menu bars don't work properly in minibuf-only frames;
2618 most of the commands try to apply themselves to the minibuffer
2619 frame itself, and get an error because you can't switch buffers
2620 in or split the minibuffer window. */
2621 if (FRAME_MINIBUF_ONLY_P (f))
2622 return;
2624 if (INTEGERP (value))
2625 nlines = XINT (value);
2626 else
2627 nlines = 0;
2629 FRAME_MENU_BAR_LINES (f) = 0;
2630 if (nlines)
2631 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2632 else
2634 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2635 free_frame_menubar (f);
2636 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2638 /* Adjust the frame size so that the client (text) dimensions
2639 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2640 set correctly. */
2641 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2642 do_pending_window_change (0);
2644 adjust_glyphs (f);
2648 /* Set the number of lines used for the tool bar of frame F to VALUE.
2649 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2650 is the old number of tool bar lines. This function changes the
2651 height of all windows on frame F to match the new tool bar height.
2652 The frame's height doesn't change. */
2654 void
2655 x_set_tool_bar_lines (f, value, oldval)
2656 struct frame *f;
2657 Lisp_Object value, oldval;
2659 int delta, nlines, root_height;
2660 Lisp_Object root_window;
2662 /* Treat tool bars like menu bars. */
2663 if (FRAME_MINIBUF_ONLY_P (f))
2664 return;
2666 /* Use VALUE only if an integer >= 0. */
2667 if (INTEGERP (value) && XINT (value) >= 0)
2668 nlines = XFASTINT (value);
2669 else
2670 nlines = 0;
2672 /* Make sure we redisplay all windows in this frame. */
2673 ++windows_or_buffers_changed;
2675 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2677 /* Don't resize the tool-bar to more than we have room for. */
2678 root_window = FRAME_ROOT_WINDOW (f);
2679 root_height = XINT (XWINDOW (root_window)->height);
2680 if (root_height - delta < 1)
2682 delta = root_height - 1;
2683 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2686 FRAME_TOOL_BAR_LINES (f) = nlines;
2687 x_change_window_heights (root_window, delta);
2688 adjust_glyphs (f);
2690 /* We also have to make sure that the internal border at the top of
2691 the frame, below the menu bar or tool bar, is redrawn when the
2692 tool bar disappears. This is so because the internal border is
2693 below the tool bar if one is displayed, but is below the menu bar
2694 if there isn't a tool bar. The tool bar draws into the area
2695 below the menu bar. */
2696 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2698 updating_frame = f;
2699 clear_frame ();
2700 clear_current_matrices (f);
2701 updating_frame = NULL;
2704 /* If the tool bar gets smaller, the internal border below it
2705 has to be cleared. It was formerly part of the display
2706 of the larger tool bar, and updating windows won't clear it. */
2707 if (delta < 0)
2709 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2710 int width = PIXEL_WIDTH (f);
2711 int y = nlines * CANON_Y_UNIT (f);
2713 BLOCK_INPUT;
2715 HDC hdc = get_frame_dc (f);
2716 w32_clear_area (f, hdc, 0, y, width, height);
2717 release_frame_dc (f, hdc);
2719 UNBLOCK_INPUT;
2721 if (WINDOWP (f->tool_bar_window))
2722 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
2727 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2728 w32_id_name.
2730 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2731 name; if NAME is a string, set F's name to NAME and set
2732 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2734 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2735 suggesting a new name, which lisp code should override; if
2736 F->explicit_name is set, ignore the new name; otherwise, set it. */
2738 void
2739 x_set_name (f, name, explicit)
2740 struct frame *f;
2741 Lisp_Object name;
2742 int explicit;
2744 /* Make sure that requests from lisp code override requests from
2745 Emacs redisplay code. */
2746 if (explicit)
2748 /* If we're switching from explicit to implicit, we had better
2749 update the mode lines and thereby update the title. */
2750 if (f->explicit_name && NILP (name))
2751 update_mode_lines = 1;
2753 f->explicit_name = ! NILP (name);
2755 else if (f->explicit_name)
2756 return;
2758 /* If NAME is nil, set the name to the w32_id_name. */
2759 if (NILP (name))
2761 /* Check for no change needed in this very common case
2762 before we do any consing. */
2763 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2764 SDATA (f->name)))
2765 return;
2766 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2768 else
2769 CHECK_STRING (name);
2771 /* Don't change the name if it's already NAME. */
2772 if (! NILP (Fstring_equal (name, f->name)))
2773 return;
2775 f->name = name;
2777 /* For setting the frame title, the title parameter should override
2778 the name parameter. */
2779 if (! NILP (f->title))
2780 name = f->title;
2782 if (FRAME_W32_WINDOW (f))
2784 if (STRING_MULTIBYTE (name))
2785 name = ENCODE_SYSTEM (name);
2787 BLOCK_INPUT;
2788 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2789 UNBLOCK_INPUT;
2793 /* This function should be called when the user's lisp code has
2794 specified a name for the frame; the name will override any set by the
2795 redisplay code. */
2796 void
2797 x_explicitly_set_name (f, arg, oldval)
2798 FRAME_PTR f;
2799 Lisp_Object arg, oldval;
2801 x_set_name (f, arg, 1);
2804 /* This function should be called by Emacs redisplay code to set the
2805 name; names set this way will never override names set by the user's
2806 lisp code. */
2807 void
2808 x_implicitly_set_name (f, arg, oldval)
2809 FRAME_PTR f;
2810 Lisp_Object arg, oldval;
2812 x_set_name (f, arg, 0);
2815 /* Change the title of frame F to NAME.
2816 If NAME is nil, use the frame name as the title.
2818 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2819 name; if NAME is a string, set F's name to NAME and set
2820 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2822 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2823 suggesting a new name, which lisp code should override; if
2824 F->explicit_name is set, ignore the new name; otherwise, set it. */
2826 void
2827 x_set_title (f, name, old_name)
2828 struct frame *f;
2829 Lisp_Object name, old_name;
2831 /* Don't change the title if it's already NAME. */
2832 if (EQ (name, f->title))
2833 return;
2835 update_mode_lines = 1;
2837 f->title = name;
2839 if (NILP (name))
2840 name = f->name;
2842 if (FRAME_W32_WINDOW (f))
2844 if (STRING_MULTIBYTE (name))
2845 name = ENCODE_SYSTEM (name);
2847 BLOCK_INPUT;
2848 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2849 UNBLOCK_INPUT;
2853 void
2854 x_set_autoraise (f, arg, oldval)
2855 struct frame *f;
2856 Lisp_Object arg, oldval;
2858 f->auto_raise = !EQ (Qnil, arg);
2861 void
2862 x_set_autolower (f, arg, oldval)
2863 struct frame *f;
2864 Lisp_Object arg, oldval;
2866 f->auto_lower = !EQ (Qnil, arg);
2869 void
2870 x_set_unsplittable (f, arg, oldval)
2871 struct frame *f;
2872 Lisp_Object arg, oldval;
2874 f->no_split = !NILP (arg);
2877 void
2878 x_set_vertical_scroll_bars (f, arg, oldval)
2879 struct frame *f;
2880 Lisp_Object arg, oldval;
2882 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2883 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2884 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2885 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2887 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2888 vertical_scroll_bar_none :
2889 /* Put scroll bars on the right by default, as is conventional
2890 on MS-Windows. */
2891 EQ (Qleft, arg)
2892 ? vertical_scroll_bar_left
2893 : vertical_scroll_bar_right;
2895 /* We set this parameter before creating the window for the
2896 frame, so we can get the geometry right from the start.
2897 However, if the window hasn't been created yet, we shouldn't
2898 call x_set_window_size. */
2899 if (FRAME_W32_WINDOW (f))
2900 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2901 do_pending_window_change (0);
2905 void
2906 x_set_scroll_bar_width (f, arg, oldval)
2907 struct frame *f;
2908 Lisp_Object arg, oldval;
2910 int wid = FONT_WIDTH (f->output_data.w32->font);
2912 if (NILP (arg))
2914 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2915 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2916 wid - 1) / wid;
2917 if (FRAME_W32_WINDOW (f))
2918 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2919 do_pending_window_change (0);
2921 else if (INTEGERP (arg) && XINT (arg) > 0
2922 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2924 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2925 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2926 + wid-1) / wid;
2927 if (FRAME_W32_WINDOW (f))
2928 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2929 do_pending_window_change (0);
2931 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2932 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2933 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2936 /* Subroutines of creating an frame. */
2938 /* Make sure that Vx_resource_name is set to a reasonable value.
2939 Fix it up, or set it to `emacs' if it is too hopeless. */
2941 static void
2942 validate_x_resource_name ()
2944 int len = 0;
2945 /* Number of valid characters in the resource name. */
2946 int good_count = 0;
2947 /* Number of invalid characters in the resource name. */
2948 int bad_count = 0;
2949 Lisp_Object new;
2950 int i;
2952 if (STRINGP (Vx_resource_name))
2954 unsigned char *p = SDATA (Vx_resource_name);
2955 int i;
2957 len = SBYTES (Vx_resource_name);
2959 /* Only letters, digits, - and _ are valid in resource names.
2960 Count the valid characters and count the invalid ones. */
2961 for (i = 0; i < len; i++)
2963 int c = p[i];
2964 if (! ((c >= 'a' && c <= 'z')
2965 || (c >= 'A' && c <= 'Z')
2966 || (c >= '0' && c <= '9')
2967 || c == '-' || c == '_'))
2968 bad_count++;
2969 else
2970 good_count++;
2973 else
2974 /* Not a string => completely invalid. */
2975 bad_count = 5, good_count = 0;
2977 /* If name is valid already, return. */
2978 if (bad_count == 0)
2979 return;
2981 /* If name is entirely invalid, or nearly so, use `emacs'. */
2982 if (good_count == 0
2983 || (good_count == 1 && bad_count > 0))
2985 Vx_resource_name = build_string ("emacs");
2986 return;
2989 /* Name is partly valid. Copy it and replace the invalid characters
2990 with underscores. */
2992 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2994 for (i = 0; i < len; i++)
2996 int c = SREF (new, i);
2997 if (! ((c >= 'a' && c <= 'z')
2998 || (c >= 'A' && c <= 'Z')
2999 || (c >= '0' && c <= '9')
3000 || c == '-' || c == '_'))
3001 SSET (new, i, '_');
3006 extern char *x_get_string_resource ();
3008 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
3009 doc: /* Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.
3010 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the
3011 class, where INSTANCE is the name under which Emacs was invoked, or
3012 the name specified by the `-name' or `-rn' command-line arguments.
3014 The optional arguments COMPONENT and SUBCLASS add to the key and the
3015 class, respectively. You must specify both of them or neither.
3016 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'
3017 and the class is `Emacs.CLASS.SUBCLASS'. */)
3018 (attribute, class, component, subclass)
3019 Lisp_Object attribute, class, component, subclass;
3021 register char *value;
3022 char *name_key;
3023 char *class_key;
3025 CHECK_STRING (attribute);
3026 CHECK_STRING (class);
3028 if (!NILP (component))
3029 CHECK_STRING (component);
3030 if (!NILP (subclass))
3031 CHECK_STRING (subclass);
3032 if (NILP (component) != NILP (subclass))
3033 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
3035 validate_x_resource_name ();
3037 /* Allocate space for the components, the dots which separate them,
3038 and the final '\0'. Make them big enough for the worst case. */
3039 name_key = (char *) alloca (SBYTES (Vx_resource_name)
3040 + (STRINGP (component)
3041 ? SBYTES (component) : 0)
3042 + SBYTES (attribute)
3043 + 3);
3045 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3046 + SBYTES (class)
3047 + (STRINGP (subclass)
3048 ? SBYTES (subclass) : 0)
3049 + 3);
3051 /* Start with emacs.FRAMENAME for the name (the specific one)
3052 and with `Emacs' for the class key (the general one). */
3053 strcpy (name_key, SDATA (Vx_resource_name));
3054 strcpy (class_key, EMACS_CLASS);
3056 strcat (class_key, ".");
3057 strcat (class_key, SDATA (class));
3059 if (!NILP (component))
3061 strcat (class_key, ".");
3062 strcat (class_key, SDATA (subclass));
3064 strcat (name_key, ".");
3065 strcat (name_key, SDATA (component));
3068 strcat (name_key, ".");
3069 strcat (name_key, SDATA (attribute));
3071 value = x_get_string_resource (Qnil,
3072 name_key, class_key);
3074 if (value != (char *) 0)
3075 return build_string (value);
3076 else
3077 return Qnil;
3080 /* Used when C code wants a resource value. */
3082 char *
3083 x_get_resource_string (attribute, class)
3084 char *attribute, *class;
3086 char *name_key;
3087 char *class_key;
3088 struct frame *sf = SELECTED_FRAME ();
3090 /* Allocate space for the components, the dots which separate them,
3091 and the final '\0'. */
3092 name_key = (char *) alloca (SBYTES (Vinvocation_name)
3093 + strlen (attribute) + 2);
3094 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3095 + strlen (class) + 2);
3097 sprintf (name_key, "%s.%s",
3098 SDATA (Vinvocation_name),
3099 attribute);
3100 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
3102 return x_get_string_resource (sf, name_key, class_key);
3105 /* Types we might convert a resource string into. */
3106 enum resource_types
3108 RES_TYPE_NUMBER,
3109 RES_TYPE_FLOAT,
3110 RES_TYPE_BOOLEAN,
3111 RES_TYPE_STRING,
3112 RES_TYPE_SYMBOL
3115 /* Return the value of parameter PARAM.
3117 First search ALIST, then Vdefault_frame_alist, then the X defaults
3118 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3120 Convert the resource to the type specified by desired_type.
3122 If no default is specified, return Qunbound. If you call
3123 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3124 and don't let it get stored in any Lisp-visible variables! */
3126 static Lisp_Object
3127 w32_get_arg (alist, param, attribute, class, type)
3128 Lisp_Object alist, param;
3129 char *attribute;
3130 char *class;
3131 enum resource_types type;
3133 register Lisp_Object tem;
3135 tem = Fassq (param, alist);
3136 if (EQ (tem, Qnil))
3137 tem = Fassq (param, Vdefault_frame_alist);
3138 if (EQ (tem, Qnil))
3141 if (attribute)
3143 tem = Fx_get_resource (build_string (attribute),
3144 build_string (class),
3145 Qnil, Qnil);
3147 if (NILP (tem))
3148 return Qunbound;
3150 switch (type)
3152 case RES_TYPE_NUMBER:
3153 return make_number (atoi (SDATA (tem)));
3155 case RES_TYPE_FLOAT:
3156 return make_float (atof (SDATA (tem)));
3158 case RES_TYPE_BOOLEAN:
3159 tem = Fdowncase (tem);
3160 if (!strcmp (SDATA (tem), "on")
3161 || !strcmp (SDATA (tem), "true"))
3162 return Qt;
3163 else
3164 return Qnil;
3166 case RES_TYPE_STRING:
3167 return tem;
3169 case RES_TYPE_SYMBOL:
3170 /* As a special case, we map the values `true' and `on'
3171 to Qt, and `false' and `off' to Qnil. */
3173 Lisp_Object lower;
3174 lower = Fdowncase (tem);
3175 if (!strcmp (SDATA (lower), "on")
3176 || !strcmp (SDATA (lower), "true"))
3177 return Qt;
3178 else if (!strcmp (SDATA (lower), "off")
3179 || !strcmp (SDATA (lower), "false"))
3180 return Qnil;
3181 else
3182 return Fintern (tem, Qnil);
3185 default:
3186 abort ();
3189 else
3190 return Qunbound;
3192 return Fcdr (tem);
3195 /* Record in frame F the specified or default value according to ALIST
3196 of the parameter named PROP (a Lisp symbol).
3197 If no value is specified for PROP, look for an X default for XPROP
3198 on the frame named NAME.
3199 If that is not found either, use the value DEFLT. */
3201 static Lisp_Object
3202 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3203 struct frame *f;
3204 Lisp_Object alist;
3205 Lisp_Object prop;
3206 Lisp_Object deflt;
3207 char *xprop;
3208 char *xclass;
3209 enum resource_types type;
3211 Lisp_Object tem;
3213 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3214 if (EQ (tem, Qunbound))
3215 tem = deflt;
3216 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3217 return tem;
3220 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3221 doc: /* Parse an X-style geometry string STRING.
3222 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).
3223 The properties returned may include `top', `left', `height', and `width'.
3224 The value of `left' or `top' may be an integer,
3225 or a list (+ N) meaning N pixels relative to top/left corner,
3226 or a list (- N) meaning -N pixels relative to bottom/right corner. */)
3227 (string)
3228 Lisp_Object string;
3230 int geometry, x, y;
3231 unsigned int width, height;
3232 Lisp_Object result;
3234 CHECK_STRING (string);
3236 geometry = XParseGeometry ((char *) SDATA (string),
3237 &x, &y, &width, &height);
3239 result = Qnil;
3240 if (geometry & XValue)
3242 Lisp_Object element;
3244 if (x >= 0 && (geometry & XNegative))
3245 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3246 else if (x < 0 && ! (geometry & XNegative))
3247 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3248 else
3249 element = Fcons (Qleft, make_number (x));
3250 result = Fcons (element, result);
3253 if (geometry & YValue)
3255 Lisp_Object element;
3257 if (y >= 0 && (geometry & YNegative))
3258 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3259 else if (y < 0 && ! (geometry & YNegative))
3260 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3261 else
3262 element = Fcons (Qtop, make_number (y));
3263 result = Fcons (element, result);
3266 if (geometry & WidthValue)
3267 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3268 if (geometry & HeightValue)
3269 result = Fcons (Fcons (Qheight, make_number (height)), result);
3271 return result;
3274 /* Calculate the desired size and position of this window,
3275 and return the flags saying which aspects were specified.
3277 This function does not make the coordinates positive. */
3279 #define DEFAULT_ROWS 40
3280 #define DEFAULT_COLS 80
3282 static int
3283 x_figure_window_size (f, parms)
3284 struct frame *f;
3285 Lisp_Object parms;
3287 register Lisp_Object tem0, tem1, tem2;
3288 long window_prompting = 0;
3290 /* Default values if we fall through.
3291 Actually, if that happens we should get
3292 window manager prompting. */
3293 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3294 f->height = DEFAULT_ROWS;
3295 /* Window managers expect that if program-specified
3296 positions are not (0,0), they're intentional, not defaults. */
3297 f->output_data.w32->top_pos = 0;
3298 f->output_data.w32->left_pos = 0;
3300 /* Ensure that old new_width and new_height will not override the
3301 values set here. */
3302 FRAME_NEW_WIDTH (f) = 0;
3303 FRAME_NEW_HEIGHT (f) = 0;
3305 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3306 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3307 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3308 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3310 if (!EQ (tem0, Qunbound))
3312 CHECK_NUMBER (tem0);
3313 f->height = XINT (tem0);
3315 if (!EQ (tem1, Qunbound))
3317 CHECK_NUMBER (tem1);
3318 SET_FRAME_WIDTH (f, XINT (tem1));
3320 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3321 window_prompting |= USSize;
3322 else
3323 window_prompting |= PSize;
3326 f->output_data.w32->vertical_scroll_bar_extra
3327 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3329 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3330 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3331 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3333 x_compute_fringe_widths (f, 0);
3335 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3336 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3338 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3339 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3340 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3341 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3343 if (EQ (tem0, Qminus))
3345 f->output_data.w32->top_pos = 0;
3346 window_prompting |= YNegative;
3348 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3349 && CONSP (XCDR (tem0))
3350 && INTEGERP (XCAR (XCDR (tem0))))
3352 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3353 window_prompting |= YNegative;
3355 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3356 && CONSP (XCDR (tem0))
3357 && INTEGERP (XCAR (XCDR (tem0))))
3359 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3361 else if (EQ (tem0, Qunbound))
3362 f->output_data.w32->top_pos = 0;
3363 else
3365 CHECK_NUMBER (tem0);
3366 f->output_data.w32->top_pos = XINT (tem0);
3367 if (f->output_data.w32->top_pos < 0)
3368 window_prompting |= YNegative;
3371 if (EQ (tem1, Qminus))
3373 f->output_data.w32->left_pos = 0;
3374 window_prompting |= XNegative;
3376 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3377 && CONSP (XCDR (tem1))
3378 && INTEGERP (XCAR (XCDR (tem1))))
3380 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3381 window_prompting |= XNegative;
3383 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3384 && CONSP (XCDR (tem1))
3385 && INTEGERP (XCAR (XCDR (tem1))))
3387 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3389 else if (EQ (tem1, Qunbound))
3390 f->output_data.w32->left_pos = 0;
3391 else
3393 CHECK_NUMBER (tem1);
3394 f->output_data.w32->left_pos = XINT (tem1);
3395 if (f->output_data.w32->left_pos < 0)
3396 window_prompting |= XNegative;
3399 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3400 window_prompting |= USPosition;
3401 else
3402 window_prompting |= PPosition;
3405 if (f->output_data.w32->want_fullscreen != FULLSCREEN_NONE)
3407 int left, top;
3408 int width, height;
3410 /* It takes both for some WM:s to place it where we want */
3411 window_prompting = USPosition | PPosition;
3412 x_fullscreen_adjust (f, &width, &height, &top, &left);
3413 f->width = width;
3414 f->height = height;
3415 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3416 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3417 f->output_data.w32->left_pos = left;
3418 f->output_data.w32->top_pos = top;
3421 return window_prompting;
3426 extern LRESULT CALLBACK w32_wnd_proc ();
3428 BOOL
3429 w32_init_class (hinst)
3430 HINSTANCE hinst;
3432 WNDCLASS wc;
3434 wc.style = CS_HREDRAW | CS_VREDRAW;
3435 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3436 wc.cbClsExtra = 0;
3437 wc.cbWndExtra = WND_EXTRA_BYTES;
3438 wc.hInstance = hinst;
3439 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3440 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3441 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3442 wc.lpszMenuName = NULL;
3443 wc.lpszClassName = EMACS_CLASS;
3445 return (RegisterClass (&wc));
3448 HWND
3449 w32_createscrollbar (f, bar)
3450 struct frame *f;
3451 struct scroll_bar * bar;
3453 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3454 /* Position and size of scroll bar. */
3455 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3456 XINT(bar->top),
3457 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3458 XINT(bar->height),
3459 FRAME_W32_WINDOW (f),
3460 NULL,
3461 hinst,
3462 NULL));
3465 void
3466 w32_createwindow (f)
3467 struct frame *f;
3469 HWND hwnd;
3470 RECT rect;
3472 rect.left = rect.top = 0;
3473 rect.right = PIXEL_WIDTH (f);
3474 rect.bottom = PIXEL_HEIGHT (f);
3476 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3477 FRAME_EXTERNAL_MENU_BAR (f));
3479 /* Do first time app init */
3481 if (!hprevinst)
3483 w32_init_class (hinst);
3486 FRAME_W32_WINDOW (f) = hwnd
3487 = CreateWindow (EMACS_CLASS,
3488 f->namebuf,
3489 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3490 f->output_data.w32->left_pos,
3491 f->output_data.w32->top_pos,
3492 rect.right - rect.left,
3493 rect.bottom - rect.top,
3494 NULL,
3495 NULL,
3496 hinst,
3497 NULL);
3499 if (hwnd)
3501 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3502 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3503 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3504 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3505 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3507 /* Enable drag-n-drop. */
3508 DragAcceptFiles (hwnd, TRUE);
3510 /* Do this to discard the default setting specified by our parent. */
3511 ShowWindow (hwnd, SW_HIDE);
3515 void
3516 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3517 W32Msg * wmsg;
3518 HWND hwnd;
3519 UINT msg;
3520 WPARAM wParam;
3521 LPARAM lParam;
3523 wmsg->msg.hwnd = hwnd;
3524 wmsg->msg.message = msg;
3525 wmsg->msg.wParam = wParam;
3526 wmsg->msg.lParam = lParam;
3527 wmsg->msg.time = GetMessageTime ();
3529 post_msg (wmsg);
3532 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3533 between left and right keys as advertised. We test for this
3534 support dynamically, and set a flag when the support is absent. If
3535 absent, we keep track of the left and right control and alt keys
3536 ourselves. This is particularly necessary on keyboards that rely
3537 upon the AltGr key, which is represented as having the left control
3538 and right alt keys pressed. For these keyboards, we need to know
3539 when the left alt key has been pressed in addition to the AltGr key
3540 so that we can properly support M-AltGr-key sequences (such as M-@
3541 on Swedish keyboards). */
3543 #define EMACS_LCONTROL 0
3544 #define EMACS_RCONTROL 1
3545 #define EMACS_LMENU 2
3546 #define EMACS_RMENU 3
3548 static int modifiers[4];
3549 static int modifiers_recorded;
3550 static int modifier_key_support_tested;
3552 static void
3553 test_modifier_support (unsigned int wparam)
3555 unsigned int l, r;
3557 if (wparam != VK_CONTROL && wparam != VK_MENU)
3558 return;
3559 if (wparam == VK_CONTROL)
3561 l = VK_LCONTROL;
3562 r = VK_RCONTROL;
3564 else
3566 l = VK_LMENU;
3567 r = VK_RMENU;
3569 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3570 modifiers_recorded = 1;
3571 else
3572 modifiers_recorded = 0;
3573 modifier_key_support_tested = 1;
3576 static void
3577 record_keydown (unsigned int wparam, unsigned int lparam)
3579 int i;
3581 if (!modifier_key_support_tested)
3582 test_modifier_support (wparam);
3584 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3585 return;
3587 if (wparam == VK_CONTROL)
3588 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3589 else
3590 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3592 modifiers[i] = 1;
3595 static void
3596 record_keyup (unsigned int wparam, unsigned int lparam)
3598 int i;
3600 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3601 return;
3603 if (wparam == VK_CONTROL)
3604 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3605 else
3606 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3608 modifiers[i] = 0;
3611 /* Emacs can lose focus while a modifier key has been pressed. When
3612 it regains focus, be conservative and clear all modifiers since
3613 we cannot reconstruct the left and right modifier state. */
3614 static void
3615 reset_modifiers ()
3617 SHORT ctrl, alt;
3619 if (GetFocus () == NULL)
3620 /* Emacs doesn't have keyboard focus. Do nothing. */
3621 return;
3623 ctrl = GetAsyncKeyState (VK_CONTROL);
3624 alt = GetAsyncKeyState (VK_MENU);
3626 if (!(ctrl & 0x08000))
3627 /* Clear any recorded control modifier state. */
3628 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3630 if (!(alt & 0x08000))
3631 /* Clear any recorded alt modifier state. */
3632 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3634 /* Update the state of all modifier keys, because modifiers used in
3635 hot-key combinations can get stuck on if Emacs loses focus as a
3636 result of a hot-key being pressed. */
3638 BYTE keystate[256];
3640 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3642 GetKeyboardState (keystate);
3643 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3644 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3645 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3646 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3647 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3648 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3649 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3650 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3651 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3652 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3653 SetKeyboardState (keystate);
3657 /* Synchronize modifier state with what is reported with the current
3658 keystroke. Even if we cannot distinguish between left and right
3659 modifier keys, we know that, if no modifiers are set, then neither
3660 the left or right modifier should be set. */
3661 static void
3662 sync_modifiers ()
3664 if (!modifiers_recorded)
3665 return;
3667 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3668 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3670 if (!(GetKeyState (VK_MENU) & 0x8000))
3671 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3674 static int
3675 modifier_set (int vkey)
3677 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3678 return (GetKeyState (vkey) & 0x1);
3679 if (!modifiers_recorded)
3680 return (GetKeyState (vkey) & 0x8000);
3682 switch (vkey)
3684 case VK_LCONTROL:
3685 return modifiers[EMACS_LCONTROL];
3686 case VK_RCONTROL:
3687 return modifiers[EMACS_RCONTROL];
3688 case VK_LMENU:
3689 return modifiers[EMACS_LMENU];
3690 case VK_RMENU:
3691 return modifiers[EMACS_RMENU];
3693 return (GetKeyState (vkey) & 0x8000);
3696 /* Convert between the modifier bits W32 uses and the modifier bits
3697 Emacs uses. */
3699 unsigned int
3700 w32_key_to_modifier (int key)
3702 Lisp_Object key_mapping;
3704 switch (key)
3706 case VK_LWIN:
3707 key_mapping = Vw32_lwindow_modifier;
3708 break;
3709 case VK_RWIN:
3710 key_mapping = Vw32_rwindow_modifier;
3711 break;
3712 case VK_APPS:
3713 key_mapping = Vw32_apps_modifier;
3714 break;
3715 case VK_SCROLL:
3716 key_mapping = Vw32_scroll_lock_modifier;
3717 break;
3718 default:
3719 key_mapping = Qnil;
3722 /* NB. This code runs in the input thread, asychronously to the lisp
3723 thread, so we must be careful to ensure access to lisp data is
3724 thread-safe. The following code is safe because the modifier
3725 variable values are updated atomically from lisp and symbols are
3726 not relocated by GC. Also, we don't have to worry about seeing GC
3727 markbits here. */
3728 if (EQ (key_mapping, Qhyper))
3729 return hyper_modifier;
3730 if (EQ (key_mapping, Qsuper))
3731 return super_modifier;
3732 if (EQ (key_mapping, Qmeta))
3733 return meta_modifier;
3734 if (EQ (key_mapping, Qalt))
3735 return alt_modifier;
3736 if (EQ (key_mapping, Qctrl))
3737 return ctrl_modifier;
3738 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3739 return ctrl_modifier;
3740 if (EQ (key_mapping, Qshift))
3741 return shift_modifier;
3743 /* Don't generate any modifier if not explicitly requested. */
3744 return 0;
3747 unsigned int
3748 w32_get_modifiers ()
3750 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3751 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3752 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3753 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3754 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3755 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3756 (modifier_set (VK_MENU) ?
3757 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3760 /* We map the VK_* modifiers into console modifier constants
3761 so that we can use the same routines to handle both console
3762 and window input. */
3764 static int
3765 construct_console_modifiers ()
3767 int mods;
3769 mods = 0;
3770 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3771 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3772 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3773 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3774 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3775 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3776 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3777 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3778 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3779 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3780 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3782 return mods;
3785 static int
3786 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3788 int mods;
3790 /* Convert to emacs modifiers. */
3791 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3793 return mods;
3796 unsigned int
3797 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3799 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3800 return virt_key;
3802 if (virt_key == VK_RETURN)
3803 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3805 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3806 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3808 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3809 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3811 if (virt_key == VK_CLEAR)
3812 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3814 return virt_key;
3817 /* List of special key combinations which w32 would normally capture,
3818 but emacs should grab instead. Not directly visible to lisp, to
3819 simplify synchronization. Each item is an integer encoding a virtual
3820 key code and modifier combination to capture. */
3821 Lisp_Object w32_grabbed_keys;
3823 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3824 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3825 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3826 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3828 /* Register hot-keys for reserved key combinations when Emacs has
3829 keyboard focus, since this is the only way Emacs can receive key
3830 combinations like Alt-Tab which are used by the system. */
3832 static void
3833 register_hot_keys (hwnd)
3834 HWND hwnd;
3836 Lisp_Object keylist;
3838 /* Use GC_CONSP, since we are called asynchronously. */
3839 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3841 Lisp_Object key = XCAR (keylist);
3843 /* Deleted entries get set to nil. */
3844 if (!INTEGERP (key))
3845 continue;
3847 RegisterHotKey (hwnd, HOTKEY_ID (key),
3848 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3852 static void
3853 unregister_hot_keys (hwnd)
3854 HWND hwnd;
3856 Lisp_Object keylist;
3858 /* Use GC_CONSP, since we are called asynchronously. */
3859 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3861 Lisp_Object key = XCAR (keylist);
3863 if (!INTEGERP (key))
3864 continue;
3866 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3870 /* Main message dispatch loop. */
3872 static void
3873 w32_msg_pump (deferred_msg * msg_buf)
3875 MSG msg;
3876 int result;
3877 HWND focus_window;
3879 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3881 while (GetMessage (&msg, NULL, 0, 0))
3883 if (msg.hwnd == NULL)
3885 switch (msg.message)
3887 case WM_NULL:
3888 /* Produced by complete_deferred_msg; just ignore. */
3889 break;
3890 case WM_EMACS_CREATEWINDOW:
3891 w32_createwindow ((struct frame *) msg.wParam);
3892 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3893 abort ();
3894 break;
3895 case WM_EMACS_SETLOCALE:
3896 SetThreadLocale (msg.wParam);
3897 /* Reply is not expected. */
3898 break;
3899 case WM_EMACS_SETKEYBOARDLAYOUT:
3900 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3901 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3902 result, 0))
3903 abort ();
3904 break;
3905 case WM_EMACS_REGISTER_HOT_KEY:
3906 focus_window = GetFocus ();
3907 if (focus_window != NULL)
3908 RegisterHotKey (focus_window,
3909 HOTKEY_ID (msg.wParam),
3910 HOTKEY_MODIFIERS (msg.wParam),
3911 HOTKEY_VK_CODE (msg.wParam));
3912 /* Reply is not expected. */
3913 break;
3914 case WM_EMACS_UNREGISTER_HOT_KEY:
3915 focus_window = GetFocus ();
3916 if (focus_window != NULL)
3917 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3918 /* Mark item as erased. NB: this code must be
3919 thread-safe. The next line is okay because the cons
3920 cell is never made into garbage and is not relocated by
3921 GC. */
3922 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
3923 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3924 abort ();
3925 break;
3926 case WM_EMACS_TOGGLE_LOCK_KEY:
3928 int vk_code = (int) msg.wParam;
3929 int cur_state = (GetKeyState (vk_code) & 1);
3930 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3932 /* NB: This code must be thread-safe. It is safe to
3933 call NILP because symbols are not relocated by GC,
3934 and pointer here is not touched by GC (so the markbit
3935 can't be set). Numbers are safe because they are
3936 immediate values. */
3937 if (NILP (new_state)
3938 || (NUMBERP (new_state)
3939 && ((XUINT (new_state)) & 1) != cur_state))
3941 one_w32_display_info.faked_key = vk_code;
3943 keybd_event ((BYTE) vk_code,
3944 (BYTE) MapVirtualKey (vk_code, 0),
3945 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3946 keybd_event ((BYTE) vk_code,
3947 (BYTE) MapVirtualKey (vk_code, 0),
3948 KEYEVENTF_EXTENDEDKEY | 0, 0);
3949 keybd_event ((BYTE) vk_code,
3950 (BYTE) MapVirtualKey (vk_code, 0),
3951 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3952 cur_state = !cur_state;
3954 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3955 cur_state, 0))
3956 abort ();
3958 break;
3959 default:
3960 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3963 else
3965 DispatchMessage (&msg);
3968 /* Exit nested loop when our deferred message has completed. */
3969 if (msg_buf->completed)
3970 break;
3974 deferred_msg * deferred_msg_head;
3976 static deferred_msg *
3977 find_deferred_msg (HWND hwnd, UINT msg)
3979 deferred_msg * item;
3981 /* Don't actually need synchronization for read access, since
3982 modification of single pointer is always atomic. */
3983 /* enter_crit (); */
3985 for (item = deferred_msg_head; item != NULL; item = item->next)
3986 if (item->w32msg.msg.hwnd == hwnd
3987 && item->w32msg.msg.message == msg)
3988 break;
3990 /* leave_crit (); */
3992 return item;
3995 static LRESULT
3996 send_deferred_msg (deferred_msg * msg_buf,
3997 HWND hwnd,
3998 UINT msg,
3999 WPARAM wParam,
4000 LPARAM lParam)
4002 /* Only input thread can send deferred messages. */
4003 if (GetCurrentThreadId () != dwWindowsThreadId)
4004 abort ();
4006 /* It is an error to send a message that is already deferred. */
4007 if (find_deferred_msg (hwnd, msg) != NULL)
4008 abort ();
4010 /* Enforced synchronization is not needed because this is the only
4011 function that alters deferred_msg_head, and the following critical
4012 section is guaranteed to only be serially reentered (since only the
4013 input thread can call us). */
4015 /* enter_crit (); */
4017 msg_buf->completed = 0;
4018 msg_buf->next = deferred_msg_head;
4019 deferred_msg_head = msg_buf;
4020 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
4022 /* leave_crit (); */
4024 /* Start a new nested message loop to process other messages until
4025 this one is completed. */
4026 w32_msg_pump (msg_buf);
4028 deferred_msg_head = msg_buf->next;
4030 return msg_buf->result;
4033 void
4034 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
4036 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
4038 if (msg_buf == NULL)
4039 /* Message may have been cancelled, so don't abort(). */
4040 return;
4042 msg_buf->result = result;
4043 msg_buf->completed = 1;
4045 /* Ensure input thread is woken so it notices the completion. */
4046 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4049 void
4050 cancel_all_deferred_msgs ()
4052 deferred_msg * item;
4054 /* Don't actually need synchronization for read access, since
4055 modification of single pointer is always atomic. */
4056 /* enter_crit (); */
4058 for (item = deferred_msg_head; item != NULL; item = item->next)
4060 item->result = 0;
4061 item->completed = 1;
4064 /* leave_crit (); */
4066 /* Ensure input thread is woken so it notices the completion. */
4067 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4070 DWORD
4071 w32_msg_worker (dw)
4072 DWORD dw;
4074 MSG msg;
4075 deferred_msg dummy_buf;
4077 /* Ensure our message queue is created */
4079 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
4081 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
4082 abort ();
4084 memset (&dummy_buf, 0, sizeof (dummy_buf));
4085 dummy_buf.w32msg.msg.hwnd = NULL;
4086 dummy_buf.w32msg.msg.message = WM_NULL;
4088 /* This is the inital message loop which should only exit when the
4089 application quits. */
4090 w32_msg_pump (&dummy_buf);
4092 return 0;
4095 static void
4096 post_character_message (hwnd, msg, wParam, lParam, modifiers)
4097 HWND hwnd;
4098 UINT msg;
4099 WPARAM wParam;
4100 LPARAM lParam;
4101 DWORD modifiers;
4104 W32Msg wmsg;
4106 wmsg.dwModifiers = modifiers;
4108 /* Detect quit_char and set quit-flag directly. Note that we
4109 still need to post a message to ensure the main thread will be
4110 woken up if blocked in sys_select(), but we do NOT want to post
4111 the quit_char message itself (because it will usually be as if
4112 the user had typed quit_char twice). Instead, we post a dummy
4113 message that has no particular effect. */
4115 int c = wParam;
4116 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
4117 c = make_ctrl_char (c) & 0377;
4118 if (c == quit_char
4119 || (wmsg.dwModifiers == 0 &&
4120 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
4122 Vquit_flag = Qt;
4124 /* The choice of message is somewhat arbitrary, as long as
4125 the main thread handler just ignores it. */
4126 msg = WM_NULL;
4128 /* Interrupt any blocking system calls. */
4129 signal_quit ();
4131 /* As a safety precaution, forcibly complete any deferred
4132 messages. This is a kludge, but I don't see any particularly
4133 clean way to handle the situation where a deferred message is
4134 "dropped" in the lisp thread, and will thus never be
4135 completed, eg. by the user trying to activate the menubar
4136 when the lisp thread is busy, and then typing C-g when the
4137 menubar doesn't open promptly (with the result that the
4138 menubar never responds at all because the deferred
4139 WM_INITMENU message is never completed). Another problem
4140 situation is when the lisp thread calls SendMessage (to send
4141 a window manager command) when a message has been deferred;
4142 the lisp thread gets blocked indefinitely waiting for the
4143 deferred message to be completed, which itself is waiting for
4144 the lisp thread to respond.
4146 Note that we don't want to block the input thread waiting for
4147 a reponse from the lisp thread (although that would at least
4148 solve the deadlock problem above), because we want to be able
4149 to receive C-g to interrupt the lisp thread. */
4150 cancel_all_deferred_msgs ();
4154 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4157 /* Main window procedure */
4159 LRESULT CALLBACK
4160 w32_wnd_proc (hwnd, msg, wParam, lParam)
4161 HWND hwnd;
4162 UINT msg;
4163 WPARAM wParam;
4164 LPARAM lParam;
4166 struct frame *f;
4167 struct w32_display_info *dpyinfo = &one_w32_display_info;
4168 W32Msg wmsg;
4169 int windows_translate;
4170 int key;
4172 /* Note that it is okay to call x_window_to_frame, even though we are
4173 not running in the main lisp thread, because frame deletion
4174 requires the lisp thread to synchronize with this thread. Thus, if
4175 a frame struct is returned, it can be used without concern that the
4176 lisp thread might make it disappear while we are using it.
4178 NB. Walking the frame list in this thread is safe (as long as
4179 writes of Lisp_Object slots are atomic, which they are on Windows).
4180 Although delete-frame can destructively modify the frame list while
4181 we are walking it, a garbage collection cannot occur until after
4182 delete-frame has synchronized with this thread.
4184 It is also safe to use functions that make GDI calls, such as
4185 w32_clear_rect, because these functions must obtain a DC handle
4186 from the frame struct using get_frame_dc which is thread-aware. */
4188 switch (msg)
4190 case WM_ERASEBKGND:
4191 f = x_window_to_frame (dpyinfo, hwnd);
4192 if (f)
4194 HDC hdc = get_frame_dc (f);
4195 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4196 w32_clear_rect (f, hdc, &wmsg.rect);
4197 release_frame_dc (f, hdc);
4199 #if defined (W32_DEBUG_DISPLAY)
4200 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
4202 wmsg.rect.left, wmsg.rect.top,
4203 wmsg.rect.right, wmsg.rect.bottom));
4204 #endif /* W32_DEBUG_DISPLAY */
4206 return 1;
4207 case WM_PALETTECHANGED:
4208 /* ignore our own changes */
4209 if ((HWND)wParam != hwnd)
4211 f = x_window_to_frame (dpyinfo, hwnd);
4212 if (f)
4213 /* get_frame_dc will realize our palette and force all
4214 frames to be redrawn if needed. */
4215 release_frame_dc (f, get_frame_dc (f));
4217 return 0;
4218 case WM_PAINT:
4220 PAINTSTRUCT paintStruct;
4221 RECT update_rect;
4222 bzero (&update_rect, sizeof (update_rect));
4224 f = x_window_to_frame (dpyinfo, hwnd);
4225 if (f == 0)
4227 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
4228 return 0;
4231 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4232 fails. Apparently this can happen under some
4233 circumstances. */
4234 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
4236 enter_crit ();
4237 BeginPaint (hwnd, &paintStruct);
4239 /* The rectangles returned by GetUpdateRect and BeginPaint
4240 do not always match. Play it safe by assuming both areas
4241 are invalid. */
4242 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
4244 #if defined (W32_DEBUG_DISPLAY)
4245 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
4247 wmsg.rect.left, wmsg.rect.top,
4248 wmsg.rect.right, wmsg.rect.bottom));
4249 DebPrint ((" [update region is %d,%d-%d,%d]\n",
4250 update_rect.left, update_rect.top,
4251 update_rect.right, update_rect.bottom));
4252 #endif
4253 EndPaint (hwnd, &paintStruct);
4254 leave_crit ();
4256 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4258 return 0;
4261 /* If GetUpdateRect returns 0 (meaning there is no update
4262 region), assume the whole window needs to be repainted. */
4263 GetClientRect(hwnd, &wmsg.rect);
4264 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4265 return 0;
4268 case WM_INPUTLANGCHANGE:
4269 /* Inform lisp thread of keyboard layout changes. */
4270 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4272 /* Clear dead keys in the keyboard state; for simplicity only
4273 preserve modifier key states. */
4275 int i;
4276 BYTE keystate[256];
4278 GetKeyboardState (keystate);
4279 for (i = 0; i < 256; i++)
4280 if (1
4281 && i != VK_SHIFT
4282 && i != VK_LSHIFT
4283 && i != VK_RSHIFT
4284 && i != VK_CAPITAL
4285 && i != VK_NUMLOCK
4286 && i != VK_SCROLL
4287 && i != VK_CONTROL
4288 && i != VK_LCONTROL
4289 && i != VK_RCONTROL
4290 && i != VK_MENU
4291 && i != VK_LMENU
4292 && i != VK_RMENU
4293 && i != VK_LWIN
4294 && i != VK_RWIN)
4295 keystate[i] = 0;
4296 SetKeyboardState (keystate);
4298 goto dflt;
4300 case WM_HOTKEY:
4301 /* Synchronize hot keys with normal input. */
4302 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4303 return (0);
4305 case WM_KEYUP:
4306 case WM_SYSKEYUP:
4307 record_keyup (wParam, lParam);
4308 goto dflt;
4310 case WM_KEYDOWN:
4311 case WM_SYSKEYDOWN:
4312 /* Ignore keystrokes we fake ourself; see below. */
4313 if (dpyinfo->faked_key == wParam)
4315 dpyinfo->faked_key = 0;
4316 /* Make sure TranslateMessage sees them though (as long as
4317 they don't produce WM_CHAR messages). This ensures that
4318 indicator lights are toggled promptly on Windows 9x, for
4319 example. */
4320 if (lispy_function_keys[wParam] != 0)
4322 windows_translate = 1;
4323 goto translate;
4325 return 0;
4328 /* Synchronize modifiers with current keystroke. */
4329 sync_modifiers ();
4330 record_keydown (wParam, lParam);
4331 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4333 windows_translate = 0;
4335 switch (wParam)
4337 case VK_LWIN:
4338 if (NILP (Vw32_pass_lwindow_to_system))
4340 /* Prevent system from acting on keyup (which opens the
4341 Start menu if no other key was pressed) by simulating a
4342 press of Space which we will ignore. */
4343 if (GetAsyncKeyState (wParam) & 1)
4345 if (NUMBERP (Vw32_phantom_key_code))
4346 key = XUINT (Vw32_phantom_key_code) & 255;
4347 else
4348 key = VK_SPACE;
4349 dpyinfo->faked_key = key;
4350 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4353 if (!NILP (Vw32_lwindow_modifier))
4354 return 0;
4355 break;
4356 case VK_RWIN:
4357 if (NILP (Vw32_pass_rwindow_to_system))
4359 if (GetAsyncKeyState (wParam) & 1)
4361 if (NUMBERP (Vw32_phantom_key_code))
4362 key = XUINT (Vw32_phantom_key_code) & 255;
4363 else
4364 key = VK_SPACE;
4365 dpyinfo->faked_key = key;
4366 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4369 if (!NILP (Vw32_rwindow_modifier))
4370 return 0;
4371 break;
4372 case VK_APPS:
4373 if (!NILP (Vw32_apps_modifier))
4374 return 0;
4375 break;
4376 case VK_MENU:
4377 if (NILP (Vw32_pass_alt_to_system))
4378 /* Prevent DefWindowProc from activating the menu bar if an
4379 Alt key is pressed and released by itself. */
4380 return 0;
4381 windows_translate = 1;
4382 break;
4383 case VK_CAPITAL:
4384 /* Decide whether to treat as modifier or function key. */
4385 if (NILP (Vw32_enable_caps_lock))
4386 goto disable_lock_key;
4387 windows_translate = 1;
4388 break;
4389 case VK_NUMLOCK:
4390 /* Decide whether to treat as modifier or function key. */
4391 if (NILP (Vw32_enable_num_lock))
4392 goto disable_lock_key;
4393 windows_translate = 1;
4394 break;
4395 case VK_SCROLL:
4396 /* Decide whether to treat as modifier or function key. */
4397 if (NILP (Vw32_scroll_lock_modifier))
4398 goto disable_lock_key;
4399 windows_translate = 1;
4400 break;
4401 disable_lock_key:
4402 /* Ensure the appropriate lock key state (and indicator light)
4403 remains in the same state. We do this by faking another
4404 press of the relevant key. Apparently, this really is the
4405 only way to toggle the state of the indicator lights. */
4406 dpyinfo->faked_key = wParam;
4407 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4408 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4409 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4410 KEYEVENTF_EXTENDEDKEY | 0, 0);
4411 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4412 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4413 /* Ensure indicator lights are updated promptly on Windows 9x
4414 (TranslateMessage apparently does this), after forwarding
4415 input event. */
4416 post_character_message (hwnd, msg, wParam, lParam,
4417 w32_get_key_modifiers (wParam, lParam));
4418 windows_translate = 1;
4419 break;
4420 case VK_CONTROL:
4421 case VK_SHIFT:
4422 case VK_PROCESSKEY: /* Generated by IME. */
4423 windows_translate = 1;
4424 break;
4425 case VK_CANCEL:
4426 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4427 which is confusing for purposes of key binding; convert
4428 VK_CANCEL events into VK_PAUSE events. */
4429 wParam = VK_PAUSE;
4430 break;
4431 case VK_PAUSE:
4432 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4433 for purposes of key binding; convert these back into
4434 VK_NUMLOCK events, at least when we want to see NumLock key
4435 presses. (Note that there is never any possibility that
4436 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4437 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4438 wParam = VK_NUMLOCK;
4439 break;
4440 default:
4441 /* If not defined as a function key, change it to a WM_CHAR message. */
4442 if (lispy_function_keys[wParam] == 0)
4444 DWORD modifiers = construct_console_modifiers ();
4446 if (!NILP (Vw32_recognize_altgr)
4447 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4449 /* Always let TranslateMessage handle AltGr key chords;
4450 for some reason, ToAscii doesn't always process AltGr
4451 chords correctly. */
4452 windows_translate = 1;
4454 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4456 /* Handle key chords including any modifiers other
4457 than shift directly, in order to preserve as much
4458 modifier information as possible. */
4459 if ('A' <= wParam && wParam <= 'Z')
4461 /* Don't translate modified alphabetic keystrokes,
4462 so the user doesn't need to constantly switch
4463 layout to type control or meta keystrokes when
4464 the normal layout translates alphabetic
4465 characters to non-ascii characters. */
4466 if (!modifier_set (VK_SHIFT))
4467 wParam += ('a' - 'A');
4468 msg = WM_CHAR;
4470 else
4472 /* Try to handle other keystrokes by determining the
4473 base character (ie. translating the base key plus
4474 shift modifier). */
4475 int add;
4476 int isdead = 0;
4477 KEY_EVENT_RECORD key;
4479 key.bKeyDown = TRUE;
4480 key.wRepeatCount = 1;
4481 key.wVirtualKeyCode = wParam;
4482 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4483 key.uChar.AsciiChar = 0;
4484 key.dwControlKeyState = modifiers;
4486 add = w32_kbd_patch_key (&key);
4487 /* 0 means an unrecognised keycode, negative means
4488 dead key. Ignore both. */
4489 while (--add >= 0)
4491 /* Forward asciified character sequence. */
4492 post_character_message
4493 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4494 w32_get_key_modifiers (wParam, lParam));
4495 w32_kbd_patch_key (&key);
4497 return 0;
4500 else
4502 /* Let TranslateMessage handle everything else. */
4503 windows_translate = 1;
4508 translate:
4509 if (windows_translate)
4511 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4513 windows_msg.time = GetMessageTime ();
4514 TranslateMessage (&windows_msg);
4515 goto dflt;
4518 /* Fall through */
4520 case WM_SYSCHAR:
4521 case WM_CHAR:
4522 post_character_message (hwnd, msg, wParam, lParam,
4523 w32_get_key_modifiers (wParam, lParam));
4524 break;
4526 /* Simulate middle mouse button events when left and right buttons
4527 are used together, but only if user has two button mouse. */
4528 case WM_LBUTTONDOWN:
4529 case WM_RBUTTONDOWN:
4530 if (XINT (Vw32_num_mouse_buttons) > 2)
4531 goto handle_plain_button;
4534 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4535 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4537 if (button_state & this)
4538 return 0;
4540 if (button_state == 0)
4541 SetCapture (hwnd);
4543 button_state |= this;
4545 if (button_state & other)
4547 if (mouse_button_timer)
4549 KillTimer (hwnd, mouse_button_timer);
4550 mouse_button_timer = 0;
4552 /* Generate middle mouse event instead. */
4553 msg = WM_MBUTTONDOWN;
4554 button_state |= MMOUSE;
4556 else if (button_state & MMOUSE)
4558 /* Ignore button event if we've already generated a
4559 middle mouse down event. This happens if the
4560 user releases and press one of the two buttons
4561 after we've faked a middle mouse event. */
4562 return 0;
4564 else
4566 /* Flush out saved message. */
4567 post_msg (&saved_mouse_button_msg);
4569 wmsg.dwModifiers = w32_get_modifiers ();
4570 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4572 /* Clear message buffer. */
4573 saved_mouse_button_msg.msg.hwnd = 0;
4575 else
4577 /* Hold onto message for now. */
4578 mouse_button_timer =
4579 SetTimer (hwnd, MOUSE_BUTTON_ID,
4580 XINT (Vw32_mouse_button_tolerance), NULL);
4581 saved_mouse_button_msg.msg.hwnd = hwnd;
4582 saved_mouse_button_msg.msg.message = msg;
4583 saved_mouse_button_msg.msg.wParam = wParam;
4584 saved_mouse_button_msg.msg.lParam = lParam;
4585 saved_mouse_button_msg.msg.time = GetMessageTime ();
4586 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4589 return 0;
4591 case WM_LBUTTONUP:
4592 case WM_RBUTTONUP:
4593 if (XINT (Vw32_num_mouse_buttons) > 2)
4594 goto handle_plain_button;
4597 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4598 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4600 if ((button_state & this) == 0)
4601 return 0;
4603 button_state &= ~this;
4605 if (button_state & MMOUSE)
4607 /* Only generate event when second button is released. */
4608 if ((button_state & other) == 0)
4610 msg = WM_MBUTTONUP;
4611 button_state &= ~MMOUSE;
4613 if (button_state) abort ();
4615 else
4616 return 0;
4618 else
4620 /* Flush out saved message if necessary. */
4621 if (saved_mouse_button_msg.msg.hwnd)
4623 post_msg (&saved_mouse_button_msg);
4626 wmsg.dwModifiers = w32_get_modifiers ();
4627 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4629 /* Always clear message buffer and cancel timer. */
4630 saved_mouse_button_msg.msg.hwnd = 0;
4631 KillTimer (hwnd, mouse_button_timer);
4632 mouse_button_timer = 0;
4634 if (button_state == 0)
4635 ReleaseCapture ();
4637 return 0;
4639 case WM_XBUTTONDOWN:
4640 case WM_XBUTTONUP:
4641 if (w32_pass_extra_mouse_buttons_to_system)
4642 goto dflt;
4643 /* else fall through and process them. */
4644 case WM_MBUTTONDOWN:
4645 case WM_MBUTTONUP:
4646 handle_plain_button:
4648 BOOL up;
4649 int button;
4651 if (parse_button (msg, HIWORD (wParam), &button, &up))
4653 if (up) ReleaseCapture ();
4654 else SetCapture (hwnd);
4655 button = (button == 0) ? LMOUSE :
4656 ((button == 1) ? MMOUSE : RMOUSE);
4657 if (up)
4658 button_state &= ~button;
4659 else
4660 button_state |= button;
4664 wmsg.dwModifiers = w32_get_modifiers ();
4665 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4667 /* Need to return true for XBUTTON messages, false for others,
4668 to indicate that we processed the message. */
4669 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4671 case WM_MOUSEMOVE:
4672 /* If the mouse has just moved into the frame, start tracking
4673 it, so we will be notified when it leaves the frame. Mouse
4674 tracking only works under W98 and NT4 and later. On earlier
4675 versions, there is no way of telling when the mouse leaves the
4676 frame, so we just have to put up with help-echo and mouse
4677 highlighting remaining while the frame is not active. */
4678 if (track_mouse_event_fn && !track_mouse_window)
4680 TRACKMOUSEEVENT tme;
4681 tme.cbSize = sizeof (tme);
4682 tme.dwFlags = TME_LEAVE;
4683 tme.hwndTrack = hwnd;
4685 track_mouse_event_fn (&tme);
4686 track_mouse_window = hwnd;
4688 case WM_VSCROLL:
4689 if (XINT (Vw32_mouse_move_interval) <= 0
4690 || (msg == WM_MOUSEMOVE && button_state == 0))
4692 wmsg.dwModifiers = w32_get_modifiers ();
4693 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4694 return 0;
4697 /* Hang onto mouse move and scroll messages for a bit, to avoid
4698 sending such events to Emacs faster than it can process them.
4699 If we get more events before the timer from the first message
4700 expires, we just replace the first message. */
4702 if (saved_mouse_move_msg.msg.hwnd == 0)
4703 mouse_move_timer =
4704 SetTimer (hwnd, MOUSE_MOVE_ID,
4705 XINT (Vw32_mouse_move_interval), NULL);
4707 /* Hold onto message for now. */
4708 saved_mouse_move_msg.msg.hwnd = hwnd;
4709 saved_mouse_move_msg.msg.message = msg;
4710 saved_mouse_move_msg.msg.wParam = wParam;
4711 saved_mouse_move_msg.msg.lParam = lParam;
4712 saved_mouse_move_msg.msg.time = GetMessageTime ();
4713 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4715 return 0;
4717 case WM_MOUSEWHEEL:
4718 wmsg.dwModifiers = w32_get_modifiers ();
4719 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4720 return 0;
4722 case WM_DROPFILES:
4723 wmsg.dwModifiers = w32_get_modifiers ();
4724 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4725 return 0;
4727 case WM_TIMER:
4728 /* Flush out saved messages if necessary. */
4729 if (wParam == mouse_button_timer)
4731 if (saved_mouse_button_msg.msg.hwnd)
4733 post_msg (&saved_mouse_button_msg);
4734 saved_mouse_button_msg.msg.hwnd = 0;
4736 KillTimer (hwnd, mouse_button_timer);
4737 mouse_button_timer = 0;
4739 else if (wParam == mouse_move_timer)
4741 if (saved_mouse_move_msg.msg.hwnd)
4743 post_msg (&saved_mouse_move_msg);
4744 saved_mouse_move_msg.msg.hwnd = 0;
4746 KillTimer (hwnd, mouse_move_timer);
4747 mouse_move_timer = 0;
4749 else if (wParam == menu_free_timer)
4751 KillTimer (hwnd, menu_free_timer);
4752 menu_free_timer = 0;
4753 f = x_window_to_frame (dpyinfo, hwnd);
4754 if (!f->output_data.w32->menu_command_in_progress)
4756 /* Free memory used by owner-drawn and help-echo strings. */
4757 w32_free_menu_strings (hwnd);
4758 f->output_data.w32->menubar_active = 0;
4761 return 0;
4763 case WM_NCACTIVATE:
4764 /* Windows doesn't send us focus messages when putting up and
4765 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4766 The only indication we get that something happened is receiving
4767 this message afterwards. So this is a good time to reset our
4768 keyboard modifiers' state. */
4769 reset_modifiers ();
4770 goto dflt;
4772 case WM_INITMENU:
4773 button_state = 0;
4774 ReleaseCapture ();
4775 /* We must ensure menu bar is fully constructed and up to date
4776 before allowing user interaction with it. To achieve this
4777 we send this message to the lisp thread and wait for a
4778 reply (whose value is not actually needed) to indicate that
4779 the menu bar is now ready for use, so we can now return.
4781 To remain responsive in the meantime, we enter a nested message
4782 loop that can process all other messages.
4784 However, we skip all this if the message results from calling
4785 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4786 thread a message because it is blocked on us at this point. We
4787 set menubar_active before calling TrackPopupMenu to indicate
4788 this (there is no possibility of confusion with real menubar
4789 being active). */
4791 f = x_window_to_frame (dpyinfo, hwnd);
4792 if (f
4793 && (f->output_data.w32->menubar_active
4794 /* We can receive this message even in the absence of a
4795 menubar (ie. when the system menu is activated) - in this
4796 case we do NOT want to forward the message, otherwise it
4797 will cause the menubar to suddenly appear when the user
4798 had requested it to be turned off! */
4799 || f->output_data.w32->menubar_widget == NULL))
4800 return 0;
4803 deferred_msg msg_buf;
4805 /* Detect if message has already been deferred; in this case
4806 we cannot return any sensible value to ignore this. */
4807 if (find_deferred_msg (hwnd, msg) != NULL)
4808 abort ();
4810 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4813 case WM_EXITMENULOOP:
4814 f = x_window_to_frame (dpyinfo, hwnd);
4816 /* If a menu command is not already in progress, check again
4817 after a short delay, since Windows often (always?) sends the
4818 WM_EXITMENULOOP before the corresponding WM_COMMAND message. */
4819 if (f && !f->output_data.w32->menu_command_in_progress)
4820 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4821 goto dflt;
4823 case WM_MENUSELECT:
4824 /* Direct handling of help_echo in menus. Should be safe now
4825 that we generate the help_echo by placing a help event in the
4826 keyboard buffer. */
4828 HMENU menu = (HMENU) lParam;
4829 UINT menu_item = (UINT) LOWORD (wParam);
4830 UINT flags = (UINT) HIWORD (wParam);
4832 w32_menu_display_help (hwnd, menu, menu_item, flags);
4834 return 0;
4836 case WM_MEASUREITEM:
4837 f = x_window_to_frame (dpyinfo, hwnd);
4838 if (f)
4840 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4842 if (pMis->CtlType == ODT_MENU)
4844 /* Work out dimensions for popup menu titles. */
4845 char * title = (char *) pMis->itemData;
4846 HDC hdc = GetDC (hwnd);
4847 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4848 LOGFONT menu_logfont;
4849 HFONT old_font;
4850 SIZE size;
4852 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4853 menu_logfont.lfWeight = FW_BOLD;
4854 menu_font = CreateFontIndirect (&menu_logfont);
4855 old_font = SelectObject (hdc, menu_font);
4857 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4858 if (title)
4860 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4861 pMis->itemWidth = size.cx;
4862 if (pMis->itemHeight < size.cy)
4863 pMis->itemHeight = size.cy;
4865 else
4866 pMis->itemWidth = 0;
4868 SelectObject (hdc, old_font);
4869 DeleteObject (menu_font);
4870 ReleaseDC (hwnd, hdc);
4871 return TRUE;
4874 return 0;
4876 case WM_DRAWITEM:
4877 f = x_window_to_frame (dpyinfo, hwnd);
4878 if (f)
4880 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4882 if (pDis->CtlType == ODT_MENU)
4884 /* Draw popup menu title. */
4885 char * title = (char *) pDis->itemData;
4886 if (title)
4888 HDC hdc = pDis->hDC;
4889 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4890 LOGFONT menu_logfont;
4891 HFONT old_font;
4893 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4894 menu_logfont.lfWeight = FW_BOLD;
4895 menu_font = CreateFontIndirect (&menu_logfont);
4896 old_font = SelectObject (hdc, menu_font);
4898 /* Always draw title as if not selected. */
4899 ExtTextOut (hdc,
4900 pDis->rcItem.left
4901 + GetSystemMetrics (SM_CXMENUCHECK),
4902 pDis->rcItem.top,
4903 ETO_OPAQUE, &pDis->rcItem,
4904 title, strlen (title), NULL);
4906 SelectObject (hdc, old_font);
4907 DeleteObject (menu_font);
4909 return TRUE;
4912 return 0;
4914 #if 0
4915 /* Still not right - can't distinguish between clicks in the
4916 client area of the frame from clicks forwarded from the scroll
4917 bars - may have to hook WM_NCHITTEST to remember the mouse
4918 position and then check if it is in the client area ourselves. */
4919 case WM_MOUSEACTIVATE:
4920 /* Discard the mouse click that activates a frame, allowing the
4921 user to click anywhere without changing point (or worse!).
4922 Don't eat mouse clicks on scrollbars though!! */
4923 if (LOWORD (lParam) == HTCLIENT )
4924 return MA_ACTIVATEANDEAT;
4925 goto dflt;
4926 #endif
4928 case WM_MOUSELEAVE:
4929 /* No longer tracking mouse. */
4930 track_mouse_window = NULL;
4932 case WM_ACTIVATEAPP:
4933 case WM_ACTIVATE:
4934 case WM_WINDOWPOSCHANGED:
4935 case WM_SHOWWINDOW:
4936 /* Inform lisp thread that a frame might have just been obscured
4937 or exposed, so should recheck visibility of all frames. */
4938 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4939 goto dflt;
4941 case WM_SETFOCUS:
4942 dpyinfo->faked_key = 0;
4943 reset_modifiers ();
4944 register_hot_keys (hwnd);
4945 goto command;
4946 case WM_KILLFOCUS:
4947 unregister_hot_keys (hwnd);
4948 button_state = 0;
4949 ReleaseCapture ();
4950 /* Relinquish the system caret. */
4951 if (w32_system_caret_hwnd)
4953 w32_visible_system_caret_hwnd = NULL;
4954 w32_system_caret_hwnd = NULL;
4955 DestroyCaret ();
4957 goto command;
4958 case WM_COMMAND:
4959 f = x_window_to_frame (dpyinfo, hwnd);
4960 if (f && HIWORD (wParam) == 0)
4962 f->output_data.w32->menu_command_in_progress = 1;
4963 if (menu_free_timer)
4965 KillTimer (hwnd, menu_free_timer);
4966 menu_free_timer = 0;
4969 case WM_MOVE:
4970 case WM_SIZE:
4971 command:
4972 wmsg.dwModifiers = w32_get_modifiers ();
4973 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4974 goto dflt;
4976 case WM_CLOSE:
4977 wmsg.dwModifiers = w32_get_modifiers ();
4978 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4979 return 0;
4981 case WM_WINDOWPOSCHANGING:
4982 /* Don't restrict the sizing of tip frames. */
4983 if (hwnd == tip_window)
4984 return 0;
4986 WINDOWPLACEMENT wp;
4987 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4989 wp.length = sizeof (WINDOWPLACEMENT);
4990 GetWindowPlacement (hwnd, &wp);
4992 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4994 RECT rect;
4995 int wdiff;
4996 int hdiff;
4997 DWORD font_width;
4998 DWORD line_height;
4999 DWORD internal_border;
5000 DWORD scrollbar_extra;
5001 RECT wr;
5003 wp.length = sizeof(wp);
5004 GetWindowRect (hwnd, &wr);
5006 enter_crit ();
5008 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
5009 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
5010 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
5011 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
5013 leave_crit ();
5015 memset (&rect, 0, sizeof (rect));
5016 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
5017 GetMenu (hwnd) != NULL);
5019 /* Force width and height of client area to be exact
5020 multiples of the character cell dimensions. */
5021 wdiff = (lppos->cx - (rect.right - rect.left)
5022 - 2 * internal_border - scrollbar_extra)
5023 % font_width;
5024 hdiff = (lppos->cy - (rect.bottom - rect.top)
5025 - 2 * internal_border)
5026 % line_height;
5028 if (wdiff || hdiff)
5030 /* For right/bottom sizing we can just fix the sizes.
5031 However for top/left sizing we will need to fix the X
5032 and Y positions as well. */
5034 lppos->cx -= wdiff;
5035 lppos->cy -= hdiff;
5037 if (wp.showCmd != SW_SHOWMAXIMIZED
5038 && (lppos->flags & SWP_NOMOVE) == 0)
5040 if (lppos->x != wr.left || lppos->y != wr.top)
5042 lppos->x += wdiff;
5043 lppos->y += hdiff;
5045 else
5047 lppos->flags |= SWP_NOMOVE;
5051 return 0;
5056 goto dflt;
5058 case WM_GETMINMAXINFO:
5059 /* Hack to correct bug that allows Emacs frames to be resized
5060 below the Minimum Tracking Size. */
5061 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
5062 /* Hack to allow resizing the Emacs frame above the screen size.
5063 Note that Windows 9x limits coordinates to 16-bits. */
5064 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
5065 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
5066 return 0;
5068 case WM_EMACS_CREATESCROLLBAR:
5069 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
5070 (struct scroll_bar *) lParam);
5072 case WM_EMACS_SHOWWINDOW:
5073 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
5075 case WM_EMACS_SETFOREGROUND:
5077 HWND foreground_window;
5078 DWORD foreground_thread, retval;
5080 /* On NT 5.0, and apparently Windows 98, it is necessary to
5081 attach to the thread that currently has focus in order to
5082 pull the focus away from it. */
5083 foreground_window = GetForegroundWindow ();
5084 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
5085 if (!foreground_window
5086 || foreground_thread == GetCurrentThreadId ()
5087 || !AttachThreadInput (GetCurrentThreadId (),
5088 foreground_thread, TRUE))
5089 foreground_thread = 0;
5091 retval = SetForegroundWindow ((HWND) wParam);
5093 /* Detach from the previous foreground thread. */
5094 if (foreground_thread)
5095 AttachThreadInput (GetCurrentThreadId (),
5096 foreground_thread, FALSE);
5098 return retval;
5101 case WM_EMACS_SETWINDOWPOS:
5103 WINDOWPOS * pos = (WINDOWPOS *) wParam;
5104 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5105 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
5108 case WM_EMACS_DESTROYWINDOW:
5109 DragAcceptFiles ((HWND) wParam, FALSE);
5110 return DestroyWindow ((HWND) wParam);
5112 case WM_EMACS_HIDE_CARET:
5113 return HideCaret (hwnd);
5115 case WM_EMACS_SHOW_CARET:
5116 return ShowCaret (hwnd);
5118 case WM_EMACS_DESTROY_CARET:
5119 w32_system_caret_hwnd = NULL;
5120 w32_visible_system_caret_hwnd = NULL;
5121 return DestroyCaret ();
5123 case WM_EMACS_TRACK_CARET:
5124 /* If there is currently no system caret, create one. */
5125 if (w32_system_caret_hwnd == NULL)
5127 /* Use the default caret width, and avoid changing it
5128 unneccesarily, as it confuses screen reader software. */
5129 w32_system_caret_hwnd = hwnd;
5130 CreateCaret (hwnd, NULL, 0,
5131 w32_system_caret_height);
5134 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
5135 return 0;
5136 /* Ensure visible caret gets turned on when requested. */
5137 else if (w32_use_visible_system_caret
5138 && w32_visible_system_caret_hwnd != hwnd)
5140 w32_visible_system_caret_hwnd = hwnd;
5141 return ShowCaret (hwnd);
5143 /* Ensure visible caret gets turned off when requested. */
5144 else if (!w32_use_visible_system_caret
5145 && w32_visible_system_caret_hwnd)
5147 w32_visible_system_caret_hwnd = NULL;
5148 return HideCaret (hwnd);
5150 else
5151 return 1;
5153 case WM_EMACS_TRACKPOPUPMENU:
5155 UINT flags;
5156 POINT *pos;
5157 int retval;
5158 pos = (POINT *)lParam;
5159 flags = TPM_CENTERALIGN;
5160 if (button_state & LMOUSE)
5161 flags |= TPM_LEFTBUTTON;
5162 else if (button_state & RMOUSE)
5163 flags |= TPM_RIGHTBUTTON;
5165 /* Remember we did a SetCapture on the initial mouse down event,
5166 so for safety, we make sure the capture is cancelled now. */
5167 ReleaseCapture ();
5168 button_state = 0;
5170 /* Use menubar_active to indicate that WM_INITMENU is from
5171 TrackPopupMenu below, and should be ignored. */
5172 f = x_window_to_frame (dpyinfo, hwnd);
5173 if (f)
5174 f->output_data.w32->menubar_active = 1;
5176 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
5177 0, hwnd, NULL))
5179 MSG amsg;
5180 /* Eat any mouse messages during popupmenu */
5181 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
5182 PM_REMOVE));
5183 /* Get the menu selection, if any */
5184 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
5186 retval = LOWORD (amsg.wParam);
5188 else
5190 retval = 0;
5193 else
5195 retval = -1;
5198 return retval;
5201 default:
5202 /* Check for messages registered at runtime. */
5203 if (msg == msh_mousewheel)
5205 wmsg.dwModifiers = w32_get_modifiers ();
5206 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5207 return 0;
5210 dflt:
5211 return DefWindowProc (hwnd, msg, wParam, lParam);
5215 /* The most common default return code for handled messages is 0. */
5216 return 0;
5219 void
5220 my_create_window (f)
5221 struct frame * f;
5223 MSG msg;
5225 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
5226 abort ();
5227 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5231 /* Create a tooltip window. Unlike my_create_window, we do not do this
5232 indirectly via the Window thread, as we do not need to process Window
5233 messages for the tooltip. Creating tooltips indirectly also creates
5234 deadlocks when tooltips are created for menu items. */
5235 void
5236 my_create_tip_window (f)
5237 struct frame *f;
5239 RECT rect;
5241 rect.left = rect.top = 0;
5242 rect.right = PIXEL_WIDTH (f);
5243 rect.bottom = PIXEL_HEIGHT (f);
5245 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
5246 FRAME_EXTERNAL_MENU_BAR (f));
5248 tip_window = FRAME_W32_WINDOW (f)
5249 = CreateWindow (EMACS_CLASS,
5250 f->namebuf,
5251 f->output_data.w32->dwStyle,
5252 f->output_data.w32->left_pos,
5253 f->output_data.w32->top_pos,
5254 rect.right - rect.left,
5255 rect.bottom - rect.top,
5256 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5257 NULL,
5258 hinst,
5259 NULL);
5261 if (tip_window)
5263 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
5264 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
5265 SetWindowLong (tip_window, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
5266 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5268 /* Tip frames have no scrollbars. */
5269 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
5271 /* Do this to discard the default setting specified by our parent. */
5272 ShowWindow (tip_window, SW_HIDE);
5277 /* Create and set up the w32 window for frame F. */
5279 static void
5280 w32_window (f, window_prompting, minibuffer_only)
5281 struct frame *f;
5282 long window_prompting;
5283 int minibuffer_only;
5285 BLOCK_INPUT;
5287 /* Use the resource name as the top-level window name
5288 for looking up resources. Make a non-Lisp copy
5289 for the window manager, so GC relocation won't bother it.
5291 Elsewhere we specify the window name for the window manager. */
5294 char *str = (char *) SDATA (Vx_resource_name);
5295 f->namebuf = (char *) xmalloc (strlen (str) + 1);
5296 strcpy (f->namebuf, str);
5299 my_create_window (f);
5301 validate_x_resource_name ();
5303 /* x_set_name normally ignores requests to set the name if the
5304 requested name is the same as the current name. This is the one
5305 place where that assumption isn't correct; f->name is set, but
5306 the server hasn't been told. */
5308 Lisp_Object name;
5309 int explicit = f->explicit_name;
5311 f->explicit_name = 0;
5312 name = f->name;
5313 f->name = Qnil;
5314 x_set_name (f, name, explicit);
5317 UNBLOCK_INPUT;
5319 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5320 initialize_frame_menubar (f);
5322 if (FRAME_W32_WINDOW (f) == 0)
5323 error ("Unable to create window");
5326 /* Handle the icon stuff for this window. Perhaps later we might
5327 want an x_set_icon_position which can be called interactively as
5328 well. */
5330 static void
5331 x_icon (f, parms)
5332 struct frame *f;
5333 Lisp_Object parms;
5335 Lisp_Object icon_x, icon_y;
5337 /* Set the position of the icon. Note that Windows 95 groups all
5338 icons in the tray. */
5339 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5340 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5341 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5343 CHECK_NUMBER (icon_x);
5344 CHECK_NUMBER (icon_y);
5346 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5347 error ("Both left and top icon corners of icon must be specified");
5349 BLOCK_INPUT;
5351 if (! EQ (icon_x, Qunbound))
5352 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5354 #if 0 /* TODO */
5355 /* Start up iconic or window? */
5356 x_wm_set_window_state
5357 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5358 ? IconicState
5359 : NormalState));
5361 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
5362 ? f->icon_name
5363 : f->name)));
5364 #endif
5366 UNBLOCK_INPUT;
5370 static void
5371 x_make_gc (f)
5372 struct frame *f;
5374 XGCValues gc_values;
5376 BLOCK_INPUT;
5378 /* Create the GC's of this frame.
5379 Note that many default values are used. */
5381 /* Normal video */
5382 gc_values.font = f->output_data.w32->font;
5384 /* Cursor has cursor-color background, background-color foreground. */
5385 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5386 gc_values.background = f->output_data.w32->cursor_pixel;
5387 f->output_data.w32->cursor_gc
5388 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5389 (GCFont | GCForeground | GCBackground),
5390 &gc_values);
5392 /* Reliefs. */
5393 f->output_data.w32->white_relief.gc = 0;
5394 f->output_data.w32->black_relief.gc = 0;
5396 UNBLOCK_INPUT;
5400 /* Handler for signals raised during x_create_frame and
5401 x_create_top_frame. FRAME is the frame which is partially
5402 constructed. */
5404 static Lisp_Object
5405 unwind_create_frame (frame)
5406 Lisp_Object frame;
5408 struct frame *f = XFRAME (frame);
5410 /* If frame is ``official'', nothing to do. */
5411 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
5413 #ifdef GLYPH_DEBUG
5414 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5415 #endif
5417 x_free_frame_resources (f);
5419 /* Check that reference counts are indeed correct. */
5420 xassert (dpyinfo->reference_count == dpyinfo_refcount);
5421 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
5423 return Qt;
5426 return Qnil;
5430 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5431 1, 1, 0,
5432 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5433 Returns an Emacs frame object.
5434 ALIST is an alist of frame parameters.
5435 If the parameters specify that the frame should not have a minibuffer,
5436 and do not specify a specific minibuffer window to use,
5437 then `default-minibuffer-frame' must be a frame whose minibuffer can
5438 be shared by the new frame.
5440 This function is an internal primitive--use `make-frame' instead. */)
5441 (parms)
5442 Lisp_Object parms;
5444 struct frame *f;
5445 Lisp_Object frame, tem;
5446 Lisp_Object name;
5447 int minibuffer_only = 0;
5448 long window_prompting = 0;
5449 int width, height;
5450 int count = SPECPDL_INDEX ();
5451 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5452 Lisp_Object display;
5453 struct w32_display_info *dpyinfo = NULL;
5454 Lisp_Object parent;
5455 struct kboard *kb;
5457 check_w32 ();
5459 /* Use this general default value to start with
5460 until we know if this frame has a specified name. */
5461 Vx_resource_name = Vinvocation_name;
5463 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5464 if (EQ (display, Qunbound))
5465 display = Qnil;
5466 dpyinfo = check_x_display_info (display);
5467 #ifdef MULTI_KBOARD
5468 kb = dpyinfo->kboard;
5469 #else
5470 kb = &the_only_kboard;
5471 #endif
5473 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5474 if (!STRINGP (name)
5475 && ! EQ (name, Qunbound)
5476 && ! NILP (name))
5477 error ("Invalid frame name--not a string or nil");
5479 if (STRINGP (name))
5480 Vx_resource_name = name;
5482 /* See if parent window is specified. */
5483 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5484 if (EQ (parent, Qunbound))
5485 parent = Qnil;
5486 if (! NILP (parent))
5487 CHECK_NUMBER (parent);
5489 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5490 /* No need to protect DISPLAY because that's not used after passing
5491 it to make_frame_without_minibuffer. */
5492 frame = Qnil;
5493 GCPRO4 (parms, parent, name, frame);
5494 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5495 RES_TYPE_SYMBOL);
5496 if (EQ (tem, Qnone) || NILP (tem))
5497 f = make_frame_without_minibuffer (Qnil, kb, display);
5498 else if (EQ (tem, Qonly))
5500 f = make_minibuffer_frame ();
5501 minibuffer_only = 1;
5503 else if (WINDOWP (tem))
5504 f = make_frame_without_minibuffer (tem, kb, display);
5505 else
5506 f = make_frame (1);
5508 XSETFRAME (frame, f);
5510 /* Note that Windows does support scroll bars. */
5511 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5512 /* By default, make scrollbars the system standard width. */
5513 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5515 f->output_method = output_w32;
5516 f->output_data.w32 =
5517 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5518 bzero (f->output_data.w32, sizeof (struct w32_output));
5519 FRAME_FONTSET (f) = -1;
5520 record_unwind_protect (unwind_create_frame, frame);
5522 f->icon_name
5523 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5524 if (! STRINGP (f->icon_name))
5525 f->icon_name = Qnil;
5527 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5528 #ifdef MULTI_KBOARD
5529 FRAME_KBOARD (f) = kb;
5530 #endif
5532 /* Specify the parent under which to make this window. */
5534 if (!NILP (parent))
5536 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5537 f->output_data.w32->explicit_parent = 1;
5539 else
5541 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5542 f->output_data.w32->explicit_parent = 0;
5545 /* Set the name; the functions to which we pass f expect the name to
5546 be set. */
5547 if (EQ (name, Qunbound) || NILP (name))
5549 f->name = build_string (dpyinfo->w32_id_name);
5550 f->explicit_name = 0;
5552 else
5554 f->name = name;
5555 f->explicit_name = 1;
5556 /* use the frame's title when getting resources for this frame. */
5557 specbind (Qx_resource_name, name);
5560 /* Extract the window parameters from the supplied values
5561 that are needed to determine window geometry. */
5563 Lisp_Object font;
5565 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5567 BLOCK_INPUT;
5568 /* First, try whatever font the caller has specified. */
5569 if (STRINGP (font))
5571 tem = Fquery_fontset (font, Qnil);
5572 if (STRINGP (tem))
5573 font = x_new_fontset (f, SDATA (tem));
5574 else
5575 font = x_new_font (f, SDATA (font));
5577 /* Try out a font which we hope has bold and italic variations. */
5578 if (!STRINGP (font))
5579 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5580 if (! STRINGP (font))
5581 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5582 /* If those didn't work, look for something which will at least work. */
5583 if (! STRINGP (font))
5584 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5585 UNBLOCK_INPUT;
5586 if (! STRINGP (font))
5587 font = build_string ("Fixedsys");
5589 x_default_parameter (f, parms, Qfont, font,
5590 "font", "Font", RES_TYPE_STRING);
5593 x_default_parameter (f, parms, Qborder_width, make_number (2),
5594 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5595 /* This defaults to 2 in order to match xterm. We recognize either
5596 internalBorderWidth or internalBorder (which is what xterm calls
5597 it). */
5598 if (NILP (Fassq (Qinternal_border_width, parms)))
5600 Lisp_Object value;
5602 value = w32_get_arg (parms, Qinternal_border_width,
5603 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5604 if (! EQ (value, Qunbound))
5605 parms = Fcons (Fcons (Qinternal_border_width, value),
5606 parms);
5608 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5609 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5610 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5611 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5612 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5614 /* Also do the stuff which must be set before the window exists. */
5615 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5616 "foreground", "Foreground", RES_TYPE_STRING);
5617 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5618 "background", "Background", RES_TYPE_STRING);
5619 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5620 "pointerColor", "Foreground", RES_TYPE_STRING);
5621 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5622 "cursorColor", "Foreground", RES_TYPE_STRING);
5623 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5624 "borderColor", "BorderColor", RES_TYPE_STRING);
5625 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5626 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5627 x_default_parameter (f, parms, Qline_spacing, Qnil,
5628 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5629 x_default_parameter (f, parms, Qleft_fringe, Qnil,
5630 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5631 x_default_parameter (f, parms, Qright_fringe, Qnil,
5632 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5635 /* Init faces before x_default_parameter is called for scroll-bar
5636 parameters because that function calls x_set_scroll_bar_width,
5637 which calls change_frame_size, which calls Fset_window_buffer,
5638 which runs hooks, which call Fvertical_motion. At the end, we
5639 end up in init_iterator with a null face cache, which should not
5640 happen. */
5641 init_frame_faces (f);
5643 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5644 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5645 x_default_parameter (f, parms, Qtool_bar_lines, make_number (1),
5646 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5648 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5649 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5650 x_default_parameter (f, parms, Qtitle, Qnil,
5651 "title", "Title", RES_TYPE_STRING);
5652 x_default_parameter (f, parms, Qfullscreen, Qnil,
5653 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5655 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5656 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5658 /* Add the tool-bar height to the initial frame height so that the
5659 user gets a text display area of the size he specified with -g or
5660 via .Xdefaults. Later changes of the tool-bar height don't
5661 change the frame size. This is done so that users can create
5662 tall Emacs frames without having to guess how tall the tool-bar
5663 will get. */
5664 if (FRAME_TOOL_BAR_LINES (f))
5666 int margin, relief, bar_height;
5668 relief = (tool_bar_button_relief >= 0
5669 ? tool_bar_button_relief
5670 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
5672 if (INTEGERP (Vtool_bar_button_margin)
5673 && XINT (Vtool_bar_button_margin) > 0)
5674 margin = XFASTINT (Vtool_bar_button_margin);
5675 else if (CONSP (Vtool_bar_button_margin)
5676 && INTEGERP (XCDR (Vtool_bar_button_margin))
5677 && XINT (XCDR (Vtool_bar_button_margin)) > 0)
5678 margin = XFASTINT (XCDR (Vtool_bar_button_margin));
5679 else
5680 margin = 0;
5682 bar_height = DEFAULT_TOOL_BAR_IMAGE_HEIGHT + 2 * margin + 2 * relief;
5683 f->height += (bar_height + CANON_Y_UNIT (f) - 1) / CANON_Y_UNIT (f);
5686 window_prompting = x_figure_window_size (f, parms);
5688 if (window_prompting & XNegative)
5690 if (window_prompting & YNegative)
5691 f->output_data.w32->win_gravity = SouthEastGravity;
5692 else
5693 f->output_data.w32->win_gravity = NorthEastGravity;
5695 else
5697 if (window_prompting & YNegative)
5698 f->output_data.w32->win_gravity = SouthWestGravity;
5699 else
5700 f->output_data.w32->win_gravity = NorthWestGravity;
5703 f->output_data.w32->size_hint_flags = window_prompting;
5705 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5706 f->no_split = minibuffer_only || EQ (tem, Qt);
5708 w32_window (f, window_prompting, minibuffer_only);
5709 x_icon (f, parms);
5711 x_make_gc (f);
5713 /* Now consider the frame official. */
5714 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5715 Vframe_list = Fcons (frame, Vframe_list);
5717 /* We need to do this after creating the window, so that the
5718 icon-creation functions can say whose icon they're describing. */
5719 x_default_parameter (f, parms, Qicon_type, Qnil,
5720 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5722 x_default_parameter (f, parms, Qauto_raise, Qnil,
5723 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5724 x_default_parameter (f, parms, Qauto_lower, Qnil,
5725 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5726 x_default_parameter (f, parms, Qcursor_type, Qbox,
5727 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5728 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5729 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5731 /* Dimensions, especially f->height, must be done via change_frame_size.
5732 Change will not be effected unless different from the current
5733 f->height. */
5734 width = f->width;
5735 height = f->height;
5737 f->height = 0;
5738 SET_FRAME_WIDTH (f, 0);
5739 change_frame_size (f, height, width, 1, 0, 0);
5741 /* Tell the server what size and position, etc, we want, and how
5742 badly we want them. This should be done after we have the menu
5743 bar so that its size can be taken into account. */
5744 BLOCK_INPUT;
5745 x_wm_set_size_hint (f, window_prompting, 0);
5746 UNBLOCK_INPUT;
5748 /* Avoid a bug that causes the new frame to never become visible if
5749 an echo area message is displayed during the following call1. */
5750 specbind(Qredisplay_dont_pause, Qt);
5752 /* Set up faces after all frame parameters are known. This call
5753 also merges in face attributes specified for new frames. If we
5754 don't do this, the `menu' face for instance won't have the right
5755 colors, and the menu bar won't appear in the specified colors for
5756 new frames. */
5757 call1 (Qface_set_after_frame_default, frame);
5759 /* Make the window appear on the frame and enable display, unless
5760 the caller says not to. However, with explicit parent, Emacs
5761 cannot control visibility, so don't try. */
5762 if (! f->output_data.w32->explicit_parent)
5764 Lisp_Object visibility;
5766 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5767 if (EQ (visibility, Qunbound))
5768 visibility = Qt;
5770 if (EQ (visibility, Qicon))
5771 x_iconify_frame (f);
5772 else if (! NILP (visibility))
5773 x_make_frame_visible (f);
5774 else
5775 /* Must have been Qnil. */
5778 UNGCPRO;
5780 /* Make sure windows on this frame appear in calls to next-window
5781 and similar functions. */
5782 Vwindow_list = Qnil;
5784 return unbind_to (count, frame);
5787 /* FRAME is used only to get a handle on the X display. We don't pass the
5788 display info directly because we're called from frame.c, which doesn't
5789 know about that structure. */
5790 Lisp_Object
5791 x_get_focus_frame (frame)
5792 struct frame *frame;
5794 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5795 Lisp_Object xfocus;
5796 if (! dpyinfo->w32_focus_frame)
5797 return Qnil;
5799 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5800 return xfocus;
5803 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5804 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
5805 (frame)
5806 Lisp_Object frame;
5808 x_focus_on_frame (check_x_frame (frame));
5809 return Qnil;
5813 /* Return the charset portion of a font name. */
5814 char * xlfd_charset_of_font (char * fontname)
5816 char *charset, *encoding;
5818 encoding = strrchr(fontname, '-');
5819 if (!encoding || encoding == fontname)
5820 return NULL;
5822 for (charset = encoding - 1; charset >= fontname; charset--)
5823 if (*charset == '-')
5824 break;
5826 if (charset == fontname || strcmp(charset, "-*-*") == 0)
5827 return NULL;
5829 return charset + 1;
5832 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5833 int size, char* filename);
5834 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
5835 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
5836 char * charset);
5837 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
5839 static struct font_info *
5840 w32_load_system_font (f,fontname,size)
5841 struct frame *f;
5842 char * fontname;
5843 int size;
5845 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5846 Lisp_Object font_names;
5848 /* Get a list of all the fonts that match this name. Once we
5849 have a list of matching fonts, we compare them against the fonts
5850 we already have loaded by comparing names. */
5851 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5853 if (!NILP (font_names))
5855 Lisp_Object tail;
5856 int i;
5858 /* First check if any are already loaded, as that is cheaper
5859 than loading another one. */
5860 for (i = 0; i < dpyinfo->n_fonts; i++)
5861 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5862 if (dpyinfo->font_table[i].name
5863 && (!strcmp (dpyinfo->font_table[i].name,
5864 SDATA (XCAR (tail)))
5865 || !strcmp (dpyinfo->font_table[i].full_name,
5866 SDATA (XCAR (tail)))))
5867 return (dpyinfo->font_table + i);
5869 fontname = (char *) SDATA (XCAR (font_names));
5871 else if (w32_strict_fontnames)
5873 /* If EnumFontFamiliesEx was available, we got a full list of
5874 fonts back so stop now to avoid the possibility of loading a
5875 random font. If we had to fall back to EnumFontFamilies, the
5876 list is incomplete, so continue whether the font we want was
5877 listed or not. */
5878 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5879 FARPROC enum_font_families_ex
5880 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5881 if (enum_font_families_ex)
5882 return NULL;
5885 /* Load the font and add it to the table. */
5887 char *full_name, *encoding, *charset;
5888 XFontStruct *font;
5889 struct font_info *fontp;
5890 LOGFONT lf;
5891 BOOL ok;
5892 int codepage;
5893 int i;
5895 if (!fontname || !x_to_w32_font (fontname, &lf))
5896 return (NULL);
5898 if (!*lf.lfFaceName)
5899 /* If no name was specified for the font, we get a random font
5900 from CreateFontIndirect - this is not particularly
5901 desirable, especially since CreateFontIndirect does not
5902 fill out the missing name in lf, so we never know what we
5903 ended up with. */
5904 return NULL;
5906 /* Specify anti-aliasing to prevent Cleartype fonts being used,
5907 since those fonts leave garbage behind. */
5908 lf.lfQuality = ANTIALIASED_QUALITY;
5910 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5911 bzero (font, sizeof (*font));
5913 /* Set bdf to NULL to indicate that this is a Windows font. */
5914 font->bdf = NULL;
5916 BLOCK_INPUT;
5918 font->hfont = CreateFontIndirect (&lf);
5920 if (font->hfont == NULL)
5922 ok = FALSE;
5924 else
5926 HDC hdc;
5927 HANDLE oldobj;
5929 codepage = w32_codepage_for_font (fontname);
5931 hdc = GetDC (dpyinfo->root_window);
5932 oldobj = SelectObject (hdc, font->hfont);
5934 ok = GetTextMetrics (hdc, &font->tm);
5935 if (codepage == CP_UNICODE)
5936 font->double_byte_p = 1;
5937 else
5939 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
5940 don't report themselves as double byte fonts, when
5941 patently they are. So instead of trusting
5942 GetFontLanguageInfo, we check the properties of the
5943 codepage directly, since that is ultimately what we are
5944 working from anyway. */
5945 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
5946 CPINFO cpi = {0};
5947 GetCPInfo (codepage, &cpi);
5948 font->double_byte_p = cpi.MaxCharSize > 1;
5951 SelectObject (hdc, oldobj);
5952 ReleaseDC (dpyinfo->root_window, hdc);
5953 /* Fill out details in lf according to the font that was
5954 actually loaded. */
5955 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5956 lf.lfWidth = font->tm.tmAveCharWidth;
5957 lf.lfWeight = font->tm.tmWeight;
5958 lf.lfItalic = font->tm.tmItalic;
5959 lf.lfCharSet = font->tm.tmCharSet;
5960 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5961 ? VARIABLE_PITCH : FIXED_PITCH);
5962 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5963 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5965 w32_cache_char_metrics (font);
5968 UNBLOCK_INPUT;
5970 if (!ok)
5972 w32_unload_font (dpyinfo, font);
5973 return (NULL);
5976 /* Find a free slot in the font table. */
5977 for (i = 0; i < dpyinfo->n_fonts; ++i)
5978 if (dpyinfo->font_table[i].name == NULL)
5979 break;
5981 /* If no free slot found, maybe enlarge the font table. */
5982 if (i == dpyinfo->n_fonts
5983 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5985 int sz;
5986 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5987 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5988 dpyinfo->font_table
5989 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5992 fontp = dpyinfo->font_table + i;
5993 if (i == dpyinfo->n_fonts)
5994 ++dpyinfo->n_fonts;
5996 /* Now fill in the slots of *FONTP. */
5997 BLOCK_INPUT;
5998 fontp->font = font;
5999 fontp->font_idx = i;
6000 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
6001 bcopy (fontname, fontp->name, strlen (fontname) + 1);
6003 charset = xlfd_charset_of_font (fontname);
6005 /* Cache the W32 codepage for a font. This makes w32_encode_char
6006 (called for every glyph during redisplay) much faster. */
6007 fontp->codepage = codepage;
6009 /* Work out the font's full name. */
6010 full_name = (char *)xmalloc (100);
6011 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
6012 fontp->full_name = full_name;
6013 else
6015 /* If all else fails - just use the name we used to load it. */
6016 xfree (full_name);
6017 fontp->full_name = fontp->name;
6020 fontp->size = FONT_WIDTH (font);
6021 fontp->height = FONT_HEIGHT (font);
6023 /* The slot `encoding' specifies how to map a character
6024 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
6025 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
6026 (0:0x20..0x7F, 1:0xA0..0xFF,
6027 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
6028 2:0xA020..0xFF7F). For the moment, we don't know which charset
6029 uses this font. So, we set information in fontp->encoding[1]
6030 which is never used by any charset. If mapping can't be
6031 decided, set FONT_ENCODING_NOT_DECIDED. */
6033 /* SJIS fonts need to be set to type 4, all others seem to work as
6034 type FONT_ENCODING_NOT_DECIDED. */
6035 encoding = strrchr (fontp->name, '-');
6036 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
6037 fontp->encoding[1] = 4;
6038 else
6039 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
6041 /* The following three values are set to 0 under W32, which is
6042 what they get set to if XGetFontProperty fails under X. */
6043 fontp->baseline_offset = 0;
6044 fontp->relative_compose = 0;
6045 fontp->default_ascent = 0;
6047 /* Set global flag fonts_changed_p to non-zero if the font loaded
6048 has a character with a smaller width than any other character
6049 before, or if the font loaded has a smaller height than any
6050 other font loaded before. If this happens, it will make a
6051 glyph matrix reallocation necessary. */
6052 fonts_changed_p |= x_compute_min_glyph_bounds (f);
6053 UNBLOCK_INPUT;
6054 return fontp;
6058 /* Load font named FONTNAME of size SIZE for frame F, and return a
6059 pointer to the structure font_info while allocating it dynamically.
6060 If loading fails, return NULL. */
6061 struct font_info *
6062 w32_load_font (f,fontname,size)
6063 struct frame *f;
6064 char * fontname;
6065 int size;
6067 Lisp_Object bdf_fonts;
6068 struct font_info *retval = NULL;
6070 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
6072 while (!retval && CONSP (bdf_fonts))
6074 char *bdf_name, *bdf_file;
6075 Lisp_Object bdf_pair;
6077 bdf_name = SDATA (XCAR (bdf_fonts));
6078 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
6079 bdf_file = SDATA (XCDR (bdf_pair));
6081 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
6083 bdf_fonts = XCDR (bdf_fonts);
6086 if (retval)
6087 return retval;
6089 return w32_load_system_font(f, fontname, size);
6093 void
6094 w32_unload_font (dpyinfo, font)
6095 struct w32_display_info *dpyinfo;
6096 XFontStruct * font;
6098 if (font)
6100 if (font->per_char) xfree (font->per_char);
6101 if (font->bdf) w32_free_bdf_font (font->bdf);
6103 if (font->hfont) DeleteObject(font->hfont);
6104 xfree (font);
6108 /* The font conversion stuff between x and w32 */
6110 /* X font string is as follows (from faces.el)
6111 * (let ((- "[-?]")
6112 * (foundry "[^-]+")
6113 * (family "[^-]+")
6114 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
6115 * (weight\? "\\([^-]*\\)") ; 1
6116 * (slant "\\([ior]\\)") ; 2
6117 * (slant\? "\\([^-]?\\)") ; 2
6118 * (swidth "\\([^-]*\\)") ; 3
6119 * (adstyle "[^-]*") ; 4
6120 * (pixelsize "[0-9]+")
6121 * (pointsize "[0-9][0-9]+")
6122 * (resx "[0-9][0-9]+")
6123 * (resy "[0-9][0-9]+")
6124 * (spacing "[cmp?*]")
6125 * (avgwidth "[0-9]+")
6126 * (registry "[^-]+")
6127 * (encoding "[^-]+")
6131 static LONG
6132 x_to_w32_weight (lpw)
6133 char * lpw;
6135 if (!lpw) return (FW_DONTCARE);
6137 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
6138 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
6139 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
6140 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
6141 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
6142 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
6143 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
6144 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
6145 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
6146 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
6147 else
6148 return FW_DONTCARE;
6152 static char *
6153 w32_to_x_weight (fnweight)
6154 int fnweight;
6156 if (fnweight >= FW_HEAVY) return "heavy";
6157 if (fnweight >= FW_EXTRABOLD) return "extrabold";
6158 if (fnweight >= FW_BOLD) return "bold";
6159 if (fnweight >= FW_SEMIBOLD) return "demibold";
6160 if (fnweight >= FW_MEDIUM) return "medium";
6161 if (fnweight >= FW_NORMAL) return "normal";
6162 if (fnweight >= FW_LIGHT) return "light";
6163 if (fnweight >= FW_EXTRALIGHT) return "extralight";
6164 if (fnweight >= FW_THIN) return "thin";
6165 else
6166 return "*";
6169 static LONG
6170 x_to_w32_charset (lpcs)
6171 char * lpcs;
6173 Lisp_Object this_entry, w32_charset;
6174 char *charset;
6175 int len = strlen (lpcs);
6177 /* Support "*-#nnn" format for unknown charsets. */
6178 if (strncmp (lpcs, "*-#", 3) == 0)
6179 return atoi (lpcs + 3);
6181 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
6182 charset = alloca (len + 1);
6183 strcpy (charset, lpcs);
6184 lpcs = strchr (charset, '*');
6185 if (lpcs)
6186 *lpcs = 0;
6188 /* Look through w32-charset-info-alist for the character set.
6189 Format of each entry is
6190 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6192 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6194 if (NILP(this_entry))
6196 /* At startup, we want iso8859-1 fonts to come up properly. */
6197 if (stricmp(charset, "iso8859-1") == 0)
6198 return ANSI_CHARSET;
6199 else
6200 return DEFAULT_CHARSET;
6203 w32_charset = Fcar (Fcdr (this_entry));
6205 /* Translate Lisp symbol to number. */
6206 if (w32_charset == Qw32_charset_ansi)
6207 return ANSI_CHARSET;
6208 if (w32_charset == Qw32_charset_symbol)
6209 return SYMBOL_CHARSET;
6210 if (w32_charset == Qw32_charset_shiftjis)
6211 return SHIFTJIS_CHARSET;
6212 if (w32_charset == Qw32_charset_hangeul)
6213 return HANGEUL_CHARSET;
6214 if (w32_charset == Qw32_charset_chinesebig5)
6215 return CHINESEBIG5_CHARSET;
6216 if (w32_charset == Qw32_charset_gb2312)
6217 return GB2312_CHARSET;
6218 if (w32_charset == Qw32_charset_oem)
6219 return OEM_CHARSET;
6220 #ifdef JOHAB_CHARSET
6221 if (w32_charset == Qw32_charset_johab)
6222 return JOHAB_CHARSET;
6223 if (w32_charset == Qw32_charset_easteurope)
6224 return EASTEUROPE_CHARSET;
6225 if (w32_charset == Qw32_charset_turkish)
6226 return TURKISH_CHARSET;
6227 if (w32_charset == Qw32_charset_baltic)
6228 return BALTIC_CHARSET;
6229 if (w32_charset == Qw32_charset_russian)
6230 return RUSSIAN_CHARSET;
6231 if (w32_charset == Qw32_charset_arabic)
6232 return ARABIC_CHARSET;
6233 if (w32_charset == Qw32_charset_greek)
6234 return GREEK_CHARSET;
6235 if (w32_charset == Qw32_charset_hebrew)
6236 return HEBREW_CHARSET;
6237 if (w32_charset == Qw32_charset_vietnamese)
6238 return VIETNAMESE_CHARSET;
6239 if (w32_charset == Qw32_charset_thai)
6240 return THAI_CHARSET;
6241 if (w32_charset == Qw32_charset_mac)
6242 return MAC_CHARSET;
6243 #endif /* JOHAB_CHARSET */
6244 #ifdef UNICODE_CHARSET
6245 if (w32_charset == Qw32_charset_unicode)
6246 return UNICODE_CHARSET;
6247 #endif
6249 return DEFAULT_CHARSET;
6253 static char *
6254 w32_to_x_charset (fncharset)
6255 int fncharset;
6257 static char buf[32];
6258 Lisp_Object charset_type;
6260 switch (fncharset)
6262 case ANSI_CHARSET:
6263 /* Handle startup case of w32-charset-info-alist not
6264 being set up yet. */
6265 if (NILP(Vw32_charset_info_alist))
6266 return "iso8859-1";
6267 charset_type = Qw32_charset_ansi;
6268 break;
6269 case DEFAULT_CHARSET:
6270 charset_type = Qw32_charset_default;
6271 break;
6272 case SYMBOL_CHARSET:
6273 charset_type = Qw32_charset_symbol;
6274 break;
6275 case SHIFTJIS_CHARSET:
6276 charset_type = Qw32_charset_shiftjis;
6277 break;
6278 case HANGEUL_CHARSET:
6279 charset_type = Qw32_charset_hangeul;
6280 break;
6281 case GB2312_CHARSET:
6282 charset_type = Qw32_charset_gb2312;
6283 break;
6284 case CHINESEBIG5_CHARSET:
6285 charset_type = Qw32_charset_chinesebig5;
6286 break;
6287 case OEM_CHARSET:
6288 charset_type = Qw32_charset_oem;
6289 break;
6291 /* More recent versions of Windows (95 and NT4.0) define more
6292 character sets. */
6293 #ifdef EASTEUROPE_CHARSET
6294 case EASTEUROPE_CHARSET:
6295 charset_type = Qw32_charset_easteurope;
6296 break;
6297 case TURKISH_CHARSET:
6298 charset_type = Qw32_charset_turkish;
6299 break;
6300 case BALTIC_CHARSET:
6301 charset_type = Qw32_charset_baltic;
6302 break;
6303 case RUSSIAN_CHARSET:
6304 charset_type = Qw32_charset_russian;
6305 break;
6306 case ARABIC_CHARSET:
6307 charset_type = Qw32_charset_arabic;
6308 break;
6309 case GREEK_CHARSET:
6310 charset_type = Qw32_charset_greek;
6311 break;
6312 case HEBREW_CHARSET:
6313 charset_type = Qw32_charset_hebrew;
6314 break;
6315 case VIETNAMESE_CHARSET:
6316 charset_type = Qw32_charset_vietnamese;
6317 break;
6318 case THAI_CHARSET:
6319 charset_type = Qw32_charset_thai;
6320 break;
6321 case MAC_CHARSET:
6322 charset_type = Qw32_charset_mac;
6323 break;
6324 case JOHAB_CHARSET:
6325 charset_type = Qw32_charset_johab;
6326 break;
6327 #endif
6329 #ifdef UNICODE_CHARSET
6330 case UNICODE_CHARSET:
6331 charset_type = Qw32_charset_unicode;
6332 break;
6333 #endif
6334 default:
6335 /* Encode numerical value of unknown charset. */
6336 sprintf (buf, "*-#%u", fncharset);
6337 return buf;
6341 Lisp_Object rest;
6342 char * best_match = NULL;
6344 /* Look through w32-charset-info-alist for the character set.
6345 Prefer ISO codepages, and prefer lower numbers in the ISO
6346 range. Only return charsets for codepages which are installed.
6348 Format of each entry is
6349 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6351 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6353 char * x_charset;
6354 Lisp_Object w32_charset;
6355 Lisp_Object codepage;
6357 Lisp_Object this_entry = XCAR (rest);
6359 /* Skip invalid entries in alist. */
6360 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6361 || !CONSP (XCDR (this_entry))
6362 || !SYMBOLP (XCAR (XCDR (this_entry))))
6363 continue;
6365 x_charset = SDATA (XCAR (this_entry));
6366 w32_charset = XCAR (XCDR (this_entry));
6367 codepage = XCDR (XCDR (this_entry));
6369 /* Look for Same charset and a valid codepage (or non-int
6370 which means ignore). */
6371 if (w32_charset == charset_type
6372 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6373 || IsValidCodePage (XINT (codepage))))
6375 /* If we don't have a match already, then this is the
6376 best. */
6377 if (!best_match)
6378 best_match = x_charset;
6379 /* If this is an ISO codepage, and the best so far isn't,
6380 then this is better. */
6381 else if (strnicmp (best_match, "iso", 3) != 0
6382 && strnicmp (x_charset, "iso", 3) == 0)
6383 best_match = x_charset;
6384 /* If both are ISO8859 codepages, choose the one with the
6385 lowest number in the encoding field. */
6386 else if (strnicmp (best_match, "iso8859-", 8) == 0
6387 && strnicmp (x_charset, "iso8859-", 8) == 0)
6389 int best_enc = atoi (best_match + 8);
6390 int this_enc = atoi (x_charset + 8);
6391 if (this_enc > 0 && this_enc < best_enc)
6392 best_match = x_charset;
6397 /* If no match, encode the numeric value. */
6398 if (!best_match)
6400 sprintf (buf, "*-#%u", fncharset);
6401 return buf;
6404 strncpy(buf, best_match, 31);
6405 buf[31] = '\0';
6406 return buf;
6411 /* Return all the X charsets that map to a font. */
6412 static Lisp_Object
6413 w32_to_all_x_charsets (fncharset)
6414 int fncharset;
6416 static char buf[32];
6417 Lisp_Object charset_type;
6418 Lisp_Object retval = Qnil;
6420 switch (fncharset)
6422 case ANSI_CHARSET:
6423 /* Handle startup case of w32-charset-info-alist not
6424 being set up yet. */
6425 if (NILP(Vw32_charset_info_alist))
6426 return Fcons (build_string ("iso8859-1"), Qnil);
6428 charset_type = Qw32_charset_ansi;
6429 break;
6430 case DEFAULT_CHARSET:
6431 charset_type = Qw32_charset_default;
6432 break;
6433 case SYMBOL_CHARSET:
6434 charset_type = Qw32_charset_symbol;
6435 break;
6436 case SHIFTJIS_CHARSET:
6437 charset_type = Qw32_charset_shiftjis;
6438 break;
6439 case HANGEUL_CHARSET:
6440 charset_type = Qw32_charset_hangeul;
6441 break;
6442 case GB2312_CHARSET:
6443 charset_type = Qw32_charset_gb2312;
6444 break;
6445 case CHINESEBIG5_CHARSET:
6446 charset_type = Qw32_charset_chinesebig5;
6447 break;
6448 case OEM_CHARSET:
6449 charset_type = Qw32_charset_oem;
6450 break;
6452 /* More recent versions of Windows (95 and NT4.0) define more
6453 character sets. */
6454 #ifdef EASTEUROPE_CHARSET
6455 case EASTEUROPE_CHARSET:
6456 charset_type = Qw32_charset_easteurope;
6457 break;
6458 case TURKISH_CHARSET:
6459 charset_type = Qw32_charset_turkish;
6460 break;
6461 case BALTIC_CHARSET:
6462 charset_type = Qw32_charset_baltic;
6463 break;
6464 case RUSSIAN_CHARSET:
6465 charset_type = Qw32_charset_russian;
6466 break;
6467 case ARABIC_CHARSET:
6468 charset_type = Qw32_charset_arabic;
6469 break;
6470 case GREEK_CHARSET:
6471 charset_type = Qw32_charset_greek;
6472 break;
6473 case HEBREW_CHARSET:
6474 charset_type = Qw32_charset_hebrew;
6475 break;
6476 case VIETNAMESE_CHARSET:
6477 charset_type = Qw32_charset_vietnamese;
6478 break;
6479 case THAI_CHARSET:
6480 charset_type = Qw32_charset_thai;
6481 break;
6482 case MAC_CHARSET:
6483 charset_type = Qw32_charset_mac;
6484 break;
6485 case JOHAB_CHARSET:
6486 charset_type = Qw32_charset_johab;
6487 break;
6488 #endif
6490 #ifdef UNICODE_CHARSET
6491 case UNICODE_CHARSET:
6492 charset_type = Qw32_charset_unicode;
6493 break;
6494 #endif
6495 default:
6496 /* Encode numerical value of unknown charset. */
6497 sprintf (buf, "*-#%u", fncharset);
6498 return Fcons (build_string (buf), Qnil);
6502 Lisp_Object rest;
6503 /* Look through w32-charset-info-alist for the character set.
6504 Only return charsets for codepages which are installed.
6506 Format of each entry in Vw32_charset_info_alist is
6507 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6509 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6511 Lisp_Object x_charset;
6512 Lisp_Object w32_charset;
6513 Lisp_Object codepage;
6515 Lisp_Object this_entry = XCAR (rest);
6517 /* Skip invalid entries in alist. */
6518 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6519 || !CONSP (XCDR (this_entry))
6520 || !SYMBOLP (XCAR (XCDR (this_entry))))
6521 continue;
6523 x_charset = XCAR (this_entry);
6524 w32_charset = XCAR (XCDR (this_entry));
6525 codepage = XCDR (XCDR (this_entry));
6527 /* Look for Same charset and a valid codepage (or non-int
6528 which means ignore). */
6529 if (w32_charset == charset_type
6530 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6531 || IsValidCodePage (XINT (codepage))))
6533 retval = Fcons (x_charset, retval);
6537 /* If no match, encode the numeric value. */
6538 if (NILP (retval))
6540 sprintf (buf, "*-#%u", fncharset);
6541 return Fcons (build_string (buf), Qnil);
6544 return retval;
6548 /* Get the Windows codepage corresponding to the specified font. The
6549 charset info in the font name is used to look up
6550 w32-charset-to-codepage-alist. */
6551 int
6552 w32_codepage_for_font (char *fontname)
6554 Lisp_Object codepage, entry;
6555 char *charset_str, *charset, *end;
6557 if (NILP (Vw32_charset_info_alist))
6558 return CP_DEFAULT;
6560 /* Extract charset part of font string. */
6561 charset = xlfd_charset_of_font (fontname);
6563 if (!charset)
6564 return CP_UNKNOWN;
6566 charset_str = (char *) alloca (strlen (charset) + 1);
6567 strcpy (charset_str, charset);
6569 #if 0
6570 /* Remove leading "*-". */
6571 if (strncmp ("*-", charset_str, 2) == 0)
6572 charset = charset_str + 2;
6573 else
6574 #endif
6575 charset = charset_str;
6577 /* Stop match at wildcard (including preceding '-'). */
6578 if (end = strchr (charset, '*'))
6580 if (end > charset && *(end-1) == '-')
6581 end--;
6582 *end = '\0';
6585 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6586 if (NILP (entry))
6587 return CP_UNKNOWN;
6589 codepage = Fcdr (Fcdr (entry));
6591 if (NILP (codepage))
6592 return CP_8BIT;
6593 else if (XFASTINT (codepage) == XFASTINT (Qt))
6594 return CP_UNICODE;
6595 else if (INTEGERP (codepage))
6596 return XINT (codepage);
6597 else
6598 return CP_UNKNOWN;
6602 static BOOL
6603 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6604 LOGFONT * lplogfont;
6605 char * lpxstr;
6606 int len;
6607 char * specific_charset;
6609 char* fonttype;
6610 char *fontname;
6611 char height_pixels[8];
6612 char height_dpi[8];
6613 char width_pixels[8];
6614 char *fontname_dash;
6615 int display_resy = (int) one_w32_display_info.resy;
6616 int display_resx = (int) one_w32_display_info.resx;
6617 int bufsz;
6618 struct coding_system coding;
6620 if (!lpxstr) abort ();
6622 if (!lplogfont)
6623 return FALSE;
6625 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6626 fonttype = "raster";
6627 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6628 fonttype = "outline";
6629 else
6630 fonttype = "unknown";
6632 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
6633 &coding);
6634 coding.src_multibyte = 0;
6635 coding.dst_multibyte = 1;
6636 coding.mode |= CODING_MODE_LAST_BLOCK;
6637 /* We explicitely disable composition handling because selection
6638 data should not contain any composition sequence. */
6639 coding.composing = COMPOSITION_DISABLED;
6640 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6642 fontname = alloca(sizeof(*fontname) * bufsz);
6643 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6644 strlen(lplogfont->lfFaceName), bufsz - 1);
6645 *(fontname + coding.produced) = '\0';
6647 /* Replace dashes with underscores so the dashes are not
6648 misinterpreted. */
6649 fontname_dash = fontname;
6650 while (fontname_dash = strchr (fontname_dash, '-'))
6651 *fontname_dash = '_';
6653 if (lplogfont->lfHeight)
6655 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6656 sprintf (height_dpi, "%u",
6657 abs (lplogfont->lfHeight) * 720 / display_resy);
6659 else
6661 strcpy (height_pixels, "*");
6662 strcpy (height_dpi, "*");
6664 if (lplogfont->lfWidth)
6665 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6666 else
6667 strcpy (width_pixels, "*");
6669 _snprintf (lpxstr, len - 1,
6670 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6671 fonttype, /* foundry */
6672 fontname, /* family */
6673 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6674 lplogfont->lfItalic?'i':'r', /* slant */
6675 /* setwidth name */
6676 /* add style name */
6677 height_pixels, /* pixel size */
6678 height_dpi, /* point size */
6679 display_resx, /* resx */
6680 display_resy, /* resy */
6681 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6682 ? 'p' : 'c', /* spacing */
6683 width_pixels, /* avg width */
6684 specific_charset ? specific_charset
6685 : w32_to_x_charset (lplogfont->lfCharSet)
6686 /* charset registry and encoding */
6689 lpxstr[len - 1] = 0; /* just to be sure */
6690 return (TRUE);
6693 static BOOL
6694 x_to_w32_font (lpxstr, lplogfont)
6695 char * lpxstr;
6696 LOGFONT * lplogfont;
6698 struct coding_system coding;
6700 if (!lplogfont) return (FALSE);
6702 memset (lplogfont, 0, sizeof (*lplogfont));
6704 /* Set default value for each field. */
6705 #if 1
6706 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6707 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6708 lplogfont->lfQuality = DEFAULT_QUALITY;
6709 #else
6710 /* go for maximum quality */
6711 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6712 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6713 lplogfont->lfQuality = PROOF_QUALITY;
6714 #endif
6716 lplogfont->lfCharSet = DEFAULT_CHARSET;
6717 lplogfont->lfWeight = FW_DONTCARE;
6718 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6720 if (!lpxstr)
6721 return FALSE;
6723 /* Provide a simple escape mechanism for specifying Windows font names
6724 * directly -- if font spec does not beginning with '-', assume this
6725 * format:
6726 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6729 if (*lpxstr == '-')
6731 int fields, tem;
6732 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6733 width[10], resy[10], remainder[50];
6734 char * encoding;
6735 int dpi = (int) one_w32_display_info.resy;
6737 fields = sscanf (lpxstr,
6738 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
6739 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6740 if (fields == EOF)
6741 return (FALSE);
6743 /* In the general case when wildcards cover more than one field,
6744 we don't know which field is which, so don't fill any in.
6745 However, we need to cope with this particular form, which is
6746 generated by font_list_1 (invoked by try_font_list):
6747 "-raster-6x10-*-gb2312*-*"
6748 and make sure to correctly parse the charset field. */
6749 if (fields == 3)
6751 fields = sscanf (lpxstr,
6752 "-%*[^-]-%49[^-]-*-%49s",
6753 name, remainder);
6755 else if (fields < 9)
6757 fields = 0;
6758 remainder[0] = 0;
6761 if (fields > 0 && name[0] != '*')
6763 int bufsize;
6764 unsigned char *buf;
6766 setup_coding_system
6767 (Fcheck_coding_system (Vlocale_coding_system), &coding);
6768 coding.src_multibyte = 1;
6769 coding.dst_multibyte = 1;
6770 bufsize = encoding_buffer_size (&coding, strlen (name));
6771 buf = (unsigned char *) alloca (bufsize);
6772 coding.mode |= CODING_MODE_LAST_BLOCK;
6773 encode_coding (&coding, name, buf, strlen (name), bufsize);
6774 if (coding.produced >= LF_FACESIZE)
6775 coding.produced = LF_FACESIZE - 1;
6776 buf[coding.produced] = 0;
6777 strcpy (lplogfont->lfFaceName, buf);
6779 else
6781 lplogfont->lfFaceName[0] = '\0';
6784 fields--;
6786 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6788 fields--;
6790 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6792 fields--;
6794 if (fields > 0 && pixels[0] != '*')
6795 lplogfont->lfHeight = atoi (pixels);
6797 fields--;
6798 fields--;
6799 if (fields > 0 && resy[0] != '*')
6801 tem = atoi (resy);
6802 if (tem > 0) dpi = tem;
6805 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6806 lplogfont->lfHeight = atoi (height) * dpi / 720;
6808 if (fields > 0)
6809 lplogfont->lfPitchAndFamily =
6810 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6812 fields--;
6814 if (fields > 0 && width[0] != '*')
6815 lplogfont->lfWidth = atoi (width) / 10;
6817 fields--;
6819 /* Strip the trailing '-' if present. (it shouldn't be, as it
6820 fails the test against xlfd-tight-regexp in fontset.el). */
6822 int len = strlen (remainder);
6823 if (len > 0 && remainder[len-1] == '-')
6824 remainder[len-1] = 0;
6826 encoding = remainder;
6827 #if 0
6828 if (strncmp (encoding, "*-", 2) == 0)
6829 encoding += 2;
6830 #endif
6831 lplogfont->lfCharSet = x_to_w32_charset (encoding);
6833 else
6835 int fields;
6836 char name[100], height[10], width[10], weight[20];
6838 fields = sscanf (lpxstr,
6839 "%99[^:]:%9[^:]:%9[^:]:%19s",
6840 name, height, width, weight);
6842 if (fields == EOF) return (FALSE);
6844 if (fields > 0)
6846 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6847 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6849 else
6851 lplogfont->lfFaceName[0] = 0;
6854 fields--;
6856 if (fields > 0)
6857 lplogfont->lfHeight = atoi (height);
6859 fields--;
6861 if (fields > 0)
6862 lplogfont->lfWidth = atoi (width);
6864 fields--;
6866 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6869 /* This makes TrueType fonts work better. */
6870 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6872 return (TRUE);
6875 /* Strip the pixel height and point height from the given xlfd, and
6876 return the pixel height. If no pixel height is specified, calculate
6877 one from the point height, or if that isn't defined either, return
6878 0 (which usually signifies a scalable font).
6880 static int
6881 xlfd_strip_height (char *fontname)
6883 int pixel_height, field_number;
6884 char *read_from, *write_to;
6886 xassert (fontname);
6888 pixel_height = field_number = 0;
6889 write_to = NULL;
6891 /* Look for height fields. */
6892 for (read_from = fontname; *read_from; read_from++)
6894 if (*read_from == '-')
6896 field_number++;
6897 if (field_number == 7) /* Pixel height. */
6899 read_from++;
6900 write_to = read_from;
6902 /* Find end of field. */
6903 for (;*read_from && *read_from != '-'; read_from++)
6906 /* Split the fontname at end of field. */
6907 if (*read_from)
6909 *read_from = '\0';
6910 read_from++;
6912 pixel_height = atoi (write_to);
6913 /* Blank out field. */
6914 if (read_from > write_to)
6916 *write_to = '-';
6917 write_to++;
6919 /* If the pixel height field is at the end (partial xlfd),
6920 return now. */
6921 else
6922 return pixel_height;
6924 /* If we got a pixel height, the point height can be
6925 ignored. Just blank it out and break now. */
6926 if (pixel_height)
6928 /* Find end of point size field. */
6929 for (; *read_from && *read_from != '-'; read_from++)
6932 if (*read_from)
6933 read_from++;
6935 /* Blank out the point size field. */
6936 if (read_from > write_to)
6938 *write_to = '-';
6939 write_to++;
6941 else
6942 return pixel_height;
6944 break;
6946 /* If the point height is already blank, break now. */
6947 if (*read_from == '-')
6949 read_from++;
6950 break;
6953 else if (field_number == 8)
6955 /* If we didn't get a pixel height, try to get the point
6956 height and convert that. */
6957 int point_size;
6958 char *point_size_start = read_from++;
6960 /* Find end of field. */
6961 for (; *read_from && *read_from != '-'; read_from++)
6964 if (*read_from)
6966 *read_from = '\0';
6967 read_from++;
6970 point_size = atoi (point_size_start);
6972 /* Convert to pixel height. */
6973 pixel_height = point_size
6974 * one_w32_display_info.height_in / 720;
6976 /* Blank out this field and break. */
6977 *write_to = '-';
6978 write_to++;
6979 break;
6984 /* Shift the rest of the font spec into place. */
6985 if (write_to && read_from > write_to)
6987 for (; *read_from; read_from++, write_to++)
6988 *write_to = *read_from;
6989 *write_to = '\0';
6992 return pixel_height;
6995 /* Assume parameter 1 is fully qualified, no wildcards. */
6996 static BOOL
6997 w32_font_match (fontname, pattern)
6998 char * fontname;
6999 char * pattern;
7001 char *regex = alloca (strlen (pattern) * 2 + 3);
7002 char *font_name_copy = alloca (strlen (fontname) + 1);
7003 char *ptr;
7005 /* Copy fontname so we can modify it during comparison. */
7006 strcpy (font_name_copy, fontname);
7008 ptr = regex;
7009 *ptr++ = '^';
7011 /* Turn pattern into a regexp and do a regexp match. */
7012 for (; *pattern; pattern++)
7014 if (*pattern == '?')
7015 *ptr++ = '.';
7016 else if (*pattern == '*')
7018 *ptr++ = '.';
7019 *ptr++ = '*';
7021 else
7022 *ptr++ = *pattern;
7024 *ptr = '$';
7025 *(ptr + 1) = '\0';
7027 /* Strip out font heights and compare them seperately, since
7028 rounding error can cause mismatches. This also allows a
7029 comparison between a font that declares only a pixel height and a
7030 pattern that declares the point height.
7033 int font_height, pattern_height;
7035 font_height = xlfd_strip_height (font_name_copy);
7036 pattern_height = xlfd_strip_height (regex);
7038 /* Compare now, and don't bother doing expensive regexp matching
7039 if the heights differ. */
7040 if (font_height && pattern_height && (font_height != pattern_height))
7041 return FALSE;
7044 return (fast_c_string_match_ignore_case (build_string (regex),
7045 font_name_copy) >= 0);
7048 /* Callback functions, and a structure holding info they need, for
7049 listing system fonts on W32. We need one set of functions to do the
7050 job properly, but these don't work on NT 3.51 and earlier, so we
7051 have a second set which don't handle character sets properly to
7052 fall back on.
7054 In both cases, there are two passes made. The first pass gets one
7055 font from each family, the second pass lists all the fonts from
7056 each family. */
7058 typedef struct enumfont_t
7060 HDC hdc;
7061 int numFonts;
7062 LOGFONT logfont;
7063 XFontStruct *size_ref;
7064 Lisp_Object pattern;
7065 Lisp_Object list;
7066 } enumfont_t;
7069 static void
7070 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
7073 static int CALLBACK
7074 enum_font_cb2 (lplf, lptm, FontType, lpef)
7075 ENUMLOGFONT * lplf;
7076 NEWTEXTMETRIC * lptm;
7077 int FontType;
7078 enumfont_t * lpef;
7080 /* Ignore struck out and underlined versions of fonts. */
7081 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
7082 return 1;
7084 /* Only return fonts with names starting with @ if they were
7085 explicitly specified, since Microsoft uses an initial @ to
7086 denote fonts for vertical writing, without providing a more
7087 convenient way of identifying them. */
7088 if (lplf->elfLogFont.lfFaceName[0] == '@'
7089 && lpef->logfont.lfFaceName[0] != '@')
7090 return 1;
7092 /* Check that the character set matches if it was specified */
7093 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
7094 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
7095 return 1;
7097 if (FontType == RASTER_FONTTYPE)
7099 /* DBCS raster fonts have problems displaying, so skip them. */
7100 int charset = lplf->elfLogFont.lfCharSet;
7101 if (charset == SHIFTJIS_CHARSET
7102 || charset == HANGEUL_CHARSET
7103 || charset == CHINESEBIG5_CHARSET
7104 || charset == GB2312_CHARSET
7105 #ifdef JOHAB_CHARSET
7106 || charset == JOHAB_CHARSET
7107 #endif
7109 return 1;
7113 char buf[100];
7114 Lisp_Object width = Qnil;
7115 Lisp_Object charset_list = Qnil;
7116 char *charset = NULL;
7118 /* Truetype fonts do not report their true metrics until loaded */
7119 if (FontType != RASTER_FONTTYPE)
7121 if (!NILP (lpef->pattern))
7123 /* Scalable fonts are as big as you want them to be. */
7124 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
7125 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
7126 width = make_number (lpef->logfont.lfWidth);
7128 else
7130 lplf->elfLogFont.lfHeight = 0;
7131 lplf->elfLogFont.lfWidth = 0;
7135 /* Make sure the height used here is the same as everywhere
7136 else (ie character height, not cell height). */
7137 if (lplf->elfLogFont.lfHeight > 0)
7139 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
7140 if (FontType == RASTER_FONTTYPE)
7141 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
7142 else
7143 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
7146 if (!NILP (lpef->pattern))
7148 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
7150 /* We already checked charsets above, but DEFAULT_CHARSET
7151 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
7152 if (charset
7153 && strncmp (charset, "*-*", 3) != 0
7154 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
7155 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
7156 return 1;
7159 if (charset)
7160 charset_list = Fcons (build_string (charset), Qnil);
7161 else
7162 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
7164 /* Loop through the charsets. */
7165 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
7167 Lisp_Object this_charset = Fcar (charset_list);
7168 charset = SDATA (this_charset);
7170 /* List bold and italic variations if w32-enable-synthesized-fonts
7171 is non-nil and this is a plain font. */
7172 if (w32_enable_synthesized_fonts
7173 && lplf->elfLogFont.lfWeight == FW_NORMAL
7174 && lplf->elfLogFont.lfItalic == FALSE)
7176 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7177 charset, width);
7178 /* bold. */
7179 lplf->elfLogFont.lfWeight = FW_BOLD;
7180 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7181 charset, width);
7182 /* bold italic. */
7183 lplf->elfLogFont.lfItalic = TRUE;
7184 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7185 charset, width);
7186 /* italic. */
7187 lplf->elfLogFont.lfWeight = FW_NORMAL;
7188 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7189 charset, width);
7191 else
7192 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7193 charset, width);
7197 return 1;
7200 static void
7201 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
7202 enumfont_t * lpef;
7203 LOGFONT * logfont;
7204 char * match_charset;
7205 Lisp_Object width;
7207 char buf[100];
7209 if (!w32_to_x_font (logfont, buf, 100, match_charset))
7210 return;
7212 if (NILP (lpef->pattern)
7213 || w32_font_match (buf, SDATA (lpef->pattern)))
7215 /* Check if we already listed this font. This may happen if
7216 w32_enable_synthesized_fonts is non-nil, and there are real
7217 bold and italic versions of the font. */
7218 Lisp_Object font_name = build_string (buf);
7219 if (NILP (Fmember (font_name, lpef->list)))
7221 Lisp_Object entry = Fcons (font_name, width);
7222 lpef->list = Fcons (entry, lpef->list);
7223 lpef->numFonts++;
7229 static int CALLBACK
7230 enum_font_cb1 (lplf, lptm, FontType, lpef)
7231 ENUMLOGFONT * lplf;
7232 NEWTEXTMETRIC * lptm;
7233 int FontType;
7234 enumfont_t * lpef;
7236 return EnumFontFamilies (lpef->hdc,
7237 lplf->elfLogFont.lfFaceName,
7238 (FONTENUMPROC) enum_font_cb2,
7239 (LPARAM) lpef);
7243 static int CALLBACK
7244 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
7245 ENUMLOGFONTEX * lplf;
7246 NEWTEXTMETRICEX * lptm;
7247 int font_type;
7248 enumfont_t * lpef;
7250 /* We are not interested in the extra info we get back from the 'Ex
7251 version - only the fact that we get character set variations
7252 enumerated seperately. */
7253 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
7254 font_type, lpef);
7257 static int CALLBACK
7258 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
7259 ENUMLOGFONTEX * lplf;
7260 NEWTEXTMETRICEX * lptm;
7261 int font_type;
7262 enumfont_t * lpef;
7264 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7265 FARPROC enum_font_families_ex
7266 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7267 /* We don't really expect EnumFontFamiliesEx to disappear once we
7268 get here, so don't bother handling it gracefully. */
7269 if (enum_font_families_ex == NULL)
7270 error ("gdi32.dll has disappeared!");
7271 return enum_font_families_ex (lpef->hdc,
7272 &lplf->elfLogFont,
7273 (FONTENUMPROC) enum_fontex_cb2,
7274 (LPARAM) lpef, 0);
7277 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
7278 and xterm.c in Emacs 20.3) */
7280 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
7282 char *fontname, *ptnstr;
7283 Lisp_Object list, tem, newlist = Qnil;
7284 int n_fonts = 0;
7286 list = Vw32_bdf_filename_alist;
7287 ptnstr = SDATA (pattern);
7289 for ( ; CONSP (list); list = XCDR (list))
7291 tem = XCAR (list);
7292 if (CONSP (tem))
7293 fontname = SDATA (XCAR (tem));
7294 else if (STRINGP (tem))
7295 fontname = SDATA (tem);
7296 else
7297 continue;
7299 if (w32_font_match (fontname, ptnstr))
7301 newlist = Fcons (XCAR (tem), newlist);
7302 n_fonts++;
7303 if (n_fonts >= max_names)
7304 break;
7308 return newlist;
7312 /* Return a list of names of available fonts matching PATTERN on frame
7313 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
7314 to be listed. Frame F NULL means we have not yet created any
7315 frame, which means we can't get proper size info, as we don't have
7316 a device context to use for GetTextMetrics.
7317 MAXNAMES sets a limit on how many fonts to match. */
7319 Lisp_Object
7320 w32_list_fonts (f, pattern, size, maxnames)
7321 struct frame *f;
7322 Lisp_Object pattern;
7323 int size;
7324 int maxnames;
7326 Lisp_Object patterns, key = Qnil, tem, tpat;
7327 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
7328 struct w32_display_info *dpyinfo = &one_w32_display_info;
7329 int n_fonts = 0;
7331 patterns = Fassoc (pattern, Valternate_fontname_alist);
7332 if (NILP (patterns))
7333 patterns = Fcons (pattern, Qnil);
7335 for (; CONSP (patterns); patterns = XCDR (patterns))
7337 enumfont_t ef;
7338 int codepage;
7340 tpat = XCAR (patterns);
7342 if (!STRINGP (tpat))
7343 continue;
7345 /* Avoid expensive EnumFontFamilies functions if we are not
7346 going to be able to output one of these anyway. */
7347 codepage = w32_codepage_for_font (SDATA (tpat));
7348 if (codepage != CP_8BIT && codepage != CP_UNICODE
7349 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
7350 && !IsValidCodePage(codepage))
7351 continue;
7353 /* See if we cached the result for this particular query.
7354 The cache is an alist of the form:
7355 ((PATTERN (FONTNAME . WIDTH) ...) ...)
7357 if (tem = XCDR (dpyinfo->name_list_element),
7358 !NILP (list = Fassoc (tpat, tem)))
7360 list = Fcdr_safe (list);
7361 /* We have a cached list. Don't have to get the list again. */
7362 goto label_cached;
7365 BLOCK_INPUT;
7366 /* At first, put PATTERN in the cache. */
7367 ef.pattern = tpat;
7368 ef.list = Qnil;
7369 ef.numFonts = 0;
7371 /* Use EnumFontFamiliesEx where it is available, as it knows
7372 about character sets. Fall back to EnumFontFamilies for
7373 older versions of NT that don't support the 'Ex function. */
7374 x_to_w32_font (SDATA (tpat), &ef.logfont);
7376 LOGFONT font_match_pattern;
7377 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7378 FARPROC enum_font_families_ex
7379 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7381 /* We do our own pattern matching so we can handle wildcards. */
7382 font_match_pattern.lfFaceName[0] = 0;
7383 font_match_pattern.lfPitchAndFamily = 0;
7384 /* We can use the charset, because if it is a wildcard it will
7385 be DEFAULT_CHARSET anyway. */
7386 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
7388 ef.hdc = GetDC (dpyinfo->root_window);
7390 if (enum_font_families_ex)
7391 enum_font_families_ex (ef.hdc,
7392 &font_match_pattern,
7393 (FONTENUMPROC) enum_fontex_cb1,
7394 (LPARAM) &ef, 0);
7395 else
7396 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
7397 (LPARAM)&ef);
7399 ReleaseDC (dpyinfo->root_window, ef.hdc);
7402 UNBLOCK_INPUT;
7403 list = ef.list;
7405 /* Make a list of the fonts we got back.
7406 Store that in the font cache for the display. */
7407 XSETCDR (dpyinfo->name_list_element,
7408 Fcons (Fcons (tpat, list),
7409 XCDR (dpyinfo->name_list_element)));
7411 label_cached:
7412 if (NILP (list)) continue; /* Try the remaining alternatives. */
7414 newlist = second_best = Qnil;
7416 /* Make a list of the fonts that have the right width. */
7417 for (; CONSP (list); list = XCDR (list))
7419 int found_size;
7420 tem = XCAR (list);
7422 if (!CONSP (tem))
7423 continue;
7424 if (NILP (XCAR (tem)))
7425 continue;
7426 if (!size)
7428 newlist = Fcons (XCAR (tem), newlist);
7429 n_fonts++;
7430 if (n_fonts >= maxnames)
7431 break;
7432 else
7433 continue;
7435 if (!INTEGERP (XCDR (tem)))
7437 /* Since we don't yet know the size of the font, we must
7438 load it and try GetTextMetrics. */
7439 W32FontStruct thisinfo;
7440 LOGFONT lf;
7441 HDC hdc;
7442 HANDLE oldobj;
7444 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
7445 continue;
7447 BLOCK_INPUT;
7448 thisinfo.bdf = NULL;
7449 thisinfo.hfont = CreateFontIndirect (&lf);
7450 if (thisinfo.hfont == NULL)
7451 continue;
7453 hdc = GetDC (dpyinfo->root_window);
7454 oldobj = SelectObject (hdc, thisinfo.hfont);
7455 if (GetTextMetrics (hdc, &thisinfo.tm))
7456 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
7457 else
7458 XSETCDR (tem, make_number (0));
7459 SelectObject (hdc, oldobj);
7460 ReleaseDC (dpyinfo->root_window, hdc);
7461 DeleteObject(thisinfo.hfont);
7462 UNBLOCK_INPUT;
7464 found_size = XINT (XCDR (tem));
7465 if (found_size == size)
7467 newlist = Fcons (XCAR (tem), newlist);
7468 n_fonts++;
7469 if (n_fonts >= maxnames)
7470 break;
7472 /* keep track of the closest matching size in case
7473 no exact match is found. */
7474 else if (found_size > 0)
7476 if (NILP (second_best))
7477 second_best = tem;
7479 else if (found_size < size)
7481 if (XINT (XCDR (second_best)) > size
7482 || XINT (XCDR (second_best)) < found_size)
7483 second_best = tem;
7485 else
7487 if (XINT (XCDR (second_best)) > size
7488 && XINT (XCDR (second_best)) >
7489 found_size)
7490 second_best = tem;
7495 if (!NILP (newlist))
7496 break;
7497 else if (!NILP (second_best))
7499 newlist = Fcons (XCAR (second_best), Qnil);
7500 break;
7504 /* Include any bdf fonts. */
7505 if (n_fonts < maxnames)
7507 Lisp_Object combined[2];
7508 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
7509 combined[1] = newlist;
7510 newlist = Fnconc(2, combined);
7513 return newlist;
7517 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
7518 struct font_info *
7519 w32_get_font_info (f, font_idx)
7520 FRAME_PTR f;
7521 int font_idx;
7523 return (FRAME_W32_FONT_TABLE (f) + font_idx);
7527 struct font_info*
7528 w32_query_font (struct frame *f, char *fontname)
7530 int i;
7531 struct font_info *pfi;
7533 pfi = FRAME_W32_FONT_TABLE (f);
7535 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
7537 if (strcmp(pfi->name, fontname) == 0) return pfi;
7540 return NULL;
7543 /* Find a CCL program for a font specified by FONTP, and set the member
7544 `encoder' of the structure. */
7546 void
7547 w32_find_ccl_program (fontp)
7548 struct font_info *fontp;
7550 Lisp_Object list, elt;
7552 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7554 elt = XCAR (list);
7555 if (CONSP (elt)
7556 && STRINGP (XCAR (elt))
7557 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7558 >= 0))
7559 break;
7561 if (! NILP (list))
7563 struct ccl_program *ccl
7564 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7566 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7567 xfree (ccl);
7568 else
7569 fontp->font_encoder = ccl;
7574 /* Find BDF files in a specified directory. (use GCPRO when calling,
7575 as this calls lisp to get a directory listing). */
7576 static Lisp_Object
7577 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
7579 Lisp_Object filelist, list = Qnil;
7580 char fontname[100];
7582 if (!STRINGP(directory))
7583 return Qnil;
7585 filelist = Fdirectory_files (directory, Qt,
7586 build_string (".*\\.[bB][dD][fF]"), Qt);
7588 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7590 Lisp_Object filename = XCAR (filelist);
7591 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
7592 store_in_alist (&list, build_string (fontname), filename);
7594 return list;
7597 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
7598 1, 1, 0,
7599 doc: /* Return a list of BDF fonts in DIR.
7600 The list is suitable for appending to w32-bdf-filename-alist. Fonts
7601 which do not contain an xlfd description will not be included in the
7602 list. DIR may be a list of directories. */)
7603 (directory)
7604 Lisp_Object directory;
7606 Lisp_Object list = Qnil;
7607 struct gcpro gcpro1, gcpro2;
7609 if (!CONSP (directory))
7610 return w32_find_bdf_fonts_in_dir (directory);
7612 for ( ; CONSP (directory); directory = XCDR (directory))
7614 Lisp_Object pair[2];
7615 pair[0] = list;
7616 pair[1] = Qnil;
7617 GCPRO2 (directory, list);
7618 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7619 list = Fnconc( 2, pair );
7620 UNGCPRO;
7622 return list;
7626 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7627 doc: /* Internal function called by `color-defined-p', which see. */)
7628 (color, frame)
7629 Lisp_Object color, frame;
7631 XColor foo;
7632 FRAME_PTR f = check_x_frame (frame);
7634 CHECK_STRING (color);
7636 if (w32_defined_color (f, SDATA (color), &foo, 0))
7637 return Qt;
7638 else
7639 return Qnil;
7642 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7643 doc: /* Internal function called by `color-values', which see. */)
7644 (color, frame)
7645 Lisp_Object color, frame;
7647 XColor foo;
7648 FRAME_PTR f = check_x_frame (frame);
7650 CHECK_STRING (color);
7652 if (w32_defined_color (f, SDATA (color), &foo, 0))
7654 Lisp_Object rgb[3];
7656 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7657 | GetRValue (foo.pixel));
7658 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7659 | GetGValue (foo.pixel));
7660 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7661 | GetBValue (foo.pixel));
7662 return Flist (3, rgb);
7664 else
7665 return Qnil;
7668 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7669 doc: /* Internal function called by `display-color-p', which see. */)
7670 (display)
7671 Lisp_Object display;
7673 struct w32_display_info *dpyinfo = check_x_display_info (display);
7675 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7676 return Qnil;
7678 return Qt;
7681 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
7682 Sx_display_grayscale_p, 0, 1, 0,
7683 doc: /* Return t if the X display supports shades of gray.
7684 Note that color displays do support shades of gray.
7685 The optional argument DISPLAY specifies which display to ask about.
7686 DISPLAY should be either a frame or a display name (a string).
7687 If omitted or nil, that stands for the selected frame's display. */)
7688 (display)
7689 Lisp_Object display;
7691 struct w32_display_info *dpyinfo = check_x_display_info (display);
7693 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7694 return Qnil;
7696 return Qt;
7699 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
7700 Sx_display_pixel_width, 0, 1, 0,
7701 doc: /* Returns the width in pixels of DISPLAY.
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 return make_number (dpyinfo->width);
7713 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7714 Sx_display_pixel_height, 0, 1, 0,
7715 doc: /* Returns the height in pixels of DISPLAY.
7716 The optional argument DISPLAY specifies which display to ask about.
7717 DISPLAY should be either a frame or a display name (a string).
7718 If omitted or nil, that stands for the selected frame's display. */)
7719 (display)
7720 Lisp_Object display;
7722 struct w32_display_info *dpyinfo = check_x_display_info (display);
7724 return make_number (dpyinfo->height);
7727 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7728 0, 1, 0,
7729 doc: /* Returns the number of bitplanes of DISPLAY.
7730 The optional argument DISPLAY specifies which display to ask about.
7731 DISPLAY should be either a frame or a display name (a string).
7732 If omitted or nil, that stands for the selected frame's display. */)
7733 (display)
7734 Lisp_Object display;
7736 struct w32_display_info *dpyinfo = check_x_display_info (display);
7738 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7741 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7742 0, 1, 0,
7743 doc: /* Returns the number of color cells of DISPLAY.
7744 The optional argument DISPLAY specifies which display to ask about.
7745 DISPLAY should be either a frame or a display name (a string).
7746 If omitted or nil, that stands for the selected frame's display. */)
7747 (display)
7748 Lisp_Object display;
7750 struct w32_display_info *dpyinfo = check_x_display_info (display);
7751 HDC hdc;
7752 int cap;
7754 hdc = GetDC (dpyinfo->root_window);
7755 if (dpyinfo->has_palette)
7756 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7757 else
7758 cap = GetDeviceCaps (hdc,NUMCOLORS);
7760 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
7761 and because probably is more meaningful on Windows anyway */
7762 if (cap < 0)
7763 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
7765 ReleaseDC (dpyinfo->root_window, hdc);
7767 return make_number (cap);
7770 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7771 Sx_server_max_request_size,
7772 0, 1, 0,
7773 doc: /* Returns the maximum request size of the server of DISPLAY.
7774 The optional argument DISPLAY specifies which display to ask about.
7775 DISPLAY should be either a frame or a display name (a string).
7776 If omitted or nil, that stands for the selected frame's display. */)
7777 (display)
7778 Lisp_Object display;
7780 struct w32_display_info *dpyinfo = check_x_display_info (display);
7782 return make_number (1);
7785 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7786 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
7787 The optional argument DISPLAY specifies which display to ask about.
7788 DISPLAY should be either a frame or a display name (a string).
7789 If omitted or nil, that stands for the selected frame's display. */)
7790 (display)
7791 Lisp_Object display;
7793 return build_string ("Microsoft Corp.");
7796 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7797 doc: /* Returns the version numbers of the server of DISPLAY.
7798 The value is a list of three integers: the major and minor
7799 version numbers, and the vendor-specific release
7800 number. See also the function `x-server-vendor'.
7802 The optional argument DISPLAY specifies which display to ask about.
7803 DISPLAY should be either a frame or a display name (a string).
7804 If omitted or nil, that stands for the selected frame's display. */)
7805 (display)
7806 Lisp_Object display;
7808 return Fcons (make_number (w32_major_version),
7809 Fcons (make_number (w32_minor_version),
7810 Fcons (make_number (w32_build_number), Qnil)));
7813 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7814 doc: /* Returns the number of screens on the server of DISPLAY.
7815 The optional argument DISPLAY specifies which display to ask about.
7816 DISPLAY should be either a frame or a display name (a string).
7817 If omitted or nil, that stands for the selected frame's display. */)
7818 (display)
7819 Lisp_Object display;
7821 return make_number (1);
7824 DEFUN ("x-display-mm-height", Fx_display_mm_height,
7825 Sx_display_mm_height, 0, 1, 0,
7826 doc: /* Returns the height in millimeters of DISPLAY.
7827 The optional argument DISPLAY specifies which display to ask about.
7828 DISPLAY should be either a frame or a display name (a string).
7829 If omitted or nil, that stands for the selected frame's display. */)
7830 (display)
7831 Lisp_Object display;
7833 struct w32_display_info *dpyinfo = check_x_display_info (display);
7834 HDC hdc;
7835 int cap;
7837 hdc = GetDC (dpyinfo->root_window);
7839 cap = GetDeviceCaps (hdc, VERTSIZE);
7841 ReleaseDC (dpyinfo->root_window, hdc);
7843 return make_number (cap);
7846 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7847 doc: /* Returns the width in millimeters of DISPLAY.
7848 The optional argument DISPLAY specifies which display to ask about.
7849 DISPLAY should be either a frame or a display name (a string).
7850 If omitted or nil, that stands for the selected frame's display. */)
7851 (display)
7852 Lisp_Object display;
7854 struct w32_display_info *dpyinfo = check_x_display_info (display);
7856 HDC hdc;
7857 int cap;
7859 hdc = GetDC (dpyinfo->root_window);
7861 cap = GetDeviceCaps (hdc, HORZSIZE);
7863 ReleaseDC (dpyinfo->root_window, hdc);
7865 return make_number (cap);
7868 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7869 Sx_display_backing_store, 0, 1, 0,
7870 doc: /* Returns an indication of whether DISPLAY does backing store.
7871 The value may be `always', `when-mapped', or `not-useful'.
7872 The optional argument DISPLAY specifies which display to ask about.
7873 DISPLAY should be either a frame or a display name (a string).
7874 If omitted or nil, that stands for the selected frame's display. */)
7875 (display)
7876 Lisp_Object display;
7878 return intern ("not-useful");
7881 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7882 Sx_display_visual_class, 0, 1, 0,
7883 doc: /* Returns the visual class of DISPLAY.
7884 The value is one of the symbols `static-gray', `gray-scale',
7885 `static-color', `pseudo-color', `true-color', or `direct-color'.
7887 The optional argument DISPLAY specifies which display to ask about.
7888 DISPLAY should be either a frame or a display name (a string).
7889 If omitted or nil, that stands for the selected frame's display. */)
7890 (display)
7891 Lisp_Object display;
7893 struct w32_display_info *dpyinfo = check_x_display_info (display);
7894 Lisp_Object result = Qnil;
7896 if (dpyinfo->has_palette)
7897 result = intern ("pseudo-color");
7898 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
7899 result = intern ("static-grey");
7900 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
7901 result = intern ("static-color");
7902 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
7903 result = intern ("true-color");
7905 return result;
7908 DEFUN ("x-display-save-under", Fx_display_save_under,
7909 Sx_display_save_under, 0, 1, 0,
7910 doc: /* Returns t if DISPLAY supports the save-under feature.
7911 The optional argument DISPLAY specifies which display to ask about.
7912 DISPLAY should be either a frame or a display name (a string).
7913 If omitted or nil, that stands for the selected frame's display. */)
7914 (display)
7915 Lisp_Object display;
7917 return Qnil;
7921 x_pixel_width (f)
7922 register struct frame *f;
7924 return PIXEL_WIDTH (f);
7928 x_pixel_height (f)
7929 register struct frame *f;
7931 return PIXEL_HEIGHT (f);
7935 x_char_width (f)
7936 register struct frame *f;
7938 return FONT_WIDTH (f->output_data.w32->font);
7942 x_char_height (f)
7943 register struct frame *f;
7945 return f->output_data.w32->line_height;
7949 x_screen_planes (f)
7950 register struct frame *f;
7952 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7955 /* Return the display structure for the display named NAME.
7956 Open a new connection if necessary. */
7958 struct w32_display_info *
7959 x_display_info_for_name (name)
7960 Lisp_Object name;
7962 Lisp_Object names;
7963 struct w32_display_info *dpyinfo;
7965 CHECK_STRING (name);
7967 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7968 dpyinfo;
7969 dpyinfo = dpyinfo->next, names = XCDR (names))
7971 Lisp_Object tem;
7972 tem = Fstring_equal (XCAR (XCAR (names)), name);
7973 if (!NILP (tem))
7974 return dpyinfo;
7977 /* Use this general default value to start with. */
7978 Vx_resource_name = Vinvocation_name;
7980 validate_x_resource_name ();
7982 dpyinfo = w32_term_init (name, (unsigned char *)0,
7983 (char *) SDATA (Vx_resource_name));
7985 if (dpyinfo == 0)
7986 error ("Cannot connect to server %s", SDATA (name));
7988 w32_in_use = 1;
7989 XSETFASTINT (Vwindow_system_version, 3);
7991 return dpyinfo;
7994 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7995 1, 3, 0, doc: /* Open a connection to a server.
7996 DISPLAY is the name of the display to connect to.
7997 Optional second arg XRM-STRING is a string of resources in xrdb format.
7998 If the optional third arg MUST-SUCCEED is non-nil,
7999 terminate Emacs if we can't open the connection. */)
8000 (display, xrm_string, must_succeed)
8001 Lisp_Object display, xrm_string, must_succeed;
8003 unsigned char *xrm_option;
8004 struct w32_display_info *dpyinfo;
8006 /* If initialization has already been done, return now to avoid
8007 overwriting critical parts of one_w32_display_info. */
8008 if (w32_in_use)
8009 return Qnil;
8011 CHECK_STRING (display);
8012 if (! NILP (xrm_string))
8013 CHECK_STRING (xrm_string);
8015 if (! EQ (Vwindow_system, intern ("w32")))
8016 error ("Not using Microsoft Windows");
8018 /* Allow color mapping to be defined externally; first look in user's
8019 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
8021 Lisp_Object color_file;
8022 struct gcpro gcpro1;
8024 color_file = build_string("~/rgb.txt");
8026 GCPRO1 (color_file);
8028 if (NILP (Ffile_readable_p (color_file)))
8029 color_file =
8030 Fexpand_file_name (build_string ("rgb.txt"),
8031 Fsymbol_value (intern ("data-directory")));
8033 Vw32_color_map = Fw32_load_color_file (color_file);
8035 UNGCPRO;
8037 if (NILP (Vw32_color_map))
8038 Vw32_color_map = Fw32_default_color_map ();
8040 if (! NILP (xrm_string))
8041 xrm_option = (unsigned char *) SDATA (xrm_string);
8042 else
8043 xrm_option = (unsigned char *) 0;
8045 /* Use this general default value to start with. */
8046 /* First remove .exe suffix from invocation-name - it looks ugly. */
8048 char basename[ MAX_PATH ], *str;
8050 strcpy (basename, SDATA (Vinvocation_name));
8051 str = strrchr (basename, '.');
8052 if (str) *str = 0;
8053 Vinvocation_name = build_string (basename);
8055 Vx_resource_name = Vinvocation_name;
8057 validate_x_resource_name ();
8059 /* This is what opens the connection and sets x_current_display.
8060 This also initializes many symbols, such as those used for input. */
8061 dpyinfo = w32_term_init (display, xrm_option,
8062 (char *) SDATA (Vx_resource_name));
8064 if (dpyinfo == 0)
8066 if (!NILP (must_succeed))
8067 fatal ("Cannot connect to server %s.\n",
8068 SDATA (display));
8069 else
8070 error ("Cannot connect to server %s", SDATA (display));
8073 w32_in_use = 1;
8075 XSETFASTINT (Vwindow_system_version, 3);
8076 return Qnil;
8079 DEFUN ("x-close-connection", Fx_close_connection,
8080 Sx_close_connection, 1, 1, 0,
8081 doc: /* Close the connection to DISPLAY's server.
8082 For DISPLAY, specify either a frame or a display name (a string).
8083 If DISPLAY is nil, that stands for the selected frame's display. */)
8084 (display)
8085 Lisp_Object display;
8087 struct w32_display_info *dpyinfo = check_x_display_info (display);
8088 int i;
8090 if (dpyinfo->reference_count > 0)
8091 error ("Display still has frames on it");
8093 BLOCK_INPUT;
8094 /* Free the fonts in the font table. */
8095 for (i = 0; i < dpyinfo->n_fonts; i++)
8096 if (dpyinfo->font_table[i].name)
8098 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
8099 xfree (dpyinfo->font_table[i].full_name);
8100 xfree (dpyinfo->font_table[i].name);
8101 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
8103 x_destroy_all_bitmaps (dpyinfo);
8105 x_delete_display (dpyinfo);
8106 UNBLOCK_INPUT;
8108 return Qnil;
8111 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
8112 doc: /* Return the list of display names that Emacs has connections to. */)
8115 Lisp_Object tail, result;
8117 result = Qnil;
8118 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
8119 result = Fcons (XCAR (XCAR (tail)), result);
8121 return result;
8124 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
8125 doc: /* This is a noop on W32 systems. */)
8126 (on, display)
8127 Lisp_Object display, on;
8129 return Qnil;
8133 /***********************************************************************
8134 Image types
8135 ***********************************************************************/
8137 /* Value is the number of elements of vector VECTOR. */
8139 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
8141 /* List of supported image types. Use define_image_type to add new
8142 types. Use lookup_image_type to find a type for a given symbol. */
8144 static struct image_type *image_types;
8146 /* The symbol `image' which is the car of the lists used to represent
8147 images in Lisp. */
8149 extern Lisp_Object Qimage;
8151 /* The symbol `xbm' which is used as the type symbol for XBM images. */
8153 Lisp_Object Qxbm;
8155 /* Keywords. */
8157 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
8158 extern Lisp_Object QCdata, QCtype;
8159 Lisp_Object QCascent, QCmargin, QCrelief;
8160 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
8161 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
8163 /* Other symbols. */
8165 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
8167 /* Time in seconds after which images should be removed from the cache
8168 if not displayed. */
8170 Lisp_Object Vimage_cache_eviction_delay;
8172 /* Function prototypes. */
8174 static void define_image_type P_ ((struct image_type *type));
8175 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
8176 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
8177 static void x_laplace P_ ((struct frame *, struct image *));
8178 static void x_emboss P_ ((struct frame *, struct image *));
8179 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
8180 Lisp_Object));
8183 /* Define a new image type from TYPE. This adds a copy of TYPE to
8184 image_types and adds the symbol *TYPE->type to Vimage_types. */
8186 static void
8187 define_image_type (type)
8188 struct image_type *type;
8190 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
8191 The initialized data segment is read-only. */
8192 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
8193 bcopy (type, p, sizeof *p);
8194 p->next = image_types;
8195 image_types = p;
8196 Vimage_types = Fcons (*p->type, Vimage_types);
8200 /* Look up image type SYMBOL, and return a pointer to its image_type
8201 structure. Value is null if SYMBOL is not a known image type. */
8203 static INLINE struct image_type *
8204 lookup_image_type (symbol)
8205 Lisp_Object symbol;
8207 struct image_type *type;
8209 for (type = image_types; type; type = type->next)
8210 if (EQ (symbol, *type->type))
8211 break;
8213 return type;
8217 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
8218 valid image specification is a list whose car is the symbol
8219 `image', and whose rest is a property list. The property list must
8220 contain a value for key `:type'. That value must be the name of a
8221 supported image type. The rest of the property list depends on the
8222 image type. */
8225 valid_image_p (object)
8226 Lisp_Object object;
8228 int valid_p = 0;
8230 if (CONSP (object) && EQ (XCAR (object), Qimage))
8232 Lisp_Object tem;
8234 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
8235 if (EQ (XCAR (tem), QCtype))
8237 tem = XCDR (tem);
8238 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
8240 struct image_type *type;
8241 type = lookup_image_type (XCAR (tem));
8242 if (type)
8243 valid_p = type->valid_p (object);
8246 break;
8250 return valid_p;
8254 /* Log error message with format string FORMAT and argument ARG.
8255 Signaling an error, e.g. when an image cannot be loaded, is not a
8256 good idea because this would interrupt redisplay, and the error
8257 message display would lead to another redisplay. This function
8258 therefore simply displays a message. */
8260 static void
8261 image_error (format, arg1, arg2)
8262 char *format;
8263 Lisp_Object arg1, arg2;
8265 add_to_log (format, arg1, arg2);
8270 /***********************************************************************
8271 Image specifications
8272 ***********************************************************************/
8274 enum image_value_type
8276 IMAGE_DONT_CHECK_VALUE_TYPE,
8277 IMAGE_STRING_VALUE,
8278 IMAGE_STRING_OR_NIL_VALUE,
8279 IMAGE_SYMBOL_VALUE,
8280 IMAGE_POSITIVE_INTEGER_VALUE,
8281 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
8282 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
8283 IMAGE_ASCENT_VALUE,
8284 IMAGE_INTEGER_VALUE,
8285 IMAGE_FUNCTION_VALUE,
8286 IMAGE_NUMBER_VALUE,
8287 IMAGE_BOOL_VALUE
8290 /* Structure used when parsing image specifications. */
8292 struct image_keyword
8294 /* Name of keyword. */
8295 char *name;
8297 /* The type of value allowed. */
8298 enum image_value_type type;
8300 /* Non-zero means key must be present. */
8301 int mandatory_p;
8303 /* Used to recognize duplicate keywords in a property list. */
8304 int count;
8306 /* The value that was found. */
8307 Lisp_Object value;
8311 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
8312 int, Lisp_Object));
8313 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
8316 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
8317 has the format (image KEYWORD VALUE ...). One of the keyword/
8318 value pairs must be `:type TYPE'. KEYWORDS is a vector of
8319 image_keywords structures of size NKEYWORDS describing other
8320 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
8322 static int
8323 parse_image_spec (spec, keywords, nkeywords, type)
8324 Lisp_Object spec;
8325 struct image_keyword *keywords;
8326 int nkeywords;
8327 Lisp_Object type;
8329 int i;
8330 Lisp_Object plist;
8332 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
8333 return 0;
8335 plist = XCDR (spec);
8336 while (CONSP (plist))
8338 Lisp_Object key, value;
8340 /* First element of a pair must be a symbol. */
8341 key = XCAR (plist);
8342 plist = XCDR (plist);
8343 if (!SYMBOLP (key))
8344 return 0;
8346 /* There must follow a value. */
8347 if (!CONSP (plist))
8348 return 0;
8349 value = XCAR (plist);
8350 plist = XCDR (plist);
8352 /* Find key in KEYWORDS. Error if not found. */
8353 for (i = 0; i < nkeywords; ++i)
8354 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
8355 break;
8357 if (i == nkeywords)
8358 continue;
8360 /* Record that we recognized the keyword. If a keywords
8361 was found more than once, it's an error. */
8362 keywords[i].value = value;
8363 ++keywords[i].count;
8365 if (keywords[i].count > 1)
8366 return 0;
8368 /* Check type of value against allowed type. */
8369 switch (keywords[i].type)
8371 case IMAGE_STRING_VALUE:
8372 if (!STRINGP (value))
8373 return 0;
8374 break;
8376 case IMAGE_STRING_OR_NIL_VALUE:
8377 if (!STRINGP (value) && !NILP (value))
8378 return 0;
8379 break;
8381 case IMAGE_SYMBOL_VALUE:
8382 if (!SYMBOLP (value))
8383 return 0;
8384 break;
8386 case IMAGE_POSITIVE_INTEGER_VALUE:
8387 if (!INTEGERP (value) || XINT (value) <= 0)
8388 return 0;
8389 break;
8391 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
8392 if (INTEGERP (value) && XINT (value) >= 0)
8393 break;
8394 if (CONSP (value)
8395 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
8396 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
8397 break;
8398 return 0;
8400 case IMAGE_ASCENT_VALUE:
8401 if (SYMBOLP (value) && EQ (value, Qcenter))
8402 break;
8403 else if (INTEGERP (value)
8404 && XINT (value) >= 0
8405 && XINT (value) <= 100)
8406 break;
8407 return 0;
8409 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
8410 if (!INTEGERP (value) || XINT (value) < 0)
8411 return 0;
8412 break;
8414 case IMAGE_DONT_CHECK_VALUE_TYPE:
8415 break;
8417 case IMAGE_FUNCTION_VALUE:
8418 value = indirect_function (value);
8419 if (SUBRP (value)
8420 || COMPILEDP (value)
8421 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
8422 break;
8423 return 0;
8425 case IMAGE_NUMBER_VALUE:
8426 if (!INTEGERP (value) && !FLOATP (value))
8427 return 0;
8428 break;
8430 case IMAGE_INTEGER_VALUE:
8431 if (!INTEGERP (value))
8432 return 0;
8433 break;
8435 case IMAGE_BOOL_VALUE:
8436 if (!NILP (value) && !EQ (value, Qt))
8437 return 0;
8438 break;
8440 default:
8441 abort ();
8442 break;
8445 if (EQ (key, QCtype) && !EQ (type, value))
8446 return 0;
8449 /* Check that all mandatory fields are present. */
8450 for (i = 0; i < nkeywords; ++i)
8451 if (keywords[i].mandatory_p && keywords[i].count == 0)
8452 return 0;
8454 return NILP (plist);
8458 /* Return the value of KEY in image specification SPEC. Value is nil
8459 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
8460 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
8462 static Lisp_Object
8463 image_spec_value (spec, key, found)
8464 Lisp_Object spec, key;
8465 int *found;
8467 Lisp_Object tail;
8469 xassert (valid_image_p (spec));
8471 for (tail = XCDR (spec);
8472 CONSP (tail) && CONSP (XCDR (tail));
8473 tail = XCDR (XCDR (tail)))
8475 if (EQ (XCAR (tail), key))
8477 if (found)
8478 *found = 1;
8479 return XCAR (XCDR (tail));
8483 if (found)
8484 *found = 0;
8485 return Qnil;
8489 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
8490 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
8491 PIXELS non-nil means return the size in pixels, otherwise return the
8492 size in canonical character units.
8493 FRAME is the frame on which the image will be displayed. FRAME nil
8494 or omitted means use the selected frame. */)
8495 (spec, pixels, frame)
8496 Lisp_Object spec, pixels, frame;
8498 Lisp_Object size;
8500 size = Qnil;
8501 if (valid_image_p (spec))
8503 struct frame *f = check_x_frame (frame);
8504 int id = lookup_image (f, spec);
8505 struct image *img = IMAGE_FROM_ID (f, id);
8506 int width = img->width + 2 * img->hmargin;
8507 int height = img->height + 2 * img->vmargin;
8509 if (NILP (pixels))
8510 size = Fcons (make_float ((double) width / CANON_X_UNIT (f)),
8511 make_float ((double) height / CANON_Y_UNIT (f)));
8512 else
8513 size = Fcons (make_number (width), make_number (height));
8515 else
8516 error ("Invalid image specification");
8518 return size;
8522 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
8523 doc: /* Return t if image SPEC has a mask bitmap.
8524 FRAME is the frame on which the image will be displayed. FRAME nil
8525 or omitted means use the selected frame. */)
8526 (spec, frame)
8527 Lisp_Object spec, frame;
8529 Lisp_Object mask;
8531 mask = Qnil;
8532 if (valid_image_p (spec))
8534 struct frame *f = check_x_frame (frame);
8535 int id = lookup_image (f, spec);
8536 struct image *img = IMAGE_FROM_ID (f, id);
8537 if (img->mask)
8538 mask = Qt;
8540 else
8541 error ("Invalid image specification");
8543 return mask;
8547 /***********************************************************************
8548 Image type independent image structures
8549 ***********************************************************************/
8551 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
8552 static void free_image P_ ((struct frame *f, struct image *img));
8555 /* Allocate and return a new image structure for image specification
8556 SPEC. SPEC has a hash value of HASH. */
8558 static struct image *
8559 make_image (spec, hash)
8560 Lisp_Object spec;
8561 unsigned hash;
8563 struct image *img = (struct image *) xmalloc (sizeof *img);
8565 xassert (valid_image_p (spec));
8566 bzero (img, sizeof *img);
8567 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
8568 xassert (img->type != NULL);
8569 img->spec = spec;
8570 img->data.lisp_val = Qnil;
8571 img->ascent = DEFAULT_IMAGE_ASCENT;
8572 img->hash = hash;
8573 return img;
8577 /* Free image IMG which was used on frame F, including its resources. */
8579 static void
8580 free_image (f, img)
8581 struct frame *f;
8582 struct image *img;
8584 if (img)
8586 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8588 /* Remove IMG from the hash table of its cache. */
8589 if (img->prev)
8590 img->prev->next = img->next;
8591 else
8592 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
8594 if (img->next)
8595 img->next->prev = img->prev;
8597 c->images[img->id] = NULL;
8599 /* Free resources, then free IMG. */
8600 img->type->free (f, img);
8601 xfree (img);
8606 /* Prepare image IMG for display on frame F. Must be called before
8607 drawing an image. */
8609 void
8610 prepare_image_for_display (f, img)
8611 struct frame *f;
8612 struct image *img;
8614 EMACS_TIME t;
8616 /* We're about to display IMG, so set its timestamp to `now'. */
8617 EMACS_GET_TIME (t);
8618 img->timestamp = EMACS_SECS (t);
8620 /* If IMG doesn't have a pixmap yet, load it now, using the image
8621 type dependent loader function. */
8622 if (img->pixmap == 0 && !img->load_failed_p)
8623 img->load_failed_p = img->type->load (f, img) == 0;
8627 /* Value is the number of pixels for the ascent of image IMG when
8628 drawn in face FACE. */
8631 image_ascent (img, face)
8632 struct image *img;
8633 struct face *face;
8635 int height = img->height + img->vmargin;
8636 int ascent;
8638 if (img->ascent == CENTERED_IMAGE_ASCENT)
8640 if (face->font)
8641 ascent = height / 2 - (FONT_DESCENT(face->font)
8642 - FONT_BASE(face->font)) / 2;
8643 else
8644 ascent = height / 2;
8646 else
8647 ascent = (int) (height * img->ascent / 100.0);
8649 return ascent;
8654 /* Image background colors. */
8656 /* Find the "best" corner color of a bitmap. XIMG is assumed to a device
8657 context with the bitmap selected. */
8658 static COLORREF
8659 four_corners_best (ximg, width, height)
8660 HDC ximg;
8661 unsigned long width, height;
8663 COLORREF corners[4], best;
8664 int i, best_count;
8666 /* Get the colors at the corners of ximg. */
8667 corners[0] = GetPixel (ximg, 0, 0);
8668 corners[1] = GetPixel (ximg, width - 1, 0);
8669 corners[2] = GetPixel (ximg, width - 1, height - 1);
8670 corners[3] = GetPixel (ximg, 0, height - 1);
8672 /* Choose the most frequently found color as background. */
8673 for (i = best_count = 0; i < 4; ++i)
8675 int j, n;
8677 for (j = n = 0; j < 4; ++j)
8678 if (corners[i] == corners[j])
8679 ++n;
8681 if (n > best_count)
8682 best = corners[i], best_count = n;
8685 return best;
8688 /* Return the `background' field of IMG. If IMG doesn't have one yet,
8689 it is guessed heuristically. If non-zero, XIMG is an existing XImage
8690 object to use for the heuristic. */
8692 unsigned long
8693 image_background (img, f, ximg)
8694 struct image *img;
8695 struct frame *f;
8696 XImage *ximg;
8698 if (! img->background_valid)
8699 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8701 #if 0 /* TODO: Image support. */
8702 int free_ximg = !ximg;
8704 if (! ximg)
8705 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8706 0, 0, img->width, img->height, ~0, ZPixmap);
8708 img->background = four_corners_best (ximg, img->width, img->height);
8710 if (free_ximg)
8711 XDestroyImage (ximg);
8713 img->background_valid = 1;
8714 #endif
8717 return img->background;
8720 /* Return the `background_transparent' field of IMG. If IMG doesn't
8721 have one yet, it is guessed heuristically. If non-zero, MASK is an
8722 existing XImage object to use for the heuristic. */
8725 image_background_transparent (img, f, mask)
8726 struct image *img;
8727 struct frame *f;
8728 XImage *mask;
8730 if (! img->background_transparent_valid)
8731 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8733 #if 0 /* TODO: Image support. */
8734 if (img->mask)
8736 int free_mask = !mask;
8738 if (! mask)
8739 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
8740 0, 0, img->width, img->height, ~0, ZPixmap);
8742 img->background_transparent
8743 = !four_corners_best (mask, img->width, img->height);
8745 if (free_mask)
8746 XDestroyImage (mask);
8748 else
8749 #endif
8750 img->background_transparent = 0;
8752 img->background_transparent_valid = 1;
8755 return img->background_transparent;
8759 /***********************************************************************
8760 Helper functions for X image types
8761 ***********************************************************************/
8763 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
8764 int, int));
8765 static void x_clear_image P_ ((struct frame *f, struct image *img));
8766 static unsigned long x_alloc_image_color P_ ((struct frame *f,
8767 struct image *img,
8768 Lisp_Object color_name,
8769 unsigned long dflt));
8772 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
8773 free the pixmap if any. MASK_P non-zero means clear the mask
8774 pixmap if any. COLORS_P non-zero means free colors allocated for
8775 the image, if any. */
8777 static void
8778 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
8779 struct frame *f;
8780 struct image *img;
8781 int pixmap_p, mask_p, colors_p;
8783 if (pixmap_p && img->pixmap)
8785 DeleteObject (img->pixmap);
8786 img->pixmap = NULL;
8787 img->background_valid = 0;
8790 if (mask_p && img->mask)
8792 DeleteObject (img->mask);
8793 img->mask = NULL;
8794 img->background_transparent_valid = 0;
8797 if (colors_p && img->ncolors)
8799 #if 0 /* TODO: color table support. */
8800 x_free_colors (f, img->colors, img->ncolors);
8801 #endif
8802 xfree (img->colors);
8803 img->colors = NULL;
8804 img->ncolors = 0;
8808 /* Free X resources of image IMG which is used on frame F. */
8810 static void
8811 x_clear_image (f, img)
8812 struct frame *f;
8813 struct image *img;
8815 if (img->pixmap)
8817 BLOCK_INPUT;
8818 DeleteObject (img->pixmap);
8819 img->pixmap = 0;
8820 UNBLOCK_INPUT;
8823 if (img->ncolors)
8825 #if 0 /* TODO: color table support */
8827 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8829 /* If display has an immutable color map, freeing colors is not
8830 necessary and some servers don't allow it. So don't do it. */
8831 if (class != StaticColor
8832 && class != StaticGray
8833 && class != TrueColor)
8835 Colormap cmap;
8836 BLOCK_INPUT;
8837 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8838 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8839 img->ncolors, 0);
8840 UNBLOCK_INPUT;
8842 #endif
8844 xfree (img->colors);
8845 img->colors = NULL;
8846 img->ncolors = 0;
8851 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8852 cannot be allocated, use DFLT. Add a newly allocated color to
8853 IMG->colors, so that it can be freed again. Value is the pixel
8854 color. */
8856 static unsigned long
8857 x_alloc_image_color (f, img, color_name, dflt)
8858 struct frame *f;
8859 struct image *img;
8860 Lisp_Object color_name;
8861 unsigned long dflt;
8863 XColor color;
8864 unsigned long result;
8866 xassert (STRINGP (color_name));
8868 if (w32_defined_color (f, SDATA (color_name), &color, 1))
8870 /* This isn't called frequently so we get away with simply
8871 reallocating the color vector to the needed size, here. */
8872 ++img->ncolors;
8873 img->colors =
8874 (unsigned long *) xrealloc (img->colors,
8875 img->ncolors * sizeof *img->colors);
8876 img->colors[img->ncolors - 1] = color.pixel;
8877 result = color.pixel;
8879 else
8880 result = dflt;
8881 return result;
8886 /***********************************************************************
8887 Image Cache
8888 ***********************************************************************/
8890 static void cache_image P_ ((struct frame *f, struct image *img));
8891 static void postprocess_image P_ ((struct frame *, struct image *));
8894 /* Return a new, initialized image cache that is allocated from the
8895 heap. Call free_image_cache to free an image cache. */
8897 struct image_cache *
8898 make_image_cache ()
8900 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8901 int size;
8903 bzero (c, sizeof *c);
8904 c->size = 50;
8905 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8906 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8907 c->buckets = (struct image **) xmalloc (size);
8908 bzero (c->buckets, size);
8909 return c;
8913 /* Free image cache of frame F. Be aware that X frames share images
8914 caches. */
8916 void
8917 free_image_cache (f)
8918 struct frame *f;
8920 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8921 if (c)
8923 int i;
8925 /* Cache should not be referenced by any frame when freed. */
8926 xassert (c->refcount == 0);
8928 for (i = 0; i < c->used; ++i)
8929 free_image (f, c->images[i]);
8930 xfree (c->images);
8931 xfree (c);
8932 xfree (c->buckets);
8933 FRAME_X_IMAGE_CACHE (f) = NULL;
8938 /* Clear image cache of frame F. FORCE_P non-zero means free all
8939 images. FORCE_P zero means clear only images that haven't been
8940 displayed for some time. Should be called from time to time to
8941 reduce the number of loaded images. If image-eviction-seconds is
8942 non-nil, this frees images in the cache which weren't displayed for
8943 at least that many seconds. */
8945 void
8946 clear_image_cache (f, force_p)
8947 struct frame *f;
8948 int force_p;
8950 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8952 if (c && INTEGERP (Vimage_cache_eviction_delay))
8954 EMACS_TIME t;
8955 unsigned long old;
8956 int i, nfreed;
8958 EMACS_GET_TIME (t);
8959 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8961 /* Block input so that we won't be interrupted by a SIGIO
8962 while being in an inconsistent state. */
8963 BLOCK_INPUT;
8965 for (i = nfreed = 0; i < c->used; ++i)
8967 struct image *img = c->images[i];
8968 if (img != NULL
8969 && (force_p || (img->timestamp < old)))
8971 free_image (f, img);
8972 ++nfreed;
8976 /* We may be clearing the image cache because, for example,
8977 Emacs was iconified for a longer period of time. In that
8978 case, current matrices may still contain references to
8979 images freed above. So, clear these matrices. */
8980 if (nfreed)
8982 Lisp_Object tail, frame;
8984 FOR_EACH_FRAME (tail, frame)
8986 struct frame *f = XFRAME (frame);
8987 if (FRAME_W32_P (f)
8988 && FRAME_X_IMAGE_CACHE (f) == c)
8989 clear_current_matrices (f);
8992 ++windows_or_buffers_changed;
8995 UNBLOCK_INPUT;
9000 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
9001 0, 1, 0,
9002 doc: /* Clear the image cache of FRAME.
9003 FRAME nil or omitted means use the selected frame.
9004 FRAME t means clear the image caches of all frames. */)
9005 (frame)
9006 Lisp_Object frame;
9008 if (EQ (frame, Qt))
9010 Lisp_Object tail;
9012 FOR_EACH_FRAME (tail, frame)
9013 if (FRAME_W32_P (XFRAME (frame)))
9014 clear_image_cache (XFRAME (frame), 1);
9016 else
9017 clear_image_cache (check_x_frame (frame), 1);
9019 return Qnil;
9023 /* Compute masks and transform image IMG on frame F, as specified
9024 by the image's specification, */
9026 static void
9027 postprocess_image (f, img)
9028 struct frame *f;
9029 struct image *img;
9031 #if 0 /* TODO: image support. */
9032 /* Manipulation of the image's mask. */
9033 if (img->pixmap)
9035 Lisp_Object conversion, spec;
9036 Lisp_Object mask;
9038 spec = img->spec;
9040 /* `:heuristic-mask t'
9041 `:mask heuristic'
9042 means build a mask heuristically.
9043 `:heuristic-mask (R G B)'
9044 `:mask (heuristic (R G B))'
9045 means build a mask from color (R G B) in the
9046 image.
9047 `:mask nil'
9048 means remove a mask, if any. */
9050 mask = image_spec_value (spec, QCheuristic_mask, NULL);
9051 if (!NILP (mask))
9052 x_build_heuristic_mask (f, img, mask);
9053 else
9055 int found_p;
9057 mask = image_spec_value (spec, QCmask, &found_p);
9059 if (EQ (mask, Qheuristic))
9060 x_build_heuristic_mask (f, img, Qt);
9061 else if (CONSP (mask)
9062 && EQ (XCAR (mask), Qheuristic))
9064 if (CONSP (XCDR (mask)))
9065 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
9066 else
9067 x_build_heuristic_mask (f, img, XCDR (mask));
9069 else if (NILP (mask) && found_p && img->mask)
9071 DeleteObject (img->mask);
9072 img->mask = NULL;
9077 /* Should we apply an image transformation algorithm? */
9078 conversion = image_spec_value (spec, QCconversion, NULL);
9079 if (EQ (conversion, Qdisabled))
9080 x_disable_image (f, img);
9081 else if (EQ (conversion, Qlaplace))
9082 x_laplace (f, img);
9083 else if (EQ (conversion, Qemboss))
9084 x_emboss (f, img);
9085 else if (CONSP (conversion)
9086 && EQ (XCAR (conversion), Qedge_detection))
9088 Lisp_Object tem;
9089 tem = XCDR (conversion);
9090 if (CONSP (tem))
9091 x_edge_detection (f, img,
9092 Fplist_get (tem, QCmatrix),
9093 Fplist_get (tem, QCcolor_adjustment));
9096 #endif
9100 /* Return the id of image with Lisp specification SPEC on frame F.
9101 SPEC must be a valid Lisp image specification (see valid_image_p). */
9104 lookup_image (f, spec)
9105 struct frame *f;
9106 Lisp_Object spec;
9108 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9109 struct image *img;
9110 int i;
9111 unsigned hash;
9112 struct gcpro gcpro1;
9113 EMACS_TIME now;
9115 /* F must be a window-system frame, and SPEC must be a valid image
9116 specification. */
9117 xassert (FRAME_WINDOW_P (f));
9118 xassert (valid_image_p (spec));
9120 GCPRO1 (spec);
9122 /* Look up SPEC in the hash table of the image cache. */
9123 hash = sxhash (spec, 0);
9124 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
9126 for (img = c->buckets[i]; img; img = img->next)
9127 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
9128 break;
9130 /* If not found, create a new image and cache it. */
9131 if (img == NULL)
9133 extern Lisp_Object Qpostscript;
9135 BLOCK_INPUT;
9136 img = make_image (spec, hash);
9137 cache_image (f, img);
9138 img->load_failed_p = img->type->load (f, img) == 0;
9140 /* If we can't load the image, and we don't have a width and
9141 height, use some arbitrary width and height so that we can
9142 draw a rectangle for it. */
9143 if (img->load_failed_p)
9145 Lisp_Object value;
9147 value = image_spec_value (spec, QCwidth, NULL);
9148 img->width = (INTEGERP (value)
9149 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
9150 value = image_spec_value (spec, QCheight, NULL);
9151 img->height = (INTEGERP (value)
9152 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
9154 else
9156 /* Handle image type independent image attributes
9157 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF',
9158 `:background COLOR'. */
9159 Lisp_Object ascent, margin, relief, bg;
9161 ascent = image_spec_value (spec, QCascent, NULL);
9162 if (INTEGERP (ascent))
9163 img->ascent = XFASTINT (ascent);
9164 else if (EQ (ascent, Qcenter))
9165 img->ascent = CENTERED_IMAGE_ASCENT;
9167 margin = image_spec_value (spec, QCmargin, NULL);
9168 if (INTEGERP (margin) && XINT (margin) >= 0)
9169 img->vmargin = img->hmargin = XFASTINT (margin);
9170 else if (CONSP (margin) && INTEGERP (XCAR (margin))
9171 && INTEGERP (XCDR (margin)))
9173 if (XINT (XCAR (margin)) > 0)
9174 img->hmargin = XFASTINT (XCAR (margin));
9175 if (XINT (XCDR (margin)) > 0)
9176 img->vmargin = XFASTINT (XCDR (margin));
9179 relief = image_spec_value (spec, QCrelief, NULL);
9180 if (INTEGERP (relief))
9182 img->relief = XINT (relief);
9183 img->hmargin += abs (img->relief);
9184 img->vmargin += abs (img->relief);
9187 if (! img->background_valid)
9189 bg = image_spec_value (img->spec, QCbackground, NULL);
9190 if (!NILP (bg))
9192 img->background
9193 = x_alloc_image_color (f, img, bg,
9194 FRAME_BACKGROUND_PIXEL (f));
9195 img->background_valid = 1;
9199 /* Do image transformations and compute masks, unless we
9200 don't have the image yet. */
9201 if (!EQ (*img->type->type, Qpostscript))
9202 postprocess_image (f, img);
9205 UNBLOCK_INPUT;
9206 xassert (!interrupt_input_blocked);
9209 /* We're using IMG, so set its timestamp to `now'. */
9210 EMACS_GET_TIME (now);
9211 img->timestamp = EMACS_SECS (now);
9213 UNGCPRO;
9215 /* Value is the image id. */
9216 return img->id;
9220 /* Cache image IMG in the image cache of frame F. */
9222 static void
9223 cache_image (f, img)
9224 struct frame *f;
9225 struct image *img;
9227 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9228 int i;
9230 /* Find a free slot in c->images. */
9231 for (i = 0; i < c->used; ++i)
9232 if (c->images[i] == NULL)
9233 break;
9235 /* If no free slot found, maybe enlarge c->images. */
9236 if (i == c->used && c->used == c->size)
9238 c->size *= 2;
9239 c->images = (struct image **) xrealloc (c->images,
9240 c->size * sizeof *c->images);
9243 /* Add IMG to c->images, and assign IMG an id. */
9244 c->images[i] = img;
9245 img->id = i;
9246 if (i == c->used)
9247 ++c->used;
9249 /* Add IMG to the cache's hash table. */
9250 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
9251 img->next = c->buckets[i];
9252 if (img->next)
9253 img->next->prev = img;
9254 img->prev = NULL;
9255 c->buckets[i] = img;
9259 /* Call FN on every image in the image cache of frame F. Used to mark
9260 Lisp Objects in the image cache. */
9262 void
9263 forall_images_in_image_cache (f, fn)
9264 struct frame *f;
9265 void (*fn) P_ ((struct image *img));
9267 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
9269 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9270 if (c)
9272 int i;
9273 for (i = 0; i < c->used; ++i)
9274 if (c->images[i])
9275 fn (c->images[i]);
9282 /***********************************************************************
9283 W32 support code
9284 ***********************************************************************/
9286 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
9287 XImage **, Pixmap *));
9288 static void x_destroy_x_image P_ ((XImage *));
9289 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
9292 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
9293 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
9294 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
9295 via xmalloc. DEPTH of zero signifies a 24 bit image, otherwise
9296 DEPTH should indicate the bit depth of the image. Print error
9297 messages via image_error if an error occurs. Value is non-zero if
9298 successful. */
9300 static int
9301 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
9302 struct frame *f;
9303 int width, height, depth;
9304 XImage **ximg;
9305 Pixmap *pixmap;
9307 BITMAPINFOHEADER *header;
9308 HDC hdc;
9309 int scanline_width_bits;
9310 int remainder;
9311 int palette_colors = 0;
9313 if (depth == 0)
9314 depth = 24;
9316 if (depth != 1 && depth != 4 && depth != 8
9317 && depth != 16 && depth != 24 && depth != 32)
9319 image_error ("Invalid image bit depth specified", Qnil, Qnil);
9320 return 0;
9323 scanline_width_bits = width * depth;
9324 remainder = scanline_width_bits % 32;
9326 if (remainder)
9327 scanline_width_bits += 32 - remainder;
9329 /* Bitmaps with a depth less than 16 need a palette. */
9330 /* BITMAPINFO structure already contains the first RGBQUAD. */
9331 if (depth < 16)
9332 palette_colors = 1 << depth - 1;
9334 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
9335 if (*ximg == NULL)
9337 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
9338 return 0;
9341 header = &((*ximg)->info.bmiHeader);
9342 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
9343 header->biSize = sizeof (*header);
9344 header->biWidth = width;
9345 header->biHeight = -height; /* negative indicates a top-down bitmap. */
9346 header->biPlanes = 1;
9347 header->biBitCount = depth;
9348 header->biCompression = BI_RGB;
9349 header->biClrUsed = palette_colors;
9351 hdc = get_frame_dc (f);
9353 /* Create a DIBSection and raster array for the bitmap,
9354 and store its handle in *pixmap. */
9355 *pixmap = CreateDIBSection (hdc, &((*ximg)->info), DIB_RGB_COLORS,
9356 &((*ximg)->data), NULL, 0);
9358 /* Realize display palette and garbage all frames. */
9359 release_frame_dc (f, hdc);
9361 if (*pixmap == NULL)
9363 DWORD err = GetLastError();
9364 Lisp_Object errcode;
9365 /* All system errors are < 10000, so the following is safe. */
9366 XSETINT (errcode, (int) err);
9367 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
9368 x_destroy_x_image (*ximg);
9369 return 0;
9372 return 1;
9376 /* Destroy XImage XIMG. Free XIMG->data. */
9378 static void
9379 x_destroy_x_image (ximg)
9380 XImage *ximg;
9382 xassert (interrupt_input_blocked);
9383 if (ximg)
9385 /* Data will be freed by DestroyObject. */
9386 ximg->data = NULL;
9387 xfree (ximg);
9392 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
9393 are width and height of both the image and pixmap. */
9395 static void
9396 x_put_x_image (f, ximg, pixmap, width, height)
9397 struct frame *f;
9398 XImage *ximg;
9399 Pixmap pixmap;
9402 #if TODO /* W32 specific image code. */
9403 GC gc;
9405 xassert (interrupt_input_blocked);
9406 gc = XCreateGC (NULL, pixmap, 0, NULL);
9407 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
9408 XFreeGC (NULL, gc);
9409 #endif
9413 /***********************************************************************
9414 File Handling
9415 ***********************************************************************/
9417 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
9418 static char *slurp_file P_ ((char *, int *));
9421 /* Find image file FILE. Look in data-directory, then
9422 x-bitmap-file-path. Value is the full name of the file found, or
9423 nil if not found. */
9425 static Lisp_Object
9426 x_find_image_file (file)
9427 Lisp_Object file;
9429 Lisp_Object file_found, search_path;
9430 struct gcpro gcpro1, gcpro2;
9431 int fd;
9433 file_found = Qnil;
9434 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
9435 GCPRO2 (file_found, search_path);
9437 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
9438 fd = openp (search_path, file, Qnil, &file_found, Qnil);
9440 if (fd == -1)
9441 file_found = Qnil;
9442 else
9443 close (fd);
9445 UNGCPRO;
9446 return file_found;
9450 /* Read FILE into memory. Value is a pointer to a buffer allocated
9451 with xmalloc holding FILE's contents. Value is null if an error
9452 occurred. *SIZE is set to the size of the file. */
9454 static char *
9455 slurp_file (file, size)
9456 char *file;
9457 int *size;
9459 FILE *fp = NULL;
9460 char *buf = NULL;
9461 struct stat st;
9463 if (stat (file, &st) == 0
9464 && (fp = fopen (file, "r")) != NULL
9465 && (buf = (char *) xmalloc (st.st_size),
9466 fread (buf, 1, st.st_size, fp) == st.st_size))
9468 *size = st.st_size;
9469 fclose (fp);
9471 else
9473 if (fp)
9474 fclose (fp);
9475 if (buf)
9477 xfree (buf);
9478 buf = NULL;
9482 return buf;
9487 /***********************************************************************
9488 XBM images
9489 ***********************************************************************/
9491 static int xbm_scan P_ ((char **, char *, char *, int *));
9492 static int xbm_load P_ ((struct frame *f, struct image *img));
9493 static int xbm_load_image P_ ((struct frame *f, struct image *img,
9494 char *, char *));
9495 static int xbm_image_p P_ ((Lisp_Object object));
9496 static int xbm_read_bitmap_data P_ ((char *, char *, int *, int *,
9497 unsigned char **));
9498 static int xbm_file_p P_ ((Lisp_Object));
9501 /* Indices of image specification fields in xbm_format, below. */
9503 enum xbm_keyword_index
9505 XBM_TYPE,
9506 XBM_FILE,
9507 XBM_WIDTH,
9508 XBM_HEIGHT,
9509 XBM_DATA,
9510 XBM_FOREGROUND,
9511 XBM_BACKGROUND,
9512 XBM_ASCENT,
9513 XBM_MARGIN,
9514 XBM_RELIEF,
9515 XBM_ALGORITHM,
9516 XBM_HEURISTIC_MASK,
9517 XBM_MASK,
9518 XBM_LAST
9521 /* Vector of image_keyword structures describing the format
9522 of valid XBM image specifications. */
9524 static struct image_keyword xbm_format[XBM_LAST] =
9526 {":type", IMAGE_SYMBOL_VALUE, 1},
9527 {":file", IMAGE_STRING_VALUE, 0},
9528 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9529 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9530 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9531 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
9532 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
9533 {":ascent", IMAGE_ASCENT_VALUE, 0},
9534 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9535 {":relief", IMAGE_INTEGER_VALUE, 0},
9536 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9537 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9538 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9541 /* Structure describing the image type XBM. */
9543 static struct image_type xbm_type =
9545 &Qxbm,
9546 xbm_image_p,
9547 xbm_load,
9548 x_clear_image,
9549 NULL
9552 /* Tokens returned from xbm_scan. */
9554 enum xbm_token
9556 XBM_TK_IDENT = 256,
9557 XBM_TK_NUMBER
9561 /* Return non-zero if OBJECT is a valid XBM-type image specification.
9562 A valid specification is a list starting with the symbol `image'
9563 The rest of the list is a property list which must contain an
9564 entry `:type xbm..
9566 If the specification specifies a file to load, it must contain
9567 an entry `:file FILENAME' where FILENAME is a string.
9569 If the specification is for a bitmap loaded from memory it must
9570 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
9571 WIDTH and HEIGHT are integers > 0. DATA may be:
9573 1. a string large enough to hold the bitmap data, i.e. it must
9574 have a size >= (WIDTH + 7) / 8 * HEIGHT
9576 2. a bool-vector of size >= WIDTH * HEIGHT
9578 3. a vector of strings or bool-vectors, one for each line of the
9579 bitmap.
9581 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
9582 may not be specified in this case because they are defined in the
9583 XBM file.
9585 Both the file and data forms may contain the additional entries
9586 `:background COLOR' and `:foreground COLOR'. If not present,
9587 foreground and background of the frame on which the image is
9588 displayed is used. */
9590 static int
9591 xbm_image_p (object)
9592 Lisp_Object object;
9594 struct image_keyword kw[XBM_LAST];
9596 bcopy (xbm_format, kw, sizeof kw);
9597 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
9598 return 0;
9600 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
9602 if (kw[XBM_FILE].count)
9604 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
9605 return 0;
9607 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
9609 /* In-memory XBM file. */
9610 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
9611 return 0;
9613 else
9615 Lisp_Object data;
9616 int width, height;
9618 /* Entries for `:width', `:height' and `:data' must be present. */
9619 if (!kw[XBM_WIDTH].count
9620 || !kw[XBM_HEIGHT].count
9621 || !kw[XBM_DATA].count)
9622 return 0;
9624 data = kw[XBM_DATA].value;
9625 width = XFASTINT (kw[XBM_WIDTH].value);
9626 height = XFASTINT (kw[XBM_HEIGHT].value);
9628 /* Check type of data, and width and height against contents of
9629 data. */
9630 if (VECTORP (data))
9632 int i;
9634 /* Number of elements of the vector must be >= height. */
9635 if (XVECTOR (data)->size < height)
9636 return 0;
9638 /* Each string or bool-vector in data must be large enough
9639 for one line of the image. */
9640 for (i = 0; i < height; ++i)
9642 Lisp_Object elt = XVECTOR (data)->contents[i];
9644 if (STRINGP (elt))
9646 if (SCHARS (elt)
9647 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
9648 return 0;
9650 else if (BOOL_VECTOR_P (elt))
9652 if (XBOOL_VECTOR (elt)->size < width)
9653 return 0;
9655 else
9656 return 0;
9659 else if (STRINGP (data))
9661 if (SCHARS (data)
9662 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
9663 return 0;
9665 else if (BOOL_VECTOR_P (data))
9667 if (XBOOL_VECTOR (data)->size < width * height)
9668 return 0;
9670 else
9671 return 0;
9674 return 1;
9678 /* Scan a bitmap file. FP is the stream to read from. Value is
9679 either an enumerator from enum xbm_token, or a character for a
9680 single-character token, or 0 at end of file. If scanning an
9681 identifier, store the lexeme of the identifier in SVAL. If
9682 scanning a number, store its value in *IVAL. */
9684 static int
9685 xbm_scan (s, end, sval, ival)
9686 char **s, *end;
9687 char *sval;
9688 int *ival;
9690 int c;
9692 loop:
9694 /* Skip white space. */
9695 while (*s < end && (c = *(*s)++, isspace (c)))
9698 if (*s >= end)
9699 c = 0;
9700 else if (isdigit (c))
9702 int value = 0, digit;
9704 if (c == '0' && *s < end)
9706 c = *(*s)++;
9707 if (c == 'x' || c == 'X')
9709 while (*s < end)
9711 c = *(*s)++;
9712 if (isdigit (c))
9713 digit = c - '0';
9714 else if (c >= 'a' && c <= 'f')
9715 digit = c - 'a' + 10;
9716 else if (c >= 'A' && c <= 'F')
9717 digit = c - 'A' + 10;
9718 else
9719 break;
9720 value = 16 * value + digit;
9723 else if (isdigit (c))
9725 value = c - '0';
9726 while (*s < end
9727 && (c = *(*s)++, isdigit (c)))
9728 value = 8 * value + c - '0';
9731 else
9733 value = c - '0';
9734 while (*s < end
9735 && (c = *(*s)++, isdigit (c)))
9736 value = 10 * value + c - '0';
9739 if (*s < end)
9740 *s = *s - 1;
9741 *ival = value;
9742 c = XBM_TK_NUMBER;
9744 else if (isalpha (c) || c == '_')
9746 *sval++ = c;
9747 while (*s < end
9748 && (c = *(*s)++, (isalnum (c) || c == '_')))
9749 *sval++ = c;
9750 *sval = 0;
9751 if (*s < end)
9752 *s = *s - 1;
9753 c = XBM_TK_IDENT;
9755 else if (c == '/' && **s == '*')
9757 /* C-style comment. */
9758 ++*s;
9759 while (**s && (**s != '*' || *(*s + 1) != '/'))
9760 ++*s;
9761 if (**s)
9763 *s += 2;
9764 goto loop;
9768 return c;
9772 /* XBM bits seem to be backward within bytes compared with how
9773 Windows does things. */
9774 static unsigned char reflect_byte (unsigned char orig)
9776 int i;
9777 unsigned char reflected = 0x00;
9778 for (i = 0; i < 8; i++)
9780 if (orig & (0x01 << i))
9781 reflected |= 0x80 >> i;
9783 return reflected;
9787 /* Create a Windows bitmap from X bitmap data. */
9788 static HBITMAP
9789 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
9791 int i, j, w1, w2;
9792 char *bits, *p;
9793 HBITMAP bmp;
9795 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
9796 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
9797 bits = (char *) xmalloc (height * w2);
9798 bzero (bits, height * w2);
9799 for (i = 0; i < height; i++)
9801 p = bits + i*w2;
9802 for (j = 0; j < w1; j++)
9803 *p++ = reflect_byte(*data++);
9805 bmp = CreateBitmap (width, height, 1, 1, bits);
9806 xfree (bits);
9808 return bmp;
9812 /* Replacement for XReadBitmapFileData which isn't available under old
9813 X versions. CONTENTS is a pointer to a buffer to parse; END is the
9814 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
9815 the image. Return in *DATA the bitmap data allocated with xmalloc.
9816 Value is non-zero if successful. DATA null means just test if
9817 CONTENTS looks like an in-memory XBM file. */
9819 static int
9820 xbm_read_bitmap_data (contents, end, width, height, data)
9821 char *contents, *end;
9822 int *width, *height;
9823 unsigned char **data;
9825 char *s = contents;
9826 char buffer[BUFSIZ];
9827 int padding_p = 0;
9828 int v10 = 0;
9829 int bytes_per_line, i, nbytes;
9830 unsigned char *p;
9831 int value;
9832 int LA1;
9834 #define match() \
9835 LA1 = xbm_scan (&s, end, buffer, &value)
9837 #define expect(TOKEN) \
9838 if (LA1 != (TOKEN)) \
9839 goto failure; \
9840 else \
9841 match ()
9843 #define expect_ident(IDENT) \
9844 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
9845 match (); \
9846 else \
9847 goto failure
9849 *width = *height = -1;
9850 if (data)
9851 *data = NULL;
9852 LA1 = xbm_scan (&s, end, buffer, &value);
9854 /* Parse defines for width, height and hot-spots. */
9855 while (LA1 == '#')
9857 match ();
9858 expect_ident ("define");
9859 expect (XBM_TK_IDENT);
9861 if (LA1 == XBM_TK_NUMBER);
9863 char *p = strrchr (buffer, '_');
9864 p = p ? p + 1 : buffer;
9865 if (strcmp (p, "width") == 0)
9866 *width = value;
9867 else if (strcmp (p, "height") == 0)
9868 *height = value;
9870 expect (XBM_TK_NUMBER);
9873 if (*width < 0 || *height < 0)
9874 goto failure;
9875 else if (data == NULL)
9876 goto success;
9878 /* Parse bits. Must start with `static'. */
9879 expect_ident ("static");
9880 if (LA1 == XBM_TK_IDENT)
9882 if (strcmp (buffer, "unsigned") == 0)
9884 match ();
9885 expect_ident ("char");
9887 else if (strcmp (buffer, "short") == 0)
9889 match ();
9890 v10 = 1;
9891 if (*width % 16 && *width % 16 < 9)
9892 padding_p = 1;
9894 else if (strcmp (buffer, "char") == 0)
9895 match ();
9896 else
9897 goto failure;
9899 else
9900 goto failure;
9902 expect (XBM_TK_IDENT);
9903 expect ('[');
9904 expect (']');
9905 expect ('=');
9906 expect ('{');
9908 bytes_per_line = (*width + 7) / 8 + padding_p;
9909 nbytes = bytes_per_line * *height;
9910 p = *data = (char *) xmalloc (nbytes);
9912 if (v10)
9914 for (i = 0; i < nbytes; i += 2)
9916 int val = value;
9917 expect (XBM_TK_NUMBER);
9919 *p++ = val;
9920 if (!padding_p || ((i + 2) % bytes_per_line))
9921 *p++ = value >> 8;
9923 if (LA1 == ',' || LA1 == '}')
9924 match ();
9925 else
9926 goto failure;
9929 else
9931 for (i = 0; i < nbytes; ++i)
9933 int val = value;
9934 expect (XBM_TK_NUMBER);
9936 *p++ = val;
9938 if (LA1 == ',' || LA1 == '}')
9939 match ();
9940 else
9941 goto failure;
9945 success:
9946 return 1;
9948 failure:
9950 if (data && *data)
9952 xfree (*data);
9953 *data = NULL;
9955 return 0;
9957 #undef match
9958 #undef expect
9959 #undef expect_ident
9963 /* Load XBM image IMG which will be displayed on frame F from buffer
9964 CONTENTS. END is the end of the buffer. Value is non-zero if
9965 successful. */
9967 static int
9968 xbm_load_image (f, img, contents, end)
9969 struct frame *f;
9970 struct image *img;
9971 char *contents, *end;
9973 int rc;
9974 unsigned char *data;
9975 int success_p = 0;
9977 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
9978 if (rc)
9980 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9981 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9982 Lisp_Object value;
9984 xassert (img->width > 0 && img->height > 0);
9986 /* Get foreground and background colors, maybe allocate colors. */
9987 value = image_spec_value (img->spec, QCforeground, NULL);
9988 if (!NILP (value))
9989 foreground = x_alloc_image_color (f, img, value, foreground);
9990 value = image_spec_value (img->spec, QCbackground, NULL);
9991 if (!NILP (value))
9993 background = x_alloc_image_color (f, img, value, background);
9994 img->background = background;
9995 img->background_valid = 1;
9997 img->pixmap
9998 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
10000 xfree (data);
10002 if (img->pixmap == 0)
10004 x_clear_image (f, img);
10005 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
10007 else
10008 success_p = 1;
10010 else
10011 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10013 return success_p;
10017 /* Value is non-zero if DATA looks like an in-memory XBM file. */
10019 static int
10020 xbm_file_p (data)
10021 Lisp_Object data;
10023 int w, h;
10024 return (STRINGP (data)
10025 && xbm_read_bitmap_data (SDATA (data),
10026 (SDATA (data)
10027 + SBYTES (data)),
10028 &w, &h, NULL));
10032 /* Fill image IMG which is used on frame F with pixmap data. Value is
10033 non-zero if successful. */
10035 static int
10036 xbm_load (f, img)
10037 struct frame *f;
10038 struct image *img;
10040 int success_p = 0;
10041 Lisp_Object file_name;
10043 xassert (xbm_image_p (img->spec));
10045 /* If IMG->spec specifies a file name, create a non-file spec from it. */
10046 file_name = image_spec_value (img->spec, QCfile, NULL);
10047 if (STRINGP (file_name))
10049 Lisp_Object file;
10050 char *contents;
10051 int size;
10052 struct gcpro gcpro1;
10054 file = x_find_image_file (file_name);
10055 GCPRO1 (file);
10056 if (!STRINGP (file))
10058 image_error ("Cannot find image file `%s'", file_name, Qnil);
10059 UNGCPRO;
10060 return 0;
10063 contents = slurp_file (SDATA (file), &size);
10064 if (contents == NULL)
10066 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10067 UNGCPRO;
10068 return 0;
10071 success_p = xbm_load_image (f, img, contents, contents + size);
10072 UNGCPRO;
10074 else
10076 struct image_keyword fmt[XBM_LAST];
10077 Lisp_Object data;
10078 int depth;
10079 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
10080 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
10081 char *bits;
10082 int parsed_p;
10083 int in_memory_file_p = 0;
10085 /* See if data looks like an in-memory XBM file. */
10086 data = image_spec_value (img->spec, QCdata, NULL);
10087 in_memory_file_p = xbm_file_p (data);
10089 /* Parse the image specification. */
10090 bcopy (xbm_format, fmt, sizeof fmt);
10091 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
10092 xassert (parsed_p);
10094 /* Get specified width, and height. */
10095 if (!in_memory_file_p)
10097 img->width = XFASTINT (fmt[XBM_WIDTH].value);
10098 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
10099 xassert (img->width > 0 && img->height > 0);
10102 /* Get foreground and background colors, maybe allocate colors. */
10103 if (fmt[XBM_FOREGROUND].count
10104 && STRINGP (fmt[XBM_FOREGROUND].value))
10105 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
10106 foreground);
10107 if (fmt[XBM_BACKGROUND].count
10108 && STRINGP (fmt[XBM_BACKGROUND].value))
10109 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
10110 background);
10112 if (in_memory_file_p)
10113 success_p = xbm_load_image (f, img, SDATA (data),
10114 (SDATA (data)
10115 + SBYTES (data)));
10116 else
10118 if (VECTORP (data))
10120 int i;
10121 char *p;
10122 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
10124 p = bits = (char *) alloca (nbytes * img->height);
10125 for (i = 0; i < img->height; ++i, p += nbytes)
10127 Lisp_Object line = XVECTOR (data)->contents[i];
10128 if (STRINGP (line))
10129 bcopy (SDATA (line), p, nbytes);
10130 else
10131 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
10134 else if (STRINGP (data))
10135 bits = SDATA (data);
10136 else
10137 bits = XBOOL_VECTOR (data)->data;
10139 /* Create the pixmap. */
10140 depth = one_w32_display_info.n_cbits;
10141 img->pixmap
10142 = w32_create_pixmap_from_bitmap_data (img->width, img->height,
10143 bits);
10145 if (img->pixmap)
10146 success_p = 1;
10147 else
10149 image_error ("Unable to create pixmap for XBM image `%s'",
10150 img->spec, Qnil);
10151 x_clear_image (f, img);
10156 return success_p;
10161 /***********************************************************************
10162 XPM images
10163 ***********************************************************************/
10165 #if HAVE_XPM
10167 static int xpm_image_p P_ ((Lisp_Object object));
10168 static int xpm_load P_ ((struct frame *f, struct image *img));
10169 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
10171 #include "X11/xpm.h"
10173 /* The symbol `xpm' identifying XPM-format images. */
10175 Lisp_Object Qxpm;
10177 /* Indices of image specification fields in xpm_format, below. */
10179 enum xpm_keyword_index
10181 XPM_TYPE,
10182 XPM_FILE,
10183 XPM_DATA,
10184 XPM_ASCENT,
10185 XPM_MARGIN,
10186 XPM_RELIEF,
10187 XPM_ALGORITHM,
10188 XPM_HEURISTIC_MASK,
10189 XPM_MASK,
10190 XPM_COLOR_SYMBOLS,
10191 XPM_BACKGROUND,
10192 XPM_LAST
10195 /* Vector of image_keyword structures describing the format
10196 of valid XPM image specifications. */
10198 static struct image_keyword xpm_format[XPM_LAST] =
10200 {":type", IMAGE_SYMBOL_VALUE, 1},
10201 {":file", IMAGE_STRING_VALUE, 0},
10202 {":data", IMAGE_STRING_VALUE, 0},
10203 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10204 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10205 {":relief", IMAGE_INTEGER_VALUE, 0},
10206 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10207 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10208 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10209 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10210 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
10213 /* Structure describing the image type XBM. */
10215 static struct image_type xpm_type =
10217 &Qxpm,
10218 xpm_image_p,
10219 xpm_load,
10220 x_clear_image,
10221 NULL
10225 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
10226 for XPM images. Such a list must consist of conses whose car and
10227 cdr are strings. */
10229 static int
10230 xpm_valid_color_symbols_p (color_symbols)
10231 Lisp_Object color_symbols;
10233 while (CONSP (color_symbols))
10235 Lisp_Object sym = XCAR (color_symbols);
10236 if (!CONSP (sym)
10237 || !STRINGP (XCAR (sym))
10238 || !STRINGP (XCDR (sym)))
10239 break;
10240 color_symbols = XCDR (color_symbols);
10243 return NILP (color_symbols);
10247 /* Value is non-zero if OBJECT is a valid XPM image specification. */
10249 static int
10250 xpm_image_p (object)
10251 Lisp_Object object;
10253 struct image_keyword fmt[XPM_LAST];
10254 bcopy (xpm_format, fmt, sizeof fmt);
10255 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
10256 /* Either `:file' or `:data' must be present. */
10257 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
10258 /* Either no `:color-symbols' or it's a list of conses
10259 whose car and cdr are strings. */
10260 && (fmt[XPM_COLOR_SYMBOLS].count == 0
10261 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
10262 && (fmt[XPM_ASCENT].count == 0
10263 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
10267 /* Load image IMG which will be displayed on frame F. Value is
10268 non-zero if successful. */
10270 static int
10271 xpm_load (f, img)
10272 struct frame *f;
10273 struct image *img;
10275 int rc, i;
10276 XpmAttributes attrs;
10277 Lisp_Object specified_file, color_symbols;
10279 /* Configure the XPM lib. Use the visual of frame F. Allocate
10280 close colors. Return colors allocated. */
10281 bzero (&attrs, sizeof attrs);
10282 attrs.visual = FRAME_X_VISUAL (f);
10283 attrs.colormap = FRAME_X_COLORMAP (f);
10284 attrs.valuemask |= XpmVisual;
10285 attrs.valuemask |= XpmColormap;
10286 attrs.valuemask |= XpmReturnAllocPixels;
10287 #ifdef XpmAllocCloseColors
10288 attrs.alloc_close_colors = 1;
10289 attrs.valuemask |= XpmAllocCloseColors;
10290 #else
10291 attrs.closeness = 600;
10292 attrs.valuemask |= XpmCloseness;
10293 #endif
10295 /* If image specification contains symbolic color definitions, add
10296 these to `attrs'. */
10297 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
10298 if (CONSP (color_symbols))
10300 Lisp_Object tail;
10301 XpmColorSymbol *xpm_syms;
10302 int i, size;
10304 attrs.valuemask |= XpmColorSymbols;
10306 /* Count number of symbols. */
10307 attrs.numsymbols = 0;
10308 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
10309 ++attrs.numsymbols;
10311 /* Allocate an XpmColorSymbol array. */
10312 size = attrs.numsymbols * sizeof *xpm_syms;
10313 xpm_syms = (XpmColorSymbol *) alloca (size);
10314 bzero (xpm_syms, size);
10315 attrs.colorsymbols = xpm_syms;
10317 /* Fill the color symbol array. */
10318 for (tail = color_symbols, i = 0;
10319 CONSP (tail);
10320 ++i, tail = XCDR (tail))
10322 Lisp_Object name = XCAR (XCAR (tail));
10323 Lisp_Object color = XCDR (XCAR (tail));
10324 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
10325 strcpy (xpm_syms[i].name, SDATA (name));
10326 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
10327 strcpy (xpm_syms[i].value, SDATA (color));
10331 /* Create a pixmap for the image, either from a file, or from a
10332 string buffer containing data in the same format as an XPM file. */
10333 BLOCK_INPUT;
10334 specified_file = image_spec_value (img->spec, QCfile, NULL);
10335 if (STRINGP (specified_file))
10337 Lisp_Object file = x_find_image_file (specified_file);
10338 if (!STRINGP (file))
10340 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10341 UNBLOCK_INPUT;
10342 return 0;
10345 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
10346 SDATA (file), &img->pixmap, &img->mask,
10347 &attrs);
10349 else
10351 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
10352 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
10353 SDATA (buffer),
10354 &img->pixmap, &img->mask,
10355 &attrs);
10357 UNBLOCK_INPUT;
10359 if (rc == XpmSuccess)
10361 /* Remember allocated colors. */
10362 img->ncolors = attrs.nalloc_pixels;
10363 img->colors = (unsigned long *) xmalloc (img->ncolors
10364 * sizeof *img->colors);
10365 for (i = 0; i < attrs.nalloc_pixels; ++i)
10366 img->colors[i] = attrs.alloc_pixels[i];
10368 img->width = attrs.width;
10369 img->height = attrs.height;
10370 xassert (img->width > 0 && img->height > 0);
10372 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
10373 BLOCK_INPUT;
10374 XpmFreeAttributes (&attrs);
10375 UNBLOCK_INPUT;
10377 else
10379 switch (rc)
10381 case XpmOpenFailed:
10382 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
10383 break;
10385 case XpmFileInvalid:
10386 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
10387 break;
10389 case XpmNoMemory:
10390 image_error ("Out of memory (%s)", img->spec, Qnil);
10391 break;
10393 case XpmColorFailed:
10394 image_error ("Color allocation error (%s)", img->spec, Qnil);
10395 break;
10397 default:
10398 image_error ("Unknown error (%s)", img->spec, Qnil);
10399 break;
10403 return rc == XpmSuccess;
10406 #endif /* HAVE_XPM != 0 */
10409 #if 0 /* TODO : Color tables on W32. */
10410 /***********************************************************************
10411 Color table
10412 ***********************************************************************/
10414 /* An entry in the color table mapping an RGB color to a pixel color. */
10416 struct ct_color
10418 int r, g, b;
10419 unsigned long pixel;
10421 /* Next in color table collision list. */
10422 struct ct_color *next;
10425 /* The bucket vector size to use. Must be prime. */
10427 #define CT_SIZE 101
10429 /* Value is a hash of the RGB color given by R, G, and B. */
10431 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
10433 /* The color hash table. */
10435 struct ct_color **ct_table;
10437 /* Number of entries in the color table. */
10439 int ct_colors_allocated;
10441 /* Function prototypes. */
10443 static void init_color_table P_ ((void));
10444 static void free_color_table P_ ((void));
10445 static unsigned long *colors_in_color_table P_ ((int *n));
10446 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
10447 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
10450 /* Initialize the color table. */
10452 static void
10453 init_color_table ()
10455 int size = CT_SIZE * sizeof (*ct_table);
10456 ct_table = (struct ct_color **) xmalloc (size);
10457 bzero (ct_table, size);
10458 ct_colors_allocated = 0;
10462 /* Free memory associated with the color table. */
10464 static void
10465 free_color_table ()
10467 int i;
10468 struct ct_color *p, *next;
10470 for (i = 0; i < CT_SIZE; ++i)
10471 for (p = ct_table[i]; p; p = next)
10473 next = p->next;
10474 xfree (p);
10477 xfree (ct_table);
10478 ct_table = NULL;
10482 /* Value is a pixel color for RGB color R, G, B on frame F. If an
10483 entry for that color already is in the color table, return the
10484 pixel color of that entry. Otherwise, allocate a new color for R,
10485 G, B, and make an entry in the color table. */
10487 static unsigned long
10488 lookup_rgb_color (f, r, g, b)
10489 struct frame *f;
10490 int r, g, b;
10492 unsigned hash = CT_HASH_RGB (r, g, b);
10493 int i = hash % CT_SIZE;
10494 struct ct_color *p;
10496 for (p = ct_table[i]; p; p = p->next)
10497 if (p->r == r && p->g == g && p->b == b)
10498 break;
10500 if (p == NULL)
10502 COLORREF color;
10503 Colormap cmap;
10504 int rc;
10506 color = PALETTERGB (r, g, b);
10508 ++ct_colors_allocated;
10510 p = (struct ct_color *) xmalloc (sizeof *p);
10511 p->r = r;
10512 p->g = g;
10513 p->b = b;
10514 p->pixel = color;
10515 p->next = ct_table[i];
10516 ct_table[i] = p;
10519 return p->pixel;
10523 /* Look up pixel color PIXEL which is used on frame F in the color
10524 table. If not already present, allocate it. Value is PIXEL. */
10526 static unsigned long
10527 lookup_pixel_color (f, pixel)
10528 struct frame *f;
10529 unsigned long pixel;
10531 int i = pixel % CT_SIZE;
10532 struct ct_color *p;
10534 for (p = ct_table[i]; p; p = p->next)
10535 if (p->pixel == pixel)
10536 break;
10538 if (p == NULL)
10540 XColor color;
10541 Colormap cmap;
10542 int rc;
10544 BLOCK_INPUT;
10546 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10547 color.pixel = pixel;
10548 XQueryColor (NULL, cmap, &color);
10549 rc = x_alloc_nearest_color (f, cmap, &color);
10550 UNBLOCK_INPUT;
10552 if (rc)
10554 ++ct_colors_allocated;
10556 p = (struct ct_color *) xmalloc (sizeof *p);
10557 p->r = color.red;
10558 p->g = color.green;
10559 p->b = color.blue;
10560 p->pixel = pixel;
10561 p->next = ct_table[i];
10562 ct_table[i] = p;
10564 else
10565 return FRAME_FOREGROUND_PIXEL (f);
10567 return p->pixel;
10571 /* Value is a vector of all pixel colors contained in the color table,
10572 allocated via xmalloc. Set *N to the number of colors. */
10574 static unsigned long *
10575 colors_in_color_table (n)
10576 int *n;
10578 int i, j;
10579 struct ct_color *p;
10580 unsigned long *colors;
10582 if (ct_colors_allocated == 0)
10584 *n = 0;
10585 colors = NULL;
10587 else
10589 colors = (unsigned long *) xmalloc (ct_colors_allocated
10590 * sizeof *colors);
10591 *n = ct_colors_allocated;
10593 for (i = j = 0; i < CT_SIZE; ++i)
10594 for (p = ct_table[i]; p; p = p->next)
10595 colors[j++] = p->pixel;
10598 return colors;
10601 #endif /* TODO */
10604 /***********************************************************************
10605 Algorithms
10606 ***********************************************************************/
10607 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
10608 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
10609 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
10610 static void XPutPixel (XImage *, int, int, COLORREF);
10612 /* Non-zero means draw a cross on images having `:conversion
10613 disabled'. */
10615 int cross_disabled_images;
10617 /* Edge detection matrices for different edge-detection
10618 strategies. */
10620 static int emboss_matrix[9] = {
10621 /* x - 1 x x + 1 */
10622 2, -1, 0, /* y - 1 */
10623 -1, 0, 1, /* y */
10624 0, 1, -2 /* y + 1 */
10627 static int laplace_matrix[9] = {
10628 /* x - 1 x x + 1 */
10629 1, 0, 0, /* y - 1 */
10630 0, 0, 0, /* y */
10631 0, 0, -1 /* y + 1 */
10634 /* Value is the intensity of the color whose red/green/blue values
10635 are R, G, and B. */
10637 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
10640 /* On frame F, return an array of XColor structures describing image
10641 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
10642 non-zero means also fill the red/green/blue members of the XColor
10643 structures. Value is a pointer to the array of XColors structures,
10644 allocated with xmalloc; it must be freed by the caller. */
10646 static XColor *
10647 x_to_xcolors (f, img, rgb_p)
10648 struct frame *f;
10649 struct image *img;
10650 int rgb_p;
10652 int x, y;
10653 XColor *colors, *p;
10654 XImage *ximg;
10656 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
10657 #if 0 /* TODO: implement image colors. */
10658 /* Get the X image IMG->pixmap. */
10659 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
10660 0, 0, img->width, img->height, ~0, ZPixmap);
10662 /* Fill the `pixel' members of the XColor array. I wished there
10663 were an easy and portable way to circumvent XGetPixel. */
10664 p = colors;
10665 for (y = 0; y < img->height; ++y)
10667 XColor *row = p;
10669 for (x = 0; x < img->width; ++x, ++p)
10670 p->pixel = XGetPixel (ximg, x, y);
10672 if (rgb_p)
10673 x_query_colors (f, row, img->width);
10676 XDestroyImage (ximg);
10677 #endif
10678 return colors;
10681 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
10682 created with CreateDIBSection, with the pointer to the bit values
10683 stored in ximg->data. */
10685 static void XPutPixel (ximg, x, y, color)
10686 XImage * ximg;
10687 int x, y;
10688 COLORREF color;
10690 int width = ximg->info.bmiHeader.biWidth;
10691 int height = ximg->info.bmiHeader.biHeight;
10692 int rowbytes = width * 3;
10693 unsigned char * pixel;
10695 /* Don't support putting pixels in images with palettes. */
10696 xassert (ximg->info.bmiHeader.biBitCount == 24);
10698 /* Ensure scanlines are aligned on 4 byte boundaries. */
10699 if (rowbytes % 4)
10700 rowbytes += 4 - (rowbytes % 4);
10702 pixel = ximg->data + y * rowbytes + x * 3;
10703 *pixel = 255 - GetRValue (color);
10704 *(pixel + 1) = 255 - GetGValue (color);
10705 *(pixel + 2) = 255 - GetBValue (color);
10709 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
10710 RGB members are set. F is the frame on which this all happens.
10711 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
10713 static void
10714 x_from_xcolors (f, img, colors)
10715 struct frame *f;
10716 struct image *img;
10717 XColor *colors;
10719 int x, y;
10720 XImage *oimg;
10721 Pixmap pixmap;
10722 XColor *p;
10723 #if 0 /* TODO: color tables. */
10724 init_color_table ();
10725 #endif
10726 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
10727 &oimg, &pixmap);
10728 p = colors;
10729 for (y = 0; y < img->height; ++y)
10730 for (x = 0; x < img->width; ++x, ++p)
10732 unsigned long pixel;
10733 #if 0 /* TODO: color tables. */
10734 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
10735 #else
10736 pixel = PALETTERGB (p->red, p->green, p->blue);
10737 #endif
10738 XPutPixel (oimg, x, y, pixel);
10741 xfree (colors);
10742 x_clear_image_1 (f, img, 1, 0, 1);
10744 x_put_x_image (f, oimg, pixmap, img->width, img->height);
10745 x_destroy_x_image (oimg);
10746 img->pixmap = pixmap;
10747 #if 0 /* TODO: color tables. */
10748 img->colors = colors_in_color_table (&img->ncolors);
10749 free_color_table ();
10750 #endif
10754 /* On frame F, perform edge-detection on image IMG.
10756 MATRIX is a nine-element array specifying the transformation
10757 matrix. See emboss_matrix for an example.
10759 COLOR_ADJUST is a color adjustment added to each pixel of the
10760 outgoing image. */
10762 static void
10763 x_detect_edges (f, img, matrix, color_adjust)
10764 struct frame *f;
10765 struct image *img;
10766 int matrix[9], color_adjust;
10768 XColor *colors = x_to_xcolors (f, img, 1);
10769 XColor *new, *p;
10770 int x, y, i, sum;
10772 for (i = sum = 0; i < 9; ++i)
10773 sum += abs (matrix[i]);
10775 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
10777 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
10779 for (y = 0; y < img->height; ++y)
10781 p = COLOR (new, 0, y);
10782 p->red = p->green = p->blue = 0xffff/2;
10783 p = COLOR (new, img->width - 1, y);
10784 p->red = p->green = p->blue = 0xffff/2;
10787 for (x = 1; x < img->width - 1; ++x)
10789 p = COLOR (new, x, 0);
10790 p->red = p->green = p->blue = 0xffff/2;
10791 p = COLOR (new, x, img->height - 1);
10792 p->red = p->green = p->blue = 0xffff/2;
10795 for (y = 1; y < img->height - 1; ++y)
10797 p = COLOR (new, 1, y);
10799 for (x = 1; x < img->width - 1; ++x, ++p)
10801 int r, g, b, y1, x1;
10803 r = g = b = i = 0;
10804 for (y1 = y - 1; y1 < y + 2; ++y1)
10805 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
10806 if (matrix[i])
10808 XColor *t = COLOR (colors, x1, y1);
10809 r += matrix[i] * t->red;
10810 g += matrix[i] * t->green;
10811 b += matrix[i] * t->blue;
10814 r = (r / sum + color_adjust) & 0xffff;
10815 g = (g / sum + color_adjust) & 0xffff;
10816 b = (b / sum + color_adjust) & 0xffff;
10817 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
10821 xfree (colors);
10822 x_from_xcolors (f, img, new);
10824 #undef COLOR
10828 /* Perform the pre-defined `emboss' edge-detection on image IMG
10829 on frame F. */
10831 static void
10832 x_emboss (f, img)
10833 struct frame *f;
10834 struct image *img;
10836 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
10840 /* Transform image IMG which is used on frame F with a Laplace
10841 edge-detection algorithm. The result is an image that can be used
10842 to draw disabled buttons, for example. */
10844 static void
10845 x_laplace (f, img)
10846 struct frame *f;
10847 struct image *img;
10849 x_detect_edges (f, img, laplace_matrix, 45000);
10853 /* Perform edge-detection on image IMG on frame F, with specified
10854 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
10856 MATRIX must be either
10858 - a list of at least 9 numbers in row-major form
10859 - a vector of at least 9 numbers
10861 COLOR_ADJUST nil means use a default; otherwise it must be a
10862 number. */
10864 static void
10865 x_edge_detection (f, img, matrix, color_adjust)
10866 struct frame *f;
10867 struct image *img;
10868 Lisp_Object matrix, color_adjust;
10870 int i = 0;
10871 int trans[9];
10873 if (CONSP (matrix))
10875 for (i = 0;
10876 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
10877 ++i, matrix = XCDR (matrix))
10878 trans[i] = XFLOATINT (XCAR (matrix));
10880 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
10882 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
10883 trans[i] = XFLOATINT (AREF (matrix, i));
10886 if (NILP (color_adjust))
10887 color_adjust = make_number (0xffff / 2);
10889 if (i == 9 && NUMBERP (color_adjust))
10890 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
10894 /* Transform image IMG on frame F so that it looks disabled. */
10896 static void
10897 x_disable_image (f, img)
10898 struct frame *f;
10899 struct image *img;
10901 struct w32_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
10903 if (dpyinfo->n_planes * dpyinfo->n_cbits >= 2)
10905 /* Color (or grayscale). Convert to gray, and equalize. Just
10906 drawing such images with a stipple can look very odd, so
10907 we're using this method instead. */
10908 XColor *colors = x_to_xcolors (f, img, 1);
10909 XColor *p, *end;
10910 const int h = 15000;
10911 const int l = 30000;
10913 for (p = colors, end = colors + img->width * img->height;
10914 p < end;
10915 ++p)
10917 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
10918 int i2 = (0xffff - h - l) * i / 0xffff + l;
10919 p->red = p->green = p->blue = i2;
10922 x_from_xcolors (f, img, colors);
10925 /* Draw a cross over the disabled image, if we must or if we
10926 should. */
10927 if (dpyinfo->n_planes * dpyinfo->n_cbits < 2 || cross_disabled_images)
10929 #if 0 /* TODO: full image support */
10930 Display *dpy = FRAME_X_DISPLAY (f);
10931 GC gc;
10933 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
10934 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
10935 XDrawLine (dpy, img->pixmap, gc, 0, 0,
10936 img->width - 1, img->height - 1);
10937 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
10938 img->width - 1, 0);
10939 XFreeGC (dpy, gc);
10941 if (img->mask)
10943 gc = XCreateGC (dpy, img->mask, 0, NULL);
10944 XSetForeground (dpy, gc, WHITE_PIX_DEFAULT (f));
10945 XDrawLine (dpy, img->mask, gc, 0, 0,
10946 img->width - 1, img->height - 1);
10947 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
10948 img->width - 1, 0);
10949 XFreeGC (dpy, gc);
10951 #endif
10956 /* Build a mask for image IMG which is used on frame F. FILE is the
10957 name of an image file, for error messages. HOW determines how to
10958 determine the background color of IMG. If it is a list '(R G B)',
10959 with R, G, and B being integers >= 0, take that as the color of the
10960 background. Otherwise, determine the background color of IMG
10961 heuristically. Value is non-zero if successful. */
10963 static int
10964 x_build_heuristic_mask (f, img, how)
10965 struct frame *f;
10966 struct image *img;
10967 Lisp_Object how;
10969 #if 0 /* TODO: full image support. */
10970 Display *dpy = FRAME_W32_DISPLAY (f);
10971 XImage *ximg, *mask_img;
10972 int x, y, rc, use_img_background;
10973 unsigned long bg = 0;
10975 if (img->mask)
10977 XFreePixmap (FRAME_X_DISPLAY (f), img->mask);
10978 img->mask = None;
10979 img->background_transparent_valid = 0;
10982 /* Create an image and pixmap serving as mask. */
10983 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
10984 &mask_img, &img->mask);
10985 if (!rc)
10986 return 0;
10988 /* Get the X image of IMG->pixmap. */
10989 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
10990 ~0, ZPixmap);
10992 /* Determine the background color of ximg. If HOW is `(R G B)'
10993 take that as color. Otherwise, use the image's background color. */
10994 use_img_background = 1;
10996 if (CONSP (how))
10998 int rgb[3], i;
11000 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
11002 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
11003 how = XCDR (how);
11006 if (i == 3 && NILP (how))
11008 char color_name[30];
11009 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
11010 bg = x_alloc_image_color (f, img, build_string (color_name), 0);
11011 use_img_background = 0;
11015 if (use_img_background)
11016 bg = four_corners_best (ximg, img->width, img->height);
11018 /* Set all bits in mask_img to 1 whose color in ximg is different
11019 from the background color bg. */
11020 for (y = 0; y < img->height; ++y)
11021 for (x = 0; x < img->width; ++x)
11022 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
11024 /* Fill in the background_transparent field while we have the mask handy. */
11025 image_background_transparent (img, f, mask_img);
11027 /* Put mask_img into img->mask. */
11028 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
11029 x_destroy_x_image (mask_img);
11030 XDestroyImage (ximg);
11032 return 1;
11033 #else
11034 return 0;
11035 #endif
11039 /***********************************************************************
11040 PBM (mono, gray, color)
11041 ***********************************************************************/
11043 static int pbm_image_p P_ ((Lisp_Object object));
11044 static int pbm_load P_ ((struct frame *f, struct image *img));
11045 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
11047 /* The symbol `pbm' identifying images of this type. */
11049 Lisp_Object Qpbm;
11051 /* Indices of image specification fields in gs_format, below. */
11053 enum pbm_keyword_index
11055 PBM_TYPE,
11056 PBM_FILE,
11057 PBM_DATA,
11058 PBM_ASCENT,
11059 PBM_MARGIN,
11060 PBM_RELIEF,
11061 PBM_ALGORITHM,
11062 PBM_HEURISTIC_MASK,
11063 PBM_MASK,
11064 PBM_FOREGROUND,
11065 PBM_BACKGROUND,
11066 PBM_LAST
11069 /* Vector of image_keyword structures describing the format
11070 of valid user-defined image specifications. */
11072 static struct image_keyword pbm_format[PBM_LAST] =
11074 {":type", IMAGE_SYMBOL_VALUE, 1},
11075 {":file", IMAGE_STRING_VALUE, 0},
11076 {":data", IMAGE_STRING_VALUE, 0},
11077 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11078 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11079 {":relief", IMAGE_INTEGER_VALUE, 0},
11080 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11081 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11082 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11083 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
11084 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11087 /* Structure describing the image type `pbm'. */
11089 static struct image_type pbm_type =
11091 &Qpbm,
11092 pbm_image_p,
11093 pbm_load,
11094 x_clear_image,
11095 NULL
11099 /* Return non-zero if OBJECT is a valid PBM image specification. */
11101 static int
11102 pbm_image_p (object)
11103 Lisp_Object object;
11105 struct image_keyword fmt[PBM_LAST];
11107 bcopy (pbm_format, fmt, sizeof fmt);
11109 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
11110 || (fmt[PBM_ASCENT].count
11111 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
11112 return 0;
11114 /* Must specify either :data or :file. */
11115 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
11119 /* Scan a decimal number from *S and return it. Advance *S while
11120 reading the number. END is the end of the string. Value is -1 at
11121 end of input. */
11123 static int
11124 pbm_scan_number (s, end)
11125 unsigned char **s, *end;
11127 int c, val = -1;
11129 while (*s < end)
11131 /* Skip white-space. */
11132 while (*s < end && (c = *(*s)++, isspace (c)))
11135 if (c == '#')
11137 /* Skip comment to end of line. */
11138 while (*s < end && (c = *(*s)++, c != '\n'))
11141 else if (isdigit (c))
11143 /* Read decimal number. */
11144 val = c - '0';
11145 while (*s < end && (c = *(*s)++, isdigit (c)))
11146 val = 10 * val + c - '0';
11147 break;
11149 else
11150 break;
11153 return val;
11157 /* Read FILE into memory. Value is a pointer to a buffer allocated
11158 with xmalloc holding FILE's contents. Value is null if an error
11159 occurred. *SIZE is set to the size of the file. */
11161 static char *
11162 pbm_read_file (file, size)
11163 Lisp_Object file;
11164 int *size;
11166 FILE *fp = NULL;
11167 char *buf = NULL;
11168 struct stat st;
11170 if (stat (SDATA (file), &st) == 0
11171 && (fp = fopen (SDATA (file), "r")) != NULL
11172 && (buf = (char *) xmalloc (st.st_size),
11173 fread (buf, 1, st.st_size, fp) == st.st_size))
11175 *size = st.st_size;
11176 fclose (fp);
11178 else
11180 if (fp)
11181 fclose (fp);
11182 if (buf)
11184 xfree (buf);
11185 buf = NULL;
11189 return buf;
11193 /* Load PBM image IMG for use on frame F. */
11195 static int
11196 pbm_load (f, img)
11197 struct frame *f;
11198 struct image *img;
11200 int raw_p, x, y;
11201 int width, height, max_color_idx = 0;
11202 XImage *ximg;
11203 Lisp_Object file, specified_file;
11204 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
11205 struct gcpro gcpro1;
11206 unsigned char *contents = NULL;
11207 unsigned char *end, *p;
11208 int size;
11210 specified_file = image_spec_value (img->spec, QCfile, NULL);
11211 file = Qnil;
11212 GCPRO1 (file);
11214 if (STRINGP (specified_file))
11216 file = x_find_image_file (specified_file);
11217 if (!STRINGP (file))
11219 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11220 UNGCPRO;
11221 return 0;
11224 contents = slurp_file (SDATA (file), &size);
11225 if (contents == NULL)
11227 image_error ("Error reading `%s'", file, Qnil);
11228 UNGCPRO;
11229 return 0;
11232 p = contents;
11233 end = contents + size;
11235 else
11237 Lisp_Object data;
11238 data = image_spec_value (img->spec, QCdata, NULL);
11239 p = SDATA (data);
11240 end = p + SBYTES (data);
11243 /* Check magic number. */
11244 if (end - p < 2 || *p++ != 'P')
11246 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11247 error:
11248 xfree (contents);
11249 UNGCPRO;
11250 return 0;
11253 switch (*p++)
11255 case '1':
11256 raw_p = 0, type = PBM_MONO;
11257 break;
11259 case '2':
11260 raw_p = 0, type = PBM_GRAY;
11261 break;
11263 case '3':
11264 raw_p = 0, type = PBM_COLOR;
11265 break;
11267 case '4':
11268 raw_p = 1, type = PBM_MONO;
11269 break;
11271 case '5':
11272 raw_p = 1, type = PBM_GRAY;
11273 break;
11275 case '6':
11276 raw_p = 1, type = PBM_COLOR;
11277 break;
11279 default:
11280 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11281 goto error;
11284 /* Read width, height, maximum color-component. Characters
11285 starting with `#' up to the end of a line are ignored. */
11286 width = pbm_scan_number (&p, end);
11287 height = pbm_scan_number (&p, end);
11289 if (type != PBM_MONO)
11291 max_color_idx = pbm_scan_number (&p, end);
11292 if (raw_p && max_color_idx > 255)
11293 max_color_idx = 255;
11296 if (width < 0
11297 || height < 0
11298 || (type != PBM_MONO && max_color_idx < 0))
11299 goto error;
11301 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11302 goto error;
11304 #if 0 /* TODO: color tables. */
11305 /* Initialize the color hash table. */
11306 init_color_table ();
11307 #endif
11309 if (type == PBM_MONO)
11311 int c = 0, g;
11312 struct image_keyword fmt[PBM_LAST];
11313 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
11314 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
11316 /* Parse the image specification. */
11317 bcopy (pbm_format, fmt, sizeof fmt);
11318 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
11320 /* Get foreground and background colors, maybe allocate colors. */
11321 if (fmt[PBM_FOREGROUND].count
11322 && STRINGP (fmt[PBM_FOREGROUND].value))
11323 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
11324 if (fmt[PBM_BACKGROUND].count
11325 && STRINGP (fmt[PBM_BACKGROUND].value))
11327 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
11328 img->background = bg;
11329 img->background_valid = 1;
11332 for (y = 0; y < height; ++y)
11333 for (x = 0; x < width; ++x)
11335 if (raw_p)
11337 if ((x & 7) == 0)
11338 c = *p++;
11339 g = c & 0x80;
11340 c <<= 1;
11342 else
11343 g = pbm_scan_number (&p, end);
11345 XPutPixel (ximg, x, y, g ? fg : bg);
11348 else
11350 for (y = 0; y < height; ++y)
11351 for (x = 0; x < width; ++x)
11353 int r, g, b;
11355 if (type == PBM_GRAY)
11356 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
11357 else if (raw_p)
11359 r = *p++;
11360 g = *p++;
11361 b = *p++;
11363 else
11365 r = pbm_scan_number (&p, end);
11366 g = pbm_scan_number (&p, end);
11367 b = pbm_scan_number (&p, end);
11370 if (r < 0 || g < 0 || b < 0)
11372 x_destroy_x_image (ximg);
11373 image_error ("Invalid pixel value in image `%s'",
11374 img->spec, Qnil);
11375 goto error;
11378 /* RGB values are now in the range 0..max_color_idx.
11379 Scale this to the range 0..0xff supported by W32. */
11380 r = (int) ((double) r * 255 / max_color_idx);
11381 g = (int) ((double) g * 255 / max_color_idx);
11382 b = (int) ((double) b * 255 / max_color_idx);
11383 XPutPixel (ximg, x, y,
11384 #if 0 /* TODO: color tables. */
11385 lookup_rgb_color (f, r, g, b));
11386 #else
11387 PALETTERGB (r, g, b));
11388 #endif
11392 #if 0 /* TODO: color tables. */
11393 /* Store in IMG->colors the colors allocated for the image, and
11394 free the color table. */
11395 img->colors = colors_in_color_table (&img->ncolors);
11396 free_color_table ();
11397 #endif
11398 /* Maybe fill in the background field while we have ximg handy. */
11399 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11400 IMAGE_BACKGROUND (img, f, ximg);
11402 /* Put the image into a pixmap. */
11403 x_put_x_image (f, ximg, img->pixmap, width, height);
11404 x_destroy_x_image (ximg);
11406 img->width = width;
11407 img->height = height;
11409 UNGCPRO;
11410 xfree (contents);
11411 return 1;
11415 /***********************************************************************
11417 ***********************************************************************/
11419 #if HAVE_PNG
11421 #include <png.h>
11423 /* Function prototypes. */
11425 static int png_image_p P_ ((Lisp_Object object));
11426 static int png_load P_ ((struct frame *f, struct image *img));
11428 /* The symbol `png' identifying images of this type. */
11430 Lisp_Object Qpng;
11432 /* Indices of image specification fields in png_format, below. */
11434 enum png_keyword_index
11436 PNG_TYPE,
11437 PNG_DATA,
11438 PNG_FILE,
11439 PNG_ASCENT,
11440 PNG_MARGIN,
11441 PNG_RELIEF,
11442 PNG_ALGORITHM,
11443 PNG_HEURISTIC_MASK,
11444 PNG_MASK,
11445 PNG_BACKGROUND,
11446 PNG_LAST
11449 /* Vector of image_keyword structures describing the format
11450 of valid user-defined image specifications. */
11452 static struct image_keyword png_format[PNG_LAST] =
11454 {":type", IMAGE_SYMBOL_VALUE, 1},
11455 {":data", IMAGE_STRING_VALUE, 0},
11456 {":file", IMAGE_STRING_VALUE, 0},
11457 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11458 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11459 {":relief", IMAGE_INTEGER_VALUE, 0},
11460 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11461 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11462 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11463 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11466 /* Structure describing the image type `png'. */
11468 static struct image_type png_type =
11470 &Qpng,
11471 png_image_p,
11472 png_load,
11473 x_clear_image,
11474 NULL
11478 /* Return non-zero if OBJECT is a valid PNG image specification. */
11480 static int
11481 png_image_p (object)
11482 Lisp_Object object;
11484 struct image_keyword fmt[PNG_LAST];
11485 bcopy (png_format, fmt, sizeof fmt);
11487 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
11488 || (fmt[PNG_ASCENT].count
11489 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
11490 return 0;
11492 /* Must specify either the :data or :file keyword. */
11493 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
11497 /* Error and warning handlers installed when the PNG library
11498 is initialized. */
11500 static void
11501 my_png_error (png_ptr, msg)
11502 png_struct *png_ptr;
11503 char *msg;
11505 xassert (png_ptr != NULL);
11506 image_error ("PNG error: %s", build_string (msg), Qnil);
11507 longjmp (png_ptr->jmpbuf, 1);
11511 static void
11512 my_png_warning (png_ptr, msg)
11513 png_struct *png_ptr;
11514 char *msg;
11516 xassert (png_ptr != NULL);
11517 image_error ("PNG warning: %s", build_string (msg), Qnil);
11520 /* Memory source for PNG decoding. */
11522 struct png_memory_storage
11524 unsigned char *bytes; /* The data */
11525 size_t len; /* How big is it? */
11526 int index; /* Where are we? */
11530 /* Function set as reader function when reading PNG image from memory.
11531 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
11532 bytes from the input to DATA. */
11534 static void
11535 png_read_from_memory (png_ptr, data, length)
11536 png_structp png_ptr;
11537 png_bytep data;
11538 png_size_t length;
11540 struct png_memory_storage *tbr
11541 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
11543 if (length > tbr->len - tbr->index)
11544 png_error (png_ptr, "Read error");
11546 bcopy (tbr->bytes + tbr->index, data, length);
11547 tbr->index = tbr->index + length;
11550 /* Load PNG image IMG for use on frame F. Value is non-zero if
11551 successful. */
11553 static int
11554 png_load (f, img)
11555 struct frame *f;
11556 struct image *img;
11558 Lisp_Object file, specified_file;
11559 Lisp_Object specified_data;
11560 int x, y, i;
11561 XImage *ximg, *mask_img = NULL;
11562 struct gcpro gcpro1;
11563 png_struct *png_ptr = NULL;
11564 png_info *info_ptr = NULL, *end_info = NULL;
11565 FILE *volatile fp = NULL;
11566 png_byte sig[8];
11567 png_byte *volatile pixels = NULL;
11568 png_byte **volatile rows = NULL;
11569 png_uint_32 width, height;
11570 int bit_depth, color_type, interlace_type;
11571 png_byte channels;
11572 png_uint_32 row_bytes;
11573 int transparent_p;
11574 char *gamma_str;
11575 double screen_gamma, image_gamma;
11576 int intent;
11577 struct png_memory_storage tbr; /* Data to be read */
11579 /* Find out what file to load. */
11580 specified_file = image_spec_value (img->spec, QCfile, NULL);
11581 specified_data = image_spec_value (img->spec, QCdata, NULL);
11582 file = Qnil;
11583 GCPRO1 (file);
11585 if (NILP (specified_data))
11587 file = x_find_image_file (specified_file);
11588 if (!STRINGP (file))
11590 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11591 UNGCPRO;
11592 return 0;
11595 /* Open the image file. */
11596 fp = fopen (SDATA (file), "rb");
11597 if (!fp)
11599 image_error ("Cannot open image file `%s'", file, Qnil);
11600 UNGCPRO;
11601 fclose (fp);
11602 return 0;
11605 /* Check PNG signature. */
11606 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
11607 || !png_check_sig (sig, sizeof sig))
11609 image_error ("Not a PNG file:` %s'", file, Qnil);
11610 UNGCPRO;
11611 fclose (fp);
11612 return 0;
11615 else
11617 /* Read from memory. */
11618 tbr.bytes = SDATA (specified_data);
11619 tbr.len = SBYTES (specified_data);
11620 tbr.index = 0;
11622 /* Check PNG signature. */
11623 if (tbr.len < sizeof sig
11624 || !png_check_sig (tbr.bytes, sizeof sig))
11626 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
11627 UNGCPRO;
11628 return 0;
11631 /* Need to skip past the signature. */
11632 tbr.bytes += sizeof (sig);
11635 /* Initialize read and info structs for PNG lib. */
11636 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
11637 my_png_error, my_png_warning);
11638 if (!png_ptr)
11640 if (fp) fclose (fp);
11641 UNGCPRO;
11642 return 0;
11645 info_ptr = png_create_info_struct (png_ptr);
11646 if (!info_ptr)
11648 png_destroy_read_struct (&png_ptr, NULL, NULL);
11649 if (fp) fclose (fp);
11650 UNGCPRO;
11651 return 0;
11654 end_info = png_create_info_struct (png_ptr);
11655 if (!end_info)
11657 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
11658 if (fp) fclose (fp);
11659 UNGCPRO;
11660 return 0;
11663 /* Set error jump-back. We come back here when the PNG library
11664 detects an error. */
11665 if (setjmp (png_ptr->jmpbuf))
11667 error:
11668 if (png_ptr)
11669 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11670 xfree (pixels);
11671 xfree (rows);
11672 if (fp) fclose (fp);
11673 UNGCPRO;
11674 return 0;
11677 /* Read image info. */
11678 if (!NILP (specified_data))
11679 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
11680 else
11681 png_init_io (png_ptr, fp);
11683 png_set_sig_bytes (png_ptr, sizeof sig);
11684 png_read_info (png_ptr, info_ptr);
11685 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
11686 &interlace_type, NULL, NULL);
11688 /* If image contains simply transparency data, we prefer to
11689 construct a clipping mask. */
11690 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
11691 transparent_p = 1;
11692 else
11693 transparent_p = 0;
11695 /* This function is easier to write if we only have to handle
11696 one data format: RGB or RGBA with 8 bits per channel. Let's
11697 transform other formats into that format. */
11699 /* Strip more than 8 bits per channel. */
11700 if (bit_depth == 16)
11701 png_set_strip_16 (png_ptr);
11703 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
11704 if available. */
11705 png_set_expand (png_ptr);
11707 /* Convert grayscale images to RGB. */
11708 if (color_type == PNG_COLOR_TYPE_GRAY
11709 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
11710 png_set_gray_to_rgb (png_ptr);
11712 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
11713 gamma_str = getenv ("SCREEN_GAMMA");
11714 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
11716 /* Tell the PNG lib to handle gamma correction for us. */
11718 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
11719 if (png_get_sRGB (png_ptr, info_ptr, &intent))
11720 /* There is a special chunk in the image specifying the gamma. */
11721 png_set_sRGB (png_ptr, info_ptr, intent);
11722 else
11723 #endif
11724 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
11725 /* Image contains gamma information. */
11726 png_set_gamma (png_ptr, screen_gamma, image_gamma);
11727 else
11728 /* Use a default of 0.5 for the image gamma. */
11729 png_set_gamma (png_ptr, screen_gamma, 0.5);
11731 /* Handle alpha channel by combining the image with a background
11732 color. Do this only if a real alpha channel is supplied. For
11733 simple transparency, we prefer a clipping mask. */
11734 if (!transparent_p)
11736 png_color_16 *image_background;
11737 Lisp_Object specified_bg
11738 = image_spec_value (img->spec, QCbackground, NULL);
11741 if (STRINGP (specified_bg))
11742 /* The user specified `:background', use that. */
11744 COLORREF color;
11745 if (w32_defined_color (f, SDATA (specified_bg), &color, 0))
11747 png_color_16 user_bg;
11749 bzero (&user_bg, sizeof user_bg);
11750 user_bg.red = color.red;
11751 user_bg.green = color.green;
11752 user_bg.blue = color.blue;
11754 png_set_background (png_ptr, &user_bg,
11755 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11758 else if (png_get_bKGD (png_ptr, info_ptr, &image_background))
11759 /* Image contains a background color with which to
11760 combine the image. */
11761 png_set_background (png_ptr, image_background,
11762 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
11763 else
11765 /* Image does not contain a background color with which
11766 to combine the image data via an alpha channel. Use
11767 the frame's background instead. */
11768 XColor color;
11769 Colormap cmap;
11770 png_color_16 frame_background;
11772 cmap = FRAME_X_COLORMAP (f);
11773 color.pixel = FRAME_BACKGROUND_PIXEL (f);
11774 x_query_color (f, &color);
11776 bzero (&frame_background, sizeof frame_background);
11777 frame_background.red = color.red;
11778 frame_background.green = color.green;
11779 frame_background.blue = color.blue;
11781 png_set_background (png_ptr, &frame_background,
11782 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11786 /* Update info structure. */
11787 png_read_update_info (png_ptr, info_ptr);
11789 /* Get number of channels. Valid values are 1 for grayscale images
11790 and images with a palette, 2 for grayscale images with transparency
11791 information (alpha channel), 3 for RGB images, and 4 for RGB
11792 images with alpha channel, i.e. RGBA. If conversions above were
11793 sufficient we should only have 3 or 4 channels here. */
11794 channels = png_get_channels (png_ptr, info_ptr);
11795 xassert (channels == 3 || channels == 4);
11797 /* Number of bytes needed for one row of the image. */
11798 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
11800 /* Allocate memory for the image. */
11801 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
11802 rows = (png_byte **) xmalloc (height * sizeof *rows);
11803 for (i = 0; i < height; ++i)
11804 rows[i] = pixels + i * row_bytes;
11806 /* Read the entire image. */
11807 png_read_image (png_ptr, rows);
11808 png_read_end (png_ptr, info_ptr);
11809 if (fp)
11811 fclose (fp);
11812 fp = NULL;
11815 /* Create the X image and pixmap. */
11816 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11817 &img->pixmap))
11818 goto error;
11820 /* Create an image and pixmap serving as mask if the PNG image
11821 contains an alpha channel. */
11822 if (channels == 4
11823 && !transparent_p
11824 && !x_create_x_image_and_pixmap (f, width, height, 1,
11825 &mask_img, &img->mask))
11827 x_destroy_x_image (ximg);
11828 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
11829 img->pixmap = 0;
11830 goto error;
11833 /* Fill the X image and mask from PNG data. */
11834 init_color_table ();
11836 for (y = 0; y < height; ++y)
11838 png_byte *p = rows[y];
11840 for (x = 0; x < width; ++x)
11842 unsigned r, g, b;
11844 r = *p++ << 8;
11845 g = *p++ << 8;
11846 b = *p++ << 8;
11847 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
11849 /* An alpha channel, aka mask channel, associates variable
11850 transparency with an image. Where other image formats
11851 support binary transparency---fully transparent or fully
11852 opaque---PNG allows up to 254 levels of partial transparency.
11853 The PNG library implements partial transparency by combining
11854 the image with a specified background color.
11856 I'm not sure how to handle this here nicely: because the
11857 background on which the image is displayed may change, for
11858 real alpha channel support, it would be necessary to create
11859 a new image for each possible background.
11861 What I'm doing now is that a mask is created if we have
11862 boolean transparency information. Otherwise I'm using
11863 the frame's background color to combine the image with. */
11865 if (channels == 4)
11867 if (mask_img)
11868 XPutPixel (mask_img, x, y, *p > 0);
11869 ++p;
11874 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11875 /* Set IMG's background color from the PNG image, unless the user
11876 overrode it. */
11878 png_color_16 *bg;
11879 if (png_get_bKGD (png_ptr, info_ptr, &bg))
11881 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
11882 img->background_valid = 1;
11886 /* Remember colors allocated for this image. */
11887 img->colors = colors_in_color_table (&img->ncolors);
11888 free_color_table ();
11890 /* Clean up. */
11891 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11892 xfree (rows);
11893 xfree (pixels);
11895 img->width = width;
11896 img->height = height;
11898 /* Maybe fill in the background field while we have ximg handy. */
11899 IMAGE_BACKGROUND (img, f, ximg);
11901 /* Put the image into the pixmap, then free the X image and its buffer. */
11902 x_put_x_image (f, ximg, img->pixmap, width, height);
11903 x_destroy_x_image (ximg);
11905 /* Same for the mask. */
11906 if (mask_img)
11908 /* Fill in the background_transparent field while we have the mask
11909 handy. */
11910 image_background_transparent (img, f, mask_img);
11912 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
11913 x_destroy_x_image (mask_img);
11916 UNGCPRO;
11917 return 1;
11920 #endif /* HAVE_PNG != 0 */
11924 /***********************************************************************
11925 JPEG
11926 ***********************************************************************/
11928 #if HAVE_JPEG
11930 /* Work around a warning about HAVE_STDLIB_H being redefined in
11931 jconfig.h. */
11932 #ifdef HAVE_STDLIB_H
11933 #define HAVE_STDLIB_H_1
11934 #undef HAVE_STDLIB_H
11935 #endif /* HAVE_STLIB_H */
11937 #include <jpeglib.h>
11938 #include <jerror.h>
11939 #include <setjmp.h>
11941 #ifdef HAVE_STLIB_H_1
11942 #define HAVE_STDLIB_H 1
11943 #endif
11945 static int jpeg_image_p P_ ((Lisp_Object object));
11946 static int jpeg_load P_ ((struct frame *f, struct image *img));
11948 /* The symbol `jpeg' identifying images of this type. */
11950 Lisp_Object Qjpeg;
11952 /* Indices of image specification fields in gs_format, below. */
11954 enum jpeg_keyword_index
11956 JPEG_TYPE,
11957 JPEG_DATA,
11958 JPEG_FILE,
11959 JPEG_ASCENT,
11960 JPEG_MARGIN,
11961 JPEG_RELIEF,
11962 JPEG_ALGORITHM,
11963 JPEG_HEURISTIC_MASK,
11964 JPEG_MASK,
11965 JPEG_BACKGROUND,
11966 JPEG_LAST
11969 /* Vector of image_keyword structures describing the format
11970 of valid user-defined image specifications. */
11972 static struct image_keyword jpeg_format[JPEG_LAST] =
11974 {":type", IMAGE_SYMBOL_VALUE, 1},
11975 {":data", IMAGE_STRING_VALUE, 0},
11976 {":file", IMAGE_STRING_VALUE, 0},
11977 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11978 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11979 {":relief", IMAGE_INTEGER_VALUE, 0},
11980 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11981 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11982 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11983 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11986 /* Structure describing the image type `jpeg'. */
11988 static struct image_type jpeg_type =
11990 &Qjpeg,
11991 jpeg_image_p,
11992 jpeg_load,
11993 x_clear_image,
11994 NULL
11998 /* Return non-zero if OBJECT is a valid JPEG image specification. */
12000 static int
12001 jpeg_image_p (object)
12002 Lisp_Object object;
12004 struct image_keyword fmt[JPEG_LAST];
12006 bcopy (jpeg_format, fmt, sizeof fmt);
12008 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
12009 || (fmt[JPEG_ASCENT].count
12010 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
12011 return 0;
12013 /* Must specify either the :data or :file keyword. */
12014 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
12018 struct my_jpeg_error_mgr
12020 struct jpeg_error_mgr pub;
12021 jmp_buf setjmp_buffer;
12024 static void
12025 my_error_exit (cinfo)
12026 j_common_ptr cinfo;
12028 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
12029 longjmp (mgr->setjmp_buffer, 1);
12032 /* Init source method for JPEG data source manager. Called by
12033 jpeg_read_header() before any data is actually read. See
12034 libjpeg.doc from the JPEG lib distribution. */
12036 static void
12037 our_init_source (cinfo)
12038 j_decompress_ptr cinfo;
12043 /* Fill input buffer method for JPEG data source manager. Called
12044 whenever more data is needed. We read the whole image in one step,
12045 so this only adds a fake end of input marker at the end. */
12047 static boolean
12048 our_fill_input_buffer (cinfo)
12049 j_decompress_ptr cinfo;
12051 /* Insert a fake EOI marker. */
12052 struct jpeg_source_mgr *src = cinfo->src;
12053 static JOCTET buffer[2];
12055 buffer[0] = (JOCTET) 0xFF;
12056 buffer[1] = (JOCTET) JPEG_EOI;
12058 src->next_input_byte = buffer;
12059 src->bytes_in_buffer = 2;
12060 return TRUE;
12064 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
12065 is the JPEG data source manager. */
12067 static void
12068 our_skip_input_data (cinfo, num_bytes)
12069 j_decompress_ptr cinfo;
12070 long num_bytes;
12072 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
12074 if (src)
12076 if (num_bytes > src->bytes_in_buffer)
12077 ERREXIT (cinfo, JERR_INPUT_EOF);
12079 src->bytes_in_buffer -= num_bytes;
12080 src->next_input_byte += num_bytes;
12085 /* Method to terminate data source. Called by
12086 jpeg_finish_decompress() after all data has been processed. */
12088 static void
12089 our_term_source (cinfo)
12090 j_decompress_ptr cinfo;
12095 /* Set up the JPEG lib for reading an image from DATA which contains
12096 LEN bytes. CINFO is the decompression info structure created for
12097 reading the image. */
12099 static void
12100 jpeg_memory_src (cinfo, data, len)
12101 j_decompress_ptr cinfo;
12102 JOCTET *data;
12103 unsigned int len;
12105 struct jpeg_source_mgr *src;
12107 if (cinfo->src == NULL)
12109 /* First time for this JPEG object? */
12110 cinfo->src = (struct jpeg_source_mgr *)
12111 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
12112 sizeof (struct jpeg_source_mgr));
12113 src = (struct jpeg_source_mgr *) cinfo->src;
12114 src->next_input_byte = data;
12117 src = (struct jpeg_source_mgr *) cinfo->src;
12118 src->init_source = our_init_source;
12119 src->fill_input_buffer = our_fill_input_buffer;
12120 src->skip_input_data = our_skip_input_data;
12121 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
12122 src->term_source = our_term_source;
12123 src->bytes_in_buffer = len;
12124 src->next_input_byte = data;
12128 /* Load image IMG for use on frame F. Patterned after example.c
12129 from the JPEG lib. */
12131 static int
12132 jpeg_load (f, img)
12133 struct frame *f;
12134 struct image *img;
12136 struct jpeg_decompress_struct cinfo;
12137 struct my_jpeg_error_mgr mgr;
12138 Lisp_Object file, specified_file;
12139 Lisp_Object specified_data;
12140 FILE * volatile fp = NULL;
12141 JSAMPARRAY buffer;
12142 int row_stride, x, y;
12143 XImage *ximg = NULL;
12144 int rc;
12145 unsigned long *colors;
12146 int width, height;
12147 struct gcpro gcpro1;
12149 /* Open the JPEG file. */
12150 specified_file = image_spec_value (img->spec, QCfile, NULL);
12151 specified_data = image_spec_value (img->spec, QCdata, NULL);
12152 file = Qnil;
12153 GCPRO1 (file);
12155 if (NILP (specified_data))
12157 file = x_find_image_file (specified_file);
12158 if (!STRINGP (file))
12160 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12161 UNGCPRO;
12162 return 0;
12165 fp = fopen (SDATA (file), "r");
12166 if (fp == NULL)
12168 image_error ("Cannot open `%s'", file, Qnil);
12169 UNGCPRO;
12170 return 0;
12174 /* Customize libjpeg's error handling to call my_error_exit when an
12175 error is detected. This function will perform a longjmp. */
12176 cinfo.err = jpeg_std_error (&mgr.pub);
12177 mgr.pub.error_exit = my_error_exit;
12179 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
12181 if (rc == 1)
12183 /* Called from my_error_exit. Display a JPEG error. */
12184 char buffer[JMSG_LENGTH_MAX];
12185 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
12186 image_error ("Error reading JPEG image `%s': %s", img->spec,
12187 build_string (buffer));
12190 /* Close the input file and destroy the JPEG object. */
12191 if (fp)
12192 fclose (fp);
12193 jpeg_destroy_decompress (&cinfo);
12195 /* If we already have an XImage, free that. */
12196 x_destroy_x_image (ximg);
12198 /* Free pixmap and colors. */
12199 x_clear_image (f, img);
12201 UNGCPRO;
12202 return 0;
12205 /* Create the JPEG decompression object. Let it read from fp.
12206 Read the JPEG image header. */
12207 jpeg_create_decompress (&cinfo);
12209 if (NILP (specified_data))
12210 jpeg_stdio_src (&cinfo, fp);
12211 else
12212 jpeg_memory_src (&cinfo, SDATA (specified_data),
12213 SBYTES (specified_data));
12215 jpeg_read_header (&cinfo, TRUE);
12217 /* Customize decompression so that color quantization will be used.
12218 Start decompression. */
12219 cinfo.quantize_colors = TRUE;
12220 jpeg_start_decompress (&cinfo);
12221 width = img->width = cinfo.output_width;
12222 height = img->height = cinfo.output_height;
12224 /* Create X image and pixmap. */
12225 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
12226 &img->pixmap))
12227 longjmp (mgr.setjmp_buffer, 2);
12229 /* Allocate colors. When color quantization is used,
12230 cinfo.actual_number_of_colors has been set with the number of
12231 colors generated, and cinfo.colormap is a two-dimensional array
12232 of color indices in the range 0..cinfo.actual_number_of_colors.
12233 No more than 255 colors will be generated. */
12235 int i, ir, ig, ib;
12237 if (cinfo.out_color_components > 2)
12238 ir = 0, ig = 1, ib = 2;
12239 else if (cinfo.out_color_components > 1)
12240 ir = 0, ig = 1, ib = 0;
12241 else
12242 ir = 0, ig = 0, ib = 0;
12244 /* Use the color table mechanism because it handles colors that
12245 cannot be allocated nicely. Such colors will be replaced with
12246 a default color, and we don't have to care about which colors
12247 can be freed safely, and which can't. */
12248 init_color_table ();
12249 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
12250 * sizeof *colors);
12252 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
12254 /* Multiply RGB values with 255 because X expects RGB values
12255 in the range 0..0xffff. */
12256 int r = cinfo.colormap[ir][i] << 8;
12257 int g = cinfo.colormap[ig][i] << 8;
12258 int b = cinfo.colormap[ib][i] << 8;
12259 colors[i] = lookup_rgb_color (f, r, g, b);
12262 /* Remember those colors actually allocated. */
12263 img->colors = colors_in_color_table (&img->ncolors);
12264 free_color_table ();
12267 /* Read pixels. */
12268 row_stride = width * cinfo.output_components;
12269 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
12270 row_stride, 1);
12271 for (y = 0; y < height; ++y)
12273 jpeg_read_scanlines (&cinfo, buffer, 1);
12274 for (x = 0; x < cinfo.output_width; ++x)
12275 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
12278 /* Clean up. */
12279 jpeg_finish_decompress (&cinfo);
12280 jpeg_destroy_decompress (&cinfo);
12281 if (fp)
12282 fclose (fp);
12284 /* Maybe fill in the background field while we have ximg handy. */
12285 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12286 IMAGE_BACKGROUND (img, f, ximg);
12288 /* Put the image into the pixmap. */
12289 x_put_x_image (f, ximg, img->pixmap, width, height);
12290 x_destroy_x_image (ximg);
12291 UNBLOCK_INPUT;
12292 UNGCPRO;
12293 return 1;
12296 #endif /* HAVE_JPEG */
12300 /***********************************************************************
12301 TIFF
12302 ***********************************************************************/
12304 #if HAVE_TIFF
12306 #include <tiffio.h>
12308 static int tiff_image_p P_ ((Lisp_Object object));
12309 static int tiff_load P_ ((struct frame *f, struct image *img));
12311 /* The symbol `tiff' identifying images of this type. */
12313 Lisp_Object Qtiff;
12315 /* Indices of image specification fields in tiff_format, below. */
12317 enum tiff_keyword_index
12319 TIFF_TYPE,
12320 TIFF_DATA,
12321 TIFF_FILE,
12322 TIFF_ASCENT,
12323 TIFF_MARGIN,
12324 TIFF_RELIEF,
12325 TIFF_ALGORITHM,
12326 TIFF_HEURISTIC_MASK,
12327 TIFF_MASK,
12328 TIFF_BACKGROUND,
12329 TIFF_LAST
12332 /* Vector of image_keyword structures describing the format
12333 of valid user-defined image specifications. */
12335 static struct image_keyword tiff_format[TIFF_LAST] =
12337 {":type", IMAGE_SYMBOL_VALUE, 1},
12338 {":data", IMAGE_STRING_VALUE, 0},
12339 {":file", IMAGE_STRING_VALUE, 0},
12340 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12341 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12342 {":relief", IMAGE_INTEGER_VALUE, 0},
12343 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12344 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12345 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12346 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12349 /* Structure describing the image type `tiff'. */
12351 static struct image_type tiff_type =
12353 &Qtiff,
12354 tiff_image_p,
12355 tiff_load,
12356 x_clear_image,
12357 NULL
12361 /* Return non-zero if OBJECT is a valid TIFF image specification. */
12363 static int
12364 tiff_image_p (object)
12365 Lisp_Object object;
12367 struct image_keyword fmt[TIFF_LAST];
12368 bcopy (tiff_format, fmt, sizeof fmt);
12370 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
12371 || (fmt[TIFF_ASCENT].count
12372 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
12373 return 0;
12375 /* Must specify either the :data or :file keyword. */
12376 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
12380 /* Reading from a memory buffer for TIFF images Based on the PNG
12381 memory source, but we have to provide a lot of extra functions.
12382 Blah.
12384 We really only need to implement read and seek, but I am not
12385 convinced that the TIFF library is smart enough not to destroy
12386 itself if we only hand it the function pointers we need to
12387 override. */
12389 typedef struct
12391 unsigned char *bytes;
12392 size_t len;
12393 int index;
12395 tiff_memory_source;
12397 static size_t
12398 tiff_read_from_memory (data, buf, size)
12399 thandle_t data;
12400 tdata_t buf;
12401 tsize_t size;
12403 tiff_memory_source *src = (tiff_memory_source *) data;
12405 if (size > src->len - src->index)
12406 return (size_t) -1;
12407 bcopy (src->bytes + src->index, buf, size);
12408 src->index += size;
12409 return size;
12412 static size_t
12413 tiff_write_from_memory (data, buf, size)
12414 thandle_t data;
12415 tdata_t buf;
12416 tsize_t size;
12418 return (size_t) -1;
12421 static toff_t
12422 tiff_seek_in_memory (data, off, whence)
12423 thandle_t data;
12424 toff_t off;
12425 int whence;
12427 tiff_memory_source *src = (tiff_memory_source *) data;
12428 int idx;
12430 switch (whence)
12432 case SEEK_SET: /* Go from beginning of source. */
12433 idx = off;
12434 break;
12436 case SEEK_END: /* Go from end of source. */
12437 idx = src->len + off;
12438 break;
12440 case SEEK_CUR: /* Go from current position. */
12441 idx = src->index + off;
12442 break;
12444 default: /* Invalid `whence'. */
12445 return -1;
12448 if (idx > src->len || idx < 0)
12449 return -1;
12451 src->index = idx;
12452 return src->index;
12455 static int
12456 tiff_close_memory (data)
12457 thandle_t data;
12459 /* NOOP */
12460 return 0;
12463 static int
12464 tiff_mmap_memory (data, pbase, psize)
12465 thandle_t data;
12466 tdata_t *pbase;
12467 toff_t *psize;
12469 /* It is already _IN_ memory. */
12470 return 0;
12473 static void
12474 tiff_unmap_memory (data, base, size)
12475 thandle_t data;
12476 tdata_t base;
12477 toff_t size;
12479 /* We don't need to do this. */
12482 static toff_t
12483 tiff_size_of_memory (data)
12484 thandle_t data;
12486 return ((tiff_memory_source *) data)->len;
12490 static void
12491 tiff_error_handler (title, format, ap)
12492 const char *title, *format;
12493 va_list ap;
12495 char buf[512];
12496 int len;
12498 len = sprintf (buf, "TIFF error: %s ", title);
12499 vsprintf (buf + len, format, ap);
12500 add_to_log (buf, Qnil, Qnil);
12504 static void
12505 tiff_warning_handler (title, format, ap)
12506 const char *title, *format;
12507 va_list ap;
12509 char buf[512];
12510 int len;
12512 len = sprintf (buf, "TIFF warning: %s ", title);
12513 vsprintf (buf + len, format, ap);
12514 add_to_log (buf, Qnil, Qnil);
12518 /* Load TIFF image IMG for use on frame F. Value is non-zero if
12519 successful. */
12521 static int
12522 tiff_load (f, img)
12523 struct frame *f;
12524 struct image *img;
12526 Lisp_Object file, specified_file;
12527 Lisp_Object specified_data;
12528 TIFF *tiff;
12529 int width, height, x, y;
12530 uint32 *buf;
12531 int rc;
12532 XImage *ximg;
12533 struct gcpro gcpro1;
12534 tiff_memory_source memsrc;
12536 specified_file = image_spec_value (img->spec, QCfile, NULL);
12537 specified_data = image_spec_value (img->spec, QCdata, NULL);
12538 file = Qnil;
12539 GCPRO1 (file);
12541 TIFFSetErrorHandler (tiff_error_handler);
12542 TIFFSetWarningHandler (tiff_warning_handler);
12544 if (NILP (specified_data))
12546 /* Read from a file */
12547 file = x_find_image_file (specified_file);
12548 if (!STRINGP (file))
12550 image_error ("Cannot find image file `%s'", file, Qnil);
12551 UNGCPRO;
12552 return 0;
12555 /* Try to open the image file. */
12556 tiff = TIFFOpen (SDATA (file), "r");
12557 if (tiff == NULL)
12559 image_error ("Cannot open `%s'", file, Qnil);
12560 UNGCPRO;
12561 return 0;
12564 else
12566 /* Memory source! */
12567 memsrc.bytes = SDATA (specified_data);
12568 memsrc.len = SBYTES (specified_data);
12569 memsrc.index = 0;
12571 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
12572 (TIFFReadWriteProc) tiff_read_from_memory,
12573 (TIFFReadWriteProc) tiff_write_from_memory,
12574 tiff_seek_in_memory,
12575 tiff_close_memory,
12576 tiff_size_of_memory,
12577 tiff_mmap_memory,
12578 tiff_unmap_memory);
12580 if (!tiff)
12582 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
12583 UNGCPRO;
12584 return 0;
12588 /* Get width and height of the image, and allocate a raster buffer
12589 of width x height 32-bit values. */
12590 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
12591 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
12592 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
12594 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
12595 TIFFClose (tiff);
12596 if (!rc)
12598 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
12599 xfree (buf);
12600 UNGCPRO;
12601 return 0;
12604 /* Create the X image and pixmap. */
12605 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12607 xfree (buf);
12608 UNGCPRO;
12609 return 0;
12612 /* Initialize the color table. */
12613 init_color_table ();
12615 /* Process the pixel raster. Origin is in the lower-left corner. */
12616 for (y = 0; y < height; ++y)
12618 uint32 *row = buf + y * width;
12620 for (x = 0; x < width; ++x)
12622 uint32 abgr = row[x];
12623 int r = TIFFGetR (abgr) << 8;
12624 int g = TIFFGetG (abgr) << 8;
12625 int b = TIFFGetB (abgr) << 8;
12626 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
12630 /* Remember the colors allocated for the image. Free the color table. */
12631 img->colors = colors_in_color_table (&img->ncolors);
12632 free_color_table ();
12634 img->width = width;
12635 img->height = height;
12637 /* Maybe fill in the background field while we have ximg handy. */
12638 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12639 IMAGE_BACKGROUND (img, f, ximg);
12641 /* Put the image into the pixmap, then free the X image and its buffer. */
12642 x_put_x_image (f, ximg, img->pixmap, width, height);
12643 x_destroy_x_image (ximg);
12644 xfree (buf);
12646 UNGCPRO;
12647 return 1;
12650 #endif /* HAVE_TIFF != 0 */
12654 /***********************************************************************
12656 ***********************************************************************/
12658 #if HAVE_GIF
12660 #include <gif_lib.h>
12662 static int gif_image_p P_ ((Lisp_Object object));
12663 static int gif_load P_ ((struct frame *f, struct image *img));
12665 /* The symbol `gif' identifying images of this type. */
12667 Lisp_Object Qgif;
12669 /* Indices of image specification fields in gif_format, below. */
12671 enum gif_keyword_index
12673 GIF_TYPE,
12674 GIF_DATA,
12675 GIF_FILE,
12676 GIF_ASCENT,
12677 GIF_MARGIN,
12678 GIF_RELIEF,
12679 GIF_ALGORITHM,
12680 GIF_HEURISTIC_MASK,
12681 GIF_MASK,
12682 GIF_IMAGE,
12683 GIF_BACKGROUND,
12684 GIF_LAST
12687 /* Vector of image_keyword structures describing the format
12688 of valid user-defined image specifications. */
12690 static struct image_keyword gif_format[GIF_LAST] =
12692 {":type", IMAGE_SYMBOL_VALUE, 1},
12693 {":data", IMAGE_STRING_VALUE, 0},
12694 {":file", IMAGE_STRING_VALUE, 0},
12695 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12696 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12697 {":relief", IMAGE_INTEGER_VALUE, 0},
12698 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12699 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12700 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12701 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12702 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12705 /* Structure describing the image type `gif'. */
12707 static struct image_type gif_type =
12709 &Qgif,
12710 gif_image_p,
12711 gif_load,
12712 x_clear_image,
12713 NULL
12716 /* Return non-zero if OBJECT is a valid GIF image specification. */
12718 static int
12719 gif_image_p (object)
12720 Lisp_Object object;
12722 struct image_keyword fmt[GIF_LAST];
12723 bcopy (gif_format, fmt, sizeof fmt);
12725 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
12726 || (fmt[GIF_ASCENT].count
12727 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
12728 return 0;
12730 /* Must specify either the :data or :file keyword. */
12731 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
12734 /* Reading a GIF image from memory
12735 Based on the PNG memory stuff to a certain extent. */
12737 typedef struct
12739 unsigned char *bytes;
12740 size_t len;
12741 int index;
12743 gif_memory_source;
12745 /* Make the current memory source available to gif_read_from_memory.
12746 It's done this way because not all versions of libungif support
12747 a UserData field in the GifFileType structure. */
12748 static gif_memory_source *current_gif_memory_src;
12750 static int
12751 gif_read_from_memory (file, buf, len)
12752 GifFileType *file;
12753 GifByteType *buf;
12754 int len;
12756 gif_memory_source *src = current_gif_memory_src;
12758 if (len > src->len - src->index)
12759 return -1;
12761 bcopy (src->bytes + src->index, buf, len);
12762 src->index += len;
12763 return len;
12767 /* Load GIF image IMG for use on frame F. Value is non-zero if
12768 successful. */
12770 static int
12771 gif_load (f, img)
12772 struct frame *f;
12773 struct image *img;
12775 Lisp_Object file, specified_file;
12776 Lisp_Object specified_data;
12777 int rc, width, height, x, y, i;
12778 XImage *ximg;
12779 ColorMapObject *gif_color_map;
12780 unsigned long pixel_colors[256];
12781 GifFileType *gif;
12782 struct gcpro gcpro1;
12783 Lisp_Object image;
12784 int ino, image_left, image_top, image_width, image_height;
12785 gif_memory_source memsrc;
12786 unsigned char *raster;
12788 specified_file = image_spec_value (img->spec, QCfile, NULL);
12789 specified_data = image_spec_value (img->spec, QCdata, NULL);
12790 file = Qnil;
12791 GCPRO1 (file);
12793 if (NILP (specified_data))
12795 file = x_find_image_file (specified_file);
12796 if (!STRINGP (file))
12798 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12799 UNGCPRO;
12800 return 0;
12803 /* Open the GIF file. */
12804 gif = DGifOpenFileName (SDATA (file));
12805 if (gif == NULL)
12807 image_error ("Cannot open `%s'", file, Qnil);
12808 UNGCPRO;
12809 return 0;
12812 else
12814 /* Read from memory! */
12815 current_gif_memory_src = &memsrc;
12816 memsrc.bytes = SDATA (specified_data);
12817 memsrc.len = SBYTES (specified_data);
12818 memsrc.index = 0;
12820 gif = DGifOpen(&memsrc, gif_read_from_memory);
12821 if (!gif)
12823 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
12824 UNGCPRO;
12825 return 0;
12829 /* Read entire contents. */
12830 rc = DGifSlurp (gif);
12831 if (rc == GIF_ERROR)
12833 image_error ("Error reading `%s'", img->spec, Qnil);
12834 DGifCloseFile (gif);
12835 UNGCPRO;
12836 return 0;
12839 image = image_spec_value (img->spec, QCindex, NULL);
12840 ino = INTEGERP (image) ? XFASTINT (image) : 0;
12841 if (ino >= gif->ImageCount)
12843 image_error ("Invalid image number `%s' in image `%s'",
12844 image, img->spec);
12845 DGifCloseFile (gif);
12846 UNGCPRO;
12847 return 0;
12850 width = img->width = gif->SWidth;
12851 height = img->height = gif->SHeight;
12853 /* Create the X image and pixmap. */
12854 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12856 DGifCloseFile (gif);
12857 UNGCPRO;
12858 return 0;
12861 /* Allocate colors. */
12862 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
12863 if (!gif_color_map)
12864 gif_color_map = gif->SColorMap;
12865 init_color_table ();
12866 bzero (pixel_colors, sizeof pixel_colors);
12868 for (i = 0; i < gif_color_map->ColorCount; ++i)
12870 int r = gif_color_map->Colors[i].Red << 8;
12871 int g = gif_color_map->Colors[i].Green << 8;
12872 int b = gif_color_map->Colors[i].Blue << 8;
12873 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
12876 img->colors = colors_in_color_table (&img->ncolors);
12877 free_color_table ();
12879 /* Clear the part of the screen image that are not covered by
12880 the image from the GIF file. Full animated GIF support
12881 requires more than can be done here (see the gif89 spec,
12882 disposal methods). Let's simply assume that the part
12883 not covered by a sub-image is in the frame's background color. */
12884 image_top = gif->SavedImages[ino].ImageDesc.Top;
12885 image_left = gif->SavedImages[ino].ImageDesc.Left;
12886 image_width = gif->SavedImages[ino].ImageDesc.Width;
12887 image_height = gif->SavedImages[ino].ImageDesc.Height;
12889 for (y = 0; y < image_top; ++y)
12890 for (x = 0; x < width; ++x)
12891 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12893 for (y = image_top + image_height; y < height; ++y)
12894 for (x = 0; x < width; ++x)
12895 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12897 for (y = image_top; y < image_top + image_height; ++y)
12899 for (x = 0; x < image_left; ++x)
12900 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12901 for (x = image_left + image_width; x < width; ++x)
12902 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12905 /* Read the GIF image into the X image. We use a local variable
12906 `raster' here because RasterBits below is a char *, and invites
12907 problems with bytes >= 0x80. */
12908 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
12910 if (gif->SavedImages[ino].ImageDesc.Interlace)
12912 static int interlace_start[] = {0, 4, 2, 1};
12913 static int interlace_increment[] = {8, 8, 4, 2};
12914 int pass;
12915 int row = interlace_start[0];
12917 pass = 0;
12919 for (y = 0; y < image_height; y++)
12921 if (row >= image_height)
12923 row = interlace_start[++pass];
12924 while (row >= image_height)
12925 row = interlace_start[++pass];
12928 for (x = 0; x < image_width; x++)
12930 int i = raster[(y * image_width) + x];
12931 XPutPixel (ximg, x + image_left, row + image_top,
12932 pixel_colors[i]);
12935 row += interlace_increment[pass];
12938 else
12940 for (y = 0; y < image_height; ++y)
12941 for (x = 0; x < image_width; ++x)
12943 int i = raster[y* image_width + x];
12944 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
12948 DGifCloseFile (gif);
12950 /* Maybe fill in the background field while we have ximg handy. */
12951 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12952 IMAGE_BACKGROUND (img, f, ximg);
12954 /* Put the image into the pixmap, then free the X image and its buffer. */
12955 x_put_x_image (f, ximg, img->pixmap, width, height);
12956 x_destroy_x_image (ximg);
12958 UNGCPRO;
12959 return 1;
12962 #endif /* HAVE_GIF != 0 */
12966 /***********************************************************************
12967 Ghostscript
12968 ***********************************************************************/
12970 Lisp_Object Qpostscript;
12972 #ifdef HAVE_GHOSTSCRIPT
12973 static int gs_image_p P_ ((Lisp_Object object));
12974 static int gs_load P_ ((struct frame *f, struct image *img));
12975 static void gs_clear_image P_ ((struct frame *f, struct image *img));
12977 /* The symbol `postscript' identifying images of this type. */
12979 /* Keyword symbols. */
12981 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12983 /* Indices of image specification fields in gs_format, below. */
12985 enum gs_keyword_index
12987 GS_TYPE,
12988 GS_PT_WIDTH,
12989 GS_PT_HEIGHT,
12990 GS_FILE,
12991 GS_LOADER,
12992 GS_BOUNDING_BOX,
12993 GS_ASCENT,
12994 GS_MARGIN,
12995 GS_RELIEF,
12996 GS_ALGORITHM,
12997 GS_HEURISTIC_MASK,
12998 GS_MASK,
12999 GS_BACKGROUND,
13000 GS_LAST
13003 /* Vector of image_keyword structures describing the format
13004 of valid user-defined image specifications. */
13006 static struct image_keyword gs_format[GS_LAST] =
13008 {":type", IMAGE_SYMBOL_VALUE, 1},
13009 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13010 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13011 {":file", IMAGE_STRING_VALUE, 1},
13012 {":loader", IMAGE_FUNCTION_VALUE, 0},
13013 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
13014 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
13015 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
13016 {":relief", IMAGE_INTEGER_VALUE, 0},
13017 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13018 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13019 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13020 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
13023 /* Structure describing the image type `ghostscript'. */
13025 static struct image_type gs_type =
13027 &Qpostscript,
13028 gs_image_p,
13029 gs_load,
13030 gs_clear_image,
13031 NULL
13035 /* Free X resources of Ghostscript image IMG which is used on frame F. */
13037 static void
13038 gs_clear_image (f, img)
13039 struct frame *f;
13040 struct image *img;
13042 /* IMG->data.ptr_val may contain a recorded colormap. */
13043 xfree (img->data.ptr_val);
13044 x_clear_image (f, img);
13048 /* Return non-zero if OBJECT is a valid Ghostscript image
13049 specification. */
13051 static int
13052 gs_image_p (object)
13053 Lisp_Object object;
13055 struct image_keyword fmt[GS_LAST];
13056 Lisp_Object tem;
13057 int i;
13059 bcopy (gs_format, fmt, sizeof fmt);
13061 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
13062 || (fmt[GS_ASCENT].count
13063 && XFASTINT (fmt[GS_ASCENT].value) > 100))
13064 return 0;
13066 /* Bounding box must be a list or vector containing 4 integers. */
13067 tem = fmt[GS_BOUNDING_BOX].value;
13068 if (CONSP (tem))
13070 for (i = 0; i < 4; ++i, tem = XCDR (tem))
13071 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
13072 return 0;
13073 if (!NILP (tem))
13074 return 0;
13076 else if (VECTORP (tem))
13078 if (XVECTOR (tem)->size != 4)
13079 return 0;
13080 for (i = 0; i < 4; ++i)
13081 if (!INTEGERP (XVECTOR (tem)->contents[i]))
13082 return 0;
13084 else
13085 return 0;
13087 return 1;
13091 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
13092 if successful. */
13094 static int
13095 gs_load (f, img)
13096 struct frame *f;
13097 struct image *img;
13099 char buffer[100];
13100 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
13101 struct gcpro gcpro1, gcpro2;
13102 Lisp_Object frame;
13103 double in_width, in_height;
13104 Lisp_Object pixel_colors = Qnil;
13106 /* Compute pixel size of pixmap needed from the given size in the
13107 image specification. Sizes in the specification are in pt. 1 pt
13108 = 1/72 in, xdpi and ydpi are stored in the frame's X display
13109 info. */
13110 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
13111 in_width = XFASTINT (pt_width) / 72.0;
13112 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
13113 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
13114 in_height = XFASTINT (pt_height) / 72.0;
13115 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
13117 /* Create the pixmap. */
13118 BLOCK_INPUT;
13119 xassert (img->pixmap == 0);
13120 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13121 img->width, img->height,
13122 one_w32_display_info.n_cbits);
13123 UNBLOCK_INPUT;
13125 if (!img->pixmap)
13127 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
13128 return 0;
13131 /* Call the loader to fill the pixmap. It returns a process object
13132 if successful. We do not record_unwind_protect here because
13133 other places in redisplay like calling window scroll functions
13134 don't either. Let the Lisp loader use `unwind-protect' instead. */
13135 GCPRO2 (window_and_pixmap_id, pixel_colors);
13137 sprintf (buffer, "%lu %lu",
13138 (unsigned long) FRAME_W32_WINDOW (f),
13139 (unsigned long) img->pixmap);
13140 window_and_pixmap_id = build_string (buffer);
13142 sprintf (buffer, "%lu %lu",
13143 FRAME_FOREGROUND_PIXEL (f),
13144 FRAME_BACKGROUND_PIXEL (f));
13145 pixel_colors = build_string (buffer);
13147 XSETFRAME (frame, f);
13148 loader = image_spec_value (img->spec, QCloader, NULL);
13149 if (NILP (loader))
13150 loader = intern ("gs-load-image");
13152 img->data.lisp_val = call6 (loader, frame, img->spec,
13153 make_number (img->width),
13154 make_number (img->height),
13155 window_and_pixmap_id,
13156 pixel_colors);
13157 UNGCPRO;
13158 return PROCESSP (img->data.lisp_val);
13162 /* Kill the Ghostscript process that was started to fill PIXMAP on
13163 frame F. Called from XTread_socket when receiving an event
13164 telling Emacs that Ghostscript has finished drawing. */
13166 void
13167 x_kill_gs_process (pixmap, f)
13168 Pixmap pixmap;
13169 struct frame *f;
13171 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
13172 int class, i;
13173 struct image *img;
13175 /* Find the image containing PIXMAP. */
13176 for (i = 0; i < c->used; ++i)
13177 if (c->images[i]->pixmap == pixmap)
13178 break;
13180 /* Should someone in between have cleared the image cache, for
13181 instance, give up. */
13182 if (i == c->used)
13183 return;
13185 /* Kill the GS process. We should have found PIXMAP in the image
13186 cache and its image should contain a process object. */
13187 img = c->images[i];
13188 xassert (PROCESSP (img->data.lisp_val));
13189 Fkill_process (img->data.lisp_val, Qnil);
13190 img->data.lisp_val = Qnil;
13192 /* On displays with a mutable colormap, figure out the colors
13193 allocated for the image by looking at the pixels of an XImage for
13194 img->pixmap. */
13195 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
13196 if (class != StaticColor && class != StaticGray && class != TrueColor)
13198 XImage *ximg;
13200 BLOCK_INPUT;
13202 /* Try to get an XImage for img->pixmep. */
13203 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
13204 0, 0, img->width, img->height, ~0, ZPixmap);
13205 if (ximg)
13207 int x, y;
13209 /* Initialize the color table. */
13210 init_color_table ();
13212 /* For each pixel of the image, look its color up in the
13213 color table. After having done so, the color table will
13214 contain an entry for each color used by the image. */
13215 for (y = 0; y < img->height; ++y)
13216 for (x = 0; x < img->width; ++x)
13218 unsigned long pixel = XGetPixel (ximg, x, y);
13219 lookup_pixel_color (f, pixel);
13222 /* Record colors in the image. Free color table and XImage. */
13223 img->colors = colors_in_color_table (&img->ncolors);
13224 free_color_table ();
13225 XDestroyImage (ximg);
13227 #if 0 /* This doesn't seem to be the case. If we free the colors
13228 here, we get a BadAccess later in x_clear_image when
13229 freeing the colors. */
13230 /* We have allocated colors once, but Ghostscript has also
13231 allocated colors on behalf of us. So, to get the
13232 reference counts right, free them once. */
13233 if (img->ncolors)
13234 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
13235 img->colors, img->ncolors, 0);
13236 #endif
13238 else
13239 image_error ("Cannot get X image of `%s'; colors will not be freed",
13240 img->spec, Qnil);
13242 UNBLOCK_INPUT;
13245 /* Now that we have the pixmap, compute mask and transform the
13246 image if requested. */
13247 BLOCK_INPUT;
13248 postprocess_image (f, img);
13249 UNBLOCK_INPUT;
13252 #endif /* HAVE_GHOSTSCRIPT */
13255 /***********************************************************************
13256 Window properties
13257 ***********************************************************************/
13259 DEFUN ("x-change-window-property", Fx_change_window_property,
13260 Sx_change_window_property, 2, 3, 0,
13261 doc: /* Change window property PROP to VALUE on the X window of FRAME.
13262 PROP and VALUE must be strings. FRAME nil or omitted means use the
13263 selected frame. Value is VALUE. */)
13264 (prop, value, frame)
13265 Lisp_Object frame, prop, value;
13267 #if 0 /* TODO : port window properties to W32 */
13268 struct frame *f = check_x_frame (frame);
13269 Atom prop_atom;
13271 CHECK_STRING (prop);
13272 CHECK_STRING (value);
13274 BLOCK_INPUT;
13275 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13276 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13277 prop_atom, XA_STRING, 8, PropModeReplace,
13278 SDATA (value), SCHARS (value));
13280 /* Make sure the property is set when we return. */
13281 XFlush (FRAME_W32_DISPLAY (f));
13282 UNBLOCK_INPUT;
13284 #endif /* TODO */
13286 return value;
13290 DEFUN ("x-delete-window-property", Fx_delete_window_property,
13291 Sx_delete_window_property, 1, 2, 0,
13292 doc: /* Remove window property PROP from X window of FRAME.
13293 FRAME nil or omitted means use the selected frame. Value is PROP. */)
13294 (prop, frame)
13295 Lisp_Object prop, frame;
13297 #if 0 /* TODO : port window properties to W32 */
13299 struct frame *f = check_x_frame (frame);
13300 Atom prop_atom;
13302 CHECK_STRING (prop);
13303 BLOCK_INPUT;
13304 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13305 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
13307 /* Make sure the property is removed when we return. */
13308 XFlush (FRAME_W32_DISPLAY (f));
13309 UNBLOCK_INPUT;
13310 #endif /* TODO */
13312 return prop;
13316 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
13317 1, 2, 0,
13318 doc: /* Value is the value of window property PROP on FRAME.
13319 If FRAME is nil or omitted, use the selected frame. Value is nil
13320 if FRAME hasn't a property with name PROP or if PROP has no string
13321 value. */)
13322 (prop, frame)
13323 Lisp_Object prop, frame;
13325 #if 0 /* TODO : port window properties to W32 */
13327 struct frame *f = check_x_frame (frame);
13328 Atom prop_atom;
13329 int rc;
13330 Lisp_Object prop_value = Qnil;
13331 char *tmp_data = NULL;
13332 Atom actual_type;
13333 int actual_format;
13334 unsigned long actual_size, bytes_remaining;
13336 CHECK_STRING (prop);
13337 BLOCK_INPUT;
13338 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13339 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13340 prop_atom, 0, 0, False, XA_STRING,
13341 &actual_type, &actual_format, &actual_size,
13342 &bytes_remaining, (unsigned char **) &tmp_data);
13343 if (rc == Success)
13345 int size = bytes_remaining;
13347 XFree (tmp_data);
13348 tmp_data = NULL;
13350 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13351 prop_atom, 0, bytes_remaining,
13352 False, XA_STRING,
13353 &actual_type, &actual_format,
13354 &actual_size, &bytes_remaining,
13355 (unsigned char **) &tmp_data);
13356 if (rc == Success)
13357 prop_value = make_string (tmp_data, size);
13359 XFree (tmp_data);
13362 UNBLOCK_INPUT;
13364 return prop_value;
13366 #endif /* TODO */
13367 return Qnil;
13372 /***********************************************************************
13373 Busy cursor
13374 ***********************************************************************/
13376 /* If non-null, an asynchronous timer that, when it expires, displays
13377 an hourglass cursor on all frames. */
13379 static struct atimer *hourglass_atimer;
13381 /* Non-zero means an hourglass cursor is currently shown. */
13383 static int hourglass_shown_p;
13385 /* Number of seconds to wait before displaying an hourglass cursor. */
13387 static Lisp_Object Vhourglass_delay;
13389 /* Default number of seconds to wait before displaying an hourglass
13390 cursor. */
13392 #define DEFAULT_HOURGLASS_DELAY 1
13394 /* Function prototypes. */
13396 static void show_hourglass P_ ((struct atimer *));
13397 static void hide_hourglass P_ ((void));
13400 /* Cancel a currently active hourglass timer, and start a new one. */
13402 void
13403 start_hourglass ()
13405 #if 0 /* TODO: cursor shape changes. */
13406 EMACS_TIME delay;
13407 int secs, usecs = 0;
13409 cancel_hourglass ();
13411 if (INTEGERP (Vhourglass_delay)
13412 && XINT (Vhourglass_delay) > 0)
13413 secs = XFASTINT (Vhourglass_delay);
13414 else if (FLOATP (Vhourglass_delay)
13415 && XFLOAT_DATA (Vhourglass_delay) > 0)
13417 Lisp_Object tem;
13418 tem = Ftruncate (Vhourglass_delay, Qnil);
13419 secs = XFASTINT (tem);
13420 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
13422 else
13423 secs = DEFAULT_HOURGLASS_DELAY;
13425 EMACS_SET_SECS_USECS (delay, secs, usecs);
13426 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
13427 show_hourglass, NULL);
13428 #endif
13432 /* Cancel the hourglass cursor timer if active, hide an hourglass
13433 cursor if shown. */
13435 void
13436 cancel_hourglass ()
13438 if (hourglass_atimer)
13440 cancel_atimer (hourglass_atimer);
13441 hourglass_atimer = NULL;
13444 if (hourglass_shown_p)
13445 hide_hourglass ();
13449 /* Timer function of hourglass_atimer. TIMER is equal to
13450 hourglass_atimer.
13452 Display an hourglass cursor on all frames by mapping the frames'
13453 hourglass_window. Set the hourglass_p flag in the frames'
13454 output_data.x structure to indicate that an hourglass cursor is
13455 shown on the frames. */
13457 static void
13458 show_hourglass (timer)
13459 struct atimer *timer;
13461 #if 0 /* TODO: cursor shape changes. */
13462 /* The timer implementation will cancel this timer automatically
13463 after this function has run. Set hourglass_atimer to null
13464 so that we know the timer doesn't have to be canceled. */
13465 hourglass_atimer = NULL;
13467 if (!hourglass_shown_p)
13469 Lisp_Object rest, frame;
13471 BLOCK_INPUT;
13473 FOR_EACH_FRAME (rest, frame)
13474 if (FRAME_W32_P (XFRAME (frame)))
13476 struct frame *f = XFRAME (frame);
13478 f->output_data.w32->hourglass_p = 1;
13480 if (!f->output_data.w32->hourglass_window)
13482 unsigned long mask = CWCursor;
13483 XSetWindowAttributes attrs;
13485 attrs.cursor = f->output_data.w32->hourglass_cursor;
13487 f->output_data.w32->hourglass_window
13488 = XCreateWindow (FRAME_X_DISPLAY (f),
13489 FRAME_OUTER_WINDOW (f),
13490 0, 0, 32000, 32000, 0, 0,
13491 InputOnly,
13492 CopyFromParent,
13493 mask, &attrs);
13496 XMapRaised (FRAME_X_DISPLAY (f),
13497 f->output_data.w32->hourglass_window);
13498 XFlush (FRAME_X_DISPLAY (f));
13501 hourglass_shown_p = 1;
13502 UNBLOCK_INPUT;
13504 #endif
13508 /* Hide the hourglass cursor on all frames, if it is currently shown. */
13510 static void
13511 hide_hourglass ()
13513 #if 0 /* TODO: cursor shape changes. */
13514 if (hourglass_shown_p)
13516 Lisp_Object rest, frame;
13518 BLOCK_INPUT;
13519 FOR_EACH_FRAME (rest, frame)
13521 struct frame *f = XFRAME (frame);
13523 if (FRAME_W32_P (f)
13524 /* Watch out for newly created frames. */
13525 && f->output_data.x->hourglass_window)
13527 XUnmapWindow (FRAME_X_DISPLAY (f),
13528 f->output_data.x->hourglass_window);
13529 /* Sync here because XTread_socket looks at the
13530 hourglass_p flag that is reset to zero below. */
13531 XSync (FRAME_X_DISPLAY (f), False);
13532 f->output_data.x->hourglass_p = 0;
13536 hourglass_shown_p = 0;
13537 UNBLOCK_INPUT;
13539 #endif
13544 /***********************************************************************
13545 Tool tips
13546 ***********************************************************************/
13548 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
13549 Lisp_Object, Lisp_Object));
13550 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
13551 Lisp_Object, int, int, int *, int *));
13553 /* The frame of a currently visible tooltip. */
13555 Lisp_Object tip_frame;
13557 /* If non-nil, a timer started that hides the last tooltip when it
13558 fires. */
13560 Lisp_Object tip_timer;
13561 Window tip_window;
13563 /* If non-nil, a vector of 3 elements containing the last args
13564 with which x-show-tip was called. See there. */
13566 Lisp_Object last_show_tip_args;
13568 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
13570 Lisp_Object Vx_max_tooltip_size;
13573 static Lisp_Object
13574 unwind_create_tip_frame (frame)
13575 Lisp_Object frame;
13577 Lisp_Object deleted;
13579 deleted = unwind_create_frame (frame);
13580 if (EQ (deleted, Qt))
13582 tip_window = NULL;
13583 tip_frame = Qnil;
13586 return deleted;
13590 /* Create a frame for a tooltip on the display described by DPYINFO.
13591 PARMS is a list of frame parameters. TEXT is the string to
13592 display in the tip frame. Value is the frame.
13594 Note that functions called here, esp. x_default_parameter can
13595 signal errors, for instance when a specified color name is
13596 undefined. We have to make sure that we're in a consistent state
13597 when this happens. */
13599 static Lisp_Object
13600 x_create_tip_frame (dpyinfo, parms, text)
13601 struct w32_display_info *dpyinfo;
13602 Lisp_Object parms, text;
13604 struct frame *f;
13605 Lisp_Object frame, tem;
13606 Lisp_Object name;
13607 long window_prompting = 0;
13608 int width, height;
13609 int count = SPECPDL_INDEX ();
13610 struct gcpro gcpro1, gcpro2, gcpro3;
13611 struct kboard *kb;
13612 int face_change_count_before = face_change_count;
13613 Lisp_Object buffer;
13614 struct buffer *old_buffer;
13616 check_w32 ();
13618 /* Use this general default value to start with until we know if
13619 this frame has a specified name. */
13620 Vx_resource_name = Vinvocation_name;
13622 #ifdef MULTI_KBOARD
13623 kb = dpyinfo->kboard;
13624 #else
13625 kb = &the_only_kboard;
13626 #endif
13628 /* Get the name of the frame to use for resource lookup. */
13629 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
13630 if (!STRINGP (name)
13631 && !EQ (name, Qunbound)
13632 && !NILP (name))
13633 error ("Invalid frame name--not a string or nil");
13634 Vx_resource_name = name;
13636 frame = Qnil;
13637 GCPRO3 (parms, name, frame);
13638 /* Make a frame without minibuffer nor mode-line. */
13639 f = make_frame (0);
13640 f->wants_modeline = 0;
13641 XSETFRAME (frame, f);
13643 buffer = Fget_buffer_create (build_string (" *tip*"));
13644 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
13645 old_buffer = current_buffer;
13646 set_buffer_internal_1 (XBUFFER (buffer));
13647 current_buffer->truncate_lines = Qnil;
13648 Ferase_buffer ();
13649 Finsert (1, &text);
13650 set_buffer_internal_1 (old_buffer);
13652 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
13653 record_unwind_protect (unwind_create_tip_frame, frame);
13655 /* By setting the output method, we're essentially saying that
13656 the frame is live, as per FRAME_LIVE_P. If we get a signal
13657 from this point on, x_destroy_window might screw up reference
13658 counts etc. */
13659 f->output_method = output_w32;
13660 f->output_data.w32 =
13661 (struct w32_output *) xmalloc (sizeof (struct w32_output));
13662 bzero (f->output_data.w32, sizeof (struct w32_output));
13664 FRAME_FONTSET (f) = -1;
13665 f->icon_name = Qnil;
13667 #if 0 /* GLYPH_DEBUG TODO: image support. */
13668 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
13669 dpyinfo_refcount = dpyinfo->reference_count;
13670 #endif /* GLYPH_DEBUG */
13671 #ifdef MULTI_KBOARD
13672 FRAME_KBOARD (f) = kb;
13673 #endif
13674 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13675 f->output_data.w32->explicit_parent = 0;
13677 /* Set the name; the functions to which we pass f expect the name to
13678 be set. */
13679 if (EQ (name, Qunbound) || NILP (name))
13681 f->name = build_string (dpyinfo->w32_id_name);
13682 f->explicit_name = 0;
13684 else
13686 f->name = name;
13687 f->explicit_name = 1;
13688 /* use the frame's title when getting resources for this frame. */
13689 specbind (Qx_resource_name, name);
13692 /* Extract the window parameters from the supplied values
13693 that are needed to determine window geometry. */
13695 Lisp_Object font;
13697 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
13699 BLOCK_INPUT;
13700 /* First, try whatever font the caller has specified. */
13701 if (STRINGP (font))
13703 tem = Fquery_fontset (font, Qnil);
13704 if (STRINGP (tem))
13705 font = x_new_fontset (f, SDATA (tem));
13706 else
13707 font = x_new_font (f, SDATA (font));
13710 /* Try out a font which we hope has bold and italic variations. */
13711 if (!STRINGP (font))
13712 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
13713 if (! STRINGP (font))
13714 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
13715 /* If those didn't work, look for something which will at least work. */
13716 if (! STRINGP (font))
13717 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
13718 UNBLOCK_INPUT;
13719 if (! STRINGP (font))
13720 font = build_string ("Fixedsys");
13722 x_default_parameter (f, parms, Qfont, font,
13723 "font", "Font", RES_TYPE_STRING);
13726 x_default_parameter (f, parms, Qborder_width, make_number (2),
13727 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
13728 /* This defaults to 2 in order to match xterm. We recognize either
13729 internalBorderWidth or internalBorder (which is what xterm calls
13730 it). */
13731 if (NILP (Fassq (Qinternal_border_width, parms)))
13733 Lisp_Object value;
13735 value = w32_get_arg (parms, Qinternal_border_width,
13736 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
13737 if (! EQ (value, Qunbound))
13738 parms = Fcons (Fcons (Qinternal_border_width, value),
13739 parms);
13741 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
13742 "internalBorderWidth", "internalBorderWidth",
13743 RES_TYPE_NUMBER);
13745 /* Also do the stuff which must be set before the window exists. */
13746 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
13747 "foreground", "Foreground", RES_TYPE_STRING);
13748 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
13749 "background", "Background", RES_TYPE_STRING);
13750 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
13751 "pointerColor", "Foreground", RES_TYPE_STRING);
13752 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
13753 "cursorColor", "Foreground", RES_TYPE_STRING);
13754 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
13755 "borderColor", "BorderColor", RES_TYPE_STRING);
13757 /* Init faces before x_default_parameter is called for scroll-bar
13758 parameters because that function calls x_set_scroll_bar_width,
13759 which calls change_frame_size, which calls Fset_window_buffer,
13760 which runs hooks, which call Fvertical_motion. At the end, we
13761 end up in init_iterator with a null face cache, which should not
13762 happen. */
13763 init_frame_faces (f);
13765 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
13766 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13768 window_prompting = x_figure_window_size (f, parms);
13770 /* No fringes on tip frame. */
13771 f->output_data.w32->fringes_extra = 0;
13772 f->output_data.w32->fringe_cols = 0;
13773 f->output_data.w32->left_fringe_width = 0;
13774 f->output_data.w32->right_fringe_width = 0;
13776 if (window_prompting & XNegative)
13778 if (window_prompting & YNegative)
13779 f->output_data.w32->win_gravity = SouthEastGravity;
13780 else
13781 f->output_data.w32->win_gravity = NorthEastGravity;
13783 else
13785 if (window_prompting & YNegative)
13786 f->output_data.w32->win_gravity = SouthWestGravity;
13787 else
13788 f->output_data.w32->win_gravity = NorthWestGravity;
13791 f->output_data.w32->size_hint_flags = window_prompting;
13793 BLOCK_INPUT;
13794 my_create_tip_window (f);
13795 UNBLOCK_INPUT;
13797 x_make_gc (f);
13799 x_default_parameter (f, parms, Qauto_raise, Qnil,
13800 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13801 x_default_parameter (f, parms, Qauto_lower, Qnil,
13802 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13803 x_default_parameter (f, parms, Qcursor_type, Qbox,
13804 "cursorType", "CursorType", RES_TYPE_SYMBOL);
13806 /* Dimensions, especially f->height, must be done via change_frame_size.
13807 Change will not be effected unless different from the current
13808 f->height. */
13809 width = f->width;
13810 height = f->height;
13811 f->height = 0;
13812 SET_FRAME_WIDTH (f, 0);
13813 change_frame_size (f, height, width, 1, 0, 0);
13815 /* Add `tooltip' frame parameter's default value. */
13816 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
13817 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
13818 Qnil));
13820 /* Set up faces after all frame parameters are known. This call
13821 also merges in face attributes specified for new frames.
13823 Frame parameters may be changed if .Xdefaults contains
13824 specifications for the default font. For example, if there is an
13825 `Emacs.default.attributeBackground: pink', the `background-color'
13826 attribute of the frame get's set, which let's the internal border
13827 of the tooltip frame appear in pink. Prevent this. */
13829 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
13831 /* Set tip_frame here, so that */
13832 tip_frame = frame;
13833 call1 (Qface_set_after_frame_default, frame);
13835 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
13836 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
13837 Qnil));
13840 f->no_split = 1;
13842 UNGCPRO;
13844 /* It is now ok to make the frame official even if we get an error
13845 below. And the frame needs to be on Vframe_list or making it
13846 visible won't work. */
13847 Vframe_list = Fcons (frame, Vframe_list);
13849 /* Now that the frame is official, it counts as a reference to
13850 its display. */
13851 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
13853 /* Setting attributes of faces of the tooltip frame from resources
13854 and similar will increment face_change_count, which leads to the
13855 clearing of all current matrices. Since this isn't necessary
13856 here, avoid it by resetting face_change_count to the value it
13857 had before we created the tip frame. */
13858 face_change_count = face_change_count_before;
13860 /* Discard the unwind_protect. */
13861 return unbind_to (count, frame);
13865 /* Compute where to display tip frame F. PARMS is the list of frame
13866 parameters for F. DX and DY are specified offsets from the current
13867 location of the mouse. WIDTH and HEIGHT are the width and height
13868 of the tooltip. Return coordinates relative to the root window of
13869 the display in *ROOT_X, and *ROOT_Y. */
13871 static void
13872 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
13873 struct frame *f;
13874 Lisp_Object parms, dx, dy;
13875 int width, height;
13876 int *root_x, *root_y;
13878 Lisp_Object left, top;
13880 /* User-specified position? */
13881 left = Fcdr (Fassq (Qleft, parms));
13882 top = Fcdr (Fassq (Qtop, parms));
13884 /* Move the tooltip window where the mouse pointer is. Resize and
13885 show it. */
13886 if (!INTEGERP (left) || !INTEGERP (top))
13888 POINT pt;
13890 BLOCK_INPUT;
13891 GetCursorPos (&pt);
13892 *root_x = pt.x;
13893 *root_y = pt.y;
13894 UNBLOCK_INPUT;
13897 if (INTEGERP (top))
13898 *root_y = XINT (top);
13899 else if (*root_y + XINT (dy) - height < 0)
13900 *root_y -= XINT (dy);
13901 else
13903 *root_y -= height;
13904 *root_y += XINT (dy);
13907 if (INTEGERP (left))
13908 *root_x = XINT (left);
13909 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
13910 /* It fits to the right of the pointer. */
13911 *root_x += XINT (dx);
13912 else if (width + XINT (dx) <= *root_x)
13913 /* It fits to the left of the pointer. */
13914 *root_x -= width + XINT (dx);
13915 else
13916 /* Put it left justified on the screen -- it ought to fit that way. */
13917 *root_x = 0;
13921 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
13922 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
13923 A tooltip window is a small window displaying a string.
13925 FRAME nil or omitted means use the selected frame.
13927 PARMS is an optional list of frame parameters which can be
13928 used to change the tooltip's appearance.
13930 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
13931 means use the default timeout of 5 seconds.
13933 If the list of frame parameters PARAMS contains a `left' parameter,
13934 the tooltip is displayed at that x-position. Otherwise it is
13935 displayed at the mouse position, with offset DX added (default is 5 if
13936 DX isn't specified). Likewise for the y-position; if a `top' frame
13937 parameter is specified, it determines the y-position of the tooltip
13938 window, otherwise it is displayed at the mouse position, with offset
13939 DY added (default is -10).
13941 A tooltip's maximum size is specified by `x-max-tooltip-size'.
13942 Text larger than the specified size is clipped. */)
13943 (string, frame, parms, timeout, dx, dy)
13944 Lisp_Object string, frame, parms, timeout, dx, dy;
13946 struct frame *f;
13947 struct window *w;
13948 int root_x, root_y;
13949 struct buffer *old_buffer;
13950 struct text_pos pos;
13951 int i, width, height;
13952 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
13953 int old_windows_or_buffers_changed = windows_or_buffers_changed;
13954 int count = SPECPDL_INDEX ();
13956 specbind (Qinhibit_redisplay, Qt);
13958 GCPRO4 (string, parms, frame, timeout);
13960 CHECK_STRING (string);
13961 f = check_x_frame (frame);
13962 if (NILP (timeout))
13963 timeout = make_number (5);
13964 else
13965 CHECK_NATNUM (timeout);
13967 if (NILP (dx))
13968 dx = make_number (5);
13969 else
13970 CHECK_NUMBER (dx);
13972 if (NILP (dy))
13973 dy = make_number (-10);
13974 else
13975 CHECK_NUMBER (dy);
13977 if (NILP (last_show_tip_args))
13978 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
13980 if (!NILP (tip_frame))
13982 Lisp_Object last_string = AREF (last_show_tip_args, 0);
13983 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
13984 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
13986 if (EQ (frame, last_frame)
13987 && !NILP (Fequal (last_string, string))
13988 && !NILP (Fequal (last_parms, parms)))
13990 struct frame *f = XFRAME (tip_frame);
13992 /* Only DX and DY have changed. */
13993 if (!NILP (tip_timer))
13995 Lisp_Object timer = tip_timer;
13996 tip_timer = Qnil;
13997 call1 (Qcancel_timer, timer);
14000 BLOCK_INPUT;
14001 compute_tip_xy (f, parms, dx, dy, PIXEL_WIDTH (f),
14002 PIXEL_HEIGHT (f), &root_x, &root_y);
14004 /* Put tooltip in topmost group and in position. */
14005 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14006 root_x, root_y, 0, 0,
14007 SWP_NOSIZE | SWP_NOACTIVATE);
14009 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14010 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14011 0, 0, 0, 0,
14012 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14014 UNBLOCK_INPUT;
14015 goto start_timer;
14019 /* Hide a previous tip, if any. */
14020 Fx_hide_tip ();
14022 ASET (last_show_tip_args, 0, string);
14023 ASET (last_show_tip_args, 1, frame);
14024 ASET (last_show_tip_args, 2, parms);
14026 /* Add default values to frame parameters. */
14027 if (NILP (Fassq (Qname, parms)))
14028 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
14029 if (NILP (Fassq (Qinternal_border_width, parms)))
14030 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
14031 if (NILP (Fassq (Qborder_width, parms)))
14032 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
14033 if (NILP (Fassq (Qborder_color, parms)))
14034 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
14035 if (NILP (Fassq (Qbackground_color, parms)))
14036 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
14037 parms);
14039 /* Block input until the tip has been fully drawn, to avoid crashes
14040 when drawing tips in menus. */
14041 BLOCK_INPUT;
14043 /* Create a frame for the tooltip, and record it in the global
14044 variable tip_frame. */
14045 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
14046 f = XFRAME (frame);
14048 /* Set up the frame's root window. */
14049 w = XWINDOW (FRAME_ROOT_WINDOW (f));
14050 w->left = w->top = make_number (0);
14052 if (CONSP (Vx_max_tooltip_size)
14053 && INTEGERP (XCAR (Vx_max_tooltip_size))
14054 && XINT (XCAR (Vx_max_tooltip_size)) > 0
14055 && INTEGERP (XCDR (Vx_max_tooltip_size))
14056 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
14058 w->width = XCAR (Vx_max_tooltip_size);
14059 w->height = XCDR (Vx_max_tooltip_size);
14061 else
14063 w->width = make_number (80);
14064 w->height = make_number (40);
14067 f->window_width = XINT (w->width);
14068 adjust_glyphs (f);
14069 w->pseudo_window_p = 1;
14071 /* Display the tooltip text in a temporary buffer. */
14072 old_buffer = current_buffer;
14073 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
14074 current_buffer->truncate_lines = Qnil;
14075 clear_glyph_matrix (w->desired_matrix);
14076 clear_glyph_matrix (w->current_matrix);
14077 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
14078 try_window (FRAME_ROOT_WINDOW (f), pos);
14080 /* Compute width and height of the tooltip. */
14081 width = height = 0;
14082 for (i = 0; i < w->desired_matrix->nrows; ++i)
14084 struct glyph_row *row = &w->desired_matrix->rows[i];
14085 struct glyph *last;
14086 int row_width;
14088 /* Stop at the first empty row at the end. */
14089 if (!row->enabled_p || !row->displays_text_p)
14090 break;
14092 /* Let the row go over the full width of the frame. */
14093 row->full_width_p = 1;
14095 #ifdef TODO /* Investigate why some fonts need more width than is
14096 calculated for some tooltips. */
14097 /* There's a glyph at the end of rows that is use to place
14098 the cursor there. Don't include the width of this glyph. */
14099 if (row->used[TEXT_AREA])
14101 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
14102 row_width = row->pixel_width - last->pixel_width;
14104 else
14105 #endif
14106 row_width = row->pixel_width;
14108 /* TODO: find why tips do not draw along baseline as instructed. */
14109 height += row->height;
14110 width = max (width, row_width);
14113 /* Add the frame's internal border to the width and height the X
14114 window should have. */
14115 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14116 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14118 /* Move the tooltip window where the mouse pointer is. Resize and
14119 show it. */
14120 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
14123 /* Adjust Window size to take border into account. */
14124 RECT rect;
14125 rect.left = rect.top = 0;
14126 rect.right = width;
14127 rect.bottom = height;
14128 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
14129 FRAME_EXTERNAL_MENU_BAR (f));
14131 /* Position and size tooltip, and put it in the topmost group. */
14132 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14133 root_x, root_y, rect.right - rect.left,
14134 rect.bottom - rect.top, SWP_NOACTIVATE);
14136 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14137 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14138 0, 0, 0, 0,
14139 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14141 /* Let redisplay know that we have made the frame visible already. */
14142 f->async_visible = 1;
14144 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
14147 /* Draw into the window. */
14148 w->must_be_updated_p = 1;
14149 update_single_window (w, 1);
14151 UNBLOCK_INPUT;
14153 /* Restore original current buffer. */
14154 set_buffer_internal_1 (old_buffer);
14155 windows_or_buffers_changed = old_windows_or_buffers_changed;
14157 start_timer:
14158 /* Let the tip disappear after timeout seconds. */
14159 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
14160 intern ("x-hide-tip"));
14162 UNGCPRO;
14163 return unbind_to (count, Qnil);
14167 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
14168 doc: /* Hide the current tooltip window, if there is any.
14169 Value is t if tooltip was open, nil otherwise. */)
14172 int count;
14173 Lisp_Object deleted, frame, timer;
14174 struct gcpro gcpro1, gcpro2;
14176 /* Return quickly if nothing to do. */
14177 if (NILP (tip_timer) && NILP (tip_frame))
14178 return Qnil;
14180 frame = tip_frame;
14181 timer = tip_timer;
14182 GCPRO2 (frame, timer);
14183 tip_frame = tip_timer = deleted = Qnil;
14185 count = SPECPDL_INDEX ();
14186 specbind (Qinhibit_redisplay, Qt);
14187 specbind (Qinhibit_quit, Qt);
14189 if (!NILP (timer))
14190 call1 (Qcancel_timer, timer);
14192 if (FRAMEP (frame))
14194 Fdelete_frame (frame, Qnil);
14195 deleted = Qt;
14198 UNGCPRO;
14199 return unbind_to (count, deleted);
14204 /***********************************************************************
14205 File selection dialog
14206 ***********************************************************************/
14207 extern Lisp_Object Qfile_name_history;
14209 /* Callback for altering the behaviour of the Open File dialog.
14210 Makes the Filename text field contain "Current Directory" and be
14211 read-only when "Directories" is selected in the filter. This
14212 allows us to work around the fact that the standard Open File
14213 dialog does not support directories. */
14214 UINT CALLBACK
14215 file_dialog_callback (hwnd, msg, wParam, lParam)
14216 HWND hwnd;
14217 UINT msg;
14218 WPARAM wParam;
14219 LPARAM lParam;
14221 if (msg == WM_NOTIFY)
14223 OFNOTIFY * notify = (OFNOTIFY *)lParam;
14224 /* Detect when the Filter dropdown is changed. */
14225 if (notify->hdr.code == CDN_TYPECHANGE)
14227 HWND dialog = GetParent (hwnd);
14228 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
14230 /* Directories is in index 2. */
14231 if (notify->lpOFN->nFilterIndex == 2)
14233 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14234 "Current Directory");
14235 EnableWindow (edit_control, FALSE);
14237 else
14239 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14240 "");
14241 EnableWindow (edit_control, TRUE);
14245 return 0;
14248 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
14249 doc: /* Read file name, prompting with PROMPT in directory DIR.
14250 Use a file selection dialog.
14251 Select DEFAULT-FILENAME in the dialog's file selection box, if
14252 specified. Ensure that file exists if MUSTMATCH is non-nil. */)
14253 (prompt, dir, default_filename, mustmatch)
14254 Lisp_Object prompt, dir, default_filename, mustmatch;
14256 struct frame *f = SELECTED_FRAME ();
14257 Lisp_Object file = Qnil;
14258 int count = SPECPDL_INDEX ();
14259 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
14260 char filename[MAX_PATH + 1];
14261 char init_dir[MAX_PATH + 1];
14263 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
14264 CHECK_STRING (prompt);
14265 CHECK_STRING (dir);
14267 /* Create the dialog with PROMPT as title, using DIR as initial
14268 directory and using "*" as pattern. */
14269 dir = Fexpand_file_name (dir, Qnil);
14270 strncpy (init_dir, SDATA (dir), MAX_PATH);
14271 init_dir[MAX_PATH] = '\0';
14272 unixtodos_filename (init_dir);
14274 if (STRINGP (default_filename))
14276 char *file_name_only;
14277 char *full_path_name = SDATA (default_filename);
14279 unixtodos_filename (full_path_name);
14281 file_name_only = strrchr (full_path_name, '\\');
14282 if (!file_name_only)
14283 file_name_only = full_path_name;
14284 else
14286 file_name_only++;
14289 strncpy (filename, file_name_only, MAX_PATH);
14290 filename[MAX_PATH] = '\0';
14292 else
14293 filename[0] = '\0';
14296 OPENFILENAME file_details;
14298 /* Prevent redisplay. */
14299 specbind (Qinhibit_redisplay, Qt);
14300 BLOCK_INPUT;
14302 bzero (&file_details, sizeof (file_details));
14303 file_details.lStructSize = sizeof (file_details);
14304 file_details.hwndOwner = FRAME_W32_WINDOW (f);
14305 /* Undocumented Bug in Common File Dialog:
14306 If a filter is not specified, shell links are not resolved. */
14307 file_details.lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
14308 file_details.lpstrFile = filename;
14309 file_details.nMaxFile = sizeof (filename);
14310 file_details.lpstrInitialDir = init_dir;
14311 file_details.lpstrTitle = SDATA (prompt);
14312 file_details.Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
14313 | OFN_EXPLORER | OFN_ENABLEHOOK);
14314 if (!NILP (mustmatch))
14315 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
14317 file_details.lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
14319 if (GetOpenFileName (&file_details))
14321 dostounix_filename (filename);
14322 if (file_details.nFilterIndex == 2)
14324 /* "Folder Only" selected - strip dummy file name. */
14325 char * last = strrchr (filename, '/');
14326 *last = '\0';
14329 file = DECODE_FILE(build_string (filename));
14331 /* User cancelled the dialog without making a selection. */
14332 else if (!CommDlgExtendedError ())
14333 file = Qnil;
14334 /* An error occurred, fallback on reading from the mini-buffer. */
14335 else
14336 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
14337 dir, mustmatch, dir, Qfile_name_history,
14338 default_filename, Qnil);
14340 UNBLOCK_INPUT;
14341 file = unbind_to (count, file);
14344 UNGCPRO;
14346 /* Make "Cancel" equivalent to C-g. */
14347 if (NILP (file))
14348 Fsignal (Qquit, Qnil);
14350 return unbind_to (count, file);
14355 /***********************************************************************
14356 w32 specialized functions
14357 ***********************************************************************/
14359 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
14360 doc: /* Select a font using the W32 font dialog.
14361 Returns an X font string corresponding to the selection. */)
14362 (frame, include_proportional)
14363 Lisp_Object frame, include_proportional;
14365 FRAME_PTR f = check_x_frame (frame);
14366 CHOOSEFONT cf;
14367 LOGFONT lf;
14368 TEXTMETRIC tm;
14369 HDC hdc;
14370 HANDLE oldobj;
14371 char buf[100];
14373 bzero (&cf, sizeof (cf));
14374 bzero (&lf, sizeof (lf));
14376 cf.lStructSize = sizeof (cf);
14377 cf.hwndOwner = FRAME_W32_WINDOW (f);
14378 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
14380 /* Unless include_proportional is non-nil, limit the selection to
14381 monospaced fonts. */
14382 if (NILP (include_proportional))
14383 cf.Flags |= CF_FIXEDPITCHONLY;
14385 cf.lpLogFont = &lf;
14387 /* Initialize as much of the font details as we can from the current
14388 default font. */
14389 hdc = GetDC (FRAME_W32_WINDOW (f));
14390 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
14391 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
14392 if (GetTextMetrics (hdc, &tm))
14394 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
14395 lf.lfWeight = tm.tmWeight;
14396 lf.lfItalic = tm.tmItalic;
14397 lf.lfUnderline = tm.tmUnderlined;
14398 lf.lfStrikeOut = tm.tmStruckOut;
14399 lf.lfCharSet = tm.tmCharSet;
14400 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
14402 SelectObject (hdc, oldobj);
14403 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
14405 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
14406 return Qnil;
14408 return build_string (buf);
14411 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
14412 Sw32_send_sys_command, 1, 2, 0,
14413 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
14414 Some useful values for command are #xf030 to maximise frame (#xf020
14415 to minimize), #xf120 to restore frame to original size, and #xf100
14416 to activate the menubar for keyboard access. #xf140 activates the
14417 screen saver if defined.
14419 If optional parameter FRAME is not specified, use selected frame. */)
14420 (command, frame)
14421 Lisp_Object command, frame;
14423 FRAME_PTR f = check_x_frame (frame);
14425 CHECK_NUMBER (command);
14427 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
14429 return Qnil;
14432 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
14433 doc: /* Get Windows to perform OPERATION on DOCUMENT.
14434 This is a wrapper around the ShellExecute system function, which
14435 invokes the application registered to handle OPERATION for DOCUMENT.
14436 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
14437 nil for the default action), and DOCUMENT is typically the name of a
14438 document file or URL, but can also be a program executable to run or
14439 a directory to open in the Windows Explorer.
14441 If DOCUMENT is a program executable, PARAMETERS can be a string
14442 containing command line parameters, but otherwise should be nil.
14444 SHOW-FLAG can be used to control whether the invoked application is hidden
14445 or minimized. If SHOW-FLAG is nil, the application is displayed normally,
14446 otherwise it is an integer representing a ShowWindow flag:
14448 0 - start hidden
14449 1 - start normally
14450 3 - start maximized
14451 6 - start minimized */)
14452 (operation, document, parameters, show_flag)
14453 Lisp_Object operation, document, parameters, show_flag;
14455 Lisp_Object current_dir;
14457 CHECK_STRING (document);
14459 /* Encode filename and current directory. */
14460 current_dir = ENCODE_FILE (current_buffer->directory);
14461 document = ENCODE_FILE (document);
14462 if ((int) ShellExecute (NULL,
14463 (STRINGP (operation) ?
14464 SDATA (operation) : NULL),
14465 SDATA (document),
14466 (STRINGP (parameters) ?
14467 SDATA (parameters) : NULL),
14468 SDATA (current_dir),
14469 (INTEGERP (show_flag) ?
14470 XINT (show_flag) : SW_SHOWDEFAULT))
14471 > 32)
14472 return Qt;
14473 error ("ShellExecute failed: %s", w32_strerror (0));
14476 /* Lookup virtual keycode from string representing the name of a
14477 non-ascii keystroke into the corresponding virtual key, using
14478 lispy_function_keys. */
14479 static int
14480 lookup_vk_code (char *key)
14482 int i;
14484 for (i = 0; i < 256; i++)
14485 if (lispy_function_keys[i] != 0
14486 && strcmp (lispy_function_keys[i], key) == 0)
14487 return i;
14489 return -1;
14492 /* Convert a one-element vector style key sequence to a hot key
14493 definition. */
14494 static int
14495 w32_parse_hot_key (key)
14496 Lisp_Object key;
14498 /* Copied from Fdefine_key and store_in_keymap. */
14499 register Lisp_Object c;
14500 int vk_code;
14501 int lisp_modifiers;
14502 int w32_modifiers;
14503 struct gcpro gcpro1;
14505 CHECK_VECTOR (key);
14507 if (XFASTINT (Flength (key)) != 1)
14508 return Qnil;
14510 GCPRO1 (key);
14512 c = Faref (key, make_number (0));
14514 if (CONSP (c) && lucid_event_type_list_p (c))
14515 c = Fevent_convert_list (c);
14517 UNGCPRO;
14519 if (! INTEGERP (c) && ! SYMBOLP (c))
14520 error ("Key definition is invalid");
14522 /* Work out the base key and the modifiers. */
14523 if (SYMBOLP (c))
14525 c = parse_modifiers (c);
14526 lisp_modifiers = Fcar (Fcdr (c));
14527 c = Fcar (c);
14528 if (!SYMBOLP (c))
14529 abort ();
14530 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
14532 else if (INTEGERP (c))
14534 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
14535 /* Many ascii characters are their own virtual key code. */
14536 vk_code = XINT (c) & CHARACTERBITS;
14539 if (vk_code < 0 || vk_code > 255)
14540 return Qnil;
14542 if ((lisp_modifiers & meta_modifier) != 0
14543 && !NILP (Vw32_alt_is_meta))
14544 lisp_modifiers |= alt_modifier;
14546 /* Supply defs missing from mingw32. */
14547 #ifndef MOD_ALT
14548 #define MOD_ALT 0x0001
14549 #define MOD_CONTROL 0x0002
14550 #define MOD_SHIFT 0x0004
14551 #define MOD_WIN 0x0008
14552 #endif
14554 /* Convert lisp modifiers to Windows hot-key form. */
14555 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
14556 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
14557 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
14558 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
14560 return HOTKEY (vk_code, w32_modifiers);
14563 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
14564 Sw32_register_hot_key, 1, 1, 0,
14565 doc: /* Register KEY as a hot-key combination.
14566 Certain key combinations like Alt-Tab are reserved for system use on
14567 Windows, and therefore are normally intercepted by the system. However,
14568 most of these key combinations can be received by registering them as
14569 hot-keys, overriding their special meaning.
14571 KEY must be a one element key definition in vector form that would be
14572 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
14573 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
14574 is always interpreted as the Windows modifier keys.
14576 The return value is the hotkey-id if registered, otherwise nil. */)
14577 (key)
14578 Lisp_Object key;
14580 key = w32_parse_hot_key (key);
14582 if (NILP (Fmemq (key, w32_grabbed_keys)))
14584 /* Reuse an empty slot if possible. */
14585 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
14587 /* Safe to add new key to list, even if we have focus. */
14588 if (NILP (item))
14589 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
14590 else
14591 XSETCAR (item, key);
14593 /* Notify input thread about new hot-key definition, so that it
14594 takes effect without needing to switch focus. */
14595 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
14596 (WPARAM) key, 0);
14599 return key;
14602 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
14603 Sw32_unregister_hot_key, 1, 1, 0,
14604 doc: /* Unregister HOTKEY as a hot-key combination. */)
14605 (key)
14606 Lisp_Object key;
14608 Lisp_Object item;
14610 if (!INTEGERP (key))
14611 key = w32_parse_hot_key (key);
14613 item = Fmemq (key, w32_grabbed_keys);
14615 if (!NILP (item))
14617 /* Notify input thread about hot-key definition being removed, so
14618 that it takes effect without needing focus switch. */
14619 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
14620 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
14622 MSG msg;
14623 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14625 return Qt;
14627 return Qnil;
14630 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
14631 Sw32_registered_hot_keys, 0, 0, 0,
14632 doc: /* Return list of registered hot-key IDs. */)
14635 return Fcopy_sequence (w32_grabbed_keys);
14638 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
14639 Sw32_reconstruct_hot_key, 1, 1, 0,
14640 doc: /* Convert hot-key ID to a lisp key combination. */)
14641 (hotkeyid)
14642 Lisp_Object hotkeyid;
14644 int vk_code, w32_modifiers;
14645 Lisp_Object key;
14647 CHECK_NUMBER (hotkeyid);
14649 vk_code = HOTKEY_VK_CODE (hotkeyid);
14650 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
14652 if (lispy_function_keys[vk_code])
14653 key = intern (lispy_function_keys[vk_code]);
14654 else
14655 key = make_number (vk_code);
14657 key = Fcons (key, Qnil);
14658 if (w32_modifiers & MOD_SHIFT)
14659 key = Fcons (Qshift, key);
14660 if (w32_modifiers & MOD_CONTROL)
14661 key = Fcons (Qctrl, key);
14662 if (w32_modifiers & MOD_ALT)
14663 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
14664 if (w32_modifiers & MOD_WIN)
14665 key = Fcons (Qhyper, key);
14667 return key;
14670 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
14671 Sw32_toggle_lock_key, 1, 2, 0,
14672 doc: /* Toggle the state of the lock key KEY.
14673 KEY can be `capslock', `kp-numlock', or `scroll'.
14674 If the optional parameter NEW-STATE is a number, then the state of KEY
14675 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
14676 (key, new_state)
14677 Lisp_Object key, new_state;
14679 int vk_code;
14681 if (EQ (key, intern ("capslock")))
14682 vk_code = VK_CAPITAL;
14683 else if (EQ (key, intern ("kp-numlock")))
14684 vk_code = VK_NUMLOCK;
14685 else if (EQ (key, intern ("scroll")))
14686 vk_code = VK_SCROLL;
14687 else
14688 return Qnil;
14690 if (!dwWindowsThreadId)
14691 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
14693 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
14694 (WPARAM) vk_code, (LPARAM) new_state))
14696 MSG msg;
14697 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14698 return make_number (msg.wParam);
14700 return Qnil;
14703 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
14704 doc: /* Return storage information about the file system FILENAME is on.
14705 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
14706 storage of the file system, FREE is the free storage, and AVAIL is the
14707 storage available to a non-superuser. All 3 numbers are in bytes.
14708 If the underlying system call fails, value is nil. */)
14709 (filename)
14710 Lisp_Object filename;
14712 Lisp_Object encoded, value;
14714 CHECK_STRING (filename);
14715 filename = Fexpand_file_name (filename, Qnil);
14716 encoded = ENCODE_FILE (filename);
14718 value = Qnil;
14720 /* Determining the required information on Windows turns out, sadly,
14721 to be more involved than one would hope. The original Win32 api
14722 call for this will return bogus information on some systems, but we
14723 must dynamically probe for the replacement api, since that was
14724 added rather late on. */
14726 HMODULE hKernel = GetModuleHandle ("kernel32");
14727 BOOL (*pfn_GetDiskFreeSpaceEx)
14728 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
14729 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
14731 /* On Windows, we may need to specify the root directory of the
14732 volume holding FILENAME. */
14733 char rootname[MAX_PATH];
14734 char *name = SDATA (encoded);
14736 /* find the root name of the volume if given */
14737 if (isalpha (name[0]) && name[1] == ':')
14739 rootname[0] = name[0];
14740 rootname[1] = name[1];
14741 rootname[2] = '\\';
14742 rootname[3] = 0;
14744 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
14746 char *str = rootname;
14747 int slashes = 4;
14750 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
14751 break;
14752 *str++ = *name++;
14754 while ( *name );
14756 *str++ = '\\';
14757 *str = 0;
14760 if (pfn_GetDiskFreeSpaceEx)
14762 /* Unsigned large integers cannot be cast to double, so
14763 use signed ones instead. */
14764 LARGE_INTEGER availbytes;
14765 LARGE_INTEGER freebytes;
14766 LARGE_INTEGER totalbytes;
14768 if (pfn_GetDiskFreeSpaceEx(rootname,
14769 (ULARGE_INTEGER *)&availbytes,
14770 (ULARGE_INTEGER *)&totalbytes,
14771 (ULARGE_INTEGER *)&freebytes))
14772 value = list3 (make_float ((double) totalbytes.QuadPart),
14773 make_float ((double) freebytes.QuadPart),
14774 make_float ((double) availbytes.QuadPart));
14776 else
14778 DWORD sectors_per_cluster;
14779 DWORD bytes_per_sector;
14780 DWORD free_clusters;
14781 DWORD total_clusters;
14783 if (GetDiskFreeSpace(rootname,
14784 &sectors_per_cluster,
14785 &bytes_per_sector,
14786 &free_clusters,
14787 &total_clusters))
14788 value = list3 (make_float ((double) total_clusters
14789 * sectors_per_cluster * bytes_per_sector),
14790 make_float ((double) free_clusters
14791 * sectors_per_cluster * bytes_per_sector),
14792 make_float ((double) free_clusters
14793 * sectors_per_cluster * bytes_per_sector));
14797 return value;
14800 /***********************************************************************
14801 Initialization
14802 ***********************************************************************/
14804 void
14805 syms_of_w32fns ()
14807 HMODULE user32_lib = GetModuleHandle ("user32.dll");
14809 /* This is zero if not using MS-Windows. */
14810 w32_in_use = 0;
14812 /* TrackMouseEvent not available in all versions of Windows, so must load
14813 it dynamically. Do it once, here, instead of every time it is used. */
14814 track_mouse_event_fn = GetProcAddress (user32_lib, "TrackMouseEvent");
14815 track_mouse_window = NULL;
14817 w32_visible_system_caret_hwnd = NULL;
14819 Qauto_raise = intern ("auto-raise");
14820 staticpro (&Qauto_raise);
14821 Qauto_lower = intern ("auto-lower");
14822 staticpro (&Qauto_lower);
14823 Qborder_color = intern ("border-color");
14824 staticpro (&Qborder_color);
14825 Qborder_width = intern ("border-width");
14826 staticpro (&Qborder_width);
14827 Qcursor_color = intern ("cursor-color");
14828 staticpro (&Qcursor_color);
14829 Qcursor_type = intern ("cursor-type");
14830 staticpro (&Qcursor_type);
14831 Qgeometry = intern ("geometry");
14832 staticpro (&Qgeometry);
14833 Qicon_left = intern ("icon-left");
14834 staticpro (&Qicon_left);
14835 Qicon_top = intern ("icon-top");
14836 staticpro (&Qicon_top);
14837 Qicon_type = intern ("icon-type");
14838 staticpro (&Qicon_type);
14839 Qicon_name = intern ("icon-name");
14840 staticpro (&Qicon_name);
14841 Qinternal_border_width = intern ("internal-border-width");
14842 staticpro (&Qinternal_border_width);
14843 Qleft = intern ("left");
14844 staticpro (&Qleft);
14845 Qright = intern ("right");
14846 staticpro (&Qright);
14847 Qmouse_color = intern ("mouse-color");
14848 staticpro (&Qmouse_color);
14849 Qnone = intern ("none");
14850 staticpro (&Qnone);
14851 Qparent_id = intern ("parent-id");
14852 staticpro (&Qparent_id);
14853 Qscroll_bar_width = intern ("scroll-bar-width");
14854 staticpro (&Qscroll_bar_width);
14855 Qsuppress_icon = intern ("suppress-icon");
14856 staticpro (&Qsuppress_icon);
14857 Qundefined_color = intern ("undefined-color");
14858 staticpro (&Qundefined_color);
14859 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
14860 staticpro (&Qvertical_scroll_bars);
14861 Qvisibility = intern ("visibility");
14862 staticpro (&Qvisibility);
14863 Qwindow_id = intern ("window-id");
14864 staticpro (&Qwindow_id);
14865 Qx_frame_parameter = intern ("x-frame-parameter");
14866 staticpro (&Qx_frame_parameter);
14867 Qx_resource_name = intern ("x-resource-name");
14868 staticpro (&Qx_resource_name);
14869 Quser_position = intern ("user-position");
14870 staticpro (&Quser_position);
14871 Quser_size = intern ("user-size");
14872 staticpro (&Quser_size);
14873 Qscreen_gamma = intern ("screen-gamma");
14874 staticpro (&Qscreen_gamma);
14875 Qline_spacing = intern ("line-spacing");
14876 staticpro (&Qline_spacing);
14877 Qcenter = intern ("center");
14878 staticpro (&Qcenter);
14879 Qcancel_timer = intern ("cancel-timer");
14880 staticpro (&Qcancel_timer);
14881 Qfullscreen = intern ("fullscreen");
14882 staticpro (&Qfullscreen);
14883 Qfullwidth = intern ("fullwidth");
14884 staticpro (&Qfullwidth);
14885 Qfullheight = intern ("fullheight");
14886 staticpro (&Qfullheight);
14887 Qfullboth = intern ("fullboth");
14888 staticpro (&Qfullboth);
14890 Qhyper = intern ("hyper");
14891 staticpro (&Qhyper);
14892 Qsuper = intern ("super");
14893 staticpro (&Qsuper);
14894 Qmeta = intern ("meta");
14895 staticpro (&Qmeta);
14896 Qalt = intern ("alt");
14897 staticpro (&Qalt);
14898 Qctrl = intern ("ctrl");
14899 staticpro (&Qctrl);
14900 Qcontrol = intern ("control");
14901 staticpro (&Qcontrol);
14902 Qshift = intern ("shift");
14903 staticpro (&Qshift);
14904 /* This is the end of symbol initialization. */
14906 /* Text property `display' should be nonsticky by default. */
14907 Vtext_property_default_nonsticky
14908 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
14911 Qlaplace = intern ("laplace");
14912 staticpro (&Qlaplace);
14913 Qemboss = intern ("emboss");
14914 staticpro (&Qemboss);
14915 Qedge_detection = intern ("edge-detection");
14916 staticpro (&Qedge_detection);
14917 Qheuristic = intern ("heuristic");
14918 staticpro (&Qheuristic);
14919 QCmatrix = intern (":matrix");
14920 staticpro (&QCmatrix);
14921 QCcolor_adjustment = intern (":color-adjustment");
14922 staticpro (&QCcolor_adjustment);
14923 QCmask = intern (":mask");
14924 staticpro (&QCmask);
14926 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
14927 staticpro (&Qface_set_after_frame_default);
14929 Fput (Qundefined_color, Qerror_conditions,
14930 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
14931 Fput (Qundefined_color, Qerror_message,
14932 build_string ("Undefined color"));
14934 staticpro (&w32_grabbed_keys);
14935 w32_grabbed_keys = Qnil;
14937 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
14938 doc: /* An array of color name mappings for windows. */);
14939 Vw32_color_map = Qnil;
14941 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
14942 doc: /* Non-nil if alt key presses are passed on to Windows.
14943 When non-nil, for example, alt pressed and released and then space will
14944 open the System menu. When nil, Emacs silently swallows alt key events. */);
14945 Vw32_pass_alt_to_system = Qnil;
14947 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
14948 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
14949 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
14950 Vw32_alt_is_meta = Qt;
14952 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
14953 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
14954 XSETINT (Vw32_quit_key, 0);
14956 DEFVAR_LISP ("w32-pass-lwindow-to-system",
14957 &Vw32_pass_lwindow_to_system,
14958 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
14959 When non-nil, the Start menu is opened by tapping the key. */);
14960 Vw32_pass_lwindow_to_system = Qt;
14962 DEFVAR_LISP ("w32-pass-rwindow-to-system",
14963 &Vw32_pass_rwindow_to_system,
14964 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
14965 When non-nil, the Start menu is opened by tapping the key. */);
14966 Vw32_pass_rwindow_to_system = Qt;
14968 DEFVAR_INT ("w32-phantom-key-code",
14969 &Vw32_phantom_key_code,
14970 doc: /* Virtual key code used to generate \"phantom\" key presses.
14971 Value is a number between 0 and 255.
14973 Phantom key presses are generated in order to stop the system from
14974 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
14975 `w32-pass-rwindow-to-system' is nil. */);
14976 /* Although 255 is technically not a valid key code, it works and
14977 means that this hack won't interfere with any real key code. */
14978 Vw32_phantom_key_code = 255;
14980 DEFVAR_LISP ("w32-enable-num-lock",
14981 &Vw32_enable_num_lock,
14982 doc: /* Non-nil if Num Lock should act normally.
14983 Set to nil to see Num Lock as the key `kp-numlock'. */);
14984 Vw32_enable_num_lock = Qt;
14986 DEFVAR_LISP ("w32-enable-caps-lock",
14987 &Vw32_enable_caps_lock,
14988 doc: /* Non-nil if Caps Lock should act normally.
14989 Set to nil to see Caps Lock as the key `capslock'. */);
14990 Vw32_enable_caps_lock = Qt;
14992 DEFVAR_LISP ("w32-scroll-lock-modifier",
14993 &Vw32_scroll_lock_modifier,
14994 doc: /* Modifier to use for the Scroll Lock on state.
14995 The value can be hyper, super, meta, alt, control or shift for the
14996 respective modifier, or nil to see Scroll Lock as the key `scroll'.
14997 Any other value will cause the key to be ignored. */);
14998 Vw32_scroll_lock_modifier = Qt;
15000 DEFVAR_LISP ("w32-lwindow-modifier",
15001 &Vw32_lwindow_modifier,
15002 doc: /* Modifier to use for the left \"Windows\" key.
15003 The value can be hyper, super, meta, alt, control or shift for the
15004 respective modifier, or nil to appear as the key `lwindow'.
15005 Any other value will cause the key to be ignored. */);
15006 Vw32_lwindow_modifier = Qnil;
15008 DEFVAR_LISP ("w32-rwindow-modifier",
15009 &Vw32_rwindow_modifier,
15010 doc: /* Modifier to use for the right \"Windows\" key.
15011 The value can be hyper, super, meta, alt, control or shift for the
15012 respective modifier, or nil to appear as the key `rwindow'.
15013 Any other value will cause the key to be ignored. */);
15014 Vw32_rwindow_modifier = Qnil;
15016 DEFVAR_LISP ("w32-apps-modifier",
15017 &Vw32_apps_modifier,
15018 doc: /* Modifier to use for the \"Apps\" key.
15019 The value can be hyper, super, meta, alt, control or shift for the
15020 respective modifier, or nil to appear as the key `apps'.
15021 Any other value will cause the key to be ignored. */);
15022 Vw32_apps_modifier = Qnil;
15024 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
15025 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
15026 w32_enable_synthesized_fonts = 0;
15028 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
15029 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
15030 Vw32_enable_palette = Qt;
15032 DEFVAR_INT ("w32-mouse-button-tolerance",
15033 &Vw32_mouse_button_tolerance,
15034 doc: /* Analogue of double click interval for faking middle mouse events.
15035 The value is the minimum time in milliseconds that must elapse between
15036 left/right button down events before they are considered distinct events.
15037 If both mouse buttons are depressed within this interval, a middle mouse
15038 button down event is generated instead. */);
15039 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
15041 DEFVAR_INT ("w32-mouse-move-interval",
15042 &Vw32_mouse_move_interval,
15043 doc: /* Minimum interval between mouse move events.
15044 The value is the minimum time in milliseconds that must elapse between
15045 successive mouse move (or scroll bar drag) events before they are
15046 reported as lisp events. */);
15047 XSETINT (Vw32_mouse_move_interval, 0);
15049 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
15050 &w32_pass_extra_mouse_buttons_to_system,
15051 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
15052 Recent versions of Windows support mice with up to five buttons.
15053 Since most applications don't support these extra buttons, most mouse
15054 drivers will allow you to map them to functions at the system level.
15055 If this variable is non-nil, Emacs will pass them on, allowing the
15056 system to handle them. */);
15057 w32_pass_extra_mouse_buttons_to_system = 0;
15059 init_x_parm_symbols ();
15061 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
15062 doc: /* List of directories to search for bitmap files for w32. */);
15063 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
15065 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
15066 doc: /* The shape of the pointer when over text.
15067 Changing the value does not affect existing frames
15068 unless you set the mouse color. */);
15069 Vx_pointer_shape = Qnil;
15071 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
15072 doc: /* The name Emacs uses to look up resources; for internal use only.
15073 `x-get-resource' uses this as the first component of the instance name
15074 when requesting resource values.
15075 Emacs initially sets `x-resource-name' to the name under which Emacs
15076 was invoked, or to the value specified with the `-name' or `-rn'
15077 switches, if present. */);
15078 Vx_resource_name = Qnil;
15080 Vx_nontext_pointer_shape = Qnil;
15082 Vx_mode_pointer_shape = Qnil;
15084 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
15085 doc: /* The shape of the pointer when Emacs is busy.
15086 This variable takes effect when you create a new frame
15087 or when you set the mouse color. */);
15088 Vx_hourglass_pointer_shape = Qnil;
15090 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
15091 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
15092 display_hourglass_p = 1;
15094 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
15095 doc: /* *Seconds to wait before displaying an hourglass pointer.
15096 Value must be an integer or float. */);
15097 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
15099 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
15100 &Vx_sensitive_text_pointer_shape,
15101 doc: /* The shape of the pointer when over mouse-sensitive text.
15102 This variable takes effect when you create a new frame
15103 or when you set the mouse color. */);
15104 Vx_sensitive_text_pointer_shape = Qnil;
15106 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
15107 &Vx_window_horizontal_drag_shape,
15108 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
15109 This variable takes effect when you create a new frame
15110 or when you set the mouse color. */);
15111 Vx_window_horizontal_drag_shape = Qnil;
15113 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
15114 doc: /* A string indicating the foreground color of the cursor box. */);
15115 Vx_cursor_fore_pixel = Qnil;
15117 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
15118 doc: /* Maximum size for tooltips.
15119 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
15120 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
15122 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
15123 doc: /* Non-nil if no window manager is in use.
15124 Emacs doesn't try to figure this out; this is always nil
15125 unless you set it to something else. */);
15126 /* We don't have any way to find this out, so set it to nil
15127 and maybe the user would like to set it to t. */
15128 Vx_no_window_manager = Qnil;
15130 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
15131 &Vx_pixel_size_width_font_regexp,
15132 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
15134 Since Emacs gets width of a font matching with this regexp from
15135 PIXEL_SIZE field of the name, font finding mechanism gets faster for
15136 such a font. This is especially effective for such large fonts as
15137 Chinese, Japanese, and Korean. */);
15138 Vx_pixel_size_width_font_regexp = Qnil;
15140 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
15141 doc: /* Time after which cached images are removed from the cache.
15142 When an image has not been displayed this many seconds, remove it
15143 from the image cache. Value must be an integer or nil with nil
15144 meaning don't clear the cache. */);
15145 Vimage_cache_eviction_delay = make_number (30 * 60);
15147 DEFVAR_LISP ("w32-bdf-filename-alist",
15148 &Vw32_bdf_filename_alist,
15149 doc: /* List of bdf fonts and their corresponding filenames. */);
15150 Vw32_bdf_filename_alist = Qnil;
15152 DEFVAR_BOOL ("w32-strict-fontnames",
15153 &w32_strict_fontnames,
15154 doc: /* Non-nil means only use fonts that are exact matches for those requested.
15155 Default is nil, which allows old fontnames that are not XLFD compliant,
15156 and allows third-party CJK display to work by specifying false charset
15157 fields to trick Emacs into translating to Big5, SJIS etc.
15158 Setting this to t will prevent wrong fonts being selected when
15159 fontsets are automatically created. */);
15160 w32_strict_fontnames = 0;
15162 DEFVAR_BOOL ("w32-strict-painting",
15163 &w32_strict_painting,
15164 doc: /* Non-nil means use strict rules for repainting frames.
15165 Set this to nil to get the old behaviour for repainting; this should
15166 only be necessary if the default setting causes problems. */);
15167 w32_strict_painting = 1;
15169 DEFVAR_LISP ("w32-charset-info-alist",
15170 &Vw32_charset_info_alist,
15171 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
15172 Each entry should be of the form:
15174 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
15176 where CHARSET_NAME is a string used in font names to identify the charset,
15177 WINDOWS_CHARSET is a symbol that can be one of:
15178 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
15179 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
15180 w32-charset-chinesebig5,
15181 #ifdef JOHAB_CHARSET
15182 w32-charset-johab, w32-charset-hebrew,
15183 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
15184 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
15185 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
15186 #endif
15187 #ifdef UNICODE_CHARSET
15188 w32-charset-unicode,
15189 #endif
15190 or w32-charset-oem.
15191 CODEPAGE should be an integer specifying the codepage that should be used
15192 to display the character set, t to do no translation and output as Unicode,
15193 or nil to do no translation and output as 8 bit (or multibyte on far-east
15194 versions of Windows) characters. */);
15195 Vw32_charset_info_alist = Qnil;
15197 staticpro (&Qw32_charset_ansi);
15198 Qw32_charset_ansi = intern ("w32-charset-ansi");
15199 staticpro (&Qw32_charset_symbol);
15200 Qw32_charset_symbol = intern ("w32-charset-symbol");
15201 staticpro (&Qw32_charset_shiftjis);
15202 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
15203 staticpro (&Qw32_charset_hangeul);
15204 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
15205 staticpro (&Qw32_charset_chinesebig5);
15206 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
15207 staticpro (&Qw32_charset_gb2312);
15208 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
15209 staticpro (&Qw32_charset_oem);
15210 Qw32_charset_oem = intern ("w32-charset-oem");
15212 #ifdef JOHAB_CHARSET
15214 static int w32_extra_charsets_defined = 1;
15215 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
15216 doc: /* Internal variable. */);
15218 staticpro (&Qw32_charset_johab);
15219 Qw32_charset_johab = intern ("w32-charset-johab");
15220 staticpro (&Qw32_charset_easteurope);
15221 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
15222 staticpro (&Qw32_charset_turkish);
15223 Qw32_charset_turkish = intern ("w32-charset-turkish");
15224 staticpro (&Qw32_charset_baltic);
15225 Qw32_charset_baltic = intern ("w32-charset-baltic");
15226 staticpro (&Qw32_charset_russian);
15227 Qw32_charset_russian = intern ("w32-charset-russian");
15228 staticpro (&Qw32_charset_arabic);
15229 Qw32_charset_arabic = intern ("w32-charset-arabic");
15230 staticpro (&Qw32_charset_greek);
15231 Qw32_charset_greek = intern ("w32-charset-greek");
15232 staticpro (&Qw32_charset_hebrew);
15233 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
15234 staticpro (&Qw32_charset_vietnamese);
15235 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
15236 staticpro (&Qw32_charset_thai);
15237 Qw32_charset_thai = intern ("w32-charset-thai");
15238 staticpro (&Qw32_charset_mac);
15239 Qw32_charset_mac = intern ("w32-charset-mac");
15241 #endif
15243 #ifdef UNICODE_CHARSET
15245 static int w32_unicode_charset_defined = 1;
15246 DEFVAR_BOOL ("w32-unicode-charset-defined",
15247 &w32_unicode_charset_defined,
15248 doc: /* Internal variable. */);
15250 staticpro (&Qw32_charset_unicode);
15251 Qw32_charset_unicode = intern ("w32-charset-unicode");
15252 #endif
15254 defsubr (&Sx_get_resource);
15255 #if 0 /* TODO: Port to W32 */
15256 defsubr (&Sx_change_window_property);
15257 defsubr (&Sx_delete_window_property);
15258 defsubr (&Sx_window_property);
15259 #endif
15260 defsubr (&Sxw_display_color_p);
15261 defsubr (&Sx_display_grayscale_p);
15262 defsubr (&Sxw_color_defined_p);
15263 defsubr (&Sxw_color_values);
15264 defsubr (&Sx_server_max_request_size);
15265 defsubr (&Sx_server_vendor);
15266 defsubr (&Sx_server_version);
15267 defsubr (&Sx_display_pixel_width);
15268 defsubr (&Sx_display_pixel_height);
15269 defsubr (&Sx_display_mm_width);
15270 defsubr (&Sx_display_mm_height);
15271 defsubr (&Sx_display_screens);
15272 defsubr (&Sx_display_planes);
15273 defsubr (&Sx_display_color_cells);
15274 defsubr (&Sx_display_visual_class);
15275 defsubr (&Sx_display_backing_store);
15276 defsubr (&Sx_display_save_under);
15277 defsubr (&Sx_parse_geometry);
15278 defsubr (&Sx_create_frame);
15279 defsubr (&Sx_open_connection);
15280 defsubr (&Sx_close_connection);
15281 defsubr (&Sx_display_list);
15282 defsubr (&Sx_synchronize);
15284 /* W32 specific functions */
15286 defsubr (&Sw32_focus_frame);
15287 defsubr (&Sw32_select_font);
15288 defsubr (&Sw32_define_rgb_color);
15289 defsubr (&Sw32_default_color_map);
15290 defsubr (&Sw32_load_color_file);
15291 defsubr (&Sw32_send_sys_command);
15292 defsubr (&Sw32_shell_execute);
15293 defsubr (&Sw32_register_hot_key);
15294 defsubr (&Sw32_unregister_hot_key);
15295 defsubr (&Sw32_registered_hot_keys);
15296 defsubr (&Sw32_reconstruct_hot_key);
15297 defsubr (&Sw32_toggle_lock_key);
15298 defsubr (&Sw32_find_bdf_fonts);
15300 defsubr (&Sfile_system_info);
15302 /* Setting callback functions for fontset handler. */
15303 get_font_info_func = w32_get_font_info;
15305 #if 0 /* This function pointer doesn't seem to be used anywhere.
15306 And the pointer assigned has the wrong type, anyway. */
15307 list_fonts_func = w32_list_fonts;
15308 #endif
15310 load_font_func = w32_load_font;
15311 find_ccl_program_func = w32_find_ccl_program;
15312 query_font_func = w32_query_font;
15313 set_frame_fontset_func = x_set_font;
15314 check_window_system_func = check_w32;
15316 /* Images. */
15317 Qxbm = intern ("xbm");
15318 staticpro (&Qxbm);
15319 QCconversion = intern (":conversion");
15320 staticpro (&QCconversion);
15321 QCheuristic_mask = intern (":heuristic-mask");
15322 staticpro (&QCheuristic_mask);
15323 QCcolor_symbols = intern (":color-symbols");
15324 staticpro (&QCcolor_symbols);
15325 QCascent = intern (":ascent");
15326 staticpro (&QCascent);
15327 QCmargin = intern (":margin");
15328 staticpro (&QCmargin);
15329 QCrelief = intern (":relief");
15330 staticpro (&QCrelief);
15331 Qpostscript = intern ("postscript");
15332 staticpro (&Qpostscript);
15333 #if 0 /* TODO: These need entries at top of file. */
15334 QCloader = intern (":loader");
15335 staticpro (&QCloader);
15336 QCbounding_box = intern (":bounding-box");
15337 staticpro (&QCbounding_box);
15338 QCpt_width = intern (":pt-width");
15339 staticpro (&QCpt_width);
15340 QCpt_height = intern (":pt-height");
15341 staticpro (&QCpt_height);
15342 #endif
15343 QCindex = intern (":index");
15344 staticpro (&QCindex);
15345 Qpbm = intern ("pbm");
15346 staticpro (&Qpbm);
15348 #if HAVE_XPM
15349 Qxpm = intern ("xpm");
15350 staticpro (&Qxpm);
15351 #endif
15353 #if HAVE_JPEG
15354 Qjpeg = intern ("jpeg");
15355 staticpro (&Qjpeg);
15356 #endif
15358 #if HAVE_TIFF
15359 Qtiff = intern ("tiff");
15360 staticpro (&Qtiff);
15361 #endif
15363 #if HAVE_GIF
15364 Qgif = intern ("gif");
15365 staticpro (&Qgif);
15366 #endif
15368 #if HAVE_PNG
15369 Qpng = intern ("png");
15370 staticpro (&Qpng);
15371 #endif
15373 defsubr (&Sclear_image_cache);
15374 defsubr (&Simage_size);
15375 defsubr (&Simage_mask_p);
15377 #if GLYPH_DEBUG
15378 defsubr (&Simagep);
15379 defsubr (&Slookup_image);
15380 #endif
15382 hourglass_atimer = NULL;
15383 hourglass_shown_p = 0;
15384 defsubr (&Sx_show_tip);
15385 defsubr (&Sx_hide_tip);
15386 tip_timer = Qnil;
15387 staticpro (&tip_timer);
15388 tip_frame = Qnil;
15389 staticpro (&tip_frame);
15391 last_show_tip_args = Qnil;
15392 staticpro (&last_show_tip_args);
15394 defsubr (&Sx_file_dialog);
15398 void
15399 init_xfns ()
15401 image_types = NULL;
15402 Vimage_types = Qnil;
15404 define_image_type (&pbm_type);
15405 define_image_type (&xbm_type);
15406 #if 0 /* TODO : Image support for W32 */
15407 define_image_type (&gs_type);
15408 #endif
15410 #if HAVE_XPM
15411 define_image_type (&xpm_type);
15412 #endif
15414 #if HAVE_JPEG
15415 define_image_type (&jpeg_type);
15416 #endif
15418 #if HAVE_TIFF
15419 define_image_type (&tiff_type);
15420 #endif
15422 #if HAVE_GIF
15423 define_image_type (&gif_type);
15424 #endif
15426 #if HAVE_PNG
15427 define_image_type (&png_type);
15428 #endif
15431 #undef abort
15433 void
15434 w32_abort()
15436 int button;
15437 button = MessageBox (NULL,
15438 "A fatal error has occurred!\n\n"
15439 "Select Abort to exit, Retry to debug, Ignore to continue",
15440 "Emacs Abort Dialog",
15441 MB_ICONEXCLAMATION | MB_TASKMODAL
15442 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
15443 switch (button)
15445 case IDRETRY:
15446 DebugBreak ();
15447 break;
15448 case IDIGNORE:
15449 break;
15450 case IDABORT:
15451 default:
15452 abort ();
15453 break;
15457 /* For convenience when debugging. */
15459 w32_last_error()
15461 return GetLastError ();