]> code.delx.au - gnu-emacs/blob - src/w32fns.c
(w32_load_system_font, w32_to_x_charset): Use strnicmp
[gnu-emacs] / src / w32fns.c
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.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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. */
21
22 /* Added by Kevin Gallo */
23
24 #include <config.h>
25
26 #include <signal.h>
27 #include <stdio.h>
28 #include <limits.h>
29 #include <errno.h>
30
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"
48
49 #include "bitmaps/gray.xbm"
50
51 #include <commdlg.h>
52 #include <shellapi.h>
53 #include <ctype.h>
54
55 extern void free_frame_menubar ();
56 extern void x_compute_fringe_widths P_ ((struct frame *, int));
57 extern double atof ();
58 extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
59 extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
60 extern void w32_free_menu_strings P_ ((HWND));
61
62 extern int quit_char;
63
64 /* A definition of XColor for non-X frames. */
65 #ifndef HAVE_X_WINDOWS
66 typedef struct {
67 unsigned long pixel;
68 unsigned short red, green, blue;
69 char flags;
70 char pad;
71 } XColor;
72 #endif
73
74 extern char *lispy_function_keys[];
75
76 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
77 it, and including `bitmaps/gray' more than once is a problem when
78 config.h defines `static' as an empty replacement string. */
79
80 int gray_bitmap_width = gray_width;
81 int gray_bitmap_height = gray_height;
82 unsigned char *gray_bitmap_bits = gray_bits;
83
84 /* The colormap for converting color names to RGB values */
85 Lisp_Object Vw32_color_map;
86
87 /* Non nil if alt key presses are passed on to Windows. */
88 Lisp_Object Vw32_pass_alt_to_system;
89
90 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
91 to alt_modifier. */
92 Lisp_Object Vw32_alt_is_meta;
93
94 /* If non-zero, the windows virtual key code for an alternative quit key. */
95 Lisp_Object Vw32_quit_key;
96
97 /* Non nil if left window key events are passed on to Windows (this only
98 affects whether "tapping" the key opens the Start menu). */
99 Lisp_Object Vw32_pass_lwindow_to_system;
100
101 /* Non nil if right window key events are passed on to Windows (this
102 only affects whether "tapping" the key opens the Start menu). */
103 Lisp_Object Vw32_pass_rwindow_to_system;
104
105 /* Virtual key code used to generate "phantom" key presses in order
106 to stop system from acting on Windows key events. */
107 Lisp_Object Vw32_phantom_key_code;
108
109 /* Modifier associated with the left "Windows" key, or nil to act as a
110 normal key. */
111 Lisp_Object Vw32_lwindow_modifier;
112
113 /* Modifier associated with the right "Windows" key, or nil to act as a
114 normal key. */
115 Lisp_Object Vw32_rwindow_modifier;
116
117 /* Modifier associated with the "Apps" key, or nil to act as a normal
118 key. */
119 Lisp_Object Vw32_apps_modifier;
120
121 /* Value is nil if Num Lock acts as a function key. */
122 Lisp_Object Vw32_enable_num_lock;
123
124 /* Value is nil if Caps Lock acts as a function key. */
125 Lisp_Object Vw32_enable_caps_lock;
126
127 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
128 Lisp_Object Vw32_scroll_lock_modifier;
129
130 /* Switch to control whether we inhibit requests for synthesized bold
131 and italic versions of fonts. */
132 int w32_enable_synthesized_fonts;
133
134 /* Enable palette management. */
135 Lisp_Object Vw32_enable_palette;
136
137 /* Control how close left/right button down events must be to
138 be converted to a middle button down event. */
139 Lisp_Object Vw32_mouse_button_tolerance;
140
141 /* Minimum interval between mouse movement (and scroll bar drag)
142 events that are passed on to the event loop. */
143 Lisp_Object Vw32_mouse_move_interval;
144
145 /* Flag to indicate if XBUTTON events should be passed on to Windows. */
146 int w32_pass_extra_mouse_buttons_to_system;
147
148 /* The name we're using in resource queries. */
149 Lisp_Object Vx_resource_name;
150
151 /* Non nil if no window manager is in use. */
152 Lisp_Object Vx_no_window_manager;
153
154 /* Non-zero means we're allowed to display a hourglass pointer. */
155
156 int display_hourglass_p;
157
158 /* The background and shape of the mouse pointer, and shape when not
159 over text or in the modeline. */
160
161 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
162 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
163
164 /* The shape when over mouse-sensitive text. */
165
166 Lisp_Object Vx_sensitive_text_pointer_shape;
167
168 /* Color of chars displayed in cursor box. */
169
170 Lisp_Object Vx_cursor_fore_pixel;
171
172 /* Nonzero if using Windows. */
173
174 static int w32_in_use;
175
176 /* Search path for bitmap files. */
177
178 Lisp_Object Vx_bitmap_file_path;
179
180 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
181
182 Lisp_Object Vx_pixel_size_width_font_regexp;
183
184 /* Alist of bdf fonts and the files that define them. */
185 Lisp_Object Vw32_bdf_filename_alist;
186
187 /* A flag to control whether fonts are matched strictly or not. */
188 int w32_strict_fontnames;
189
190 /* A flag to control whether we should only repaint if GetUpdateRect
191 indicates there is an update region. */
192 int w32_strict_painting;
193
194 /* Associative list linking character set strings to Windows codepages. */
195 Lisp_Object Vw32_charset_info_alist;
196
197 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
198 #ifndef VIETNAMESE_CHARSET
199 #define VIETNAMESE_CHARSET 163
200 #endif
201
202 Lisp_Object Qauto_raise;
203 Lisp_Object Qauto_lower;
204 Lisp_Object Qbar;
205 Lisp_Object Qborder_color;
206 Lisp_Object Qborder_width;
207 Lisp_Object Qbox;
208 Lisp_Object Qcursor_color;
209 Lisp_Object Qcursor_type;
210 Lisp_Object Qgeometry;
211 Lisp_Object Qicon_left;
212 Lisp_Object Qicon_top;
213 Lisp_Object Qicon_type;
214 Lisp_Object Qicon_name;
215 Lisp_Object Qinternal_border_width;
216 Lisp_Object Qleft;
217 Lisp_Object Qright;
218 Lisp_Object Qmouse_color;
219 Lisp_Object Qnone;
220 Lisp_Object Qparent_id;
221 Lisp_Object Qscroll_bar_width;
222 Lisp_Object Qsuppress_icon;
223 Lisp_Object Qundefined_color;
224 Lisp_Object Qvertical_scroll_bars;
225 Lisp_Object Qvisibility;
226 Lisp_Object Qwindow_id;
227 Lisp_Object Qx_frame_parameter;
228 Lisp_Object Qx_resource_name;
229 Lisp_Object Quser_position;
230 Lisp_Object Quser_size;
231 Lisp_Object Qscreen_gamma;
232 Lisp_Object Qline_spacing;
233 Lisp_Object Qcenter;
234 Lisp_Object Qcancel_timer;
235 Lisp_Object Qhyper;
236 Lisp_Object Qsuper;
237 Lisp_Object Qmeta;
238 Lisp_Object Qalt;
239 Lisp_Object Qctrl;
240 Lisp_Object Qcontrol;
241 Lisp_Object Qshift;
242
243 Lisp_Object Qw32_charset_ansi;
244 Lisp_Object Qw32_charset_default;
245 Lisp_Object Qw32_charset_symbol;
246 Lisp_Object Qw32_charset_shiftjis;
247 Lisp_Object Qw32_charset_hangeul;
248 Lisp_Object Qw32_charset_gb2312;
249 Lisp_Object Qw32_charset_chinesebig5;
250 Lisp_Object Qw32_charset_oem;
251
252 #ifndef JOHAB_CHARSET
253 #define JOHAB_CHARSET 130
254 #endif
255 #ifdef JOHAB_CHARSET
256 Lisp_Object Qw32_charset_easteurope;
257 Lisp_Object Qw32_charset_turkish;
258 Lisp_Object Qw32_charset_baltic;
259 Lisp_Object Qw32_charset_russian;
260 Lisp_Object Qw32_charset_arabic;
261 Lisp_Object Qw32_charset_greek;
262 Lisp_Object Qw32_charset_hebrew;
263 Lisp_Object Qw32_charset_vietnamese;
264 Lisp_Object Qw32_charset_thai;
265 Lisp_Object Qw32_charset_johab;
266 Lisp_Object Qw32_charset_mac;
267 #endif
268
269 #ifdef UNICODE_CHARSET
270 Lisp_Object Qw32_charset_unicode;
271 #endif
272
273 extern Lisp_Object Qtop;
274 extern Lisp_Object Qdisplay;
275 extern Lisp_Object Qtool_bar_lines;
276
277 /* State variables for emulating a three button mouse. */
278 #define LMOUSE 1
279 #define MMOUSE 2
280 #define RMOUSE 4
281
282 static int button_state = 0;
283 static W32Msg saved_mouse_button_msg;
284 static unsigned mouse_button_timer; /* non-zero when timer is active */
285 static W32Msg saved_mouse_move_msg;
286 static unsigned mouse_move_timer;
287
288 /* Window that is tracking the mouse. */
289 static HWND track_mouse_window;
290 FARPROC track_mouse_event_fn;
291
292 /* W95 mousewheel handler */
293 unsigned int msh_mousewheel = 0;
294
295 #define MOUSE_BUTTON_ID 1
296 #define MOUSE_MOVE_ID 2
297
298 /* The below are defined in frame.c. */
299
300 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
301 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
302 extern Lisp_Object Qtool_bar_lines;
303
304 extern Lisp_Object Vwindow_system_version;
305
306 Lisp_Object Qface_set_after_frame_default;
307
308 #ifdef GLYPH_DEBUG
309 int image_cache_refcount, dpyinfo_refcount;
310 #endif
311
312
313 /* From w32term.c. */
314 extern Lisp_Object Vw32_num_mouse_buttons;
315 extern Lisp_Object Vw32_recognize_altgr;
316
317 extern HWND w32_system_caret_hwnd;
318 extern int w32_system_caret_width;
319 extern int w32_system_caret_height;
320 extern int w32_system_caret_x;
321 extern int w32_system_caret_y;
322
323 \f
324 /* Error if we are not connected to MS-Windows. */
325 void
326 check_w32 ()
327 {
328 if (! w32_in_use)
329 error ("MS-Windows not in use or not initialized");
330 }
331
332 /* Nonzero if we can use mouse menus.
333 You should not call this unless HAVE_MENUS is defined. */
334
335 int
336 have_menus_p ()
337 {
338 return w32_in_use;
339 }
340
341 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
342 and checking validity for W32. */
343
344 FRAME_PTR
345 check_x_frame (frame)
346 Lisp_Object frame;
347 {
348 FRAME_PTR f;
349
350 if (NILP (frame))
351 frame = selected_frame;
352 CHECK_LIVE_FRAME (frame);
353 f = XFRAME (frame);
354 if (! FRAME_W32_P (f))
355 error ("non-w32 frame used");
356 return f;
357 }
358
359 /* Let the user specify an display with a frame.
360 nil stands for the selected frame--or, if that is not a w32 frame,
361 the first display on the list. */
362
363 static struct w32_display_info *
364 check_x_display_info (frame)
365 Lisp_Object frame;
366 {
367 if (NILP (frame))
368 {
369 struct frame *sf = XFRAME (selected_frame);
370
371 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
372 return FRAME_W32_DISPLAY_INFO (sf);
373 else
374 return &one_w32_display_info;
375 }
376 else if (STRINGP (frame))
377 return x_display_info_for_name (frame);
378 else
379 {
380 FRAME_PTR f;
381
382 CHECK_LIVE_FRAME (frame);
383 f = XFRAME (frame);
384 if (! FRAME_W32_P (f))
385 error ("non-w32 frame used");
386 return FRAME_W32_DISPLAY_INFO (f);
387 }
388 }
389 \f
390 /* Return the Emacs frame-object corresponding to an w32 window.
391 It could be the frame's main window or an icon window. */
392
393 /* This function can be called during GC, so use GC_xxx type test macros. */
394
395 struct frame *
396 x_window_to_frame (dpyinfo, wdesc)
397 struct w32_display_info *dpyinfo;
398 HWND wdesc;
399 {
400 Lisp_Object tail, frame;
401 struct frame *f;
402
403 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
404 {
405 frame = XCAR (tail);
406 if (!GC_FRAMEP (frame))
407 continue;
408 f = XFRAME (frame);
409 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
410 continue;
411 if (f->output_data.w32->hourglass_window == wdesc)
412 return f;
413
414 if (FRAME_W32_WINDOW (f) == wdesc)
415 return f;
416 }
417 return 0;
418 }
419
420 \f
421
422 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
423 id, which is just an int that this section returns. Bitmaps are
424 reference counted so they can be shared among frames.
425
426 Bitmap indices are guaranteed to be > 0, so a negative number can
427 be used to indicate no bitmap.
428
429 If you use x_create_bitmap_from_data, then you must keep track of
430 the bitmaps yourself. That is, creating a bitmap from the same
431 data more than once will not be caught. */
432
433
434 /* Functions to access the contents of a bitmap, given an id. */
435
436 int
437 x_bitmap_height (f, id)
438 FRAME_PTR f;
439 int id;
440 {
441 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
442 }
443
444 int
445 x_bitmap_width (f, id)
446 FRAME_PTR f;
447 int id;
448 {
449 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
450 }
451
452 int
453 x_bitmap_pixmap (f, id)
454 FRAME_PTR f;
455 int id;
456 {
457 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
458 }
459
460
461 /* Allocate a new bitmap record. Returns index of new record. */
462
463 static int
464 x_allocate_bitmap_record (f)
465 FRAME_PTR f;
466 {
467 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
468 int i;
469
470 if (dpyinfo->bitmaps == NULL)
471 {
472 dpyinfo->bitmaps_size = 10;
473 dpyinfo->bitmaps
474 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
475 dpyinfo->bitmaps_last = 1;
476 return 1;
477 }
478
479 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
480 return ++dpyinfo->bitmaps_last;
481
482 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
483 if (dpyinfo->bitmaps[i].refcount == 0)
484 return i + 1;
485
486 dpyinfo->bitmaps_size *= 2;
487 dpyinfo->bitmaps
488 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
489 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
490 return ++dpyinfo->bitmaps_last;
491 }
492
493 /* Add one reference to the reference count of the bitmap with id ID. */
494
495 void
496 x_reference_bitmap (f, id)
497 FRAME_PTR f;
498 int id;
499 {
500 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
501 }
502
503 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
504
505 int
506 x_create_bitmap_from_data (f, bits, width, height)
507 struct frame *f;
508 char *bits;
509 unsigned int width, height;
510 {
511 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
512 Pixmap bitmap;
513 int id;
514
515 bitmap = CreateBitmap (width, height,
516 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
517 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
518 bits);
519
520 if (! bitmap)
521 return -1;
522
523 id = x_allocate_bitmap_record (f);
524 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
525 dpyinfo->bitmaps[id - 1].file = NULL;
526 dpyinfo->bitmaps[id - 1].hinst = NULL;
527 dpyinfo->bitmaps[id - 1].refcount = 1;
528 dpyinfo->bitmaps[id - 1].depth = 1;
529 dpyinfo->bitmaps[id - 1].height = height;
530 dpyinfo->bitmaps[id - 1].width = width;
531
532 return id;
533 }
534
535 /* Create bitmap from file FILE for frame F. */
536
537 int
538 x_create_bitmap_from_file (f, file)
539 struct frame *f;
540 Lisp_Object file;
541 {
542 return -1;
543 #if 0 /* TODO : bitmap support */
544 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
545 unsigned int width, height;
546 HBITMAP bitmap;
547 int xhot, yhot, result, id;
548 Lisp_Object found;
549 int fd;
550 char *filename;
551 HINSTANCE hinst;
552
553 /* Look for an existing bitmap with the same name. */
554 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
555 {
556 if (dpyinfo->bitmaps[id].refcount
557 && dpyinfo->bitmaps[id].file
558 && !strcmp (dpyinfo->bitmaps[id].file, (char *) XSTRING (file)->data))
559 {
560 ++dpyinfo->bitmaps[id].refcount;
561 return id + 1;
562 }
563 }
564
565 /* Search bitmap-file-path for the file, if appropriate. */
566 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, 0);
567 if (fd < 0)
568 return -1;
569 emacs_close (fd);
570
571 filename = (char *) XSTRING (found)->data;
572
573 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
574
575 if (hinst == NULL)
576 return -1;
577
578
579 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
580 filename, &width, &height, &bitmap, &xhot, &yhot);
581 if (result != BitmapSuccess)
582 return -1;
583
584 id = x_allocate_bitmap_record (f);
585 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
586 dpyinfo->bitmaps[id - 1].refcount = 1;
587 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (XSTRING (file)->size + 1);
588 dpyinfo->bitmaps[id - 1].depth = 1;
589 dpyinfo->bitmaps[id - 1].height = height;
590 dpyinfo->bitmaps[id - 1].width = width;
591 strcpy (dpyinfo->bitmaps[id - 1].file, XSTRING (file)->data);
592
593 return id;
594 #endif /* TODO */
595 }
596
597 /* Remove reference to bitmap with id number ID. */
598
599 void
600 x_destroy_bitmap (f, id)
601 FRAME_PTR f;
602 int id;
603 {
604 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
605
606 if (id > 0)
607 {
608 --dpyinfo->bitmaps[id - 1].refcount;
609 if (dpyinfo->bitmaps[id - 1].refcount == 0)
610 {
611 BLOCK_INPUT;
612 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
613 if (dpyinfo->bitmaps[id - 1].file)
614 {
615 xfree (dpyinfo->bitmaps[id - 1].file);
616 dpyinfo->bitmaps[id - 1].file = NULL;
617 }
618 UNBLOCK_INPUT;
619 }
620 }
621 }
622
623 /* Free all the bitmaps for the display specified by DPYINFO. */
624
625 static void
626 x_destroy_all_bitmaps (dpyinfo)
627 struct w32_display_info *dpyinfo;
628 {
629 int i;
630 for (i = 0; i < dpyinfo->bitmaps_last; i++)
631 if (dpyinfo->bitmaps[i].refcount > 0)
632 {
633 DeleteObject (dpyinfo->bitmaps[i].pixmap);
634 if (dpyinfo->bitmaps[i].file)
635 xfree (dpyinfo->bitmaps[i].file);
636 }
637 dpyinfo->bitmaps_last = 0;
638 }
639 \f
640 /* Connect the frame-parameter names for W32 frames
641 to the ways of passing the parameter values to the window system.
642
643 The name of a parameter, as a Lisp symbol,
644 has an `x-frame-parameter' property which is an integer in Lisp
645 but can be interpreted as an `enum x_frame_parm' in C. */
646
647 enum x_frame_parm
648 {
649 X_PARM_FOREGROUND_COLOR,
650 X_PARM_BACKGROUND_COLOR,
651 X_PARM_MOUSE_COLOR,
652 X_PARM_CURSOR_COLOR,
653 X_PARM_BORDER_COLOR,
654 X_PARM_ICON_TYPE,
655 X_PARM_FONT,
656 X_PARM_BORDER_WIDTH,
657 X_PARM_INTERNAL_BORDER_WIDTH,
658 X_PARM_NAME,
659 X_PARM_AUTORAISE,
660 X_PARM_AUTOLOWER,
661 X_PARM_VERT_SCROLL_BAR,
662 X_PARM_VISIBILITY,
663 X_PARM_MENU_BAR_LINES
664 };
665
666
667 struct x_frame_parm_table
668 {
669 char *name;
670 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
671 };
672
673 BOOL my_show_window P_ ((struct frame *, HWND, int));
674 void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
675 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
676 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
677 static void x_change_window_heights P_ ((Lisp_Object, int));
678 /* TODO: Native Input Method support; see x_create_im. */
679 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
680 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
681 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
682 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
683 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
684 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
685 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
686 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
687 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
688 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
689 static void x_set_fringe_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
690 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
691 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
692 Lisp_Object));
693 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
694 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
695 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
696 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
697 Lisp_Object));
698 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
699 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
700 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
701 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
702 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
703 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
704 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
705 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
706 Lisp_Object));
707
708 static struct x_frame_parm_table x_frame_parms[] =
709 {
710 {"auto-raise", x_set_autoraise},
711 {"auto-lower", x_set_autolower},
712 {"background-color", x_set_background_color},
713 {"border-color", x_set_border_color},
714 {"border-width", x_set_border_width},
715 {"cursor-color", x_set_cursor_color},
716 {"cursor-type", x_set_cursor_type},
717 {"font", x_set_font},
718 {"foreground-color", x_set_foreground_color},
719 {"icon-name", x_set_icon_name},
720 {"icon-type", x_set_icon_type},
721 {"internal-border-width", x_set_internal_border_width},
722 {"menu-bar-lines", x_set_menu_bar_lines},
723 {"mouse-color", x_set_mouse_color},
724 {"name", x_explicitly_set_name},
725 {"scroll-bar-width", x_set_scroll_bar_width},
726 {"title", x_set_title},
727 {"unsplittable", x_set_unsplittable},
728 {"vertical-scroll-bars", x_set_vertical_scroll_bars},
729 {"visibility", x_set_visibility},
730 {"tool-bar-lines", x_set_tool_bar_lines},
731 {"screen-gamma", x_set_screen_gamma},
732 {"line-spacing", x_set_line_spacing},
733 {"left-fringe", x_set_fringe_width},
734 {"right-fringe", x_set_fringe_width}
735 };
736
737 /* Attach the `x-frame-parameter' properties to
738 the Lisp symbol names of parameters relevant to W32. */
739
740 void
741 init_x_parm_symbols ()
742 {
743 int i;
744
745 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
746 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
747 make_number (i));
748 }
749 \f
750 /* Change the parameters of frame F as specified by ALIST.
751 If a parameter is not specially recognized, do nothing;
752 otherwise call the `x_set_...' function for that parameter. */
753
754 void
755 x_set_frame_parameters (f, alist)
756 FRAME_PTR f;
757 Lisp_Object alist;
758 {
759 Lisp_Object tail;
760
761 /* If both of these parameters are present, it's more efficient to
762 set them both at once. So we wait until we've looked at the
763 entire list before we set them. */
764 int width, height;
765
766 /* Same here. */
767 Lisp_Object left, top;
768
769 /* Same with these. */
770 Lisp_Object icon_left, icon_top;
771
772 /* Record in these vectors all the parms specified. */
773 Lisp_Object *parms;
774 Lisp_Object *values;
775 int i, p;
776 int left_no_change = 0, top_no_change = 0;
777 int icon_left_no_change = 0, icon_top_no_change = 0;
778
779 struct gcpro gcpro1, gcpro2;
780
781 i = 0;
782 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
783 i++;
784
785 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
786 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
787
788 /* Extract parm names and values into those vectors. */
789
790 i = 0;
791 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
792 {
793 Lisp_Object elt;
794
795 elt = Fcar (tail);
796 parms[i] = Fcar (elt);
797 values[i] = Fcdr (elt);
798 i++;
799 }
800 /* TAIL and ALIST are not used again below here. */
801 alist = tail = Qnil;
802
803 GCPRO2 (*parms, *values);
804 gcpro1.nvars = i;
805 gcpro2.nvars = i;
806
807 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
808 because their values appear in VALUES and strings are not valid. */
809 top = left = Qunbound;
810 icon_left = icon_top = Qunbound;
811
812 /* Provide default values for HEIGHT and WIDTH. */
813 if (FRAME_NEW_WIDTH (f))
814 width = FRAME_NEW_WIDTH (f);
815 else
816 width = FRAME_WIDTH (f);
817
818 if (FRAME_NEW_HEIGHT (f))
819 height = FRAME_NEW_HEIGHT (f);
820 else
821 height = FRAME_HEIGHT (f);
822
823 /* Process foreground_color and background_color before anything else.
824 They are independent of other properties, but other properties (e.g.,
825 cursor_color) are dependent upon them. */
826 /* Process default font as well, since fringe widths depends on it. */
827 for (p = 0; p < i; p++)
828 {
829 Lisp_Object prop, val;
830
831 prop = parms[p];
832 val = values[p];
833 if (EQ (prop, Qforeground_color)
834 || EQ (prop, Qbackground_color)
835 || EQ (prop, Qfont))
836 {
837 register Lisp_Object param_index, old_value;
838
839 old_value = get_frame_param (f, prop);
840
841 if (NILP (Fequal (val, old_value)))
842 {
843 store_frame_param (f, prop, val);
844
845 param_index = Fget (prop, Qx_frame_parameter);
846 if (NATNUMP (param_index)
847 && (XFASTINT (param_index)
848 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
849 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
850 }
851 }
852 }
853
854 /* Now process them in reverse of specified order. */
855 for (i--; i >= 0; i--)
856 {
857 Lisp_Object prop, val;
858
859 prop = parms[i];
860 val = values[i];
861
862 if (EQ (prop, Qwidth) && NUMBERP (val))
863 width = XFASTINT (val);
864 else if (EQ (prop, Qheight) && NUMBERP (val))
865 height = XFASTINT (val);
866 else if (EQ (prop, Qtop))
867 top = val;
868 else if (EQ (prop, Qleft))
869 left = val;
870 else if (EQ (prop, Qicon_top))
871 icon_top = val;
872 else if (EQ (prop, Qicon_left))
873 icon_left = val;
874 else if (EQ (prop, Qforeground_color)
875 || EQ (prop, Qbackground_color)
876 || EQ (prop, Qfont))
877 /* Processed above. */
878 continue;
879 else
880 {
881 register Lisp_Object param_index, old_value;
882
883 old_value = get_frame_param (f, prop);
884
885 store_frame_param (f, prop, val);
886
887 param_index = Fget (prop, Qx_frame_parameter);
888 if (NATNUMP (param_index)
889 && (XFASTINT (param_index)
890 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
891 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
892 }
893 }
894
895 /* Don't die if just one of these was set. */
896 if (EQ (left, Qunbound))
897 {
898 left_no_change = 1;
899 if (f->output_data.w32->left_pos < 0)
900 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
901 else
902 XSETINT (left, f->output_data.w32->left_pos);
903 }
904 if (EQ (top, Qunbound))
905 {
906 top_no_change = 1;
907 if (f->output_data.w32->top_pos < 0)
908 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
909 else
910 XSETINT (top, f->output_data.w32->top_pos);
911 }
912
913 /* If one of the icon positions was not set, preserve or default it. */
914 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
915 {
916 icon_left_no_change = 1;
917 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
918 if (NILP (icon_left))
919 XSETINT (icon_left, 0);
920 }
921 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
922 {
923 icon_top_no_change = 1;
924 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
925 if (NILP (icon_top))
926 XSETINT (icon_top, 0);
927 }
928
929 /* Don't set these parameters unless they've been explicitly
930 specified. The window might be mapped or resized while we're in
931 this function, and we don't want to override that unless the lisp
932 code has asked for it.
933
934 Don't set these parameters unless they actually differ from the
935 window's current parameters; the window may not actually exist
936 yet. */
937 {
938 Lisp_Object frame;
939
940 check_frame_size (f, &height, &width);
941
942 XSETFRAME (frame, f);
943
944 if (width != FRAME_WIDTH (f)
945 || height != FRAME_HEIGHT (f)
946 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
947 Fset_frame_size (frame, make_number (width), make_number (height));
948
949 if ((!NILP (left) || !NILP (top))
950 && ! (left_no_change && top_no_change)
951 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
952 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
953 {
954 int leftpos = 0;
955 int toppos = 0;
956
957 /* Record the signs. */
958 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
959 if (EQ (left, Qminus))
960 f->output_data.w32->size_hint_flags |= XNegative;
961 else if (INTEGERP (left))
962 {
963 leftpos = XINT (left);
964 if (leftpos < 0)
965 f->output_data.w32->size_hint_flags |= XNegative;
966 }
967 else if (CONSP (left) && EQ (XCAR (left), Qminus)
968 && CONSP (XCDR (left))
969 && INTEGERP (XCAR (XCDR (left))))
970 {
971 leftpos = - XINT (XCAR (XCDR (left)));
972 f->output_data.w32->size_hint_flags |= XNegative;
973 }
974 else if (CONSP (left) && EQ (XCAR (left), Qplus)
975 && CONSP (XCDR (left))
976 && INTEGERP (XCAR (XCDR (left))))
977 {
978 leftpos = XINT (XCAR (XCDR (left)));
979 }
980
981 if (EQ (top, Qminus))
982 f->output_data.w32->size_hint_flags |= YNegative;
983 else if (INTEGERP (top))
984 {
985 toppos = XINT (top);
986 if (toppos < 0)
987 f->output_data.w32->size_hint_flags |= YNegative;
988 }
989 else if (CONSP (top) && EQ (XCAR (top), Qminus)
990 && CONSP (XCDR (top))
991 && INTEGERP (XCAR (XCDR (top))))
992 {
993 toppos = - XINT (XCAR (XCDR (top)));
994 f->output_data.w32->size_hint_flags |= YNegative;
995 }
996 else if (CONSP (top) && EQ (XCAR (top), Qplus)
997 && CONSP (XCDR (top))
998 && INTEGERP (XCAR (XCDR (top))))
999 {
1000 toppos = XINT (XCAR (XCDR (top)));
1001 }
1002
1003
1004 /* Store the numeric value of the position. */
1005 f->output_data.w32->top_pos = toppos;
1006 f->output_data.w32->left_pos = leftpos;
1007
1008 f->output_data.w32->win_gravity = NorthWestGravity;
1009
1010 /* Actually set that position, and convert to absolute. */
1011 x_set_offset (f, leftpos, toppos, -1);
1012 }
1013
1014 if ((!NILP (icon_left) || !NILP (icon_top))
1015 && ! (icon_left_no_change && icon_top_no_change))
1016 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1017 }
1018
1019 UNGCPRO;
1020 }
1021
1022 /* Store the screen positions of frame F into XPTR and YPTR.
1023 These are the positions of the containing window manager window,
1024 not Emacs's own window. */
1025
1026 void
1027 x_real_positions (f, xptr, yptr)
1028 FRAME_PTR f;
1029 int *xptr, *yptr;
1030 {
1031 POINT pt;
1032
1033 {
1034 RECT rect;
1035
1036 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1037 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1038
1039 pt.x = rect.left;
1040 pt.y = rect.top;
1041 }
1042
1043 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1044
1045 *xptr = pt.x;
1046 *yptr = pt.y;
1047 }
1048
1049 /* Insert a description of internally-recorded parameters of frame X
1050 into the parameter alist *ALISTPTR that is to be given to the user.
1051 Only parameters that are specific to W32
1052 and whose values are not correctly recorded in the frame's
1053 param_alist need to be considered here. */
1054
1055 void
1056 x_report_frame_params (f, alistptr)
1057 struct frame *f;
1058 Lisp_Object *alistptr;
1059 {
1060 char buf[16];
1061 Lisp_Object tem;
1062
1063 /* Represent negative positions (off the top or left screen edge)
1064 in a way that Fmodify_frame_parameters will understand correctly. */
1065 XSETINT (tem, f->output_data.w32->left_pos);
1066 if (f->output_data.w32->left_pos >= 0)
1067 store_in_alist (alistptr, Qleft, tem);
1068 else
1069 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1070
1071 XSETINT (tem, f->output_data.w32->top_pos);
1072 if (f->output_data.w32->top_pos >= 0)
1073 store_in_alist (alistptr, Qtop, tem);
1074 else
1075 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1076
1077 store_in_alist (alistptr, Qborder_width,
1078 make_number (f->output_data.w32->border_width));
1079 store_in_alist (alistptr, Qinternal_border_width,
1080 make_number (f->output_data.w32->internal_border_width));
1081 store_in_alist (alistptr, Qleft_fringe,
1082 make_number (f->output_data.w32->left_fringe_width));
1083 store_in_alist (alistptr, Qright_fringe,
1084 make_number (f->output_data.w32->right_fringe_width));
1085 store_in_alist (alistptr, Qscroll_bar_width,
1086 make_number (FRAME_HAS_VERTICAL_SCROLL_BARS (f)
1087 ? FRAME_SCROLL_BAR_PIXEL_WIDTH(f)
1088 : 0));
1089 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1090 store_in_alist (alistptr, Qwindow_id,
1091 build_string (buf));
1092 store_in_alist (alistptr, Qicon_name, f->icon_name);
1093 FRAME_SAMPLE_VISIBILITY (f);
1094 store_in_alist (alistptr, Qvisibility,
1095 (FRAME_VISIBLE_P (f) ? Qt
1096 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1097 store_in_alist (alistptr, Qdisplay,
1098 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1099 }
1100 \f
1101
1102 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
1103 Sw32_define_rgb_color, 4, 4, 0,
1104 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
1105 This adds or updates a named color to w32-color-map, making it
1106 available for use. The original entry's RGB ref is returned, or nil
1107 if the entry is new. */)
1108 (red, green, blue, name)
1109 Lisp_Object red, green, blue, name;
1110 {
1111 Lisp_Object rgb;
1112 Lisp_Object oldrgb = Qnil;
1113 Lisp_Object entry;
1114
1115 CHECK_NUMBER (red);
1116 CHECK_NUMBER (green);
1117 CHECK_NUMBER (blue);
1118 CHECK_STRING (name);
1119
1120 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1121
1122 BLOCK_INPUT;
1123
1124 /* replace existing entry in w32-color-map or add new entry. */
1125 entry = Fassoc (name, Vw32_color_map);
1126 if (NILP (entry))
1127 {
1128 entry = Fcons (name, rgb);
1129 Vw32_color_map = Fcons (entry, Vw32_color_map);
1130 }
1131 else
1132 {
1133 oldrgb = Fcdr (entry);
1134 Fsetcdr (entry, rgb);
1135 }
1136
1137 UNBLOCK_INPUT;
1138
1139 return (oldrgb);
1140 }
1141
1142 DEFUN ("w32-load-color-file", Fw32_load_color_file,
1143 Sw32_load_color_file, 1, 1, 0,
1144 doc: /* Create an alist of color entries from an external file.
1145 Assign this value to w32-color-map to replace the existing color map.
1146
1147 The file should define one named RGB color per line like so:
1148 R G B name
1149 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
1150 (filename)
1151 Lisp_Object filename;
1152 {
1153 FILE *fp;
1154 Lisp_Object cmap = Qnil;
1155 Lisp_Object abspath;
1156
1157 CHECK_STRING (filename);
1158 abspath = Fexpand_file_name (filename, Qnil);
1159
1160 fp = fopen (XSTRING (filename)->data, "rt");
1161 if (fp)
1162 {
1163 char buf[512];
1164 int red, green, blue;
1165 int num;
1166
1167 BLOCK_INPUT;
1168
1169 while (fgets (buf, sizeof (buf), fp) != NULL) {
1170 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1171 {
1172 char *name = buf + num;
1173 num = strlen (name) - 1;
1174 if (name[num] == '\n')
1175 name[num] = 0;
1176 cmap = Fcons (Fcons (build_string (name),
1177 make_number (RGB (red, green, blue))),
1178 cmap);
1179 }
1180 }
1181 fclose (fp);
1182
1183 UNBLOCK_INPUT;
1184 }
1185
1186 return cmap;
1187 }
1188
1189 /* The default colors for the w32 color map */
1190 typedef struct colormap_t
1191 {
1192 char *name;
1193 COLORREF colorref;
1194 } colormap_t;
1195
1196 colormap_t w32_color_map[] =
1197 {
1198 {"snow" , PALETTERGB (255,250,250)},
1199 {"ghost white" , PALETTERGB (248,248,255)},
1200 {"GhostWhite" , PALETTERGB (248,248,255)},
1201 {"white smoke" , PALETTERGB (245,245,245)},
1202 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1203 {"gainsboro" , PALETTERGB (220,220,220)},
1204 {"floral white" , PALETTERGB (255,250,240)},
1205 {"FloralWhite" , PALETTERGB (255,250,240)},
1206 {"old lace" , PALETTERGB (253,245,230)},
1207 {"OldLace" , PALETTERGB (253,245,230)},
1208 {"linen" , PALETTERGB (250,240,230)},
1209 {"antique white" , PALETTERGB (250,235,215)},
1210 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1211 {"papaya whip" , PALETTERGB (255,239,213)},
1212 {"PapayaWhip" , PALETTERGB (255,239,213)},
1213 {"blanched almond" , PALETTERGB (255,235,205)},
1214 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1215 {"bisque" , PALETTERGB (255,228,196)},
1216 {"peach puff" , PALETTERGB (255,218,185)},
1217 {"PeachPuff" , PALETTERGB (255,218,185)},
1218 {"navajo white" , PALETTERGB (255,222,173)},
1219 {"NavajoWhite" , PALETTERGB (255,222,173)},
1220 {"moccasin" , PALETTERGB (255,228,181)},
1221 {"cornsilk" , PALETTERGB (255,248,220)},
1222 {"ivory" , PALETTERGB (255,255,240)},
1223 {"lemon chiffon" , PALETTERGB (255,250,205)},
1224 {"LemonChiffon" , PALETTERGB (255,250,205)},
1225 {"seashell" , PALETTERGB (255,245,238)},
1226 {"honeydew" , PALETTERGB (240,255,240)},
1227 {"mint cream" , PALETTERGB (245,255,250)},
1228 {"MintCream" , PALETTERGB (245,255,250)},
1229 {"azure" , PALETTERGB (240,255,255)},
1230 {"alice blue" , PALETTERGB (240,248,255)},
1231 {"AliceBlue" , PALETTERGB (240,248,255)},
1232 {"lavender" , PALETTERGB (230,230,250)},
1233 {"lavender blush" , PALETTERGB (255,240,245)},
1234 {"LavenderBlush" , PALETTERGB (255,240,245)},
1235 {"misty rose" , PALETTERGB (255,228,225)},
1236 {"MistyRose" , PALETTERGB (255,228,225)},
1237 {"white" , PALETTERGB (255,255,255)},
1238 {"black" , PALETTERGB ( 0, 0, 0)},
1239 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1240 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1241 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1242 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1243 {"dim gray" , PALETTERGB (105,105,105)},
1244 {"DimGray" , PALETTERGB (105,105,105)},
1245 {"dim grey" , PALETTERGB (105,105,105)},
1246 {"DimGrey" , PALETTERGB (105,105,105)},
1247 {"slate gray" , PALETTERGB (112,128,144)},
1248 {"SlateGray" , PALETTERGB (112,128,144)},
1249 {"slate grey" , PALETTERGB (112,128,144)},
1250 {"SlateGrey" , PALETTERGB (112,128,144)},
1251 {"light slate gray" , PALETTERGB (119,136,153)},
1252 {"LightSlateGray" , PALETTERGB (119,136,153)},
1253 {"light slate grey" , PALETTERGB (119,136,153)},
1254 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1255 {"gray" , PALETTERGB (190,190,190)},
1256 {"grey" , PALETTERGB (190,190,190)},
1257 {"light grey" , PALETTERGB (211,211,211)},
1258 {"LightGrey" , PALETTERGB (211,211,211)},
1259 {"light gray" , PALETTERGB (211,211,211)},
1260 {"LightGray" , PALETTERGB (211,211,211)},
1261 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1262 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1263 {"navy" , PALETTERGB ( 0, 0,128)},
1264 {"navy blue" , PALETTERGB ( 0, 0,128)},
1265 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1266 {"cornflower blue" , PALETTERGB (100,149,237)},
1267 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1268 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1269 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1270 {"slate blue" , PALETTERGB (106, 90,205)},
1271 {"SlateBlue" , PALETTERGB (106, 90,205)},
1272 {"medium slate blue" , PALETTERGB (123,104,238)},
1273 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1274 {"light slate blue" , PALETTERGB (132,112,255)},
1275 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1276 {"medium blue" , PALETTERGB ( 0, 0,205)},
1277 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1278 {"royal blue" , PALETTERGB ( 65,105,225)},
1279 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1280 {"blue" , PALETTERGB ( 0, 0,255)},
1281 {"dodger blue" , PALETTERGB ( 30,144,255)},
1282 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1283 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1284 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1285 {"sky blue" , PALETTERGB (135,206,235)},
1286 {"SkyBlue" , PALETTERGB (135,206,235)},
1287 {"light sky blue" , PALETTERGB (135,206,250)},
1288 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1289 {"steel blue" , PALETTERGB ( 70,130,180)},
1290 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1291 {"light steel blue" , PALETTERGB (176,196,222)},
1292 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1293 {"light blue" , PALETTERGB (173,216,230)},
1294 {"LightBlue" , PALETTERGB (173,216,230)},
1295 {"powder blue" , PALETTERGB (176,224,230)},
1296 {"PowderBlue" , PALETTERGB (176,224,230)},
1297 {"pale turquoise" , PALETTERGB (175,238,238)},
1298 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1299 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1300 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1301 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1302 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1303 {"turquoise" , PALETTERGB ( 64,224,208)},
1304 {"cyan" , PALETTERGB ( 0,255,255)},
1305 {"light cyan" , PALETTERGB (224,255,255)},
1306 {"LightCyan" , PALETTERGB (224,255,255)},
1307 {"cadet blue" , PALETTERGB ( 95,158,160)},
1308 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1309 {"medium aquamarine" , PALETTERGB (102,205,170)},
1310 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1311 {"aquamarine" , PALETTERGB (127,255,212)},
1312 {"dark green" , PALETTERGB ( 0,100, 0)},
1313 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1314 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1315 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1316 {"dark sea green" , PALETTERGB (143,188,143)},
1317 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1318 {"sea green" , PALETTERGB ( 46,139, 87)},
1319 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1320 {"medium sea green" , PALETTERGB ( 60,179,113)},
1321 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1322 {"light sea green" , PALETTERGB ( 32,178,170)},
1323 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1324 {"pale green" , PALETTERGB (152,251,152)},
1325 {"PaleGreen" , PALETTERGB (152,251,152)},
1326 {"spring green" , PALETTERGB ( 0,255,127)},
1327 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1328 {"lawn green" , PALETTERGB (124,252, 0)},
1329 {"LawnGreen" , PALETTERGB (124,252, 0)},
1330 {"green" , PALETTERGB ( 0,255, 0)},
1331 {"chartreuse" , PALETTERGB (127,255, 0)},
1332 {"medium spring green" , PALETTERGB ( 0,250,154)},
1333 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1334 {"green yellow" , PALETTERGB (173,255, 47)},
1335 {"GreenYellow" , PALETTERGB (173,255, 47)},
1336 {"lime green" , PALETTERGB ( 50,205, 50)},
1337 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1338 {"yellow green" , PALETTERGB (154,205, 50)},
1339 {"YellowGreen" , PALETTERGB (154,205, 50)},
1340 {"forest green" , PALETTERGB ( 34,139, 34)},
1341 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1342 {"olive drab" , PALETTERGB (107,142, 35)},
1343 {"OliveDrab" , PALETTERGB (107,142, 35)},
1344 {"dark khaki" , PALETTERGB (189,183,107)},
1345 {"DarkKhaki" , PALETTERGB (189,183,107)},
1346 {"khaki" , PALETTERGB (240,230,140)},
1347 {"pale goldenrod" , PALETTERGB (238,232,170)},
1348 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1349 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1350 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1351 {"light yellow" , PALETTERGB (255,255,224)},
1352 {"LightYellow" , PALETTERGB (255,255,224)},
1353 {"yellow" , PALETTERGB (255,255, 0)},
1354 {"gold" , PALETTERGB (255,215, 0)},
1355 {"light goldenrod" , PALETTERGB (238,221,130)},
1356 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1357 {"goldenrod" , PALETTERGB (218,165, 32)},
1358 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1359 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1360 {"rosy brown" , PALETTERGB (188,143,143)},
1361 {"RosyBrown" , PALETTERGB (188,143,143)},
1362 {"indian red" , PALETTERGB (205, 92, 92)},
1363 {"IndianRed" , PALETTERGB (205, 92, 92)},
1364 {"saddle brown" , PALETTERGB (139, 69, 19)},
1365 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1366 {"sienna" , PALETTERGB (160, 82, 45)},
1367 {"peru" , PALETTERGB (205,133, 63)},
1368 {"burlywood" , PALETTERGB (222,184,135)},
1369 {"beige" , PALETTERGB (245,245,220)},
1370 {"wheat" , PALETTERGB (245,222,179)},
1371 {"sandy brown" , PALETTERGB (244,164, 96)},
1372 {"SandyBrown" , PALETTERGB (244,164, 96)},
1373 {"tan" , PALETTERGB (210,180,140)},
1374 {"chocolate" , PALETTERGB (210,105, 30)},
1375 {"firebrick" , PALETTERGB (178,34, 34)},
1376 {"brown" , PALETTERGB (165,42, 42)},
1377 {"dark salmon" , PALETTERGB (233,150,122)},
1378 {"DarkSalmon" , PALETTERGB (233,150,122)},
1379 {"salmon" , PALETTERGB (250,128,114)},
1380 {"light salmon" , PALETTERGB (255,160,122)},
1381 {"LightSalmon" , PALETTERGB (255,160,122)},
1382 {"orange" , PALETTERGB (255,165, 0)},
1383 {"dark orange" , PALETTERGB (255,140, 0)},
1384 {"DarkOrange" , PALETTERGB (255,140, 0)},
1385 {"coral" , PALETTERGB (255,127, 80)},
1386 {"light coral" , PALETTERGB (240,128,128)},
1387 {"LightCoral" , PALETTERGB (240,128,128)},
1388 {"tomato" , PALETTERGB (255, 99, 71)},
1389 {"orange red" , PALETTERGB (255, 69, 0)},
1390 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1391 {"red" , PALETTERGB (255, 0, 0)},
1392 {"hot pink" , PALETTERGB (255,105,180)},
1393 {"HotPink" , PALETTERGB (255,105,180)},
1394 {"deep pink" , PALETTERGB (255, 20,147)},
1395 {"DeepPink" , PALETTERGB (255, 20,147)},
1396 {"pink" , PALETTERGB (255,192,203)},
1397 {"light pink" , PALETTERGB (255,182,193)},
1398 {"LightPink" , PALETTERGB (255,182,193)},
1399 {"pale violet red" , PALETTERGB (219,112,147)},
1400 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1401 {"maroon" , PALETTERGB (176, 48, 96)},
1402 {"medium violet red" , PALETTERGB (199, 21,133)},
1403 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1404 {"violet red" , PALETTERGB (208, 32,144)},
1405 {"VioletRed" , PALETTERGB (208, 32,144)},
1406 {"magenta" , PALETTERGB (255, 0,255)},
1407 {"violet" , PALETTERGB (238,130,238)},
1408 {"plum" , PALETTERGB (221,160,221)},
1409 {"orchid" , PALETTERGB (218,112,214)},
1410 {"medium orchid" , PALETTERGB (186, 85,211)},
1411 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1412 {"dark orchid" , PALETTERGB (153, 50,204)},
1413 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1414 {"dark violet" , PALETTERGB (148, 0,211)},
1415 {"DarkViolet" , PALETTERGB (148, 0,211)},
1416 {"blue violet" , PALETTERGB (138, 43,226)},
1417 {"BlueViolet" , PALETTERGB (138, 43,226)},
1418 {"purple" , PALETTERGB (160, 32,240)},
1419 {"medium purple" , PALETTERGB (147,112,219)},
1420 {"MediumPurple" , PALETTERGB (147,112,219)},
1421 {"thistle" , PALETTERGB (216,191,216)},
1422 {"gray0" , PALETTERGB ( 0, 0, 0)},
1423 {"grey0" , PALETTERGB ( 0, 0, 0)},
1424 {"dark grey" , PALETTERGB (169,169,169)},
1425 {"DarkGrey" , PALETTERGB (169,169,169)},
1426 {"dark gray" , PALETTERGB (169,169,169)},
1427 {"DarkGray" , PALETTERGB (169,169,169)},
1428 {"dark blue" , PALETTERGB ( 0, 0,139)},
1429 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1430 {"dark cyan" , PALETTERGB ( 0,139,139)},
1431 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1432 {"dark magenta" , PALETTERGB (139, 0,139)},
1433 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1434 {"dark red" , PALETTERGB (139, 0, 0)},
1435 {"DarkRed" , PALETTERGB (139, 0, 0)},
1436 {"light green" , PALETTERGB (144,238,144)},
1437 {"LightGreen" , PALETTERGB (144,238,144)},
1438 };
1439
1440 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1441 0, 0, 0, doc: /* Return the default color map. */)
1442 ()
1443 {
1444 int i;
1445 colormap_t *pc = w32_color_map;
1446 Lisp_Object cmap;
1447
1448 BLOCK_INPUT;
1449
1450 cmap = Qnil;
1451
1452 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1453 pc++, i++)
1454 cmap = Fcons (Fcons (build_string (pc->name),
1455 make_number (pc->colorref)),
1456 cmap);
1457
1458 UNBLOCK_INPUT;
1459
1460 return (cmap);
1461 }
1462
1463 Lisp_Object
1464 w32_to_x_color (rgb)
1465 Lisp_Object rgb;
1466 {
1467 Lisp_Object color;
1468
1469 CHECK_NUMBER (rgb);
1470
1471 BLOCK_INPUT;
1472
1473 color = Frassq (rgb, Vw32_color_map);
1474
1475 UNBLOCK_INPUT;
1476
1477 if (!NILP (color))
1478 return (Fcar (color));
1479 else
1480 return Qnil;
1481 }
1482
1483 COLORREF
1484 w32_color_map_lookup (colorname)
1485 char *colorname;
1486 {
1487 Lisp_Object tail, ret = Qnil;
1488
1489 BLOCK_INPUT;
1490
1491 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1492 {
1493 register Lisp_Object elt, tem;
1494
1495 elt = Fcar (tail);
1496 if (!CONSP (elt)) continue;
1497
1498 tem = Fcar (elt);
1499
1500 if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
1501 {
1502 ret = XUINT (Fcdr (elt));
1503 break;
1504 }
1505
1506 QUIT;
1507 }
1508
1509
1510 UNBLOCK_INPUT;
1511
1512 return ret;
1513 }
1514
1515 COLORREF
1516 x_to_w32_color (colorname)
1517 char * colorname;
1518 {
1519 register Lisp_Object ret = Qnil;
1520
1521 BLOCK_INPUT;
1522
1523 if (colorname[0] == '#')
1524 {
1525 /* Could be an old-style RGB Device specification. */
1526 char *color;
1527 int size;
1528 color = colorname + 1;
1529
1530 size = strlen(color);
1531 if (size == 3 || size == 6 || size == 9 || size == 12)
1532 {
1533 UINT colorval;
1534 int i, pos;
1535 pos = 0;
1536 size /= 3;
1537 colorval = 0;
1538
1539 for (i = 0; i < 3; i++)
1540 {
1541 char *end;
1542 char t;
1543 unsigned long value;
1544
1545 /* The check for 'x' in the following conditional takes into
1546 account the fact that strtol allows a "0x" in front of
1547 our numbers, and we don't. */
1548 if (!isxdigit(color[0]) || color[1] == 'x')
1549 break;
1550 t = color[size];
1551 color[size] = '\0';
1552 value = strtoul(color, &end, 16);
1553 color[size] = t;
1554 if (errno == ERANGE || end - color != size)
1555 break;
1556 switch (size)
1557 {
1558 case 1:
1559 value = value * 0x10;
1560 break;
1561 case 2:
1562 break;
1563 case 3:
1564 value /= 0x10;
1565 break;
1566 case 4:
1567 value /= 0x100;
1568 break;
1569 }
1570 colorval |= (value << pos);
1571 pos += 0x8;
1572 if (i == 2)
1573 {
1574 UNBLOCK_INPUT;
1575 return (colorval);
1576 }
1577 color = end;
1578 }
1579 }
1580 }
1581 else if (strnicmp(colorname, "rgb:", 4) == 0)
1582 {
1583 char *color;
1584 UINT colorval;
1585 int i, pos;
1586 pos = 0;
1587
1588 colorval = 0;
1589 color = colorname + 4;
1590 for (i = 0; i < 3; i++)
1591 {
1592 char *end;
1593 unsigned long value;
1594
1595 /* The check for 'x' in the following conditional takes into
1596 account the fact that strtol allows a "0x" in front of
1597 our numbers, and we don't. */
1598 if (!isxdigit(color[0]) || color[1] == 'x')
1599 break;
1600 value = strtoul(color, &end, 16);
1601 if (errno == ERANGE)
1602 break;
1603 switch (end - color)
1604 {
1605 case 1:
1606 value = value * 0x10 + value;
1607 break;
1608 case 2:
1609 break;
1610 case 3:
1611 value /= 0x10;
1612 break;
1613 case 4:
1614 value /= 0x100;
1615 break;
1616 default:
1617 value = ULONG_MAX;
1618 }
1619 if (value == ULONG_MAX)
1620 break;
1621 colorval |= (value << pos);
1622 pos += 0x8;
1623 if (i == 2)
1624 {
1625 if (*end != '\0')
1626 break;
1627 UNBLOCK_INPUT;
1628 return (colorval);
1629 }
1630 if (*end != '/')
1631 break;
1632 color = end + 1;
1633 }
1634 }
1635 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1636 {
1637 /* This is an RGB Intensity specification. */
1638 char *color;
1639 UINT colorval;
1640 int i, pos;
1641 pos = 0;
1642
1643 colorval = 0;
1644 color = colorname + 5;
1645 for (i = 0; i < 3; i++)
1646 {
1647 char *end;
1648 double value;
1649 UINT val;
1650
1651 value = strtod(color, &end);
1652 if (errno == ERANGE)
1653 break;
1654 if (value < 0.0 || value > 1.0)
1655 break;
1656 val = (UINT)(0x100 * value);
1657 /* We used 0x100 instead of 0xFF to give an continuous
1658 range between 0.0 and 1.0 inclusive. The next statement
1659 fixes the 1.0 case. */
1660 if (val == 0x100)
1661 val = 0xFF;
1662 colorval |= (val << pos);
1663 pos += 0x8;
1664 if (i == 2)
1665 {
1666 if (*end != '\0')
1667 break;
1668 UNBLOCK_INPUT;
1669 return (colorval);
1670 }
1671 if (*end != '/')
1672 break;
1673 color = end + 1;
1674 }
1675 }
1676 /* I am not going to attempt to handle any of the CIE color schemes
1677 or TekHVC, since I don't know the algorithms for conversion to
1678 RGB. */
1679
1680 /* If we fail to lookup the color name in w32_color_map, then check the
1681 colorname to see if it can be crudely approximated: If the X color
1682 ends in a number (e.g., "darkseagreen2"), strip the number and
1683 return the result of looking up the base color name. */
1684 ret = w32_color_map_lookup (colorname);
1685 if (NILP (ret))
1686 {
1687 int len = strlen (colorname);
1688
1689 if (isdigit (colorname[len - 1]))
1690 {
1691 char *ptr, *approx = alloca (len + 1);
1692
1693 strcpy (approx, colorname);
1694 ptr = &approx[len - 1];
1695 while (ptr > approx && isdigit (*ptr))
1696 *ptr-- = '\0';
1697
1698 ret = w32_color_map_lookup (approx);
1699 }
1700 }
1701
1702 UNBLOCK_INPUT;
1703 return ret;
1704 }
1705
1706
1707 void
1708 w32_regenerate_palette (FRAME_PTR f)
1709 {
1710 struct w32_palette_entry * list;
1711 LOGPALETTE * log_palette;
1712 HPALETTE new_palette;
1713 int i;
1714
1715 /* don't bother trying to create palette if not supported */
1716 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1717 return;
1718
1719 log_palette = (LOGPALETTE *)
1720 alloca (sizeof (LOGPALETTE) +
1721 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1722 log_palette->palVersion = 0x300;
1723 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1724
1725 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1726 for (i = 0;
1727 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1728 i++, list = list->next)
1729 log_palette->palPalEntry[i] = list->entry;
1730
1731 new_palette = CreatePalette (log_palette);
1732
1733 enter_crit ();
1734
1735 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1736 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1737 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1738
1739 /* Realize display palette and garbage all frames. */
1740 release_frame_dc (f, get_frame_dc (f));
1741
1742 leave_crit ();
1743 }
1744
1745 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1746 #define SET_W32_COLOR(pe, color) \
1747 do \
1748 { \
1749 pe.peRed = GetRValue (color); \
1750 pe.peGreen = GetGValue (color); \
1751 pe.peBlue = GetBValue (color); \
1752 pe.peFlags = 0; \
1753 } while (0)
1754
1755 #if 0
1756 /* Keep these around in case we ever want to track color usage. */
1757 void
1758 w32_map_color (FRAME_PTR f, COLORREF color)
1759 {
1760 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1761
1762 if (NILP (Vw32_enable_palette))
1763 return;
1764
1765 /* check if color is already mapped */
1766 while (list)
1767 {
1768 if (W32_COLOR (list->entry) == color)
1769 {
1770 ++list->refcount;
1771 return;
1772 }
1773 list = list->next;
1774 }
1775
1776 /* not already mapped, so add to list and recreate Windows palette */
1777 list = (struct w32_palette_entry *)
1778 xmalloc (sizeof (struct w32_palette_entry));
1779 SET_W32_COLOR (list->entry, color);
1780 list->refcount = 1;
1781 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1782 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1783 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1784
1785 /* set flag that palette must be regenerated */
1786 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1787 }
1788
1789 void
1790 w32_unmap_color (FRAME_PTR f, COLORREF color)
1791 {
1792 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1793 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1794
1795 if (NILP (Vw32_enable_palette))
1796 return;
1797
1798 /* check if color is already mapped */
1799 while (list)
1800 {
1801 if (W32_COLOR (list->entry) == color)
1802 {
1803 if (--list->refcount == 0)
1804 {
1805 *prev = list->next;
1806 xfree (list);
1807 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1808 break;
1809 }
1810 else
1811 return;
1812 }
1813 prev = &list->next;
1814 list = list->next;
1815 }
1816
1817 /* set flag that palette must be regenerated */
1818 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1819 }
1820 #endif
1821
1822
1823 /* Gamma-correct COLOR on frame F. */
1824
1825 void
1826 gamma_correct (f, color)
1827 struct frame *f;
1828 COLORREF *color;
1829 {
1830 if (f->gamma)
1831 {
1832 *color = PALETTERGB (
1833 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1834 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1835 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1836 }
1837 }
1838
1839
1840 /* Decide if color named COLOR is valid for the display associated with
1841 the selected frame; if so, return the rgb values in COLOR_DEF.
1842 If ALLOC is nonzero, allocate a new colormap cell. */
1843
1844 int
1845 w32_defined_color (f, color, color_def, alloc)
1846 FRAME_PTR f;
1847 char *color;
1848 XColor *color_def;
1849 int alloc;
1850 {
1851 register Lisp_Object tem;
1852 COLORREF w32_color_ref;
1853
1854 tem = x_to_w32_color (color);
1855
1856 if (!NILP (tem))
1857 {
1858 if (f)
1859 {
1860 /* Apply gamma correction. */
1861 w32_color_ref = XUINT (tem);
1862 gamma_correct (f, &w32_color_ref);
1863 XSETINT (tem, w32_color_ref);
1864 }
1865
1866 /* Map this color to the palette if it is enabled. */
1867 if (!NILP (Vw32_enable_palette))
1868 {
1869 struct w32_palette_entry * entry =
1870 one_w32_display_info.color_list;
1871 struct w32_palette_entry ** prev =
1872 &one_w32_display_info.color_list;
1873
1874 /* check if color is already mapped */
1875 while (entry)
1876 {
1877 if (W32_COLOR (entry->entry) == XUINT (tem))
1878 break;
1879 prev = &entry->next;
1880 entry = entry->next;
1881 }
1882
1883 if (entry == NULL && alloc)
1884 {
1885 /* not already mapped, so add to list */
1886 entry = (struct w32_palette_entry *)
1887 xmalloc (sizeof (struct w32_palette_entry));
1888 SET_W32_COLOR (entry->entry, XUINT (tem));
1889 entry->next = NULL;
1890 *prev = entry;
1891 one_w32_display_info.num_colors++;
1892
1893 /* set flag that palette must be regenerated */
1894 one_w32_display_info.regen_palette = TRUE;
1895 }
1896 }
1897 /* Ensure COLORREF value is snapped to nearest color in (default)
1898 palette by simulating the PALETTERGB macro. This works whether
1899 or not the display device has a palette. */
1900 w32_color_ref = XUINT (tem) | 0x2000000;
1901
1902 color_def->pixel = w32_color_ref;
1903 color_def->red = GetRValue (w32_color_ref);
1904 color_def->green = GetGValue (w32_color_ref);
1905 color_def->blue = GetBValue (w32_color_ref);
1906
1907 return 1;
1908 }
1909 else
1910 {
1911 return 0;
1912 }
1913 }
1914
1915 /* Given a string ARG naming a color, compute a pixel value from it
1916 suitable for screen F.
1917 If F is not a color screen, return DEF (default) regardless of what
1918 ARG says. */
1919
1920 int
1921 x_decode_color (f, arg, def)
1922 FRAME_PTR f;
1923 Lisp_Object arg;
1924 int def;
1925 {
1926 XColor cdef;
1927
1928 CHECK_STRING (arg);
1929
1930 if (strcmp (XSTRING (arg)->data, "black") == 0)
1931 return BLACK_PIX_DEFAULT (f);
1932 else if (strcmp (XSTRING (arg)->data, "white") == 0)
1933 return WHITE_PIX_DEFAULT (f);
1934
1935 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1936 return def;
1937
1938 /* w32_defined_color is responsible for coping with failures
1939 by looking for a near-miss. */
1940 if (w32_defined_color (f, XSTRING (arg)->data, &cdef, 1))
1941 return cdef.pixel;
1942
1943 /* defined_color failed; return an ultimate default. */
1944 return def;
1945 }
1946 \f
1947 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
1948 the previous value of that parameter, NEW_VALUE is the new value. */
1949
1950 static void
1951 x_set_line_spacing (f, new_value, old_value)
1952 struct frame *f;
1953 Lisp_Object new_value, old_value;
1954 {
1955 if (NILP (new_value))
1956 f->extra_line_spacing = 0;
1957 else if (NATNUMP (new_value))
1958 f->extra_line_spacing = XFASTINT (new_value);
1959 else
1960 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
1961 Fcons (new_value, Qnil)));
1962 if (FRAME_VISIBLE_P (f))
1963 redraw_frame (f);
1964 }
1965
1966
1967 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
1968 the previous value of that parameter, NEW_VALUE is the new value. */
1969
1970 static void
1971 x_set_screen_gamma (f, new_value, old_value)
1972 struct frame *f;
1973 Lisp_Object new_value, old_value;
1974 {
1975 if (NILP (new_value))
1976 f->gamma = 0;
1977 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
1978 /* The value 0.4545 is the normal viewing gamma. */
1979 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
1980 else
1981 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
1982 Fcons (new_value, Qnil)));
1983
1984 clear_face_cache (0);
1985 }
1986
1987
1988 /* Functions called only from `x_set_frame_param'
1989 to set individual parameters.
1990
1991 If FRAME_W32_WINDOW (f) is 0,
1992 the frame is being created and its window does not exist yet.
1993 In that case, just record the parameter's new value
1994 in the standard place; do not attempt to change the window. */
1995
1996 void
1997 x_set_foreground_color (f, arg, oldval)
1998 struct frame *f;
1999 Lisp_Object arg, oldval;
2000 {
2001 struct w32_output *x = f->output_data.w32;
2002 PIX_TYPE fg, old_fg;
2003
2004 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2005 old_fg = FRAME_FOREGROUND_PIXEL (f);
2006 FRAME_FOREGROUND_PIXEL (f) = fg;
2007
2008 if (FRAME_W32_WINDOW (f) != 0)
2009 {
2010 if (x->cursor_pixel == old_fg)
2011 x->cursor_pixel = fg;
2012
2013 update_face_from_frame_parameter (f, Qforeground_color, arg);
2014 if (FRAME_VISIBLE_P (f))
2015 redraw_frame (f);
2016 }
2017 }
2018
2019 void
2020 x_set_background_color (f, arg, oldval)
2021 struct frame *f;
2022 Lisp_Object arg, oldval;
2023 {
2024 FRAME_BACKGROUND_PIXEL (f)
2025 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2026
2027 if (FRAME_W32_WINDOW (f) != 0)
2028 {
2029 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2030 FRAME_BACKGROUND_PIXEL (f));
2031
2032 update_face_from_frame_parameter (f, Qbackground_color, arg);
2033
2034 if (FRAME_VISIBLE_P (f))
2035 redraw_frame (f);
2036 }
2037 }
2038
2039 void
2040 x_set_mouse_color (f, arg, oldval)
2041 struct frame *f;
2042 Lisp_Object arg, oldval;
2043 {
2044 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2045 int count;
2046 int mask_color;
2047
2048 if (!EQ (Qnil, arg))
2049 f->output_data.w32->mouse_pixel
2050 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2051 mask_color = FRAME_BACKGROUND_PIXEL (f);
2052
2053 /* Don't let pointers be invisible. */
2054 if (mask_color == f->output_data.w32->mouse_pixel
2055 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2056 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2057
2058 #if 0 /* TODO : cursor changes */
2059 BLOCK_INPUT;
2060
2061 /* It's not okay to crash if the user selects a screwy cursor. */
2062 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2063
2064 if (!EQ (Qnil, Vx_pointer_shape))
2065 {
2066 CHECK_NUMBER (Vx_pointer_shape);
2067 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2068 }
2069 else
2070 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2071 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2072
2073 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2074 {
2075 CHECK_NUMBER (Vx_nontext_pointer_shape);
2076 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2077 XINT (Vx_nontext_pointer_shape));
2078 }
2079 else
2080 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2081 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2082
2083 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
2084 {
2085 CHECK_NUMBER (Vx_hourglass_pointer_shape);
2086 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2087 XINT (Vx_hourglass_pointer_shape));
2088 }
2089 else
2090 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2091 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2092
2093 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2094 if (!EQ (Qnil, Vx_mode_pointer_shape))
2095 {
2096 CHECK_NUMBER (Vx_mode_pointer_shape);
2097 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2098 XINT (Vx_mode_pointer_shape));
2099 }
2100 else
2101 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2102 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2103
2104 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2105 {
2106 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
2107 cross_cursor
2108 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2109 XINT (Vx_sensitive_text_pointer_shape));
2110 }
2111 else
2112 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2113
2114 if (!NILP (Vx_window_horizontal_drag_shape))
2115 {
2116 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
2117 horizontal_drag_cursor
2118 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2119 XINT (Vx_window_horizontal_drag_shape));
2120 }
2121 else
2122 horizontal_drag_cursor
2123 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2124
2125 /* Check and report errors with the above calls. */
2126 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2127 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2128
2129 {
2130 XColor fore_color, back_color;
2131
2132 fore_color.pixel = f->output_data.w32->mouse_pixel;
2133 back_color.pixel = mask_color;
2134 XQueryColor (FRAME_W32_DISPLAY (f),
2135 DefaultColormap (FRAME_W32_DISPLAY (f),
2136 DefaultScreen (FRAME_W32_DISPLAY (f))),
2137 &fore_color);
2138 XQueryColor (FRAME_W32_DISPLAY (f),
2139 DefaultColormap (FRAME_W32_DISPLAY (f),
2140 DefaultScreen (FRAME_W32_DISPLAY (f))),
2141 &back_color);
2142 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2143 &fore_color, &back_color);
2144 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2145 &fore_color, &back_color);
2146 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2147 &fore_color, &back_color);
2148 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2149 &fore_color, &back_color);
2150 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
2151 &fore_color, &back_color);
2152 }
2153
2154 if (FRAME_W32_WINDOW (f) != 0)
2155 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2156
2157 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2158 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2159 f->output_data.w32->text_cursor = cursor;
2160
2161 if (nontext_cursor != f->output_data.w32->nontext_cursor
2162 && f->output_data.w32->nontext_cursor != 0)
2163 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2164 f->output_data.w32->nontext_cursor = nontext_cursor;
2165
2166 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
2167 && f->output_data.w32->hourglass_cursor != 0)
2168 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
2169 f->output_data.w32->hourglass_cursor = hourglass_cursor;
2170
2171 if (mode_cursor != f->output_data.w32->modeline_cursor
2172 && f->output_data.w32->modeline_cursor != 0)
2173 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2174 f->output_data.w32->modeline_cursor = mode_cursor;
2175
2176 if (cross_cursor != f->output_data.w32->cross_cursor
2177 && f->output_data.w32->cross_cursor != 0)
2178 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2179 f->output_data.w32->cross_cursor = cross_cursor;
2180
2181 XFlush (FRAME_W32_DISPLAY (f));
2182 UNBLOCK_INPUT;
2183
2184 update_face_from_frame_parameter (f, Qmouse_color, arg);
2185 #endif /* TODO */
2186 }
2187
2188 /* Defined in w32term.c. */
2189 void x_update_cursor (struct frame *f, int on_p);
2190
2191 void
2192 x_set_cursor_color (f, arg, oldval)
2193 struct frame *f;
2194 Lisp_Object arg, oldval;
2195 {
2196 unsigned long fore_pixel, pixel;
2197
2198 if (!NILP (Vx_cursor_fore_pixel))
2199 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2200 WHITE_PIX_DEFAULT (f));
2201 else
2202 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2203
2204 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2205
2206 /* Make sure that the cursor color differs from the background color. */
2207 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2208 {
2209 pixel = f->output_data.w32->mouse_pixel;
2210 if (pixel == fore_pixel)
2211 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2212 }
2213
2214 FRAME_FOREGROUND_PIXEL (f) = fore_pixel;
2215 f->output_data.w32->cursor_pixel = pixel;
2216
2217 if (FRAME_W32_WINDOW (f) != 0)
2218 {
2219 if (FRAME_VISIBLE_P (f))
2220 {
2221 x_update_cursor (f, 0);
2222 x_update_cursor (f, 1);
2223 }
2224 }
2225
2226 update_face_from_frame_parameter (f, Qcursor_color, arg);
2227 }
2228
2229 /* Set the border-color of frame F to pixel value PIX.
2230 Note that this does not fully take effect if done before
2231 F has an window. */
2232 void
2233 x_set_border_pixel (f, pix)
2234 struct frame *f;
2235 int pix;
2236 {
2237 f->output_data.w32->border_pixel = pix;
2238
2239 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2240 {
2241 if (FRAME_VISIBLE_P (f))
2242 redraw_frame (f);
2243 }
2244 }
2245
2246 /* Set the border-color of frame F to value described by ARG.
2247 ARG can be a string naming a color.
2248 The border-color is used for the border that is drawn by the server.
2249 Note that this does not fully take effect if done before
2250 F has a window; it must be redone when the window is created. */
2251
2252 void
2253 x_set_border_color (f, arg, oldval)
2254 struct frame *f;
2255 Lisp_Object arg, oldval;
2256 {
2257 int pix;
2258
2259 CHECK_STRING (arg);
2260 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2261 x_set_border_pixel (f, pix);
2262 update_face_from_frame_parameter (f, Qborder_color, arg);
2263 }
2264
2265 /* Value is the internal representation of the specified cursor type
2266 ARG. If type is BAR_CURSOR, return in *WIDTH the specified width
2267 of the bar cursor. */
2268
2269 enum text_cursor_kinds
2270 x_specified_cursor_type (arg, width)
2271 Lisp_Object arg;
2272 int *width;
2273 {
2274 enum text_cursor_kinds type;
2275
2276 if (EQ (arg, Qbar))
2277 {
2278 type = BAR_CURSOR;
2279 *width = 2;
2280 }
2281 else if (CONSP (arg)
2282 && EQ (XCAR (arg), Qbar)
2283 && INTEGERP (XCDR (arg))
2284 && XINT (XCDR (arg)) >= 0)
2285 {
2286 type = BAR_CURSOR;
2287 *width = XINT (XCDR (arg));
2288 }
2289 else if (NILP (arg))
2290 type = NO_CURSOR;
2291 else
2292 /* Treat anything unknown as "box cursor".
2293 It was bad to signal an error; people have trouble fixing
2294 .Xdefaults with Emacs, when it has something bad in it. */
2295 type = FILLED_BOX_CURSOR;
2296
2297 return type;
2298 }
2299
2300 void
2301 x_set_cursor_type (f, arg, oldval)
2302 FRAME_PTR f;
2303 Lisp_Object arg, oldval;
2304 {
2305 int width;
2306
2307 FRAME_DESIRED_CURSOR (f) = x_specified_cursor_type (arg, &width);
2308 f->output_data.w32->cursor_width = width;
2309
2310 /* Make sure the cursor gets redrawn. This is overkill, but how
2311 often do people change cursor types? */
2312 update_mode_lines++;
2313 }
2314 \f
2315 void
2316 x_set_icon_type (f, arg, oldval)
2317 struct frame *f;
2318 Lisp_Object arg, oldval;
2319 {
2320 int result;
2321
2322 if (NILP (arg) && NILP (oldval))
2323 return;
2324
2325 if (STRINGP (arg) && STRINGP (oldval)
2326 && EQ (Fstring_equal (oldval, arg), Qt))
2327 return;
2328
2329 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2330 return;
2331
2332 BLOCK_INPUT;
2333
2334 result = x_bitmap_icon (f, arg);
2335 if (result)
2336 {
2337 UNBLOCK_INPUT;
2338 error ("No icon window available");
2339 }
2340
2341 UNBLOCK_INPUT;
2342 }
2343
2344 /* Return non-nil if frame F wants a bitmap icon. */
2345
2346 Lisp_Object
2347 x_icon_type (f)
2348 FRAME_PTR f;
2349 {
2350 Lisp_Object tem;
2351
2352 tem = assq_no_quit (Qicon_type, f->param_alist);
2353 if (CONSP (tem))
2354 return XCDR (tem);
2355 else
2356 return Qnil;
2357 }
2358
2359 void
2360 x_set_icon_name (f, arg, oldval)
2361 struct frame *f;
2362 Lisp_Object arg, oldval;
2363 {
2364 if (STRINGP (arg))
2365 {
2366 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2367 return;
2368 }
2369 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2370 return;
2371
2372 f->icon_name = arg;
2373
2374 #if 0
2375 if (f->output_data.w32->icon_bitmap != 0)
2376 return;
2377
2378 BLOCK_INPUT;
2379
2380 result = x_text_icon (f,
2381 (char *) XSTRING ((!NILP (f->icon_name)
2382 ? f->icon_name
2383 : !NILP (f->title)
2384 ? f->title
2385 : f->name))->data);
2386
2387 if (result)
2388 {
2389 UNBLOCK_INPUT;
2390 error ("No icon window available");
2391 }
2392
2393 /* If the window was unmapped (and its icon was mapped),
2394 the new icon is not mapped, so map the window in its stead. */
2395 if (FRAME_VISIBLE_P (f))
2396 {
2397 #ifdef USE_X_TOOLKIT
2398 XtPopup (f->output_data.w32->widget, XtGrabNone);
2399 #endif
2400 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2401 }
2402
2403 XFlush (FRAME_W32_DISPLAY (f));
2404 UNBLOCK_INPUT;
2405 #endif
2406 }
2407
2408 extern Lisp_Object x_new_font ();
2409 extern Lisp_Object x_new_fontset();
2410
2411 void
2412 x_set_font (f, arg, oldval)
2413 struct frame *f;
2414 Lisp_Object arg, oldval;
2415 {
2416 Lisp_Object result;
2417 Lisp_Object fontset_name;
2418 Lisp_Object frame;
2419 int old_fontset = FRAME_FONTSET(f);
2420
2421 CHECK_STRING (arg);
2422
2423 fontset_name = Fquery_fontset (arg, Qnil);
2424
2425 BLOCK_INPUT;
2426 result = (STRINGP (fontset_name)
2427 ? x_new_fontset (f, XSTRING (fontset_name)->data)
2428 : x_new_font (f, XSTRING (arg)->data));
2429 UNBLOCK_INPUT;
2430
2431 if (EQ (result, Qnil))
2432 error ("Font `%s' is not defined", XSTRING (arg)->data);
2433 else if (EQ (result, Qt))
2434 error ("The characters of the given font have varying widths");
2435 else if (STRINGP (result))
2436 {
2437 if (STRINGP (fontset_name))
2438 {
2439 /* Fontset names are built from ASCII font names, so the
2440 names may be equal despite there was a change. */
2441 if (old_fontset == FRAME_FONTSET (f))
2442 return;
2443 }
2444 else if (!NILP (Fequal (result, oldval)))
2445 return;
2446
2447 store_frame_param (f, Qfont, result);
2448 recompute_basic_faces (f);
2449 }
2450 else
2451 abort ();
2452
2453 do_pending_window_change (0);
2454
2455 /* Don't call `face-set-after-frame-default' when faces haven't been
2456 initialized yet. This is the case when called from
2457 Fx_create_frame. In that case, the X widget or window doesn't
2458 exist either, and we can end up in x_report_frame_params with a
2459 null widget which gives a segfault. */
2460 if (FRAME_FACE_CACHE (f))
2461 {
2462 XSETFRAME (frame, f);
2463 call1 (Qface_set_after_frame_default, frame);
2464 }
2465 }
2466
2467 static void
2468 x_set_fringe_width (f, new_value, old_value)
2469 struct frame *f;
2470 Lisp_Object new_value, old_value;
2471 {
2472 x_compute_fringe_widths (f, 1);
2473 }
2474
2475 void
2476 x_set_border_width (f, arg, oldval)
2477 struct frame *f;
2478 Lisp_Object arg, oldval;
2479 {
2480 CHECK_NUMBER (arg);
2481
2482 if (XINT (arg) == f->output_data.w32->border_width)
2483 return;
2484
2485 if (FRAME_W32_WINDOW (f) != 0)
2486 error ("Cannot change the border width of a window");
2487
2488 f->output_data.w32->border_width = XINT (arg);
2489 }
2490
2491 void
2492 x_set_internal_border_width (f, arg, oldval)
2493 struct frame *f;
2494 Lisp_Object arg, oldval;
2495 {
2496 int old = f->output_data.w32->internal_border_width;
2497
2498 CHECK_NUMBER (arg);
2499 f->output_data.w32->internal_border_width = XINT (arg);
2500 if (f->output_data.w32->internal_border_width < 0)
2501 f->output_data.w32->internal_border_width = 0;
2502
2503 if (f->output_data.w32->internal_border_width == old)
2504 return;
2505
2506 if (FRAME_W32_WINDOW (f) != 0)
2507 {
2508 x_set_window_size (f, 0, f->width, f->height);
2509 SET_FRAME_GARBAGED (f);
2510 do_pending_window_change (0);
2511 }
2512 else
2513 SET_FRAME_GARBAGED (f);
2514 }
2515
2516 void
2517 x_set_visibility (f, value, oldval)
2518 struct frame *f;
2519 Lisp_Object value, oldval;
2520 {
2521 Lisp_Object frame;
2522 XSETFRAME (frame, f);
2523
2524 if (NILP (value))
2525 Fmake_frame_invisible (frame, Qt);
2526 else if (EQ (value, Qicon))
2527 Ficonify_frame (frame);
2528 else
2529 Fmake_frame_visible (frame);
2530 }
2531
2532 \f
2533 /* Change window heights in windows rooted in WINDOW by N lines. */
2534
2535 static void
2536 x_change_window_heights (window, n)
2537 Lisp_Object window;
2538 int n;
2539 {
2540 struct window *w = XWINDOW (window);
2541
2542 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2543 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2544
2545 if (INTEGERP (w->orig_top))
2546 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2547 if (INTEGERP (w->orig_height))
2548 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2549
2550 /* Handle just the top child in a vertical split. */
2551 if (!NILP (w->vchild))
2552 x_change_window_heights (w->vchild, n);
2553
2554 /* Adjust all children in a horizontal split. */
2555 for (window = w->hchild; !NILP (window); window = w->next)
2556 {
2557 w = XWINDOW (window);
2558 x_change_window_heights (window, n);
2559 }
2560 }
2561
2562 void
2563 x_set_menu_bar_lines (f, value, oldval)
2564 struct frame *f;
2565 Lisp_Object value, oldval;
2566 {
2567 int nlines;
2568 int olines = FRAME_MENU_BAR_LINES (f);
2569
2570 /* Right now, menu bars don't work properly in minibuf-only frames;
2571 most of the commands try to apply themselves to the minibuffer
2572 frame itself, and get an error because you can't switch buffers
2573 in or split the minibuffer window. */
2574 if (FRAME_MINIBUF_ONLY_P (f))
2575 return;
2576
2577 if (INTEGERP (value))
2578 nlines = XINT (value);
2579 else
2580 nlines = 0;
2581
2582 FRAME_MENU_BAR_LINES (f) = 0;
2583 if (nlines)
2584 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2585 else
2586 {
2587 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2588 free_frame_menubar (f);
2589 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2590
2591 /* Adjust the frame size so that the client (text) dimensions
2592 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2593 set correctly. */
2594 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2595 do_pending_window_change (0);
2596 }
2597 adjust_glyphs (f);
2598 }
2599
2600
2601 /* Set the number of lines used for the tool bar of frame F to VALUE.
2602 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2603 is the old number of tool bar lines. This function changes the
2604 height of all windows on frame F to match the new tool bar height.
2605 The frame's height doesn't change. */
2606
2607 void
2608 x_set_tool_bar_lines (f, value, oldval)
2609 struct frame *f;
2610 Lisp_Object value, oldval;
2611 {
2612 int delta, nlines, root_height;
2613 Lisp_Object root_window;
2614
2615 /* Treat tool bars like menu bars. */
2616 if (FRAME_MINIBUF_ONLY_P (f))
2617 return;
2618
2619 /* Use VALUE only if an integer >= 0. */
2620 if (INTEGERP (value) && XINT (value) >= 0)
2621 nlines = XFASTINT (value);
2622 else
2623 nlines = 0;
2624
2625 /* Make sure we redisplay all windows in this frame. */
2626 ++windows_or_buffers_changed;
2627
2628 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2629
2630 /* Don't resize the tool-bar to more than we have room for. */
2631 root_window = FRAME_ROOT_WINDOW (f);
2632 root_height = XINT (XWINDOW (root_window)->height);
2633 if (root_height - delta < 1)
2634 {
2635 delta = root_height - 1;
2636 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2637 }
2638
2639 FRAME_TOOL_BAR_LINES (f) = nlines;
2640 x_change_window_heights (root_window, delta);
2641 adjust_glyphs (f);
2642
2643 /* We also have to make sure that the internal border at the top of
2644 the frame, below the menu bar or tool bar, is redrawn when the
2645 tool bar disappears. This is so because the internal border is
2646 below the tool bar if one is displayed, but is below the menu bar
2647 if there isn't a tool bar. The tool bar draws into the area
2648 below the menu bar. */
2649 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2650 {
2651 updating_frame = f;
2652 clear_frame ();
2653 clear_current_matrices (f);
2654 updating_frame = NULL;
2655 }
2656
2657 /* If the tool bar gets smaller, the internal border below it
2658 has to be cleared. It was formerly part of the display
2659 of the larger tool bar, and updating windows won't clear it. */
2660 if (delta < 0)
2661 {
2662 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2663 int width = PIXEL_WIDTH (f);
2664 int y = nlines * CANON_Y_UNIT (f);
2665
2666 BLOCK_INPUT;
2667 {
2668 HDC hdc = get_frame_dc (f);
2669 w32_clear_area (f, hdc, 0, y, width, height);
2670 release_frame_dc (f, hdc);
2671 }
2672 UNBLOCK_INPUT;
2673
2674 if (WINDOWP (f->tool_bar_window))
2675 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
2676 }
2677 }
2678
2679
2680 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2681 w32_id_name.
2682
2683 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2684 name; if NAME is a string, set F's name to NAME and set
2685 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2686
2687 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2688 suggesting a new name, which lisp code should override; if
2689 F->explicit_name is set, ignore the new name; otherwise, set it. */
2690
2691 void
2692 x_set_name (f, name, explicit)
2693 struct frame *f;
2694 Lisp_Object name;
2695 int explicit;
2696 {
2697 /* Make sure that requests from lisp code override requests from
2698 Emacs redisplay code. */
2699 if (explicit)
2700 {
2701 /* If we're switching from explicit to implicit, we had better
2702 update the mode lines and thereby update the title. */
2703 if (f->explicit_name && NILP (name))
2704 update_mode_lines = 1;
2705
2706 f->explicit_name = ! NILP (name);
2707 }
2708 else if (f->explicit_name)
2709 return;
2710
2711 /* If NAME is nil, set the name to the w32_id_name. */
2712 if (NILP (name))
2713 {
2714 /* Check for no change needed in this very common case
2715 before we do any consing. */
2716 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2717 XSTRING (f->name)->data))
2718 return;
2719 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2720 }
2721 else
2722 CHECK_STRING (name);
2723
2724 /* Don't change the name if it's already NAME. */
2725 if (! NILP (Fstring_equal (name, f->name)))
2726 return;
2727
2728 f->name = name;
2729
2730 /* For setting the frame title, the title parameter should override
2731 the name parameter. */
2732 if (! NILP (f->title))
2733 name = f->title;
2734
2735 if (FRAME_W32_WINDOW (f))
2736 {
2737 if (STRING_MULTIBYTE (name))
2738 name = ENCODE_SYSTEM (name);
2739
2740 BLOCK_INPUT;
2741 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2742 UNBLOCK_INPUT;
2743 }
2744 }
2745
2746 /* This function should be called when the user's lisp code has
2747 specified a name for the frame; the name will override any set by the
2748 redisplay code. */
2749 void
2750 x_explicitly_set_name (f, arg, oldval)
2751 FRAME_PTR f;
2752 Lisp_Object arg, oldval;
2753 {
2754 x_set_name (f, arg, 1);
2755 }
2756
2757 /* This function should be called by Emacs redisplay code to set the
2758 name; names set this way will never override names set by the user's
2759 lisp code. */
2760 void
2761 x_implicitly_set_name (f, arg, oldval)
2762 FRAME_PTR f;
2763 Lisp_Object arg, oldval;
2764 {
2765 x_set_name (f, arg, 0);
2766 }
2767 \f
2768 /* Change the title of frame F to NAME.
2769 If NAME is nil, use the frame name as the title.
2770
2771 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2772 name; if NAME is a string, set F's name to NAME and set
2773 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2774
2775 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2776 suggesting a new name, which lisp code should override; if
2777 F->explicit_name is set, ignore the new name; otherwise, set it. */
2778
2779 void
2780 x_set_title (f, name, old_name)
2781 struct frame *f;
2782 Lisp_Object name, old_name;
2783 {
2784 /* Don't change the title if it's already NAME. */
2785 if (EQ (name, f->title))
2786 return;
2787
2788 update_mode_lines = 1;
2789
2790 f->title = name;
2791
2792 if (NILP (name))
2793 name = f->name;
2794
2795 if (FRAME_W32_WINDOW (f))
2796 {
2797 if (STRING_MULTIBYTE (name))
2798 name = ENCODE_SYSTEM (name);
2799
2800 BLOCK_INPUT;
2801 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2802 UNBLOCK_INPUT;
2803 }
2804 }
2805 \f
2806 void
2807 x_set_autoraise (f, arg, oldval)
2808 struct frame *f;
2809 Lisp_Object arg, oldval;
2810 {
2811 f->auto_raise = !EQ (Qnil, arg);
2812 }
2813
2814 void
2815 x_set_autolower (f, arg, oldval)
2816 struct frame *f;
2817 Lisp_Object arg, oldval;
2818 {
2819 f->auto_lower = !EQ (Qnil, arg);
2820 }
2821
2822 void
2823 x_set_unsplittable (f, arg, oldval)
2824 struct frame *f;
2825 Lisp_Object arg, oldval;
2826 {
2827 f->no_split = !NILP (arg);
2828 }
2829
2830 void
2831 x_set_vertical_scroll_bars (f, arg, oldval)
2832 struct frame *f;
2833 Lisp_Object arg, oldval;
2834 {
2835 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2836 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2837 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2838 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2839 {
2840 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2841 vertical_scroll_bar_none :
2842 /* Put scroll bars on the right by default, as is conventional
2843 on MS-Windows. */
2844 EQ (Qleft, arg)
2845 ? vertical_scroll_bar_left
2846 : vertical_scroll_bar_right;
2847
2848 /* We set this parameter before creating the window for the
2849 frame, so we can get the geometry right from the start.
2850 However, if the window hasn't been created yet, we shouldn't
2851 call x_set_window_size. */
2852 if (FRAME_W32_WINDOW (f))
2853 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2854 do_pending_window_change (0);
2855 }
2856 }
2857
2858 void
2859 x_set_scroll_bar_width (f, arg, oldval)
2860 struct frame *f;
2861 Lisp_Object arg, oldval;
2862 {
2863 int wid = FONT_WIDTH (f->output_data.w32->font);
2864
2865 if (NILP (arg))
2866 {
2867 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2868 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2869 wid - 1) / wid;
2870 if (FRAME_W32_WINDOW (f))
2871 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2872 do_pending_window_change (0);
2873 }
2874 else if (INTEGERP (arg) && XINT (arg) > 0
2875 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2876 {
2877 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2878 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2879 + wid-1) / wid;
2880 if (FRAME_W32_WINDOW (f))
2881 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2882 do_pending_window_change (0);
2883 }
2884 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2885 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2886 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2887 }
2888 \f
2889 /* Subroutines of creating an frame. */
2890
2891 /* Make sure that Vx_resource_name is set to a reasonable value.
2892 Fix it up, or set it to `emacs' if it is too hopeless. */
2893
2894 static void
2895 validate_x_resource_name ()
2896 {
2897 int len = 0;
2898 /* Number of valid characters in the resource name. */
2899 int good_count = 0;
2900 /* Number of invalid characters in the resource name. */
2901 int bad_count = 0;
2902 Lisp_Object new;
2903 int i;
2904
2905 if (STRINGP (Vx_resource_name))
2906 {
2907 unsigned char *p = XSTRING (Vx_resource_name)->data;
2908 int i;
2909
2910 len = STRING_BYTES (XSTRING (Vx_resource_name));
2911
2912 /* Only letters, digits, - and _ are valid in resource names.
2913 Count the valid characters and count the invalid ones. */
2914 for (i = 0; i < len; i++)
2915 {
2916 int c = p[i];
2917 if (! ((c >= 'a' && c <= 'z')
2918 || (c >= 'A' && c <= 'Z')
2919 || (c >= '0' && c <= '9')
2920 || c == '-' || c == '_'))
2921 bad_count++;
2922 else
2923 good_count++;
2924 }
2925 }
2926 else
2927 /* Not a string => completely invalid. */
2928 bad_count = 5, good_count = 0;
2929
2930 /* If name is valid already, return. */
2931 if (bad_count == 0)
2932 return;
2933
2934 /* If name is entirely invalid, or nearly so, use `emacs'. */
2935 if (good_count == 0
2936 || (good_count == 1 && bad_count > 0))
2937 {
2938 Vx_resource_name = build_string ("emacs");
2939 return;
2940 }
2941
2942 /* Name is partly valid. Copy it and replace the invalid characters
2943 with underscores. */
2944
2945 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2946
2947 for (i = 0; i < len; i++)
2948 {
2949 int c = XSTRING (new)->data[i];
2950 if (! ((c >= 'a' && c <= 'z')
2951 || (c >= 'A' && c <= 'Z')
2952 || (c >= '0' && c <= '9')
2953 || c == '-' || c == '_'))
2954 XSTRING (new)->data[i] = '_';
2955 }
2956 }
2957
2958
2959 extern char *x_get_string_resource ();
2960
2961 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2962 doc: /* Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.
2963 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the
2964 class, where INSTANCE is the name under which Emacs was invoked, or
2965 the name specified by the `-name' or `-rn' command-line arguments.
2966
2967 The optional arguments COMPONENT and SUBCLASS add to the key and the
2968 class, respectively. You must specify both of them or neither.
2969 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'
2970 and the class is `Emacs.CLASS.SUBCLASS'. */)
2971 (attribute, class, component, subclass)
2972 Lisp_Object attribute, class, component, subclass;
2973 {
2974 register char *value;
2975 char *name_key;
2976 char *class_key;
2977
2978 CHECK_STRING (attribute);
2979 CHECK_STRING (class);
2980
2981 if (!NILP (component))
2982 CHECK_STRING (component);
2983 if (!NILP (subclass))
2984 CHECK_STRING (subclass);
2985 if (NILP (component) != NILP (subclass))
2986 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
2987
2988 validate_x_resource_name ();
2989
2990 /* Allocate space for the components, the dots which separate them,
2991 and the final '\0'. Make them big enough for the worst case. */
2992 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vx_resource_name))
2993 + (STRINGP (component)
2994 ? STRING_BYTES (XSTRING (component)) : 0)
2995 + STRING_BYTES (XSTRING (attribute))
2996 + 3);
2997
2998 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2999 + STRING_BYTES (XSTRING (class))
3000 + (STRINGP (subclass)
3001 ? STRING_BYTES (XSTRING (subclass)) : 0)
3002 + 3);
3003
3004 /* Start with emacs.FRAMENAME for the name (the specific one)
3005 and with `Emacs' for the class key (the general one). */
3006 strcpy (name_key, XSTRING (Vx_resource_name)->data);
3007 strcpy (class_key, EMACS_CLASS);
3008
3009 strcat (class_key, ".");
3010 strcat (class_key, XSTRING (class)->data);
3011
3012 if (!NILP (component))
3013 {
3014 strcat (class_key, ".");
3015 strcat (class_key, XSTRING (subclass)->data);
3016
3017 strcat (name_key, ".");
3018 strcat (name_key, XSTRING (component)->data);
3019 }
3020
3021 strcat (name_key, ".");
3022 strcat (name_key, XSTRING (attribute)->data);
3023
3024 value = x_get_string_resource (Qnil,
3025 name_key, class_key);
3026
3027 if (value != (char *) 0)
3028 return build_string (value);
3029 else
3030 return Qnil;
3031 }
3032
3033 /* Used when C code wants a resource value. */
3034
3035 char *
3036 x_get_resource_string (attribute, class)
3037 char *attribute, *class;
3038 {
3039 char *name_key;
3040 char *class_key;
3041 struct frame *sf = SELECTED_FRAME ();
3042
3043 /* Allocate space for the components, the dots which separate them,
3044 and the final '\0'. */
3045 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vinvocation_name))
3046 + strlen (attribute) + 2);
3047 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3048 + strlen (class) + 2);
3049
3050 sprintf (name_key, "%s.%s",
3051 XSTRING (Vinvocation_name)->data,
3052 attribute);
3053 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
3054
3055 return x_get_string_resource (sf, name_key, class_key);
3056 }
3057
3058 /* Types we might convert a resource string into. */
3059 enum resource_types
3060 {
3061 RES_TYPE_NUMBER,
3062 RES_TYPE_FLOAT,
3063 RES_TYPE_BOOLEAN,
3064 RES_TYPE_STRING,
3065 RES_TYPE_SYMBOL
3066 };
3067
3068 /* Return the value of parameter PARAM.
3069
3070 First search ALIST, then Vdefault_frame_alist, then the X defaults
3071 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3072
3073 Convert the resource to the type specified by desired_type.
3074
3075 If no default is specified, return Qunbound. If you call
3076 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3077 and don't let it get stored in any Lisp-visible variables! */
3078
3079 static Lisp_Object
3080 w32_get_arg (alist, param, attribute, class, type)
3081 Lisp_Object alist, param;
3082 char *attribute;
3083 char *class;
3084 enum resource_types type;
3085 {
3086 register Lisp_Object tem;
3087
3088 tem = Fassq (param, alist);
3089 if (EQ (tem, Qnil))
3090 tem = Fassq (param, Vdefault_frame_alist);
3091 if (EQ (tem, Qnil))
3092 {
3093
3094 if (attribute)
3095 {
3096 tem = Fx_get_resource (build_string (attribute),
3097 build_string (class),
3098 Qnil, Qnil);
3099
3100 if (NILP (tem))
3101 return Qunbound;
3102
3103 switch (type)
3104 {
3105 case RES_TYPE_NUMBER:
3106 return make_number (atoi (XSTRING (tem)->data));
3107
3108 case RES_TYPE_FLOAT:
3109 return make_float (atof (XSTRING (tem)->data));
3110
3111 case RES_TYPE_BOOLEAN:
3112 tem = Fdowncase (tem);
3113 if (!strcmp (XSTRING (tem)->data, "on")
3114 || !strcmp (XSTRING (tem)->data, "true"))
3115 return Qt;
3116 else
3117 return Qnil;
3118
3119 case RES_TYPE_STRING:
3120 return tem;
3121
3122 case RES_TYPE_SYMBOL:
3123 /* As a special case, we map the values `true' and `on'
3124 to Qt, and `false' and `off' to Qnil. */
3125 {
3126 Lisp_Object lower;
3127 lower = Fdowncase (tem);
3128 if (!strcmp (XSTRING (lower)->data, "on")
3129 || !strcmp (XSTRING (lower)->data, "true"))
3130 return Qt;
3131 else if (!strcmp (XSTRING (lower)->data, "off")
3132 || !strcmp (XSTRING (lower)->data, "false"))
3133 return Qnil;
3134 else
3135 return Fintern (tem, Qnil);
3136 }
3137
3138 default:
3139 abort ();
3140 }
3141 }
3142 else
3143 return Qunbound;
3144 }
3145 return Fcdr (tem);
3146 }
3147
3148 /* Record in frame F the specified or default value according to ALIST
3149 of the parameter named PROP (a Lisp symbol).
3150 If no value is specified for PROP, look for an X default for XPROP
3151 on the frame named NAME.
3152 If that is not found either, use the value DEFLT. */
3153
3154 static Lisp_Object
3155 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3156 struct frame *f;
3157 Lisp_Object alist;
3158 Lisp_Object prop;
3159 Lisp_Object deflt;
3160 char *xprop;
3161 char *xclass;
3162 enum resource_types type;
3163 {
3164 Lisp_Object tem;
3165
3166 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3167 if (EQ (tem, Qunbound))
3168 tem = deflt;
3169 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3170 return tem;
3171 }
3172 \f
3173 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3174 doc: /* Parse an X-style geometry string STRING.
3175 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).
3176 The properties returned may include `top', `left', `height', and `width'.
3177 The value of `left' or `top' may be an integer,
3178 or a list (+ N) meaning N pixels relative to top/left corner,
3179 or a list (- N) meaning -N pixels relative to bottom/right corner. */)
3180 (string)
3181 Lisp_Object string;
3182 {
3183 int geometry, x, y;
3184 unsigned int width, height;
3185 Lisp_Object result;
3186
3187 CHECK_STRING (string);
3188
3189 geometry = XParseGeometry ((char *) XSTRING (string)->data,
3190 &x, &y, &width, &height);
3191
3192 result = Qnil;
3193 if (geometry & XValue)
3194 {
3195 Lisp_Object element;
3196
3197 if (x >= 0 && (geometry & XNegative))
3198 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3199 else if (x < 0 && ! (geometry & XNegative))
3200 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3201 else
3202 element = Fcons (Qleft, make_number (x));
3203 result = Fcons (element, result);
3204 }
3205
3206 if (geometry & YValue)
3207 {
3208 Lisp_Object element;
3209
3210 if (y >= 0 && (geometry & YNegative))
3211 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3212 else if (y < 0 && ! (geometry & YNegative))
3213 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3214 else
3215 element = Fcons (Qtop, make_number (y));
3216 result = Fcons (element, result);
3217 }
3218
3219 if (geometry & WidthValue)
3220 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3221 if (geometry & HeightValue)
3222 result = Fcons (Fcons (Qheight, make_number (height)), result);
3223
3224 return result;
3225 }
3226
3227 /* Calculate the desired size and position of this window,
3228 and return the flags saying which aspects were specified.
3229
3230 This function does not make the coordinates positive. */
3231
3232 #define DEFAULT_ROWS 40
3233 #define DEFAULT_COLS 80
3234
3235 static int
3236 x_figure_window_size (f, parms)
3237 struct frame *f;
3238 Lisp_Object parms;
3239 {
3240 register Lisp_Object tem0, tem1, tem2;
3241 long window_prompting = 0;
3242
3243 /* Default values if we fall through.
3244 Actually, if that happens we should get
3245 window manager prompting. */
3246 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3247 f->height = DEFAULT_ROWS;
3248 /* Window managers expect that if program-specified
3249 positions are not (0,0), they're intentional, not defaults. */
3250 f->output_data.w32->top_pos = 0;
3251 f->output_data.w32->left_pos = 0;
3252
3253 /* Ensure that old new_width and new_height will not override the
3254 values set here. */
3255 FRAME_NEW_WIDTH (f) = 0;
3256 FRAME_NEW_HEIGHT (f) = 0;
3257
3258 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3259 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3260 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3261 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3262 {
3263 if (!EQ (tem0, Qunbound))
3264 {
3265 CHECK_NUMBER (tem0);
3266 f->height = XINT (tem0);
3267 }
3268 if (!EQ (tem1, Qunbound))
3269 {
3270 CHECK_NUMBER (tem1);
3271 SET_FRAME_WIDTH (f, XINT (tem1));
3272 }
3273 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3274 window_prompting |= USSize;
3275 else
3276 window_prompting |= PSize;
3277 }
3278
3279 f->output_data.w32->vertical_scroll_bar_extra
3280 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3281 ? 0
3282 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3283 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3284 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3285 x_compute_fringe_widths (f, 0);
3286 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3287 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3288
3289 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3290 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3291 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3292 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3293 {
3294 if (EQ (tem0, Qminus))
3295 {
3296 f->output_data.w32->top_pos = 0;
3297 window_prompting |= YNegative;
3298 }
3299 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3300 && CONSP (XCDR (tem0))
3301 && INTEGERP (XCAR (XCDR (tem0))))
3302 {
3303 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3304 window_prompting |= YNegative;
3305 }
3306 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3307 && CONSP (XCDR (tem0))
3308 && INTEGERP (XCAR (XCDR (tem0))))
3309 {
3310 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3311 }
3312 else if (EQ (tem0, Qunbound))
3313 f->output_data.w32->top_pos = 0;
3314 else
3315 {
3316 CHECK_NUMBER (tem0);
3317 f->output_data.w32->top_pos = XINT (tem0);
3318 if (f->output_data.w32->top_pos < 0)
3319 window_prompting |= YNegative;
3320 }
3321
3322 if (EQ (tem1, Qminus))
3323 {
3324 f->output_data.w32->left_pos = 0;
3325 window_prompting |= XNegative;
3326 }
3327 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3328 && CONSP (XCDR (tem1))
3329 && INTEGERP (XCAR (XCDR (tem1))))
3330 {
3331 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3332 window_prompting |= XNegative;
3333 }
3334 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3335 && CONSP (XCDR (tem1))
3336 && INTEGERP (XCAR (XCDR (tem1))))
3337 {
3338 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3339 }
3340 else if (EQ (tem1, Qunbound))
3341 f->output_data.w32->left_pos = 0;
3342 else
3343 {
3344 CHECK_NUMBER (tem1);
3345 f->output_data.w32->left_pos = XINT (tem1);
3346 if (f->output_data.w32->left_pos < 0)
3347 window_prompting |= XNegative;
3348 }
3349
3350 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3351 window_prompting |= USPosition;
3352 else
3353 window_prompting |= PPosition;
3354 }
3355
3356 return window_prompting;
3357 }
3358
3359 \f
3360
3361 extern LRESULT CALLBACK w32_wnd_proc ();
3362
3363 BOOL
3364 w32_init_class (hinst)
3365 HINSTANCE hinst;
3366 {
3367 WNDCLASS wc;
3368
3369 wc.style = CS_HREDRAW | CS_VREDRAW;
3370 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3371 wc.cbClsExtra = 0;
3372 wc.cbWndExtra = WND_EXTRA_BYTES;
3373 wc.hInstance = hinst;
3374 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3375 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3376 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3377 wc.lpszMenuName = NULL;
3378 wc.lpszClassName = EMACS_CLASS;
3379
3380 return (RegisterClass (&wc));
3381 }
3382
3383 HWND
3384 w32_createscrollbar (f, bar)
3385 struct frame *f;
3386 struct scroll_bar * bar;
3387 {
3388 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3389 /* Position and size of scroll bar. */
3390 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3391 XINT(bar->top),
3392 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3393 XINT(bar->height),
3394 FRAME_W32_WINDOW (f),
3395 NULL,
3396 hinst,
3397 NULL));
3398 }
3399
3400 void
3401 w32_createwindow (f)
3402 struct frame *f;
3403 {
3404 HWND hwnd;
3405 RECT rect;
3406
3407 rect.left = rect.top = 0;
3408 rect.right = PIXEL_WIDTH (f);
3409 rect.bottom = PIXEL_HEIGHT (f);
3410
3411 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3412 FRAME_EXTERNAL_MENU_BAR (f));
3413
3414 /* Do first time app init */
3415
3416 if (!hprevinst)
3417 {
3418 w32_init_class (hinst);
3419 }
3420
3421 FRAME_W32_WINDOW (f) = hwnd
3422 = CreateWindow (EMACS_CLASS,
3423 f->namebuf,
3424 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3425 f->output_data.w32->left_pos,
3426 f->output_data.w32->top_pos,
3427 rect.right - rect.left,
3428 rect.bottom - rect.top,
3429 NULL,
3430 NULL,
3431 hinst,
3432 NULL);
3433
3434 if (hwnd)
3435 {
3436 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3437 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3438 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3439 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3440 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3441
3442 /* Enable drag-n-drop. */
3443 DragAcceptFiles (hwnd, TRUE);
3444
3445 /* Do this to discard the default setting specified by our parent. */
3446 ShowWindow (hwnd, SW_HIDE);
3447 }
3448 }
3449
3450 void
3451 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3452 W32Msg * wmsg;
3453 HWND hwnd;
3454 UINT msg;
3455 WPARAM wParam;
3456 LPARAM lParam;
3457 {
3458 wmsg->msg.hwnd = hwnd;
3459 wmsg->msg.message = msg;
3460 wmsg->msg.wParam = wParam;
3461 wmsg->msg.lParam = lParam;
3462 wmsg->msg.time = GetMessageTime ();
3463
3464 post_msg (wmsg);
3465 }
3466
3467 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3468 between left and right keys as advertised. We test for this
3469 support dynamically, and set a flag when the support is absent. If
3470 absent, we keep track of the left and right control and alt keys
3471 ourselves. This is particularly necessary on keyboards that rely
3472 upon the AltGr key, which is represented as having the left control
3473 and right alt keys pressed. For these keyboards, we need to know
3474 when the left alt key has been pressed in addition to the AltGr key
3475 so that we can properly support M-AltGr-key sequences (such as M-@
3476 on Swedish keyboards). */
3477
3478 #define EMACS_LCONTROL 0
3479 #define EMACS_RCONTROL 1
3480 #define EMACS_LMENU 2
3481 #define EMACS_RMENU 3
3482
3483 static int modifiers[4];
3484 static int modifiers_recorded;
3485 static int modifier_key_support_tested;
3486
3487 static void
3488 test_modifier_support (unsigned int wparam)
3489 {
3490 unsigned int l, r;
3491
3492 if (wparam != VK_CONTROL && wparam != VK_MENU)
3493 return;
3494 if (wparam == VK_CONTROL)
3495 {
3496 l = VK_LCONTROL;
3497 r = VK_RCONTROL;
3498 }
3499 else
3500 {
3501 l = VK_LMENU;
3502 r = VK_RMENU;
3503 }
3504 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3505 modifiers_recorded = 1;
3506 else
3507 modifiers_recorded = 0;
3508 modifier_key_support_tested = 1;
3509 }
3510
3511 static void
3512 record_keydown (unsigned int wparam, unsigned int lparam)
3513 {
3514 int i;
3515
3516 if (!modifier_key_support_tested)
3517 test_modifier_support (wparam);
3518
3519 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3520 return;
3521
3522 if (wparam == VK_CONTROL)
3523 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3524 else
3525 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3526
3527 modifiers[i] = 1;
3528 }
3529
3530 static void
3531 record_keyup (unsigned int wparam, unsigned int lparam)
3532 {
3533 int i;
3534
3535 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3536 return;
3537
3538 if (wparam == VK_CONTROL)
3539 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3540 else
3541 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3542
3543 modifiers[i] = 0;
3544 }
3545
3546 /* Emacs can lose focus while a modifier key has been pressed. When
3547 it regains focus, be conservative and clear all modifiers since
3548 we cannot reconstruct the left and right modifier state. */
3549 static void
3550 reset_modifiers ()
3551 {
3552 SHORT ctrl, alt;
3553
3554 if (GetFocus () == NULL)
3555 /* Emacs doesn't have keyboard focus. Do nothing. */
3556 return;
3557
3558 ctrl = GetAsyncKeyState (VK_CONTROL);
3559 alt = GetAsyncKeyState (VK_MENU);
3560
3561 if (!(ctrl & 0x08000))
3562 /* Clear any recorded control modifier state. */
3563 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3564
3565 if (!(alt & 0x08000))
3566 /* Clear any recorded alt modifier state. */
3567 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3568
3569 /* Update the state of all modifier keys, because modifiers used in
3570 hot-key combinations can get stuck on if Emacs loses focus as a
3571 result of a hot-key being pressed. */
3572 {
3573 BYTE keystate[256];
3574
3575 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3576
3577 GetKeyboardState (keystate);
3578 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3579 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3580 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3581 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3582 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3583 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3584 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3585 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3586 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3587 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3588 SetKeyboardState (keystate);
3589 }
3590 }
3591
3592 /* Synchronize modifier state with what is reported with the current
3593 keystroke. Even if we cannot distinguish between left and right
3594 modifier keys, we know that, if no modifiers are set, then neither
3595 the left or right modifier should be set. */
3596 static void
3597 sync_modifiers ()
3598 {
3599 if (!modifiers_recorded)
3600 return;
3601
3602 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3603 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3604
3605 if (!(GetKeyState (VK_MENU) & 0x8000))
3606 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3607 }
3608
3609 static int
3610 modifier_set (int vkey)
3611 {
3612 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3613 return (GetKeyState (vkey) & 0x1);
3614 if (!modifiers_recorded)
3615 return (GetKeyState (vkey) & 0x8000);
3616
3617 switch (vkey)
3618 {
3619 case VK_LCONTROL:
3620 return modifiers[EMACS_LCONTROL];
3621 case VK_RCONTROL:
3622 return modifiers[EMACS_RCONTROL];
3623 case VK_LMENU:
3624 return modifiers[EMACS_LMENU];
3625 case VK_RMENU:
3626 return modifiers[EMACS_RMENU];
3627 }
3628 return (GetKeyState (vkey) & 0x8000);
3629 }
3630
3631 /* Convert between the modifier bits W32 uses and the modifier bits
3632 Emacs uses. */
3633
3634 unsigned int
3635 w32_key_to_modifier (int key)
3636 {
3637 Lisp_Object key_mapping;
3638
3639 switch (key)
3640 {
3641 case VK_LWIN:
3642 key_mapping = Vw32_lwindow_modifier;
3643 break;
3644 case VK_RWIN:
3645 key_mapping = Vw32_rwindow_modifier;
3646 break;
3647 case VK_APPS:
3648 key_mapping = Vw32_apps_modifier;
3649 break;
3650 case VK_SCROLL:
3651 key_mapping = Vw32_scroll_lock_modifier;
3652 break;
3653 default:
3654 key_mapping = Qnil;
3655 }
3656
3657 /* NB. This code runs in the input thread, asychronously to the lisp
3658 thread, so we must be careful to ensure access to lisp data is
3659 thread-safe. The following code is safe because the modifier
3660 variable values are updated atomically from lisp and symbols are
3661 not relocated by GC. Also, we don't have to worry about seeing GC
3662 markbits here. */
3663 if (EQ (key_mapping, Qhyper))
3664 return hyper_modifier;
3665 if (EQ (key_mapping, Qsuper))
3666 return super_modifier;
3667 if (EQ (key_mapping, Qmeta))
3668 return meta_modifier;
3669 if (EQ (key_mapping, Qalt))
3670 return alt_modifier;
3671 if (EQ (key_mapping, Qctrl))
3672 return ctrl_modifier;
3673 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3674 return ctrl_modifier;
3675 if (EQ (key_mapping, Qshift))
3676 return shift_modifier;
3677
3678 /* Don't generate any modifier if not explicitly requested. */
3679 return 0;
3680 }
3681
3682 unsigned int
3683 w32_get_modifiers ()
3684 {
3685 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3686 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3687 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3688 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3689 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3690 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3691 (modifier_set (VK_MENU) ?
3692 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3693 }
3694
3695 /* We map the VK_* modifiers into console modifier constants
3696 so that we can use the same routines to handle both console
3697 and window input. */
3698
3699 static int
3700 construct_console_modifiers ()
3701 {
3702 int mods;
3703
3704 mods = 0;
3705 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3706 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3707 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3708 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3709 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3710 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3711 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3712 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3713 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3714 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3715 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3716
3717 return mods;
3718 }
3719
3720 static int
3721 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3722 {
3723 int mods;
3724
3725 /* Convert to emacs modifiers. */
3726 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3727
3728 return mods;
3729 }
3730
3731 unsigned int
3732 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3733 {
3734 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3735 return virt_key;
3736
3737 if (virt_key == VK_RETURN)
3738 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3739
3740 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3741 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3742
3743 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3744 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3745
3746 if (virt_key == VK_CLEAR)
3747 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3748
3749 return virt_key;
3750 }
3751
3752 /* List of special key combinations which w32 would normally capture,
3753 but emacs should grab instead. Not directly visible to lisp, to
3754 simplify synchronization. Each item is an integer encoding a virtual
3755 key code and modifier combination to capture. */
3756 Lisp_Object w32_grabbed_keys;
3757
3758 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3759 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3760 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3761 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3762
3763 /* Register hot-keys for reserved key combinations when Emacs has
3764 keyboard focus, since this is the only way Emacs can receive key
3765 combinations like Alt-Tab which are used by the system. */
3766
3767 static void
3768 register_hot_keys (hwnd)
3769 HWND hwnd;
3770 {
3771 Lisp_Object keylist;
3772
3773 /* Use GC_CONSP, since we are called asynchronously. */
3774 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3775 {
3776 Lisp_Object key = XCAR (keylist);
3777
3778 /* Deleted entries get set to nil. */
3779 if (!INTEGERP (key))
3780 continue;
3781
3782 RegisterHotKey (hwnd, HOTKEY_ID (key),
3783 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3784 }
3785 }
3786
3787 static void
3788 unregister_hot_keys (hwnd)
3789 HWND hwnd;
3790 {
3791 Lisp_Object keylist;
3792
3793 /* Use GC_CONSP, since we are called asynchronously. */
3794 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3795 {
3796 Lisp_Object key = XCAR (keylist);
3797
3798 if (!INTEGERP (key))
3799 continue;
3800
3801 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3802 }
3803 }
3804
3805 /* Main message dispatch loop. */
3806
3807 static void
3808 w32_msg_pump (deferred_msg * msg_buf)
3809 {
3810 MSG msg;
3811 int result;
3812 HWND focus_window;
3813
3814 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3815
3816 while (GetMessage (&msg, NULL, 0, 0))
3817 {
3818 if (msg.hwnd == NULL)
3819 {
3820 switch (msg.message)
3821 {
3822 case WM_NULL:
3823 /* Produced by complete_deferred_msg; just ignore. */
3824 break;
3825 case WM_EMACS_CREATEWINDOW:
3826 w32_createwindow ((struct frame *) msg.wParam);
3827 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3828 abort ();
3829 break;
3830 case WM_EMACS_SETLOCALE:
3831 SetThreadLocale (msg.wParam);
3832 /* Reply is not expected. */
3833 break;
3834 case WM_EMACS_SETKEYBOARDLAYOUT:
3835 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3836 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3837 result, 0))
3838 abort ();
3839 break;
3840 case WM_EMACS_REGISTER_HOT_KEY:
3841 focus_window = GetFocus ();
3842 if (focus_window != NULL)
3843 RegisterHotKey (focus_window,
3844 HOTKEY_ID (msg.wParam),
3845 HOTKEY_MODIFIERS (msg.wParam),
3846 HOTKEY_VK_CODE (msg.wParam));
3847 /* Reply is not expected. */
3848 break;
3849 case WM_EMACS_UNREGISTER_HOT_KEY:
3850 focus_window = GetFocus ();
3851 if (focus_window != NULL)
3852 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3853 /* Mark item as erased. NB: this code must be
3854 thread-safe. The next line is okay because the cons
3855 cell is never made into garbage and is not relocated by
3856 GC. */
3857 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
3858 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3859 abort ();
3860 break;
3861 case WM_EMACS_TOGGLE_LOCK_KEY:
3862 {
3863 int vk_code = (int) msg.wParam;
3864 int cur_state = (GetKeyState (vk_code) & 1);
3865 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3866
3867 /* NB: This code must be thread-safe. It is safe to
3868 call NILP because symbols are not relocated by GC,
3869 and pointer here is not touched by GC (so the markbit
3870 can't be set). Numbers are safe because they are
3871 immediate values. */
3872 if (NILP (new_state)
3873 || (NUMBERP (new_state)
3874 && ((XUINT (new_state)) & 1) != cur_state))
3875 {
3876 one_w32_display_info.faked_key = vk_code;
3877
3878 keybd_event ((BYTE) vk_code,
3879 (BYTE) MapVirtualKey (vk_code, 0),
3880 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3881 keybd_event ((BYTE) vk_code,
3882 (BYTE) MapVirtualKey (vk_code, 0),
3883 KEYEVENTF_EXTENDEDKEY | 0, 0);
3884 keybd_event ((BYTE) vk_code,
3885 (BYTE) MapVirtualKey (vk_code, 0),
3886 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3887 cur_state = !cur_state;
3888 }
3889 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3890 cur_state, 0))
3891 abort ();
3892 }
3893 break;
3894 default:
3895 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3896 }
3897 }
3898 else
3899 {
3900 DispatchMessage (&msg);
3901 }
3902
3903 /* Exit nested loop when our deferred message has completed. */
3904 if (msg_buf->completed)
3905 break;
3906 }
3907 }
3908
3909 deferred_msg * deferred_msg_head;
3910
3911 static deferred_msg *
3912 find_deferred_msg (HWND hwnd, UINT msg)
3913 {
3914 deferred_msg * item;
3915
3916 /* Don't actually need synchronization for read access, since
3917 modification of single pointer is always atomic. */
3918 /* enter_crit (); */
3919
3920 for (item = deferred_msg_head; item != NULL; item = item->next)
3921 if (item->w32msg.msg.hwnd == hwnd
3922 && item->w32msg.msg.message == msg)
3923 break;
3924
3925 /* leave_crit (); */
3926
3927 return item;
3928 }
3929
3930 static LRESULT
3931 send_deferred_msg (deferred_msg * msg_buf,
3932 HWND hwnd,
3933 UINT msg,
3934 WPARAM wParam,
3935 LPARAM lParam)
3936 {
3937 /* Only input thread can send deferred messages. */
3938 if (GetCurrentThreadId () != dwWindowsThreadId)
3939 abort ();
3940
3941 /* It is an error to send a message that is already deferred. */
3942 if (find_deferred_msg (hwnd, msg) != NULL)
3943 abort ();
3944
3945 /* Enforced synchronization is not needed because this is the only
3946 function that alters deferred_msg_head, and the following critical
3947 section is guaranteed to only be serially reentered (since only the
3948 input thread can call us). */
3949
3950 /* enter_crit (); */
3951
3952 msg_buf->completed = 0;
3953 msg_buf->next = deferred_msg_head;
3954 deferred_msg_head = msg_buf;
3955 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3956
3957 /* leave_crit (); */
3958
3959 /* Start a new nested message loop to process other messages until
3960 this one is completed. */
3961 w32_msg_pump (msg_buf);
3962
3963 deferred_msg_head = msg_buf->next;
3964
3965 return msg_buf->result;
3966 }
3967
3968 void
3969 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3970 {
3971 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3972
3973 if (msg_buf == NULL)
3974 /* Message may have been cancelled, so don't abort(). */
3975 return;
3976
3977 msg_buf->result = result;
3978 msg_buf->completed = 1;
3979
3980 /* Ensure input thread is woken so it notices the completion. */
3981 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3982 }
3983
3984 void
3985 cancel_all_deferred_msgs ()
3986 {
3987 deferred_msg * item;
3988
3989 /* Don't actually need synchronization for read access, since
3990 modification of single pointer is always atomic. */
3991 /* enter_crit (); */
3992
3993 for (item = deferred_msg_head; item != NULL; item = item->next)
3994 {
3995 item->result = 0;
3996 item->completed = 1;
3997 }
3998
3999 /* leave_crit (); */
4000
4001 /* Ensure input thread is woken so it notices the completion. */
4002 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4003 }
4004
4005 DWORD
4006 w32_msg_worker (dw)
4007 DWORD dw;
4008 {
4009 MSG msg;
4010 deferred_msg dummy_buf;
4011
4012 /* Ensure our message queue is created */
4013
4014 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
4015
4016 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
4017 abort ();
4018
4019 memset (&dummy_buf, 0, sizeof (dummy_buf));
4020 dummy_buf.w32msg.msg.hwnd = NULL;
4021 dummy_buf.w32msg.msg.message = WM_NULL;
4022
4023 /* This is the inital message loop which should only exit when the
4024 application quits. */
4025 w32_msg_pump (&dummy_buf);
4026
4027 return 0;
4028 }
4029
4030 static void
4031 post_character_message (hwnd, msg, wParam, lParam, modifiers)
4032 HWND hwnd;
4033 UINT msg;
4034 WPARAM wParam;
4035 LPARAM lParam;
4036 DWORD modifiers;
4037
4038 {
4039 W32Msg wmsg;
4040
4041 wmsg.dwModifiers = modifiers;
4042
4043 /* Detect quit_char and set quit-flag directly. Note that we
4044 still need to post a message to ensure the main thread will be
4045 woken up if blocked in sys_select(), but we do NOT want to post
4046 the quit_char message itself (because it will usually be as if
4047 the user had typed quit_char twice). Instead, we post a dummy
4048 message that has no particular effect. */
4049 {
4050 int c = wParam;
4051 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
4052 c = make_ctrl_char (c) & 0377;
4053 if (c == quit_char
4054 || (wmsg.dwModifiers == 0 &&
4055 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
4056 {
4057 Vquit_flag = Qt;
4058
4059 /* The choice of message is somewhat arbitrary, as long as
4060 the main thread handler just ignores it. */
4061 msg = WM_NULL;
4062
4063 /* Interrupt any blocking system calls. */
4064 signal_quit ();
4065
4066 /* As a safety precaution, forcibly complete any deferred
4067 messages. This is a kludge, but I don't see any particularly
4068 clean way to handle the situation where a deferred message is
4069 "dropped" in the lisp thread, and will thus never be
4070 completed, eg. by the user trying to activate the menubar
4071 when the lisp thread is busy, and then typing C-g when the
4072 menubar doesn't open promptly (with the result that the
4073 menubar never responds at all because the deferred
4074 WM_INITMENU message is never completed). Another problem
4075 situation is when the lisp thread calls SendMessage (to send
4076 a window manager command) when a message has been deferred;
4077 the lisp thread gets blocked indefinitely waiting for the
4078 deferred message to be completed, which itself is waiting for
4079 the lisp thread to respond.
4080
4081 Note that we don't want to block the input thread waiting for
4082 a reponse from the lisp thread (although that would at least
4083 solve the deadlock problem above), because we want to be able
4084 to receive C-g to interrupt the lisp thread. */
4085 cancel_all_deferred_msgs ();
4086 }
4087 }
4088
4089 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4090 }
4091
4092 /* Main window procedure */
4093
4094 LRESULT CALLBACK
4095 w32_wnd_proc (hwnd, msg, wParam, lParam)
4096 HWND hwnd;
4097 UINT msg;
4098 WPARAM wParam;
4099 LPARAM lParam;
4100 {
4101 struct frame *f;
4102 struct w32_display_info *dpyinfo = &one_w32_display_info;
4103 W32Msg wmsg;
4104 int windows_translate;
4105 int key;
4106
4107 /* Note that it is okay to call x_window_to_frame, even though we are
4108 not running in the main lisp thread, because frame deletion
4109 requires the lisp thread to synchronize with this thread. Thus, if
4110 a frame struct is returned, it can be used without concern that the
4111 lisp thread might make it disappear while we are using it.
4112
4113 NB. Walking the frame list in this thread is safe (as long as
4114 writes of Lisp_Object slots are atomic, which they are on Windows).
4115 Although delete-frame can destructively modify the frame list while
4116 we are walking it, a garbage collection cannot occur until after
4117 delete-frame has synchronized with this thread.
4118
4119 It is also safe to use functions that make GDI calls, such as
4120 w32_clear_rect, because these functions must obtain a DC handle
4121 from the frame struct using get_frame_dc which is thread-aware. */
4122
4123 switch (msg)
4124 {
4125 case WM_ERASEBKGND:
4126 f = x_window_to_frame (dpyinfo, hwnd);
4127 if (f)
4128 {
4129 HDC hdc = get_frame_dc (f);
4130 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4131 w32_clear_rect (f, hdc, &wmsg.rect);
4132 release_frame_dc (f, hdc);
4133
4134 #if defined (W32_DEBUG_DISPLAY)
4135 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
4136 f,
4137 wmsg.rect.left, wmsg.rect.top,
4138 wmsg.rect.right, wmsg.rect.bottom));
4139 #endif /* W32_DEBUG_DISPLAY */
4140 }
4141 return 1;
4142 case WM_PALETTECHANGED:
4143 /* ignore our own changes */
4144 if ((HWND)wParam != hwnd)
4145 {
4146 f = x_window_to_frame (dpyinfo, hwnd);
4147 if (f)
4148 /* get_frame_dc will realize our palette and force all
4149 frames to be redrawn if needed. */
4150 release_frame_dc (f, get_frame_dc (f));
4151 }
4152 return 0;
4153 case WM_PAINT:
4154 {
4155 PAINTSTRUCT paintStruct;
4156 RECT update_rect;
4157
4158 f = x_window_to_frame (dpyinfo, hwnd);
4159 if (f == 0)
4160 {
4161 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
4162 return 0;
4163 }
4164
4165 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4166 fails. Apparently this can happen under some
4167 circumstances. */
4168 if (!w32_strict_painting || GetUpdateRect (hwnd, &update_rect, FALSE))
4169 {
4170 enter_crit ();
4171 BeginPaint (hwnd, &paintStruct);
4172
4173 if (w32_strict_painting)
4174 /* The rectangles returned by GetUpdateRect and BeginPaint
4175 do not always match. GetUpdateRect seems to be the
4176 more reliable of the two. */
4177 wmsg.rect = update_rect;
4178 else
4179 wmsg.rect = paintStruct.rcPaint;
4180
4181 #if defined (W32_DEBUG_DISPLAY)
4182 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
4183 f,
4184 wmsg.rect.left, wmsg.rect.top,
4185 wmsg.rect.right, wmsg.rect.bottom));
4186 DebPrint ((" [update region is %d,%d-%d,%d]\n",
4187 update_rect.left, update_rect.top,
4188 update_rect.right, update_rect.bottom));
4189 #endif
4190 EndPaint (hwnd, &paintStruct);
4191 leave_crit ();
4192
4193 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4194
4195 return 0;
4196 }
4197
4198 /* If GetUpdateRect returns 0 (meaning there is no update
4199 region), assume the whole window needs to be repainted. */
4200 GetClientRect(hwnd, &wmsg.rect);
4201 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4202 return 0;
4203 }
4204
4205 case WM_INPUTLANGCHANGE:
4206 /* Inform lisp thread of keyboard layout changes. */
4207 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4208
4209 /* Clear dead keys in the keyboard state; for simplicity only
4210 preserve modifier key states. */
4211 {
4212 int i;
4213 BYTE keystate[256];
4214
4215 GetKeyboardState (keystate);
4216 for (i = 0; i < 256; i++)
4217 if (1
4218 && i != VK_SHIFT
4219 && i != VK_LSHIFT
4220 && i != VK_RSHIFT
4221 && i != VK_CAPITAL
4222 && i != VK_NUMLOCK
4223 && i != VK_SCROLL
4224 && i != VK_CONTROL
4225 && i != VK_LCONTROL
4226 && i != VK_RCONTROL
4227 && i != VK_MENU
4228 && i != VK_LMENU
4229 && i != VK_RMENU
4230 && i != VK_LWIN
4231 && i != VK_RWIN)
4232 keystate[i] = 0;
4233 SetKeyboardState (keystate);
4234 }
4235 goto dflt;
4236
4237 case WM_HOTKEY:
4238 /* Synchronize hot keys with normal input. */
4239 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4240 return (0);
4241
4242 case WM_KEYUP:
4243 case WM_SYSKEYUP:
4244 record_keyup (wParam, lParam);
4245 goto dflt;
4246
4247 case WM_KEYDOWN:
4248 case WM_SYSKEYDOWN:
4249 /* Ignore keystrokes we fake ourself; see below. */
4250 if (dpyinfo->faked_key == wParam)
4251 {
4252 dpyinfo->faked_key = 0;
4253 /* Make sure TranslateMessage sees them though (as long as
4254 they don't produce WM_CHAR messages). This ensures that
4255 indicator lights are toggled promptly on Windows 9x, for
4256 example. */
4257 if (lispy_function_keys[wParam] != 0)
4258 {
4259 windows_translate = 1;
4260 goto translate;
4261 }
4262 return 0;
4263 }
4264
4265 /* Synchronize modifiers with current keystroke. */
4266 sync_modifiers ();
4267 record_keydown (wParam, lParam);
4268 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4269
4270 windows_translate = 0;
4271
4272 switch (wParam)
4273 {
4274 case VK_LWIN:
4275 if (NILP (Vw32_pass_lwindow_to_system))
4276 {
4277 /* Prevent system from acting on keyup (which opens the
4278 Start menu if no other key was pressed) by simulating a
4279 press of Space which we will ignore. */
4280 if (GetAsyncKeyState (wParam) & 1)
4281 {
4282 if (NUMBERP (Vw32_phantom_key_code))
4283 key = XUINT (Vw32_phantom_key_code) & 255;
4284 else
4285 key = VK_SPACE;
4286 dpyinfo->faked_key = key;
4287 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4288 }
4289 }
4290 if (!NILP (Vw32_lwindow_modifier))
4291 return 0;
4292 break;
4293 case VK_RWIN:
4294 if (NILP (Vw32_pass_rwindow_to_system))
4295 {
4296 if (GetAsyncKeyState (wParam) & 1)
4297 {
4298 if (NUMBERP (Vw32_phantom_key_code))
4299 key = XUINT (Vw32_phantom_key_code) & 255;
4300 else
4301 key = VK_SPACE;
4302 dpyinfo->faked_key = key;
4303 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4304 }
4305 }
4306 if (!NILP (Vw32_rwindow_modifier))
4307 return 0;
4308 break;
4309 case VK_APPS:
4310 if (!NILP (Vw32_apps_modifier))
4311 return 0;
4312 break;
4313 case VK_MENU:
4314 if (NILP (Vw32_pass_alt_to_system))
4315 /* Prevent DefWindowProc from activating the menu bar if an
4316 Alt key is pressed and released by itself. */
4317 return 0;
4318 windows_translate = 1;
4319 break;
4320 case VK_CAPITAL:
4321 /* Decide whether to treat as modifier or function key. */
4322 if (NILP (Vw32_enable_caps_lock))
4323 goto disable_lock_key;
4324 windows_translate = 1;
4325 break;
4326 case VK_NUMLOCK:
4327 /* Decide whether to treat as modifier or function key. */
4328 if (NILP (Vw32_enable_num_lock))
4329 goto disable_lock_key;
4330 windows_translate = 1;
4331 break;
4332 case VK_SCROLL:
4333 /* Decide whether to treat as modifier or function key. */
4334 if (NILP (Vw32_scroll_lock_modifier))
4335 goto disable_lock_key;
4336 windows_translate = 1;
4337 break;
4338 disable_lock_key:
4339 /* Ensure the appropriate lock key state (and indicator light)
4340 remains in the same state. We do this by faking another
4341 press of the relevant key. Apparently, this really is the
4342 only way to toggle the state of the indicator lights. */
4343 dpyinfo->faked_key = wParam;
4344 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4345 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4346 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4347 KEYEVENTF_EXTENDEDKEY | 0, 0);
4348 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4349 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4350 /* Ensure indicator lights are updated promptly on Windows 9x
4351 (TranslateMessage apparently does this), after forwarding
4352 input event. */
4353 post_character_message (hwnd, msg, wParam, lParam,
4354 w32_get_key_modifiers (wParam, lParam));
4355 windows_translate = 1;
4356 break;
4357 case VK_CONTROL:
4358 case VK_SHIFT:
4359 case VK_PROCESSKEY: /* Generated by IME. */
4360 windows_translate = 1;
4361 break;
4362 case VK_CANCEL:
4363 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4364 which is confusing for purposes of key binding; convert
4365 VK_CANCEL events into VK_PAUSE events. */
4366 wParam = VK_PAUSE;
4367 break;
4368 case VK_PAUSE:
4369 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4370 for purposes of key binding; convert these back into
4371 VK_NUMLOCK events, at least when we want to see NumLock key
4372 presses. (Note that there is never any possibility that
4373 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4374 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4375 wParam = VK_NUMLOCK;
4376 break;
4377 default:
4378 /* If not defined as a function key, change it to a WM_CHAR message. */
4379 if (lispy_function_keys[wParam] == 0)
4380 {
4381 DWORD modifiers = construct_console_modifiers ();
4382
4383 if (!NILP (Vw32_recognize_altgr)
4384 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4385 {
4386 /* Always let TranslateMessage handle AltGr key chords;
4387 for some reason, ToAscii doesn't always process AltGr
4388 chords correctly. */
4389 windows_translate = 1;
4390 }
4391 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4392 {
4393 /* Handle key chords including any modifiers other
4394 than shift directly, in order to preserve as much
4395 modifier information as possible. */
4396 if ('A' <= wParam && wParam <= 'Z')
4397 {
4398 /* Don't translate modified alphabetic keystrokes,
4399 so the user doesn't need to constantly switch
4400 layout to type control or meta keystrokes when
4401 the normal layout translates alphabetic
4402 characters to non-ascii characters. */
4403 if (!modifier_set (VK_SHIFT))
4404 wParam += ('a' - 'A');
4405 msg = WM_CHAR;
4406 }
4407 else
4408 {
4409 /* Try to handle other keystrokes by determining the
4410 base character (ie. translating the base key plus
4411 shift modifier). */
4412 int add;
4413 int isdead = 0;
4414 KEY_EVENT_RECORD key;
4415
4416 key.bKeyDown = TRUE;
4417 key.wRepeatCount = 1;
4418 key.wVirtualKeyCode = wParam;
4419 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4420 key.uChar.AsciiChar = 0;
4421 key.dwControlKeyState = modifiers;
4422
4423 add = w32_kbd_patch_key (&key);
4424 /* 0 means an unrecognised keycode, negative means
4425 dead key. Ignore both. */
4426 while (--add >= 0)
4427 {
4428 /* Forward asciified character sequence. */
4429 post_character_message
4430 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4431 w32_get_key_modifiers (wParam, lParam));
4432 w32_kbd_patch_key (&key);
4433 }
4434 return 0;
4435 }
4436 }
4437 else
4438 {
4439 /* Let TranslateMessage handle everything else. */
4440 windows_translate = 1;
4441 }
4442 }
4443 }
4444
4445 translate:
4446 if (windows_translate)
4447 {
4448 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4449
4450 windows_msg.time = GetMessageTime ();
4451 TranslateMessage (&windows_msg);
4452 goto dflt;
4453 }
4454
4455 /* Fall through */
4456
4457 case WM_SYSCHAR:
4458 case WM_CHAR:
4459 post_character_message (hwnd, msg, wParam, lParam,
4460 w32_get_key_modifiers (wParam, lParam));
4461 break;
4462
4463 /* Simulate middle mouse button events when left and right buttons
4464 are used together, but only if user has two button mouse. */
4465 case WM_LBUTTONDOWN:
4466 case WM_RBUTTONDOWN:
4467 if (XINT (Vw32_num_mouse_buttons) > 2)
4468 goto handle_plain_button;
4469
4470 {
4471 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4472 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4473
4474 if (button_state & this)
4475 return 0;
4476
4477 if (button_state == 0)
4478 SetCapture (hwnd);
4479
4480 button_state |= this;
4481
4482 if (button_state & other)
4483 {
4484 if (mouse_button_timer)
4485 {
4486 KillTimer (hwnd, mouse_button_timer);
4487 mouse_button_timer = 0;
4488
4489 /* Generate middle mouse event instead. */
4490 msg = WM_MBUTTONDOWN;
4491 button_state |= MMOUSE;
4492 }
4493 else if (button_state & MMOUSE)
4494 {
4495 /* Ignore button event if we've already generated a
4496 middle mouse down event. This happens if the
4497 user releases and press one of the two buttons
4498 after we've faked a middle mouse event. */
4499 return 0;
4500 }
4501 else
4502 {
4503 /* Flush out saved message. */
4504 post_msg (&saved_mouse_button_msg);
4505 }
4506 wmsg.dwModifiers = w32_get_modifiers ();
4507 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4508
4509 /* Clear message buffer. */
4510 saved_mouse_button_msg.msg.hwnd = 0;
4511 }
4512 else
4513 {
4514 /* Hold onto message for now. */
4515 mouse_button_timer =
4516 SetTimer (hwnd, MOUSE_BUTTON_ID,
4517 XINT (Vw32_mouse_button_tolerance), NULL);
4518 saved_mouse_button_msg.msg.hwnd = hwnd;
4519 saved_mouse_button_msg.msg.message = msg;
4520 saved_mouse_button_msg.msg.wParam = wParam;
4521 saved_mouse_button_msg.msg.lParam = lParam;
4522 saved_mouse_button_msg.msg.time = GetMessageTime ();
4523 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4524 }
4525 }
4526 return 0;
4527
4528 case WM_LBUTTONUP:
4529 case WM_RBUTTONUP:
4530 if (XINT (Vw32_num_mouse_buttons) > 2)
4531 goto handle_plain_button;
4532
4533 {
4534 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4535 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4536
4537 if ((button_state & this) == 0)
4538 return 0;
4539
4540 button_state &= ~this;
4541
4542 if (button_state & MMOUSE)
4543 {
4544 /* Only generate event when second button is released. */
4545 if ((button_state & other) == 0)
4546 {
4547 msg = WM_MBUTTONUP;
4548 button_state &= ~MMOUSE;
4549
4550 if (button_state) abort ();
4551 }
4552 else
4553 return 0;
4554 }
4555 else
4556 {
4557 /* Flush out saved message if necessary. */
4558 if (saved_mouse_button_msg.msg.hwnd)
4559 {
4560 post_msg (&saved_mouse_button_msg);
4561 }
4562 }
4563 wmsg.dwModifiers = w32_get_modifiers ();
4564 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4565
4566 /* Always clear message buffer and cancel timer. */
4567 saved_mouse_button_msg.msg.hwnd = 0;
4568 KillTimer (hwnd, mouse_button_timer);
4569 mouse_button_timer = 0;
4570
4571 if (button_state == 0)
4572 ReleaseCapture ();
4573 }
4574 return 0;
4575
4576 case WM_XBUTTONDOWN:
4577 case WM_XBUTTONUP:
4578 if (w32_pass_extra_mouse_buttons_to_system)
4579 goto dflt;
4580 /* else fall through and process them. */
4581 case WM_MBUTTONDOWN:
4582 case WM_MBUTTONUP:
4583 handle_plain_button:
4584 {
4585 BOOL up;
4586 int button;
4587
4588 if (parse_button (msg, HIWORD (wParam), &button, &up))
4589 {
4590 if (up) ReleaseCapture ();
4591 else SetCapture (hwnd);
4592 button = (button == 0) ? LMOUSE :
4593 ((button == 1) ? MMOUSE : RMOUSE);
4594 if (up)
4595 button_state &= ~button;
4596 else
4597 button_state |= button;
4598 }
4599 }
4600
4601 wmsg.dwModifiers = w32_get_modifiers ();
4602 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4603
4604 /* Need to return true for XBUTTON messages, false for others,
4605 to indicate that we processed the message. */
4606 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4607
4608 case WM_MOUSEMOVE:
4609 /* If the mouse has just moved into the frame, start tracking
4610 it, so we will be notified when it leaves the frame. Mouse
4611 tracking only works under W98 and NT4 and later. On earlier
4612 versions, there is no way of telling when the mouse leaves the
4613 frame, so we just have to put up with help-echo and mouse
4614 highlighting remaining while the frame is not active. */
4615 if (track_mouse_event_fn && !track_mouse_window)
4616 {
4617 TRACKMOUSEEVENT tme;
4618 tme.cbSize = sizeof (tme);
4619 tme.dwFlags = TME_LEAVE;
4620 tme.hwndTrack = hwnd;
4621
4622 track_mouse_event_fn (&tme);
4623 track_mouse_window = hwnd;
4624 }
4625 case WM_VSCROLL:
4626 if (XINT (Vw32_mouse_move_interval) <= 0
4627 || (msg == WM_MOUSEMOVE && button_state == 0))
4628 {
4629 wmsg.dwModifiers = w32_get_modifiers ();
4630 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4631 return 0;
4632 }
4633
4634 /* Hang onto mouse move and scroll messages for a bit, to avoid
4635 sending such events to Emacs faster than it can process them.
4636 If we get more events before the timer from the first message
4637 expires, we just replace the first message. */
4638
4639 if (saved_mouse_move_msg.msg.hwnd == 0)
4640 mouse_move_timer =
4641 SetTimer (hwnd, MOUSE_MOVE_ID,
4642 XINT (Vw32_mouse_move_interval), NULL);
4643
4644 /* Hold onto message for now. */
4645 saved_mouse_move_msg.msg.hwnd = hwnd;
4646 saved_mouse_move_msg.msg.message = msg;
4647 saved_mouse_move_msg.msg.wParam = wParam;
4648 saved_mouse_move_msg.msg.lParam = lParam;
4649 saved_mouse_move_msg.msg.time = GetMessageTime ();
4650 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4651
4652 return 0;
4653
4654 case WM_MOUSEWHEEL:
4655 wmsg.dwModifiers = w32_get_modifiers ();
4656 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4657 return 0;
4658
4659 case WM_DROPFILES:
4660 wmsg.dwModifiers = w32_get_modifiers ();
4661 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4662 return 0;
4663
4664 case WM_TIMER:
4665 /* Flush out saved messages if necessary. */
4666 if (wParam == mouse_button_timer)
4667 {
4668 if (saved_mouse_button_msg.msg.hwnd)
4669 {
4670 post_msg (&saved_mouse_button_msg);
4671 saved_mouse_button_msg.msg.hwnd = 0;
4672 }
4673 KillTimer (hwnd, mouse_button_timer);
4674 mouse_button_timer = 0;
4675 }
4676 else if (wParam == mouse_move_timer)
4677 {
4678 if (saved_mouse_move_msg.msg.hwnd)
4679 {
4680 post_msg (&saved_mouse_move_msg);
4681 saved_mouse_move_msg.msg.hwnd = 0;
4682 }
4683 KillTimer (hwnd, mouse_move_timer);
4684 mouse_move_timer = 0;
4685 }
4686 return 0;
4687
4688 case WM_NCACTIVATE:
4689 /* Windows doesn't send us focus messages when putting up and
4690 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4691 The only indication we get that something happened is receiving
4692 this message afterwards. So this is a good time to reset our
4693 keyboard modifiers' state. */
4694 reset_modifiers ();
4695 goto dflt;
4696
4697 case WM_INITMENU:
4698 button_state = 0;
4699 ReleaseCapture ();
4700 /* We must ensure menu bar is fully constructed and up to date
4701 before allowing user interaction with it. To achieve this
4702 we send this message to the lisp thread and wait for a
4703 reply (whose value is not actually needed) to indicate that
4704 the menu bar is now ready for use, so we can now return.
4705
4706 To remain responsive in the meantime, we enter a nested message
4707 loop that can process all other messages.
4708
4709 However, we skip all this if the message results from calling
4710 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4711 thread a message because it is blocked on us at this point. We
4712 set menubar_active before calling TrackPopupMenu to indicate
4713 this (there is no possibility of confusion with real menubar
4714 being active). */
4715
4716 f = x_window_to_frame (dpyinfo, hwnd);
4717 if (f
4718 && (f->output_data.w32->menubar_active
4719 /* We can receive this message even in the absence of a
4720 menubar (ie. when the system menu is activated) - in this
4721 case we do NOT want to forward the message, otherwise it
4722 will cause the menubar to suddenly appear when the user
4723 had requested it to be turned off! */
4724 || f->output_data.w32->menubar_widget == NULL))
4725 return 0;
4726
4727 {
4728 deferred_msg msg_buf;
4729
4730 /* Detect if message has already been deferred; in this case
4731 we cannot return any sensible value to ignore this. */
4732 if (find_deferred_msg (hwnd, msg) != NULL)
4733 abort ();
4734
4735 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4736 }
4737
4738 case WM_EXITMENULOOP:
4739 f = x_window_to_frame (dpyinfo, hwnd);
4740
4741 /* Free memory used by owner-drawn and help-echo strings. */
4742 w32_free_menu_strings (hwnd);
4743
4744 /* Indicate that menubar can be modified again. */
4745 if (f)
4746 f->output_data.w32->menubar_active = 0;
4747 goto dflt;
4748
4749 case WM_MENUSELECT:
4750 /* Direct handling of help_echo in menus. Should be safe now
4751 that we generate the help_echo by placing a help event in the
4752 keyboard buffer. */
4753 {
4754 HMENU menu = (HMENU) lParam;
4755 UINT menu_item = (UINT) LOWORD (wParam);
4756 UINT flags = (UINT) HIWORD (wParam);
4757
4758 w32_menu_display_help (hwnd, menu, menu_item, flags);
4759 }
4760 return 0;
4761
4762 case WM_MEASUREITEM:
4763 f = x_window_to_frame (dpyinfo, hwnd);
4764 if (f)
4765 {
4766 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4767
4768 if (pMis->CtlType == ODT_MENU)
4769 {
4770 /* Work out dimensions for popup menu titles. */
4771 char * title = (char *) pMis->itemData;
4772 HDC hdc = GetDC (hwnd);
4773 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4774 LOGFONT menu_logfont;
4775 HFONT old_font;
4776 SIZE size;
4777
4778 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4779 menu_logfont.lfWeight = FW_BOLD;
4780 menu_font = CreateFontIndirect (&menu_logfont);
4781 old_font = SelectObject (hdc, menu_font);
4782
4783 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4784 if (title)
4785 {
4786 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4787 pMis->itemWidth = size.cx;
4788 if (pMis->itemHeight < size.cy)
4789 pMis->itemHeight = size.cy;
4790 }
4791 else
4792 pMis->itemWidth = 0;
4793
4794 SelectObject (hdc, old_font);
4795 DeleteObject (menu_font);
4796 ReleaseDC (hwnd, hdc);
4797 return TRUE;
4798 }
4799 }
4800 return 0;
4801
4802 case WM_DRAWITEM:
4803 f = x_window_to_frame (dpyinfo, hwnd);
4804 if (f)
4805 {
4806 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4807
4808 if (pDis->CtlType == ODT_MENU)
4809 {
4810 /* Draw popup menu title. */
4811 char * title = (char *) pDis->itemData;
4812 if (title)
4813 {
4814 HDC hdc = pDis->hDC;
4815 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4816 LOGFONT menu_logfont;
4817 HFONT old_font;
4818
4819 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4820 menu_logfont.lfWeight = FW_BOLD;
4821 menu_font = CreateFontIndirect (&menu_logfont);
4822 old_font = SelectObject (hdc, menu_font);
4823
4824 /* Always draw title as if not selected. */
4825 ExtTextOut (hdc,
4826 pDis->rcItem.left
4827 + GetSystemMetrics (SM_CXMENUCHECK),
4828 pDis->rcItem.top,
4829 ETO_OPAQUE, &pDis->rcItem,
4830 title, strlen (title), NULL);
4831
4832 SelectObject (hdc, old_font);
4833 DeleteObject (menu_font);
4834 }
4835 return TRUE;
4836 }
4837 }
4838 return 0;
4839
4840 #if 0
4841 /* Still not right - can't distinguish between clicks in the
4842 client area of the frame from clicks forwarded from the scroll
4843 bars - may have to hook WM_NCHITTEST to remember the mouse
4844 position and then check if it is in the client area ourselves. */
4845 case WM_MOUSEACTIVATE:
4846 /* Discard the mouse click that activates a frame, allowing the
4847 user to click anywhere without changing point (or worse!).
4848 Don't eat mouse clicks on scrollbars though!! */
4849 if (LOWORD (lParam) == HTCLIENT )
4850 return MA_ACTIVATEANDEAT;
4851 goto dflt;
4852 #endif
4853
4854 case WM_MOUSELEAVE:
4855 /* No longer tracking mouse. */
4856 track_mouse_window = NULL;
4857
4858 case WM_ACTIVATEAPP:
4859 case WM_ACTIVATE:
4860 case WM_WINDOWPOSCHANGED:
4861 case WM_SHOWWINDOW:
4862 /* Inform lisp thread that a frame might have just been obscured
4863 or exposed, so should recheck visibility of all frames. */
4864 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4865 goto dflt;
4866
4867 case WM_SETFOCUS:
4868 dpyinfo->faked_key = 0;
4869 reset_modifiers ();
4870 register_hot_keys (hwnd);
4871 goto command;
4872 case WM_KILLFOCUS:
4873 unregister_hot_keys (hwnd);
4874 button_state = 0;
4875 ReleaseCapture ();
4876 /* Relinquish the system caret. */
4877 if (w32_system_caret_hwnd)
4878 {
4879 DestroyCaret ();
4880 w32_system_caret_hwnd = NULL;
4881 }
4882 case WM_MOVE:
4883 case WM_SIZE:
4884 case WM_COMMAND:
4885 command:
4886 wmsg.dwModifiers = w32_get_modifiers ();
4887 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4888 goto dflt;
4889
4890 case WM_CLOSE:
4891 wmsg.dwModifiers = w32_get_modifiers ();
4892 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4893 return 0;
4894
4895 case WM_WINDOWPOSCHANGING:
4896 /* Don't restrict the sizing of tip frames. */
4897 if (hwnd == tip_window)
4898 return 0;
4899 {
4900 WINDOWPLACEMENT wp;
4901 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4902
4903 wp.length = sizeof (WINDOWPLACEMENT);
4904 GetWindowPlacement (hwnd, &wp);
4905
4906 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4907 {
4908 RECT rect;
4909 int wdiff;
4910 int hdiff;
4911 DWORD font_width;
4912 DWORD line_height;
4913 DWORD internal_border;
4914 DWORD scrollbar_extra;
4915 RECT wr;
4916
4917 wp.length = sizeof(wp);
4918 GetWindowRect (hwnd, &wr);
4919
4920 enter_crit ();
4921
4922 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4923 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4924 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4925 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
4926
4927 leave_crit ();
4928
4929 memset (&rect, 0, sizeof (rect));
4930 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4931 GetMenu (hwnd) != NULL);
4932
4933 /* Force width and height of client area to be exact
4934 multiples of the character cell dimensions. */
4935 wdiff = (lppos->cx - (rect.right - rect.left)
4936 - 2 * internal_border - scrollbar_extra)
4937 % font_width;
4938 hdiff = (lppos->cy - (rect.bottom - rect.top)
4939 - 2 * internal_border)
4940 % line_height;
4941
4942 if (wdiff || hdiff)
4943 {
4944 /* For right/bottom sizing we can just fix the sizes.
4945 However for top/left sizing we will need to fix the X
4946 and Y positions as well. */
4947
4948 lppos->cx -= wdiff;
4949 lppos->cy -= hdiff;
4950
4951 if (wp.showCmd != SW_SHOWMAXIMIZED
4952 && (lppos->flags & SWP_NOMOVE) == 0)
4953 {
4954 if (lppos->x != wr.left || lppos->y != wr.top)
4955 {
4956 lppos->x += wdiff;
4957 lppos->y += hdiff;
4958 }
4959 else
4960 {
4961 lppos->flags |= SWP_NOMOVE;
4962 }
4963 }
4964
4965 return 0;
4966 }
4967 }
4968 }
4969
4970 goto dflt;
4971
4972 case WM_GETMINMAXINFO:
4973 /* Hack to correct bug that allows Emacs frames to be resized
4974 below the Minimum Tracking Size. */
4975 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
4976 /* Hack to allow resizing the Emacs frame above the screen size.
4977 Note that Windows 9x limits coordinates to 16-bits. */
4978 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
4979 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
4980 return 0;
4981
4982 case WM_EMACS_CREATESCROLLBAR:
4983 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
4984 (struct scroll_bar *) lParam);
4985
4986 case WM_EMACS_SHOWWINDOW:
4987 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4988
4989 case WM_EMACS_SETFOREGROUND:
4990 {
4991 HWND foreground_window;
4992 DWORD foreground_thread, retval;
4993
4994 /* On NT 5.0, and apparently Windows 98, it is necessary to
4995 attach to the thread that currently has focus in order to
4996 pull the focus away from it. */
4997 foreground_window = GetForegroundWindow ();
4998 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4999 if (!foreground_window
5000 || foreground_thread == GetCurrentThreadId ()
5001 || !AttachThreadInput (GetCurrentThreadId (),
5002 foreground_thread, TRUE))
5003 foreground_thread = 0;
5004
5005 retval = SetForegroundWindow ((HWND) wParam);
5006
5007 /* Detach from the previous foreground thread. */
5008 if (foreground_thread)
5009 AttachThreadInput (GetCurrentThreadId (),
5010 foreground_thread, FALSE);
5011
5012 return retval;
5013 }
5014
5015 case WM_EMACS_SETWINDOWPOS:
5016 {
5017 WINDOWPOS * pos = (WINDOWPOS *) wParam;
5018 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5019 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
5020 }
5021
5022 case WM_EMACS_DESTROYWINDOW:
5023 DragAcceptFiles ((HWND) wParam, FALSE);
5024 return DestroyWindow ((HWND) wParam);
5025
5026 case WM_EMACS_DESTROY_CARET:
5027 w32_system_caret_hwnd = NULL;
5028 return DestroyCaret ();
5029
5030 case WM_EMACS_TRACK_CARET:
5031 /* If there is currently no system caret, create one. */
5032 if (w32_system_caret_hwnd == NULL)
5033 {
5034 w32_system_caret_hwnd = hwnd;
5035 CreateCaret (hwnd, NULL, w32_system_caret_width,
5036 w32_system_caret_height);
5037 }
5038 return SetCaretPos (w32_system_caret_x, w32_system_caret_y);
5039
5040 case WM_EMACS_TRACKPOPUPMENU:
5041 {
5042 UINT flags;
5043 POINT *pos;
5044 int retval;
5045 pos = (POINT *)lParam;
5046 flags = TPM_CENTERALIGN;
5047 if (button_state & LMOUSE)
5048 flags |= TPM_LEFTBUTTON;
5049 else if (button_state & RMOUSE)
5050 flags |= TPM_RIGHTBUTTON;
5051
5052 /* Remember we did a SetCapture on the initial mouse down event,
5053 so for safety, we make sure the capture is cancelled now. */
5054 ReleaseCapture ();
5055 button_state = 0;
5056
5057 /* Use menubar_active to indicate that WM_INITMENU is from
5058 TrackPopupMenu below, and should be ignored. */
5059 f = x_window_to_frame (dpyinfo, hwnd);
5060 if (f)
5061 f->output_data.w32->menubar_active = 1;
5062
5063 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
5064 0, hwnd, NULL))
5065 {
5066 MSG amsg;
5067 /* Eat any mouse messages during popupmenu */
5068 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
5069 PM_REMOVE));
5070 /* Get the menu selection, if any */
5071 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
5072 {
5073 retval = LOWORD (amsg.wParam);
5074 }
5075 else
5076 {
5077 retval = 0;
5078 }
5079 }
5080 else
5081 {
5082 retval = -1;
5083 }
5084
5085 return retval;
5086 }
5087
5088 default:
5089 /* Check for messages registered at runtime. */
5090 if (msg == msh_mousewheel)
5091 {
5092 wmsg.dwModifiers = w32_get_modifiers ();
5093 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5094 return 0;
5095 }
5096
5097 dflt:
5098 return DefWindowProc (hwnd, msg, wParam, lParam);
5099 }
5100
5101
5102 /* The most common default return code for handled messages is 0. */
5103 return 0;
5104 }
5105
5106 void
5107 my_create_window (f)
5108 struct frame * f;
5109 {
5110 MSG msg;
5111
5112 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
5113 abort ();
5114 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5115 }
5116
5117
5118 /* Create a tooltip window. Unlike my_create_window, we do not do this
5119 indirectly via the Window thread, as we do not need to process Window
5120 messages for the tooltip. Creating tooltips indirectly also creates
5121 deadlocks when tooltips are created for menu items. */
5122 void
5123 my_create_tip_window (f)
5124 struct frame *f;
5125 {
5126 RECT rect;
5127
5128 rect.left = rect.top = 0;
5129 rect.right = PIXEL_WIDTH (f);
5130 rect.bottom = PIXEL_HEIGHT (f);
5131
5132 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
5133 FRAME_EXTERNAL_MENU_BAR (f));
5134
5135 tip_window = FRAME_W32_WINDOW (f)
5136 = CreateWindow (EMACS_CLASS,
5137 f->namebuf,
5138 f->output_data.w32->dwStyle,
5139 f->output_data.w32->left_pos,
5140 f->output_data.w32->top_pos,
5141 rect.right - rect.left,
5142 rect.bottom - rect.top,
5143 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5144 NULL,
5145 hinst,
5146 NULL);
5147
5148 if (tip_window)
5149 {
5150 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
5151 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
5152 SetWindowLong (tip_window, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
5153 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5154
5155 /* Tip frames have no scrollbars. */
5156 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
5157
5158 /* Do this to discard the default setting specified by our parent. */
5159 ShowWindow (tip_window, SW_HIDE);
5160 }
5161 }
5162
5163
5164 /* Create and set up the w32 window for frame F. */
5165
5166 static void
5167 w32_window (f, window_prompting, minibuffer_only)
5168 struct frame *f;
5169 long window_prompting;
5170 int minibuffer_only;
5171 {
5172 BLOCK_INPUT;
5173
5174 /* Use the resource name as the top-level window name
5175 for looking up resources. Make a non-Lisp copy
5176 for the window manager, so GC relocation won't bother it.
5177
5178 Elsewhere we specify the window name for the window manager. */
5179
5180 {
5181 char *str = (char *) XSTRING (Vx_resource_name)->data;
5182 f->namebuf = (char *) xmalloc (strlen (str) + 1);
5183 strcpy (f->namebuf, str);
5184 }
5185
5186 my_create_window (f);
5187
5188 validate_x_resource_name ();
5189
5190 /* x_set_name normally ignores requests to set the name if the
5191 requested name is the same as the current name. This is the one
5192 place where that assumption isn't correct; f->name is set, but
5193 the server hasn't been told. */
5194 {
5195 Lisp_Object name;
5196 int explicit = f->explicit_name;
5197
5198 f->explicit_name = 0;
5199 name = f->name;
5200 f->name = Qnil;
5201 x_set_name (f, name, explicit);
5202 }
5203
5204 UNBLOCK_INPUT;
5205
5206 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5207 initialize_frame_menubar (f);
5208
5209 if (FRAME_W32_WINDOW (f) == 0)
5210 error ("Unable to create window");
5211 }
5212
5213 /* Handle the icon stuff for this window. Perhaps later we might
5214 want an x_set_icon_position which can be called interactively as
5215 well. */
5216
5217 static void
5218 x_icon (f, parms)
5219 struct frame *f;
5220 Lisp_Object parms;
5221 {
5222 Lisp_Object icon_x, icon_y;
5223
5224 /* Set the position of the icon. Note that Windows 95 groups all
5225 icons in the tray. */
5226 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5227 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5228 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5229 {
5230 CHECK_NUMBER (icon_x);
5231 CHECK_NUMBER (icon_y);
5232 }
5233 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5234 error ("Both left and top icon corners of icon must be specified");
5235
5236 BLOCK_INPUT;
5237
5238 if (! EQ (icon_x, Qunbound))
5239 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5240
5241 #if 0 /* TODO */
5242 /* Start up iconic or window? */
5243 x_wm_set_window_state
5244 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5245 ? IconicState
5246 : NormalState));
5247
5248 x_text_icon (f, (char *) XSTRING ((!NILP (f->icon_name)
5249 ? f->icon_name
5250 : f->name))->data);
5251 #endif
5252
5253 UNBLOCK_INPUT;
5254 }
5255
5256
5257 static void
5258 x_make_gc (f)
5259 struct frame *f;
5260 {
5261 XGCValues gc_values;
5262
5263 BLOCK_INPUT;
5264
5265 /* Create the GC's of this frame.
5266 Note that many default values are used. */
5267
5268 /* Normal video */
5269 gc_values.font = f->output_data.w32->font;
5270
5271 /* Cursor has cursor-color background, background-color foreground. */
5272 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5273 gc_values.background = f->output_data.w32->cursor_pixel;
5274 f->output_data.w32->cursor_gc
5275 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5276 (GCFont | GCForeground | GCBackground),
5277 &gc_values);
5278
5279 /* Reliefs. */
5280 f->output_data.w32->white_relief.gc = 0;
5281 f->output_data.w32->black_relief.gc = 0;
5282
5283 UNBLOCK_INPUT;
5284 }
5285
5286
5287 /* Handler for signals raised during x_create_frame and
5288 x_create_top_frame. FRAME is the frame which is partially
5289 constructed. */
5290
5291 static Lisp_Object
5292 unwind_create_frame (frame)
5293 Lisp_Object frame;
5294 {
5295 struct frame *f = XFRAME (frame);
5296
5297 /* If frame is ``official'', nothing to do. */
5298 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
5299 {
5300 #ifdef GLYPH_DEBUG
5301 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5302 #endif
5303
5304 x_free_frame_resources (f);
5305
5306 /* Check that reference counts are indeed correct. */
5307 xassert (dpyinfo->reference_count == dpyinfo_refcount);
5308 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
5309
5310 return Qt;
5311 }
5312
5313 return Qnil;
5314 }
5315
5316
5317 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5318 1, 1, 0,
5319 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5320 Returns an Emacs frame object.
5321 ALIST is an alist of frame parameters.
5322 If the parameters specify that the frame should not have a minibuffer,
5323 and do not specify a specific minibuffer window to use,
5324 then `default-minibuffer-frame' must be a frame whose minibuffer can
5325 be shared by the new frame.
5326
5327 This function is an internal primitive--use `make-frame' instead. */)
5328 (parms)
5329 Lisp_Object parms;
5330 {
5331 struct frame *f;
5332 Lisp_Object frame, tem;
5333 Lisp_Object name;
5334 int minibuffer_only = 0;
5335 long window_prompting = 0;
5336 int width, height;
5337 int count = BINDING_STACK_SIZE ();
5338 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5339 Lisp_Object display;
5340 struct w32_display_info *dpyinfo = NULL;
5341 Lisp_Object parent;
5342 struct kboard *kb;
5343
5344 check_w32 ();
5345
5346 /* Use this general default value to start with
5347 until we know if this frame has a specified name. */
5348 Vx_resource_name = Vinvocation_name;
5349
5350 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5351 if (EQ (display, Qunbound))
5352 display = Qnil;
5353 dpyinfo = check_x_display_info (display);
5354 #ifdef MULTI_KBOARD
5355 kb = dpyinfo->kboard;
5356 #else
5357 kb = &the_only_kboard;
5358 #endif
5359
5360 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5361 if (!STRINGP (name)
5362 && ! EQ (name, Qunbound)
5363 && ! NILP (name))
5364 error ("Invalid frame name--not a string or nil");
5365
5366 if (STRINGP (name))
5367 Vx_resource_name = name;
5368
5369 /* See if parent window is specified. */
5370 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5371 if (EQ (parent, Qunbound))
5372 parent = Qnil;
5373 if (! NILP (parent))
5374 CHECK_NUMBER (parent);
5375
5376 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5377 /* No need to protect DISPLAY because that's not used after passing
5378 it to make_frame_without_minibuffer. */
5379 frame = Qnil;
5380 GCPRO4 (parms, parent, name, frame);
5381 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5382 RES_TYPE_SYMBOL);
5383 if (EQ (tem, Qnone) || NILP (tem))
5384 f = make_frame_without_minibuffer (Qnil, kb, display);
5385 else if (EQ (tem, Qonly))
5386 {
5387 f = make_minibuffer_frame ();
5388 minibuffer_only = 1;
5389 }
5390 else if (WINDOWP (tem))
5391 f = make_frame_without_minibuffer (tem, kb, display);
5392 else
5393 f = make_frame (1);
5394
5395 XSETFRAME (frame, f);
5396
5397 /* Note that Windows does support scroll bars. */
5398 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5399 /* By default, make scrollbars the system standard width. */
5400 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5401
5402 f->output_method = output_w32;
5403 f->output_data.w32 =
5404 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5405 bzero (f->output_data.w32, sizeof (struct w32_output));
5406 FRAME_FONTSET (f) = -1;
5407 record_unwind_protect (unwind_create_frame, frame);
5408
5409 f->icon_name
5410 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5411 if (! STRINGP (f->icon_name))
5412 f->icon_name = Qnil;
5413
5414 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5415 #ifdef MULTI_KBOARD
5416 FRAME_KBOARD (f) = kb;
5417 #endif
5418
5419 /* Specify the parent under which to make this window. */
5420
5421 if (!NILP (parent))
5422 {
5423 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5424 f->output_data.w32->explicit_parent = 1;
5425 }
5426 else
5427 {
5428 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5429 f->output_data.w32->explicit_parent = 0;
5430 }
5431
5432 /* Set the name; the functions to which we pass f expect the name to
5433 be set. */
5434 if (EQ (name, Qunbound) || NILP (name))
5435 {
5436 f->name = build_string (dpyinfo->w32_id_name);
5437 f->explicit_name = 0;
5438 }
5439 else
5440 {
5441 f->name = name;
5442 f->explicit_name = 1;
5443 /* use the frame's title when getting resources for this frame. */
5444 specbind (Qx_resource_name, name);
5445 }
5446
5447 /* Extract the window parameters from the supplied values
5448 that are needed to determine window geometry. */
5449 {
5450 Lisp_Object font;
5451
5452 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5453
5454 BLOCK_INPUT;
5455 /* First, try whatever font the caller has specified. */
5456 if (STRINGP (font))
5457 {
5458 tem = Fquery_fontset (font, Qnil);
5459 if (STRINGP (tem))
5460 font = x_new_fontset (f, XSTRING (tem)->data);
5461 else
5462 font = x_new_font (f, XSTRING (font)->data);
5463 }
5464 /* Try out a font which we hope has bold and italic variations. */
5465 if (!STRINGP (font))
5466 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5467 if (! STRINGP (font))
5468 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5469 /* If those didn't work, look for something which will at least work. */
5470 if (! STRINGP (font))
5471 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5472 UNBLOCK_INPUT;
5473 if (! STRINGP (font))
5474 font = build_string ("Fixedsys");
5475
5476 x_default_parameter (f, parms, Qfont, font,
5477 "font", "Font", RES_TYPE_STRING);
5478 }
5479
5480 x_default_parameter (f, parms, Qborder_width, make_number (2),
5481 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5482 /* This defaults to 2 in order to match xterm. We recognize either
5483 internalBorderWidth or internalBorder (which is what xterm calls
5484 it). */
5485 if (NILP (Fassq (Qinternal_border_width, parms)))
5486 {
5487 Lisp_Object value;
5488
5489 value = w32_get_arg (parms, Qinternal_border_width,
5490 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5491 if (! EQ (value, Qunbound))
5492 parms = Fcons (Fcons (Qinternal_border_width, value),
5493 parms);
5494 }
5495 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5496 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5497 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5498 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5499 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5500
5501 /* Also do the stuff which must be set before the window exists. */
5502 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5503 "foreground", "Foreground", RES_TYPE_STRING);
5504 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5505 "background", "Background", RES_TYPE_STRING);
5506 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5507 "pointerColor", "Foreground", RES_TYPE_STRING);
5508 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5509 "cursorColor", "Foreground", RES_TYPE_STRING);
5510 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5511 "borderColor", "BorderColor", RES_TYPE_STRING);
5512 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5513 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5514 x_default_parameter (f, parms, Qline_spacing, Qnil,
5515 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5516 x_default_parameter (f, parms, Qleft_fringe, Qnil,
5517 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5518 x_default_parameter (f, parms, Qright_fringe, Qnil,
5519 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5520
5521
5522 /* Init faces before x_default_parameter is called for scroll-bar
5523 parameters because that function calls x_set_scroll_bar_width,
5524 which calls change_frame_size, which calls Fset_window_buffer,
5525 which runs hooks, which call Fvertical_motion. At the end, we
5526 end up in init_iterator with a null face cache, which should not
5527 happen. */
5528 init_frame_faces (f);
5529
5530 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5531 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5532 x_default_parameter (f, parms, Qtool_bar_lines, make_number (0),
5533 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5534 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5535 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5536 x_default_parameter (f, parms, Qtitle, Qnil,
5537 "title", "Title", RES_TYPE_STRING);
5538
5539 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5540 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5541
5542 /* Add the tool-bar height to the initial frame height so that the
5543 user gets a text display area of the size he specified with -g or
5544 via .Xdefaults. Later changes of the tool-bar height don't
5545 change the frame size. This is done so that users can create
5546 tall Emacs frames without having to guess how tall the tool-bar
5547 will get. */
5548 if (FRAME_TOOL_BAR_LINES (f))
5549 {
5550 int margin, relief, bar_height;
5551
5552 relief = (tool_bar_button_relief >= 0
5553 ? tool_bar_button_relief
5554 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
5555
5556 if (INTEGERP (Vtool_bar_button_margin)
5557 && XINT (Vtool_bar_button_margin) > 0)
5558 margin = XFASTINT (Vtool_bar_button_margin);
5559 else if (CONSP (Vtool_bar_button_margin)
5560 && INTEGERP (XCDR (Vtool_bar_button_margin))
5561 && XINT (XCDR (Vtool_bar_button_margin)) > 0)
5562 margin = XFASTINT (XCDR (Vtool_bar_button_margin));
5563 else
5564 margin = 0;
5565
5566 bar_height = DEFAULT_TOOL_BAR_IMAGE_HEIGHT + 2 * margin + 2 * relief;
5567 f->height += (bar_height + CANON_Y_UNIT (f) - 1) / CANON_Y_UNIT (f);
5568 }
5569
5570 window_prompting = x_figure_window_size (f, parms);
5571
5572 if (window_prompting & XNegative)
5573 {
5574 if (window_prompting & YNegative)
5575 f->output_data.w32->win_gravity = SouthEastGravity;
5576 else
5577 f->output_data.w32->win_gravity = NorthEastGravity;
5578 }
5579 else
5580 {
5581 if (window_prompting & YNegative)
5582 f->output_data.w32->win_gravity = SouthWestGravity;
5583 else
5584 f->output_data.w32->win_gravity = NorthWestGravity;
5585 }
5586
5587 f->output_data.w32->size_hint_flags = window_prompting;
5588
5589 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5590 f->no_split = minibuffer_only || EQ (tem, Qt);
5591
5592 w32_window (f, window_prompting, minibuffer_only);
5593 x_icon (f, parms);
5594
5595 x_make_gc (f);
5596
5597 /* Now consider the frame official. */
5598 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5599 Vframe_list = Fcons (frame, Vframe_list);
5600
5601 /* We need to do this after creating the window, so that the
5602 icon-creation functions can say whose icon they're describing. */
5603 x_default_parameter (f, parms, Qicon_type, Qnil,
5604 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5605
5606 x_default_parameter (f, parms, Qauto_raise, Qnil,
5607 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5608 x_default_parameter (f, parms, Qauto_lower, Qnil,
5609 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5610 x_default_parameter (f, parms, Qcursor_type, Qbox,
5611 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5612 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5613 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5614
5615 /* Dimensions, especially f->height, must be done via change_frame_size.
5616 Change will not be effected unless different from the current
5617 f->height. */
5618 width = f->width;
5619 height = f->height;
5620
5621 f->height = 0;
5622 SET_FRAME_WIDTH (f, 0);
5623 change_frame_size (f, height, width, 1, 0, 0);
5624
5625 /* Tell the server what size and position, etc, we want, and how
5626 badly we want them. This should be done after we have the menu
5627 bar so that its size can be taken into account. */
5628 BLOCK_INPUT;
5629 x_wm_set_size_hint (f, window_prompting, 0);
5630 UNBLOCK_INPUT;
5631
5632 /* Avoid a bug that causes the new frame to never become visible if
5633 an echo area message is displayed during the following call1. */
5634 specbind(Qredisplay_dont_pause, Qt);
5635
5636 /* Set up faces after all frame parameters are known. This call
5637 also merges in face attributes specified for new frames. If we
5638 don't do this, the `menu' face for instance won't have the right
5639 colors, and the menu bar won't appear in the specified colors for
5640 new frames. */
5641 call1 (Qface_set_after_frame_default, frame);
5642
5643 /* Make the window appear on the frame and enable display, unless
5644 the caller says not to. However, with explicit parent, Emacs
5645 cannot control visibility, so don't try. */
5646 if (! f->output_data.w32->explicit_parent)
5647 {
5648 Lisp_Object visibility;
5649
5650 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5651 if (EQ (visibility, Qunbound))
5652 visibility = Qt;
5653
5654 if (EQ (visibility, Qicon))
5655 x_iconify_frame (f);
5656 else if (! NILP (visibility))
5657 x_make_frame_visible (f);
5658 else
5659 /* Must have been Qnil. */
5660 ;
5661 }
5662 UNGCPRO;
5663
5664 /* Make sure windows on this frame appear in calls to next-window
5665 and similar functions. */
5666 Vwindow_list = Qnil;
5667
5668 return unbind_to (count, frame);
5669 }
5670
5671 /* FRAME is used only to get a handle on the X display. We don't pass the
5672 display info directly because we're called from frame.c, which doesn't
5673 know about that structure. */
5674 Lisp_Object
5675 x_get_focus_frame (frame)
5676 struct frame *frame;
5677 {
5678 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5679 Lisp_Object xfocus;
5680 if (! dpyinfo->w32_focus_frame)
5681 return Qnil;
5682
5683 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5684 return xfocus;
5685 }
5686
5687 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5688 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
5689 (frame)
5690 Lisp_Object frame;
5691 {
5692 x_focus_on_frame (check_x_frame (frame));
5693 return Qnil;
5694 }
5695
5696 \f
5697 /* Return the charset portion of a font name. */
5698 char * xlfd_charset_of_font (char * fontname)
5699 {
5700 char *charset, *encoding;
5701
5702 encoding = strrchr(fontname, '-');
5703 if (!encoding || encoding == fontname)
5704 return NULL;
5705
5706 for (charset = encoding - 1; charset >= fontname; charset--)
5707 if (*charset == '-')
5708 break;
5709
5710 if (charset == fontname || strcmp(charset, "-*-*") == 0)
5711 return NULL;
5712
5713 return charset + 1;
5714 }
5715
5716 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5717 int size, char* filename);
5718 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
5719 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
5720 char * charset);
5721 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
5722
5723 static struct font_info *
5724 w32_load_system_font (f,fontname,size)
5725 struct frame *f;
5726 char * fontname;
5727 int size;
5728 {
5729 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5730 Lisp_Object font_names;
5731
5732 /* Get a list of all the fonts that match this name. Once we
5733 have a list of matching fonts, we compare them against the fonts
5734 we already have loaded by comparing names. */
5735 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5736
5737 if (!NILP (font_names))
5738 {
5739 Lisp_Object tail;
5740 int i;
5741
5742 /* First check if any are already loaded, as that is cheaper
5743 than loading another one. */
5744 for (i = 0; i < dpyinfo->n_fonts; i++)
5745 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5746 if (dpyinfo->font_table[i].name
5747 && (!strcmp (dpyinfo->font_table[i].name,
5748 XSTRING (XCAR (tail))->data)
5749 || !strcmp (dpyinfo->font_table[i].full_name,
5750 XSTRING (XCAR (tail))->data)))
5751 return (dpyinfo->font_table + i);
5752
5753 fontname = (char *) XSTRING (XCAR (font_names))->data;
5754 }
5755 else if (w32_strict_fontnames)
5756 {
5757 /* If EnumFontFamiliesEx was available, we got a full list of
5758 fonts back so stop now to avoid the possibility of loading a
5759 random font. If we had to fall back to EnumFontFamilies, the
5760 list is incomplete, so continue whether the font we want was
5761 listed or not. */
5762 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5763 FARPROC enum_font_families_ex
5764 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5765 if (enum_font_families_ex)
5766 return NULL;
5767 }
5768
5769 /* Load the font and add it to the table. */
5770 {
5771 char *full_name, *encoding, *charset;
5772 XFontStruct *font;
5773 struct font_info *fontp;
5774 LOGFONT lf;
5775 BOOL ok;
5776 int codepage;
5777 int i;
5778
5779 if (!fontname || !x_to_w32_font (fontname, &lf))
5780 return (NULL);
5781
5782 if (!*lf.lfFaceName)
5783 /* If no name was specified for the font, we get a random font
5784 from CreateFontIndirect - this is not particularly
5785 desirable, especially since CreateFontIndirect does not
5786 fill out the missing name in lf, so we never know what we
5787 ended up with. */
5788 return NULL;
5789
5790 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5791 bzero (font, sizeof (*font));
5792
5793 /* Set bdf to NULL to indicate that this is a Windows font. */
5794 font->bdf = NULL;
5795
5796 BLOCK_INPUT;
5797
5798 font->hfont = CreateFontIndirect (&lf);
5799
5800 if (font->hfont == NULL)
5801 {
5802 ok = FALSE;
5803 }
5804 else
5805 {
5806 HDC hdc;
5807 HANDLE oldobj;
5808
5809 codepage = w32_codepage_for_font (fontname);
5810
5811 hdc = GetDC (dpyinfo->root_window);
5812 oldobj = SelectObject (hdc, font->hfont);
5813
5814 ok = GetTextMetrics (hdc, &font->tm);
5815 if (codepage == CP_UNICODE)
5816 font->double_byte_p = 1;
5817 else
5818 {
5819 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
5820 don't report themselves as double byte fonts, when
5821 patently they are. So instead of trusting
5822 GetFontLanguageInfo, we check the properties of the
5823 codepage directly, since that is ultimately what we are
5824 working from anyway. */
5825 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
5826 CPINFO cpi = {0};
5827 GetCPInfo (codepage, &cpi);
5828 font->double_byte_p = cpi.MaxCharSize > 1;
5829 }
5830
5831 SelectObject (hdc, oldobj);
5832 ReleaseDC (dpyinfo->root_window, hdc);
5833 /* Fill out details in lf according to the font that was
5834 actually loaded. */
5835 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5836 lf.lfWidth = font->tm.tmAveCharWidth;
5837 lf.lfWeight = font->tm.tmWeight;
5838 lf.lfItalic = font->tm.tmItalic;
5839 lf.lfCharSet = font->tm.tmCharSet;
5840 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5841 ? VARIABLE_PITCH : FIXED_PITCH);
5842 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5843 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5844
5845 w32_cache_char_metrics (font);
5846 }
5847
5848 UNBLOCK_INPUT;
5849
5850 if (!ok)
5851 {
5852 w32_unload_font (dpyinfo, font);
5853 return (NULL);
5854 }
5855
5856 /* Find a free slot in the font table. */
5857 for (i = 0; i < dpyinfo->n_fonts; ++i)
5858 if (dpyinfo->font_table[i].name == NULL)
5859 break;
5860
5861 /* If no free slot found, maybe enlarge the font table. */
5862 if (i == dpyinfo->n_fonts
5863 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5864 {
5865 int sz;
5866 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5867 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5868 dpyinfo->font_table
5869 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5870 }
5871
5872 fontp = dpyinfo->font_table + i;
5873 if (i == dpyinfo->n_fonts)
5874 ++dpyinfo->n_fonts;
5875
5876 /* Now fill in the slots of *FONTP. */
5877 BLOCK_INPUT;
5878 fontp->font = font;
5879 fontp->font_idx = i;
5880 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5881 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5882
5883 charset = xlfd_charset_of_font (fontname);
5884
5885 /* Cache the W32 codepage for a font. This makes w32_encode_char
5886 (called for every glyph during redisplay) much faster. */
5887 fontp->codepage = codepage;
5888
5889 /* Work out the font's full name. */
5890 full_name = (char *)xmalloc (100);
5891 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
5892 fontp->full_name = full_name;
5893 else
5894 {
5895 /* If all else fails - just use the name we used to load it. */
5896 xfree (full_name);
5897 fontp->full_name = fontp->name;
5898 }
5899
5900 fontp->size = FONT_WIDTH (font);
5901 fontp->height = FONT_HEIGHT (font);
5902
5903 /* The slot `encoding' specifies how to map a character
5904 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
5905 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
5906 (0:0x20..0x7F, 1:0xA0..0xFF,
5907 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
5908 2:0xA020..0xFF7F). For the moment, we don't know which charset
5909 uses this font. So, we set information in fontp->encoding[1]
5910 which is never used by any charset. If mapping can't be
5911 decided, set FONT_ENCODING_NOT_DECIDED. */
5912
5913 /* SJIS fonts need to be set to type 4, all others seem to work as
5914 type FONT_ENCODING_NOT_DECIDED. */
5915 encoding = strrchr (fontp->name, '-');
5916 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
5917 fontp->encoding[1] = 4;
5918 else
5919 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
5920
5921 /* The following three values are set to 0 under W32, which is
5922 what they get set to if XGetFontProperty fails under X. */
5923 fontp->baseline_offset = 0;
5924 fontp->relative_compose = 0;
5925 fontp->default_ascent = 0;
5926
5927 /* Set global flag fonts_changed_p to non-zero if the font loaded
5928 has a character with a smaller width than any other character
5929 before, or if the font loaded has a smalle>r height than any
5930 other font loaded before. If this happens, it will make a
5931 glyph matrix reallocation necessary. */
5932 fonts_changed_p = x_compute_min_glyph_bounds (f);
5933 UNBLOCK_INPUT;
5934 return fontp;
5935 }
5936 }
5937
5938 /* Load font named FONTNAME of size SIZE for frame F, and return a
5939 pointer to the structure font_info while allocating it dynamically.
5940 If loading fails, return NULL. */
5941 struct font_info *
5942 w32_load_font (f,fontname,size)
5943 struct frame *f;
5944 char * fontname;
5945 int size;
5946 {
5947 Lisp_Object bdf_fonts;
5948 struct font_info *retval = NULL;
5949
5950 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
5951
5952 while (!retval && CONSP (bdf_fonts))
5953 {
5954 char *bdf_name, *bdf_file;
5955 Lisp_Object bdf_pair;
5956
5957 bdf_name = XSTRING (XCAR (bdf_fonts))->data;
5958 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
5959 bdf_file = XSTRING (XCDR (bdf_pair))->data;
5960
5961 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
5962
5963 bdf_fonts = XCDR (bdf_fonts);
5964 }
5965
5966 if (retval)
5967 return retval;
5968
5969 return w32_load_system_font(f, fontname, size);
5970 }
5971
5972
5973 void
5974 w32_unload_font (dpyinfo, font)
5975 struct w32_display_info *dpyinfo;
5976 XFontStruct * font;
5977 {
5978 if (font)
5979 {
5980 if (font->per_char) xfree (font->per_char);
5981 if (font->bdf) w32_free_bdf_font (font->bdf);
5982
5983 if (font->hfont) DeleteObject(font->hfont);
5984 xfree (font);
5985 }
5986 }
5987
5988 /* The font conversion stuff between x and w32 */
5989
5990 /* X font string is as follows (from faces.el)
5991 * (let ((- "[-?]")
5992 * (foundry "[^-]+")
5993 * (family "[^-]+")
5994 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
5995 * (weight\? "\\([^-]*\\)") ; 1
5996 * (slant "\\([ior]\\)") ; 2
5997 * (slant\? "\\([^-]?\\)") ; 2
5998 * (swidth "\\([^-]*\\)") ; 3
5999 * (adstyle "[^-]*") ; 4
6000 * (pixelsize "[0-9]+")
6001 * (pointsize "[0-9][0-9]+")
6002 * (resx "[0-9][0-9]+")
6003 * (resy "[0-9][0-9]+")
6004 * (spacing "[cmp?*]")
6005 * (avgwidth "[0-9]+")
6006 * (registry "[^-]+")
6007 * (encoding "[^-]+")
6008 * )
6009 */
6010
6011 static LONG
6012 x_to_w32_weight (lpw)
6013 char * lpw;
6014 {
6015 if (!lpw) return (FW_DONTCARE);
6016
6017 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
6018 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
6019 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
6020 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
6021 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
6022 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
6023 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
6024 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
6025 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
6026 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
6027 else
6028 return FW_DONTCARE;
6029 }
6030
6031
6032 static char *
6033 w32_to_x_weight (fnweight)
6034 int fnweight;
6035 {
6036 if (fnweight >= FW_HEAVY) return "heavy";
6037 if (fnweight >= FW_EXTRABOLD) return "extrabold";
6038 if (fnweight >= FW_BOLD) return "bold";
6039 if (fnweight >= FW_SEMIBOLD) return "demibold";
6040 if (fnweight >= FW_MEDIUM) return "medium";
6041 if (fnweight >= FW_NORMAL) return "normal";
6042 if (fnweight >= FW_LIGHT) return "light";
6043 if (fnweight >= FW_EXTRALIGHT) return "extralight";
6044 if (fnweight >= FW_THIN) return "thin";
6045 else
6046 return "*";
6047 }
6048
6049 static LONG
6050 x_to_w32_charset (lpcs)
6051 char * lpcs;
6052 {
6053 Lisp_Object this_entry, w32_charset;
6054 char *charset;
6055 int len = strlen (lpcs);
6056
6057 /* Support "*-#nnn" format for unknown charsets. */
6058 if (strncmp (lpcs, "*-#", 3) == 0)
6059 return atoi (lpcs + 3);
6060
6061 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
6062 charset = alloca (len + 1);
6063 strcpy (charset, lpcs);
6064 lpcs = strchr (charset, '*');
6065 if (lpcs)
6066 *lpcs = 0;
6067
6068 /* Look through w32-charset-info-alist for the character set.
6069 Format of each entry is
6070 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6071 */
6072 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6073
6074 if (NILP(this_entry))
6075 {
6076 /* At startup, we want iso8859-1 fonts to come up properly. */
6077 if (stricmp(charset, "iso8859-1") == 0)
6078 return ANSI_CHARSET;
6079 else
6080 return DEFAULT_CHARSET;
6081 }
6082
6083 w32_charset = Fcar (Fcdr (this_entry));
6084
6085 /* Translate Lisp symbol to number. */
6086 if (w32_charset == Qw32_charset_ansi)
6087 return ANSI_CHARSET;
6088 if (w32_charset == Qw32_charset_symbol)
6089 return SYMBOL_CHARSET;
6090 if (w32_charset == Qw32_charset_shiftjis)
6091 return SHIFTJIS_CHARSET;
6092 if (w32_charset == Qw32_charset_hangeul)
6093 return HANGEUL_CHARSET;
6094 if (w32_charset == Qw32_charset_chinesebig5)
6095 return CHINESEBIG5_CHARSET;
6096 if (w32_charset == Qw32_charset_gb2312)
6097 return GB2312_CHARSET;
6098 if (w32_charset == Qw32_charset_oem)
6099 return OEM_CHARSET;
6100 #ifdef JOHAB_CHARSET
6101 if (w32_charset == Qw32_charset_johab)
6102 return JOHAB_CHARSET;
6103 if (w32_charset == Qw32_charset_easteurope)
6104 return EASTEUROPE_CHARSET;
6105 if (w32_charset == Qw32_charset_turkish)
6106 return TURKISH_CHARSET;
6107 if (w32_charset == Qw32_charset_baltic)
6108 return BALTIC_CHARSET;
6109 if (w32_charset == Qw32_charset_russian)
6110 return RUSSIAN_CHARSET;
6111 if (w32_charset == Qw32_charset_arabic)
6112 return ARABIC_CHARSET;
6113 if (w32_charset == Qw32_charset_greek)
6114 return GREEK_CHARSET;
6115 if (w32_charset == Qw32_charset_hebrew)
6116 return HEBREW_CHARSET;
6117 if (w32_charset == Qw32_charset_vietnamese)
6118 return VIETNAMESE_CHARSET;
6119 if (w32_charset == Qw32_charset_thai)
6120 return THAI_CHARSET;
6121 if (w32_charset == Qw32_charset_mac)
6122 return MAC_CHARSET;
6123 #endif /* JOHAB_CHARSET */
6124 #ifdef UNICODE_CHARSET
6125 if (w32_charset == Qw32_charset_unicode)
6126 return UNICODE_CHARSET;
6127 #endif
6128
6129 return DEFAULT_CHARSET;
6130 }
6131
6132
6133 static char *
6134 w32_to_x_charset (fncharset)
6135 int fncharset;
6136 {
6137 static char buf[32];
6138 Lisp_Object charset_type;
6139
6140 switch (fncharset)
6141 {
6142 case ANSI_CHARSET:
6143 /* Handle startup case of w32-charset-info-alist not
6144 being set up yet. */
6145 if (NILP(Vw32_charset_info_alist))
6146 return "iso8859-1";
6147 charset_type = Qw32_charset_ansi;
6148 break;
6149 case DEFAULT_CHARSET:
6150 charset_type = Qw32_charset_default;
6151 break;
6152 case SYMBOL_CHARSET:
6153 charset_type = Qw32_charset_symbol;
6154 break;
6155 case SHIFTJIS_CHARSET:
6156 charset_type = Qw32_charset_shiftjis;
6157 break;
6158 case HANGEUL_CHARSET:
6159 charset_type = Qw32_charset_hangeul;
6160 break;
6161 case GB2312_CHARSET:
6162 charset_type = Qw32_charset_gb2312;
6163 break;
6164 case CHINESEBIG5_CHARSET:
6165 charset_type = Qw32_charset_chinesebig5;
6166 break;
6167 case OEM_CHARSET:
6168 charset_type = Qw32_charset_oem;
6169 break;
6170
6171 /* More recent versions of Windows (95 and NT4.0) define more
6172 character sets. */
6173 #ifdef EASTEUROPE_CHARSET
6174 case EASTEUROPE_CHARSET:
6175 charset_type = Qw32_charset_easteurope;
6176 break;
6177 case TURKISH_CHARSET:
6178 charset_type = Qw32_charset_turkish;
6179 break;
6180 case BALTIC_CHARSET:
6181 charset_type = Qw32_charset_baltic;
6182 break;
6183 case RUSSIAN_CHARSET:
6184 charset_type = Qw32_charset_russian;
6185 break;
6186 case ARABIC_CHARSET:
6187 charset_type = Qw32_charset_arabic;
6188 break;
6189 case GREEK_CHARSET:
6190 charset_type = Qw32_charset_greek;
6191 break;
6192 case HEBREW_CHARSET:
6193 charset_type = Qw32_charset_hebrew;
6194 break;
6195 case VIETNAMESE_CHARSET:
6196 charset_type = Qw32_charset_vietnamese;
6197 break;
6198 case THAI_CHARSET:
6199 charset_type = Qw32_charset_thai;
6200 break;
6201 case MAC_CHARSET:
6202 charset_type = Qw32_charset_mac;
6203 break;
6204 case JOHAB_CHARSET:
6205 charset_type = Qw32_charset_johab;
6206 break;
6207 #endif
6208
6209 #ifdef UNICODE_CHARSET
6210 case UNICODE_CHARSET:
6211 charset_type = Qw32_charset_unicode;
6212 break;
6213 #endif
6214 default:
6215 /* Encode numerical value of unknown charset. */
6216 sprintf (buf, "*-#%u", fncharset);
6217 return buf;
6218 }
6219
6220 {
6221 Lisp_Object rest;
6222 char * best_match = NULL;
6223
6224 /* Look through w32-charset-info-alist for the character set.
6225 Prefer ISO codepages, and prefer lower numbers in the ISO
6226 range. Only return charsets for codepages which are installed.
6227
6228 Format of each entry is
6229 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6230 */
6231 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6232 {
6233 char * x_charset;
6234 Lisp_Object w32_charset;
6235 Lisp_Object codepage;
6236
6237 Lisp_Object this_entry = XCAR (rest);
6238
6239 /* Skip invalid entries in alist. */
6240 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6241 || !CONSP (XCDR (this_entry))
6242 || !SYMBOLP (XCAR (XCDR (this_entry))))
6243 continue;
6244
6245 x_charset = XSTRING (XCAR (this_entry))->data;
6246 w32_charset = XCAR (XCDR (this_entry));
6247 codepage = XCDR (XCDR (this_entry));
6248
6249 /* Look for Same charset and a valid codepage (or non-int
6250 which means ignore). */
6251 if (w32_charset == charset_type
6252 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6253 || IsValidCodePage (XINT (codepage))))
6254 {
6255 /* If we don't have a match already, then this is the
6256 best. */
6257 if (!best_match)
6258 best_match = x_charset;
6259 /* If this is an ISO codepage, and the best so far isn't,
6260 then this is better. */
6261 else if (strnicmp (best_match, "iso", 3) != 0
6262 && strnicmp (x_charset, "iso", 3) == 0)
6263 best_match = x_charset;
6264 /* If both are ISO8859 codepages, choose the one with the
6265 lowest number in the encoding field. */
6266 else if (strnicmp (best_match, "iso8859-", 8) == 0
6267 && strnicmp (x_charset, "iso8859-", 8) == 0)
6268 {
6269 int best_enc = atoi (best_match + 8);
6270 int this_enc = atoi (x_charset + 8);
6271 if (this_enc > 0 && this_enc < best_enc)
6272 best_match = x_charset;
6273 }
6274 }
6275 }
6276
6277 /* If no match, encode the numeric value. */
6278 if (!best_match)
6279 {
6280 sprintf (buf, "*-#%u", fncharset);
6281 return buf;
6282 }
6283
6284 strncpy(buf, best_match, 31);
6285 buf[31] = '\0';
6286 return buf;
6287 }
6288 }
6289
6290
6291 /* Return all the X charsets that map to a font. */
6292 static Lisp_Object
6293 w32_to_all_x_charsets (fncharset)
6294 int fncharset;
6295 {
6296 static char buf[32];
6297 Lisp_Object charset_type;
6298 Lisp_Object retval = Qnil;
6299
6300 switch (fncharset)
6301 {
6302 case ANSI_CHARSET:
6303 /* Handle startup case of w32-charset-info-alist not
6304 being set up yet. */
6305 if (NILP(Vw32_charset_info_alist))
6306 return "iso8859-1";
6307 charset_type = Qw32_charset_ansi;
6308 break;
6309 case DEFAULT_CHARSET:
6310 charset_type = Qw32_charset_default;
6311 break;
6312 case SYMBOL_CHARSET:
6313 charset_type = Qw32_charset_symbol;
6314 break;
6315 case SHIFTJIS_CHARSET:
6316 charset_type = Qw32_charset_shiftjis;
6317 break;
6318 case HANGEUL_CHARSET:
6319 charset_type = Qw32_charset_hangeul;
6320 break;
6321 case GB2312_CHARSET:
6322 charset_type = Qw32_charset_gb2312;
6323 break;
6324 case CHINESEBIG5_CHARSET:
6325 charset_type = Qw32_charset_chinesebig5;
6326 break;
6327 case OEM_CHARSET:
6328 charset_type = Qw32_charset_oem;
6329 break;
6330
6331 /* More recent versions of Windows (95 and NT4.0) define more
6332 character sets. */
6333 #ifdef EASTEUROPE_CHARSET
6334 case EASTEUROPE_CHARSET:
6335 charset_type = Qw32_charset_easteurope;
6336 break;
6337 case TURKISH_CHARSET:
6338 charset_type = Qw32_charset_turkish;
6339 break;
6340 case BALTIC_CHARSET:
6341 charset_type = Qw32_charset_baltic;
6342 break;
6343 case RUSSIAN_CHARSET:
6344 charset_type = Qw32_charset_russian;
6345 break;
6346 case ARABIC_CHARSET:
6347 charset_type = Qw32_charset_arabic;
6348 break;
6349 case GREEK_CHARSET:
6350 charset_type = Qw32_charset_greek;
6351 break;
6352 case HEBREW_CHARSET:
6353 charset_type = Qw32_charset_hebrew;
6354 break;
6355 case VIETNAMESE_CHARSET:
6356 charset_type = Qw32_charset_vietnamese;
6357 break;
6358 case THAI_CHARSET:
6359 charset_type = Qw32_charset_thai;
6360 break;
6361 case MAC_CHARSET:
6362 charset_type = Qw32_charset_mac;
6363 break;
6364 case JOHAB_CHARSET:
6365 charset_type = Qw32_charset_johab;
6366 break;
6367 #endif
6368
6369 #ifdef UNICODE_CHARSET
6370 case UNICODE_CHARSET:
6371 charset_type = Qw32_charset_unicode;
6372 break;
6373 #endif
6374 default:
6375 /* Encode numerical value of unknown charset. */
6376 sprintf (buf, "*-#%u", fncharset);
6377 return Fcons (build_string (buf), Qnil);
6378 }
6379
6380 {
6381 Lisp_Object rest;
6382 /* Look through w32-charset-info-alist for the character set.
6383 Only return charsets for codepages which are installed.
6384
6385 Format of each entry in Vw32_charset_info_alist is
6386 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6387 */
6388 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6389 {
6390 Lisp_Object x_charset;
6391 Lisp_Object w32_charset;
6392 Lisp_Object codepage;
6393
6394 Lisp_Object this_entry = XCAR (rest);
6395
6396 /* Skip invalid entries in alist. */
6397 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6398 || !CONSP (XCDR (this_entry))
6399 || !SYMBOLP (XCAR (XCDR (this_entry))))
6400 continue;
6401
6402 x_charset = XCAR (this_entry);
6403 w32_charset = XCAR (XCDR (this_entry));
6404 codepage = XCDR (XCDR (this_entry));
6405
6406 /* Look for Same charset and a valid codepage (or non-int
6407 which means ignore). */
6408 if (w32_charset == charset_type
6409 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6410 || IsValidCodePage (XINT (codepage))))
6411 {
6412 retval = Fcons (x_charset, retval);
6413 }
6414 }
6415
6416 /* If no match, encode the numeric value. */
6417 if (NILP (retval))
6418 {
6419 sprintf (buf, "*-#%u", fncharset);
6420 return Fcons (build_string (buf), Qnil);
6421 }
6422
6423 return retval;
6424 }
6425 }
6426
6427 /* Get the Windows codepage corresponding to the specified font. The
6428 charset info in the font name is used to look up
6429 w32-charset-to-codepage-alist. */
6430 int
6431 w32_codepage_for_font (char *fontname)
6432 {
6433 Lisp_Object codepage, entry;
6434 char *charset_str, *charset, *end;
6435
6436 if (NILP (Vw32_charset_info_alist))
6437 return CP_DEFAULT;
6438
6439 /* Extract charset part of font string. */
6440 charset = xlfd_charset_of_font (fontname);
6441
6442 if (!charset)
6443 return CP_UNKNOWN;
6444
6445 charset_str = (char *) alloca (strlen (charset) + 1);
6446 strcpy (charset_str, charset);
6447
6448 #if 0
6449 /* Remove leading "*-". */
6450 if (strncmp ("*-", charset_str, 2) == 0)
6451 charset = charset_str + 2;
6452 else
6453 #endif
6454 charset = charset_str;
6455
6456 /* Stop match at wildcard (including preceding '-'). */
6457 if (end = strchr (charset, '*'))
6458 {
6459 if (end > charset && *(end-1) == '-')
6460 end--;
6461 *end = '\0';
6462 }
6463
6464 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6465 if (NILP (entry))
6466 return CP_UNKNOWN;
6467
6468 codepage = Fcdr (Fcdr (entry));
6469
6470 if (NILP (codepage))
6471 return CP_8BIT;
6472 else if (XFASTINT (codepage) == XFASTINT (Qt))
6473 return CP_UNICODE;
6474 else if (INTEGERP (codepage))
6475 return XINT (codepage);
6476 else
6477 return CP_UNKNOWN;
6478 }
6479
6480
6481 static BOOL
6482 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6483 LOGFONT * lplogfont;
6484 char * lpxstr;
6485 int len;
6486 char * specific_charset;
6487 {
6488 char* fonttype;
6489 char *fontname;
6490 char height_pixels[8];
6491 char height_dpi[8];
6492 char width_pixels[8];
6493 char *fontname_dash;
6494 int display_resy = one_w32_display_info.resy;
6495 int display_resx = one_w32_display_info.resx;
6496 int bufsz;
6497 struct coding_system coding;
6498
6499 if (!lpxstr) abort ();
6500
6501 if (!lplogfont)
6502 return FALSE;
6503
6504 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6505 fonttype = "raster";
6506 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6507 fonttype = "outline";
6508 else
6509 fonttype = "unknown";
6510
6511 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
6512 &coding);
6513 coding.src_multibyte = 0;
6514 coding.dst_multibyte = 1;
6515 coding.mode |= CODING_MODE_LAST_BLOCK;
6516 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6517
6518 fontname = alloca(sizeof(*fontname) * bufsz);
6519 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6520 strlen(lplogfont->lfFaceName), bufsz - 1);
6521 *(fontname + coding.produced) = '\0';
6522
6523 /* Replace dashes with underscores so the dashes are not
6524 misinterpreted. */
6525 fontname_dash = fontname;
6526 while (fontname_dash = strchr (fontname_dash, '-'))
6527 *fontname_dash = '_';
6528
6529 if (lplogfont->lfHeight)
6530 {
6531 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6532 sprintf (height_dpi, "%u",
6533 abs (lplogfont->lfHeight) * 720 / display_resy);
6534 }
6535 else
6536 {
6537 strcpy (height_pixels, "*");
6538 strcpy (height_dpi, "*");
6539 }
6540 if (lplogfont->lfWidth)
6541 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6542 else
6543 strcpy (width_pixels, "*");
6544
6545 _snprintf (lpxstr, len - 1,
6546 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6547 fonttype, /* foundry */
6548 fontname, /* family */
6549 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6550 lplogfont->lfItalic?'i':'r', /* slant */
6551 /* setwidth name */
6552 /* add style name */
6553 height_pixels, /* pixel size */
6554 height_dpi, /* point size */
6555 display_resx, /* resx */
6556 display_resy, /* resy */
6557 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6558 ? 'p' : 'c', /* spacing */
6559 width_pixels, /* avg width */
6560 specific_charset ? specific_charset
6561 : w32_to_x_charset (lplogfont->lfCharSet)
6562 /* charset registry and encoding */
6563 );
6564
6565 lpxstr[len - 1] = 0; /* just to be sure */
6566 return (TRUE);
6567 }
6568
6569 static BOOL
6570 x_to_w32_font (lpxstr, lplogfont)
6571 char * lpxstr;
6572 LOGFONT * lplogfont;
6573 {
6574 struct coding_system coding;
6575
6576 if (!lplogfont) return (FALSE);
6577
6578 memset (lplogfont, 0, sizeof (*lplogfont));
6579
6580 /* Set default value for each field. */
6581 #if 1
6582 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6583 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6584 lplogfont->lfQuality = DEFAULT_QUALITY;
6585 #else
6586 /* go for maximum quality */
6587 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6588 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6589 lplogfont->lfQuality = PROOF_QUALITY;
6590 #endif
6591
6592 lplogfont->lfCharSet = DEFAULT_CHARSET;
6593 lplogfont->lfWeight = FW_DONTCARE;
6594 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6595
6596 if (!lpxstr)
6597 return FALSE;
6598
6599 /* Provide a simple escape mechanism for specifying Windows font names
6600 * directly -- if font spec does not beginning with '-', assume this
6601 * format:
6602 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6603 */
6604
6605 if (*lpxstr == '-')
6606 {
6607 int fields, tem;
6608 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6609 width[10], resy[10], remainder[50];
6610 char * encoding;
6611 int dpi = one_w32_display_info.resy;
6612
6613 fields = sscanf (lpxstr,
6614 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
6615 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6616 if (fields == EOF)
6617 return (FALSE);
6618
6619 /* In the general case when wildcards cover more than one field,
6620 we don't know which field is which, so don't fill any in.
6621 However, we need to cope with this particular form, which is
6622 generated by font_list_1 (invoked by try_font_list):
6623 "-raster-6x10-*-gb2312*-*"
6624 and make sure to correctly parse the charset field. */
6625 if (fields == 3)
6626 {
6627 fields = sscanf (lpxstr,
6628 "-%*[^-]-%49[^-]-*-%49s",
6629 name, remainder);
6630 }
6631 else if (fields < 9)
6632 {
6633 fields = 0;
6634 remainder[0] = 0;
6635 }
6636
6637 if (fields > 0 && name[0] != '*')
6638 {
6639 int bufsize;
6640 unsigned char *buf;
6641
6642 setup_coding_system
6643 (Fcheck_coding_system (Vlocale_coding_system), &coding);
6644 coding.src_multibyte = 1;
6645 coding.dst_multibyte = 1;
6646 bufsize = encoding_buffer_size (&coding, strlen (name));
6647 buf = (unsigned char *) alloca (bufsize);
6648 coding.mode |= CODING_MODE_LAST_BLOCK;
6649 encode_coding (&coding, name, buf, strlen (name), bufsize);
6650 if (coding.produced >= LF_FACESIZE)
6651 coding.produced = LF_FACESIZE - 1;
6652 buf[coding.produced] = 0;
6653 strcpy (lplogfont->lfFaceName, buf);
6654 }
6655 else
6656 {
6657 lplogfont->lfFaceName[0] = '\0';
6658 }
6659
6660 fields--;
6661
6662 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6663
6664 fields--;
6665
6666 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6667
6668 fields--;
6669
6670 if (fields > 0 && pixels[0] != '*')
6671 lplogfont->lfHeight = atoi (pixels);
6672
6673 fields--;
6674 fields--;
6675 if (fields > 0 && resy[0] != '*')
6676 {
6677 tem = atoi (resy);
6678 if (tem > 0) dpi = tem;
6679 }
6680
6681 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6682 lplogfont->lfHeight = atoi (height) * dpi / 720;
6683
6684 if (fields > 0)
6685 lplogfont->lfPitchAndFamily =
6686 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6687
6688 fields--;
6689
6690 if (fields > 0 && width[0] != '*')
6691 lplogfont->lfWidth = atoi (width) / 10;
6692
6693 fields--;
6694
6695 /* Strip the trailing '-' if present. (it shouldn't be, as it
6696 fails the test against xlfd-tight-regexp in fontset.el). */
6697 {
6698 int len = strlen (remainder);
6699 if (len > 0 && remainder[len-1] == '-')
6700 remainder[len-1] = 0;
6701 }
6702 encoding = remainder;
6703 #if 0
6704 if (strncmp (encoding, "*-", 2) == 0)
6705 encoding += 2;
6706 #endif
6707 lplogfont->lfCharSet = x_to_w32_charset (encoding);
6708 }
6709 else
6710 {
6711 int fields;
6712 char name[100], height[10], width[10], weight[20];
6713
6714 fields = sscanf (lpxstr,
6715 "%99[^:]:%9[^:]:%9[^:]:%19s",
6716 name, height, width, weight);
6717
6718 if (fields == EOF) return (FALSE);
6719
6720 if (fields > 0)
6721 {
6722 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6723 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6724 }
6725 else
6726 {
6727 lplogfont->lfFaceName[0] = 0;
6728 }
6729
6730 fields--;
6731
6732 if (fields > 0)
6733 lplogfont->lfHeight = atoi (height);
6734
6735 fields--;
6736
6737 if (fields > 0)
6738 lplogfont->lfWidth = atoi (width);
6739
6740 fields--;
6741
6742 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6743 }
6744
6745 /* This makes TrueType fonts work better. */
6746 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6747
6748 return (TRUE);
6749 }
6750
6751 /* Strip the pixel height and point height from the given xlfd, and
6752 return the pixel height. If no pixel height is specified, calculate
6753 one from the point height, or if that isn't defined either, return
6754 0 (which usually signifies a scalable font).
6755 */
6756 static int
6757 xlfd_strip_height (char *fontname)
6758 {
6759 int pixel_height, field_number;
6760 char *read_from, *write_to;
6761
6762 xassert (fontname);
6763
6764 pixel_height = field_number = 0;
6765 write_to = NULL;
6766
6767 /* Look for height fields. */
6768 for (read_from = fontname; *read_from; read_from++)
6769 {
6770 if (*read_from == '-')
6771 {
6772 field_number++;
6773 if (field_number == 7) /* Pixel height. */
6774 {
6775 read_from++;
6776 write_to = read_from;
6777
6778 /* Find end of field. */
6779 for (;*read_from && *read_from != '-'; read_from++)
6780 ;
6781
6782 /* Split the fontname at end of field. */
6783 if (*read_from)
6784 {
6785 *read_from = '\0';
6786 read_from++;
6787 }
6788 pixel_height = atoi (write_to);
6789 /* Blank out field. */
6790 if (read_from > write_to)
6791 {
6792 *write_to = '-';
6793 write_to++;
6794 }
6795 /* If the pixel height field is at the end (partial xlfd),
6796 return now. */
6797 else
6798 return pixel_height;
6799
6800 /* If we got a pixel height, the point height can be
6801 ignored. Just blank it out and break now. */
6802 if (pixel_height)
6803 {
6804 /* Find end of point size field. */
6805 for (; *read_from && *read_from != '-'; read_from++)
6806 ;
6807
6808 if (*read_from)
6809 read_from++;
6810
6811 /* Blank out the point size field. */
6812 if (read_from > write_to)
6813 {
6814 *write_to = '-';
6815 write_to++;
6816 }
6817 else
6818 return pixel_height;
6819
6820 break;
6821 }
6822 /* If the point height is already blank, break now. */
6823 if (*read_from == '-')
6824 {
6825 read_from++;
6826 break;
6827 }
6828 }
6829 else if (field_number == 8)
6830 {
6831 /* If we didn't get a pixel height, try to get the point
6832 height and convert that. */
6833 int point_size;
6834 char *point_size_start = read_from++;
6835
6836 /* Find end of field. */
6837 for (; *read_from && *read_from != '-'; read_from++)
6838 ;
6839
6840 if (*read_from)
6841 {
6842 *read_from = '\0';
6843 read_from++;
6844 }
6845
6846 point_size = atoi (point_size_start);
6847
6848 /* Convert to pixel height. */
6849 pixel_height = point_size
6850 * one_w32_display_info.height_in / 720;
6851
6852 /* Blank out this field and break. */
6853 *write_to = '-';
6854 write_to++;
6855 break;
6856 }
6857 }
6858 }
6859
6860 /* Shift the rest of the font spec into place. */
6861 if (write_to && read_from > write_to)
6862 {
6863 for (; *read_from; read_from++, write_to++)
6864 *write_to = *read_from;
6865 *write_to = '\0';
6866 }
6867
6868 return pixel_height;
6869 }
6870
6871 /* Assume parameter 1 is fully qualified, no wildcards. */
6872 static BOOL
6873 w32_font_match (fontname, pattern)
6874 char * fontname;
6875 char * pattern;
6876 {
6877 char *regex = alloca (strlen (pattern) * 2 + 3);
6878 char *font_name_copy = alloca (strlen (fontname) + 1);
6879 char *ptr;
6880
6881 /* Copy fontname so we can modify it during comparison. */
6882 strcpy (font_name_copy, fontname);
6883
6884 ptr = regex;
6885 *ptr++ = '^';
6886
6887 /* Turn pattern into a regexp and do a regexp match. */
6888 for (; *pattern; pattern++)
6889 {
6890 if (*pattern == '?')
6891 *ptr++ = '.';
6892 else if (*pattern == '*')
6893 {
6894 *ptr++ = '.';
6895 *ptr++ = '*';
6896 }
6897 else
6898 *ptr++ = *pattern;
6899 }
6900 *ptr = '$';
6901 *(ptr + 1) = '\0';
6902
6903 /* Strip out font heights and compare them seperately, since
6904 rounding error can cause mismatches. This also allows a
6905 comparison between a font that declares only a pixel height and a
6906 pattern that declares the point height.
6907 */
6908 {
6909 int font_height, pattern_height;
6910
6911 font_height = xlfd_strip_height (font_name_copy);
6912 pattern_height = xlfd_strip_height (regex);
6913
6914 /* Compare now, and don't bother doing expensive regexp matching
6915 if the heights differ. */
6916 if (font_height && pattern_height && (font_height != pattern_height))
6917 return FALSE;
6918 }
6919
6920 return (fast_c_string_match_ignore_case (build_string (regex),
6921 font_name_copy) >= 0);
6922 }
6923
6924 /* Callback functions, and a structure holding info they need, for
6925 listing system fonts on W32. We need one set of functions to do the
6926 job properly, but these don't work on NT 3.51 and earlier, so we
6927 have a second set which don't handle character sets properly to
6928 fall back on.
6929
6930 In both cases, there are two passes made. The first pass gets one
6931 font from each family, the second pass lists all the fonts from
6932 each family. */
6933
6934 typedef struct enumfont_t
6935 {
6936 HDC hdc;
6937 int numFonts;
6938 LOGFONT logfont;
6939 XFontStruct *size_ref;
6940 Lisp_Object *pattern;
6941 Lisp_Object list;
6942 Lisp_Object *tail;
6943 } enumfont_t;
6944
6945
6946 static void
6947 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
6948
6949
6950 static int CALLBACK
6951 enum_font_cb2 (lplf, lptm, FontType, lpef)
6952 ENUMLOGFONT * lplf;
6953 NEWTEXTMETRIC * lptm;
6954 int FontType;
6955 enumfont_t * lpef;
6956 {
6957 /* Ignore struck out and underlined versions of fonts. */
6958 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
6959 return 1;
6960
6961 /* Only return fonts with names starting with @ if they were
6962 explicitly specified, since Microsoft uses an initial @ to
6963 denote fonts for vertical writing, without providing a more
6964 convenient way of identifying them. */
6965 if (lplf->elfLogFont.lfFaceName[0] == '@'
6966 && lpef->logfont.lfFaceName[0] != '@')
6967 return 1;
6968
6969 /* Check that the character set matches if it was specified */
6970 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
6971 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
6972 return 1;
6973
6974 {
6975 char buf[100];
6976 Lisp_Object width = Qnil;
6977 Lisp_Object charset_list = Qnil;
6978 char *charset = NULL;
6979
6980 /* Truetype fonts do not report their true metrics until loaded */
6981 if (FontType != RASTER_FONTTYPE)
6982 {
6983 if (!NILP (*(lpef->pattern)))
6984 {
6985 /* Scalable fonts are as big as you want them to be. */
6986 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
6987 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
6988 width = make_number (lpef->logfont.lfWidth);
6989 }
6990 else
6991 {
6992 lplf->elfLogFont.lfHeight = 0;
6993 lplf->elfLogFont.lfWidth = 0;
6994 }
6995 }
6996
6997 /* Make sure the height used here is the same as everywhere
6998 else (ie character height, not cell height). */
6999 if (lplf->elfLogFont.lfHeight > 0)
7000 {
7001 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
7002 if (FontType == RASTER_FONTTYPE)
7003 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
7004 else
7005 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
7006 }
7007
7008 if (!NILP (*(lpef->pattern)))
7009 {
7010 charset = xlfd_charset_of_font (XSTRING(*(lpef->pattern))->data);
7011
7012 /* Ensure that charset is valid for this font.
7013 Continue if invalid in case charset contains a wildcard. */
7014 if (charset
7015 && (x_to_w32_charset (charset) != lplf->elfLogFont.lfCharSet))
7016 charset = NULL;
7017 }
7018
7019 if (charset)
7020 charset_list = Fcons (build_string (charset), Qnil);
7021 else
7022 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
7023
7024 /* Loop through the charsets. */
7025 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
7026 {
7027 Lisp_Object this_charset = Fcar (charset_list);
7028 charset = XSTRING (this_charset)->data;
7029
7030 /* List bold and italic variations if w32-enable-synthesized-fonts
7031 is non-nil and this is a plain font. */
7032 if (w32_enable_synthesized_fonts
7033 && lplf->elfLogFont.lfWeight == FW_NORMAL
7034 && lplf->elfLogFont.lfItalic == FALSE)
7035 {
7036 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7037 charset, width);
7038 /* bold. */
7039 lplf->elfLogFont.lfWeight = FW_BOLD;
7040 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7041 charset, width);
7042 /* bold italic. */
7043 lplf->elfLogFont.lfItalic = TRUE;
7044 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7045 charset, width);
7046 /* italic. */
7047 lplf->elfLogFont.lfWeight = FW_NORMAL;
7048 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7049 charset, width);
7050 }
7051 else
7052 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7053 charset, width);
7054 }
7055 }
7056
7057 return 1;
7058 }
7059
7060 static void
7061 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
7062 enumfont_t * lpef;
7063 LOGFONT * logfont;
7064 char * match_charset;
7065 Lisp_Object width;
7066 {
7067 char buf[100];
7068
7069 if (!w32_to_x_font (logfont, buf, 100, match_charset))
7070 return;
7071
7072 if (NILP (*(lpef->pattern))
7073 || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
7074 {
7075 /* Check if we already listed this font. This may happen if
7076 w32_enable_synthesized_fonts is non-nil, and there are real
7077 bold and italic versions of the font. */
7078 Lisp_Object font_name = build_string (buf);
7079 if (NILP (Fmember (font_name, lpef->list)))
7080 {
7081 *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
7082 lpef->tail = &(XCDR (*lpef->tail));
7083 lpef->numFonts++;
7084 }
7085 }
7086 }
7087
7088
7089 static int CALLBACK
7090 enum_font_cb1 (lplf, lptm, FontType, lpef)
7091 ENUMLOGFONT * lplf;
7092 NEWTEXTMETRIC * lptm;
7093 int FontType;
7094 enumfont_t * lpef;
7095 {
7096 return EnumFontFamilies (lpef->hdc,
7097 lplf->elfLogFont.lfFaceName,
7098 (FONTENUMPROC) enum_font_cb2,
7099 (LPARAM) lpef);
7100 }
7101
7102
7103 static int CALLBACK
7104 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
7105 ENUMLOGFONTEX * lplf;
7106 NEWTEXTMETRICEX * lptm;
7107 int font_type;
7108 enumfont_t * lpef;
7109 {
7110 /* We are not interested in the extra info we get back from the 'Ex
7111 version - only the fact that we get character set variations
7112 enumerated seperately. */
7113 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
7114 font_type, lpef);
7115 }
7116
7117 static int CALLBACK
7118 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
7119 ENUMLOGFONTEX * lplf;
7120 NEWTEXTMETRICEX * lptm;
7121 int font_type;
7122 enumfont_t * lpef;
7123 {
7124 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7125 FARPROC enum_font_families_ex
7126 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7127 /* We don't really expect EnumFontFamiliesEx to disappear once we
7128 get here, so don't bother handling it gracefully. */
7129 if (enum_font_families_ex == NULL)
7130 error ("gdi32.dll has disappeared!");
7131 return enum_font_families_ex (lpef->hdc,
7132 &lplf->elfLogFont,
7133 (FONTENUMPROC) enum_fontex_cb2,
7134 (LPARAM) lpef, 0);
7135 }
7136
7137 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
7138 and xterm.c in Emacs 20.3) */
7139
7140 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
7141 {
7142 char *fontname, *ptnstr;
7143 Lisp_Object list, tem, newlist = Qnil;
7144 int n_fonts = 0;
7145
7146 list = Vw32_bdf_filename_alist;
7147 ptnstr = XSTRING (pattern)->data;
7148
7149 for ( ; CONSP (list); list = XCDR (list))
7150 {
7151 tem = XCAR (list);
7152 if (CONSP (tem))
7153 fontname = XSTRING (XCAR (tem))->data;
7154 else if (STRINGP (tem))
7155 fontname = XSTRING (tem)->data;
7156 else
7157 continue;
7158
7159 if (w32_font_match (fontname, ptnstr))
7160 {
7161 newlist = Fcons (XCAR (tem), newlist);
7162 n_fonts++;
7163 if (n_fonts >= max_names)
7164 break;
7165 }
7166 }
7167
7168 return newlist;
7169 }
7170
7171
7172 /* Return a list of names of available fonts matching PATTERN on frame
7173 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
7174 to be listed. Frame F NULL means we have not yet created any
7175 frame, which means we can't get proper size info, as we don't have
7176 a device context to use for GetTextMetrics.
7177 MAXNAMES sets a limit on how many fonts to match. */
7178
7179 Lisp_Object
7180 w32_list_fonts (f, pattern, size, maxnames)
7181 struct frame *f;
7182 Lisp_Object pattern;
7183 int size;
7184 int maxnames;
7185 {
7186 Lisp_Object patterns, key = Qnil, tem, tpat;
7187 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
7188 struct w32_display_info *dpyinfo = &one_w32_display_info;
7189 int n_fonts = 0;
7190
7191 patterns = Fassoc (pattern, Valternate_fontname_alist);
7192 if (NILP (patterns))
7193 patterns = Fcons (pattern, Qnil);
7194
7195 for (; CONSP (patterns); patterns = XCDR (patterns))
7196 {
7197 enumfont_t ef;
7198 int codepage;
7199
7200 tpat = XCAR (patterns);
7201
7202 if (!STRINGP (tpat))
7203 continue;
7204
7205 /* Avoid expensive EnumFontFamilies functions if we are not
7206 going to be able to output one of these anyway. */
7207 codepage = w32_codepage_for_font (XSTRING (tpat)->data);
7208 if (codepage != CP_8BIT && codepage != CP_UNICODE
7209 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
7210 && !IsValidCodePage(codepage))
7211 continue;
7212
7213 /* See if we cached the result for this particular query.
7214 The cache is an alist of the form:
7215 ((PATTERN (FONTNAME . WIDTH) ...) ...)
7216 */
7217 if (tem = XCDR (dpyinfo->name_list_element),
7218 !NILP (list = Fassoc (tpat, tem)))
7219 {
7220 list = Fcdr_safe (list);
7221 /* We have a cached list. Don't have to get the list again. */
7222 goto label_cached;
7223 }
7224
7225 BLOCK_INPUT;
7226 /* At first, put PATTERN in the cache. */
7227 list = Qnil;
7228 ef.pattern = &tpat;
7229 ef.list = list;
7230 ef.tail = &list;
7231 ef.numFonts = 0;
7232
7233 /* Use EnumFontFamiliesEx where it is available, as it knows
7234 about character sets. Fall back to EnumFontFamilies for
7235 older versions of NT that don't support the 'Ex function. */
7236 x_to_w32_font (XSTRING (tpat)->data, &ef.logfont);
7237 {
7238 LOGFONT font_match_pattern;
7239 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7240 FARPROC enum_font_families_ex
7241 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7242
7243 /* We do our own pattern matching so we can handle wildcards. */
7244 font_match_pattern.lfFaceName[0] = 0;
7245 font_match_pattern.lfPitchAndFamily = 0;
7246 /* We can use the charset, because if it is a wildcard it will
7247 be DEFAULT_CHARSET anyway. */
7248 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
7249
7250 ef.hdc = GetDC (dpyinfo->root_window);
7251
7252 if (enum_font_families_ex)
7253 enum_font_families_ex (ef.hdc,
7254 &font_match_pattern,
7255 (FONTENUMPROC) enum_fontex_cb1,
7256 (LPARAM) &ef, 0);
7257 else
7258 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
7259 (LPARAM)&ef);
7260
7261 ReleaseDC (dpyinfo->root_window, ef.hdc);
7262 }
7263
7264 UNBLOCK_INPUT;
7265
7266 /* Make a list of the fonts we got back.
7267 Store that in the font cache for the display. */
7268 XSETCDR (dpyinfo->name_list_element,
7269 Fcons (Fcons (tpat, list),
7270 XCDR (dpyinfo->name_list_element)));
7271
7272 label_cached:
7273 if (NILP (list)) continue; /* Try the remaining alternatives. */
7274
7275 newlist = second_best = Qnil;
7276
7277 /* Make a list of the fonts that have the right width. */
7278 for (; CONSP (list); list = XCDR (list))
7279 {
7280 int found_size;
7281 tem = XCAR (list);
7282
7283 if (!CONSP (tem))
7284 continue;
7285 if (NILP (XCAR (tem)))
7286 continue;
7287 if (!size)
7288 {
7289 newlist = Fcons (XCAR (tem), newlist);
7290 n_fonts++;
7291 if (n_fonts >= maxnames)
7292 break;
7293 else
7294 continue;
7295 }
7296 if (!INTEGERP (XCDR (tem)))
7297 {
7298 /* Since we don't yet know the size of the font, we must
7299 load it and try GetTextMetrics. */
7300 W32FontStruct thisinfo;
7301 LOGFONT lf;
7302 HDC hdc;
7303 HANDLE oldobj;
7304
7305 if (!x_to_w32_font (XSTRING (XCAR (tem))->data, &lf))
7306 continue;
7307
7308 BLOCK_INPUT;
7309 thisinfo.bdf = NULL;
7310 thisinfo.hfont = CreateFontIndirect (&lf);
7311 if (thisinfo.hfont == NULL)
7312 continue;
7313
7314 hdc = GetDC (dpyinfo->root_window);
7315 oldobj = SelectObject (hdc, thisinfo.hfont);
7316 if (GetTextMetrics (hdc, &thisinfo.tm))
7317 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
7318 else
7319 XSETCDR (tem, make_number (0));
7320 SelectObject (hdc, oldobj);
7321 ReleaseDC (dpyinfo->root_window, hdc);
7322 DeleteObject(thisinfo.hfont);
7323 UNBLOCK_INPUT;
7324 }
7325 found_size = XINT (XCDR (tem));
7326 if (found_size == size)
7327 {
7328 newlist = Fcons (XCAR (tem), newlist);
7329 n_fonts++;
7330 if (n_fonts >= maxnames)
7331 break;
7332 }
7333 /* keep track of the closest matching size in case
7334 no exact match is found. */
7335 else if (found_size > 0)
7336 {
7337 if (NILP (second_best))
7338 second_best = tem;
7339
7340 else if (found_size < size)
7341 {
7342 if (XINT (XCDR (second_best)) > size
7343 || XINT (XCDR (second_best)) < found_size)
7344 second_best = tem;
7345 }
7346 else
7347 {
7348 if (XINT (XCDR (second_best)) > size
7349 && XINT (XCDR (second_best)) >
7350 found_size)
7351 second_best = tem;
7352 }
7353 }
7354 }
7355
7356 if (!NILP (newlist))
7357 break;
7358 else if (!NILP (second_best))
7359 {
7360 newlist = Fcons (XCAR (second_best), Qnil);
7361 break;
7362 }
7363 }
7364
7365 /* Include any bdf fonts. */
7366 if (n_fonts < maxnames)
7367 {
7368 Lisp_Object combined[2];
7369 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
7370 combined[1] = newlist;
7371 newlist = Fnconc(2, combined);
7372 }
7373
7374 return newlist;
7375 }
7376
7377
7378 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
7379 struct font_info *
7380 w32_get_font_info (f, font_idx)
7381 FRAME_PTR f;
7382 int font_idx;
7383 {
7384 return (FRAME_W32_FONT_TABLE (f) + font_idx);
7385 }
7386
7387
7388 struct font_info*
7389 w32_query_font (struct frame *f, char *fontname)
7390 {
7391 int i;
7392 struct font_info *pfi;
7393
7394 pfi = FRAME_W32_FONT_TABLE (f);
7395
7396 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
7397 {
7398 if (strcmp(pfi->name, fontname) == 0) return pfi;
7399 }
7400
7401 return NULL;
7402 }
7403
7404 /* Find a CCL program for a font specified by FONTP, and set the member
7405 `encoder' of the structure. */
7406
7407 void
7408 w32_find_ccl_program (fontp)
7409 struct font_info *fontp;
7410 {
7411 Lisp_Object list, elt;
7412
7413 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7414 {
7415 elt = XCAR (list);
7416 if (CONSP (elt)
7417 && STRINGP (XCAR (elt))
7418 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7419 >= 0))
7420 break;
7421 }
7422 if (! NILP (list))
7423 {
7424 struct ccl_program *ccl
7425 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7426
7427 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7428 xfree (ccl);
7429 else
7430 fontp->font_encoder = ccl;
7431 }
7432 }
7433
7434 \f
7435 /* Find BDF files in a specified directory. (use GCPRO when calling,
7436 as this calls lisp to get a directory listing). */
7437 static Lisp_Object
7438 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
7439 {
7440 Lisp_Object filelist, list = Qnil;
7441 char fontname[100];
7442
7443 if (!STRINGP(directory))
7444 return Qnil;
7445
7446 filelist = Fdirectory_files (directory, Qt,
7447 build_string (".*\\.[bB][dD][fF]"), Qt);
7448
7449 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7450 {
7451 Lisp_Object filename = XCAR (filelist);
7452 if (w32_BDF_to_x_font (XSTRING (filename)->data, fontname, 100))
7453 store_in_alist (&list, build_string (fontname), filename);
7454 }
7455 return list;
7456 }
7457
7458 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
7459 1, 1, 0,
7460 doc: /* Return a list of BDF fonts in DIR.
7461 The list is suitable for appending to w32-bdf-filename-alist. Fonts
7462 which do not contain an xlfd description will not be included in the
7463 list. DIR may be a list of directories. */)
7464 (directory)
7465 Lisp_Object directory;
7466 {
7467 Lisp_Object list = Qnil;
7468 struct gcpro gcpro1, gcpro2;
7469
7470 if (!CONSP (directory))
7471 return w32_find_bdf_fonts_in_dir (directory);
7472
7473 for ( ; CONSP (directory); directory = XCDR (directory))
7474 {
7475 Lisp_Object pair[2];
7476 pair[0] = list;
7477 pair[1] = Qnil;
7478 GCPRO2 (directory, list);
7479 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7480 list = Fnconc( 2, pair );
7481 UNGCPRO;
7482 }
7483 return list;
7484 }
7485
7486 \f
7487 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7488 doc: /* Internal function called by `color-defined-p', which see. */)
7489 (color, frame)
7490 Lisp_Object color, frame;
7491 {
7492 XColor foo;
7493 FRAME_PTR f = check_x_frame (frame);
7494
7495 CHECK_STRING (color);
7496
7497 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7498 return Qt;
7499 else
7500 return Qnil;
7501 }
7502
7503 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7504 doc: /* Internal function called by `color-values', which see. */)
7505 (color, frame)
7506 Lisp_Object color, frame;
7507 {
7508 XColor foo;
7509 FRAME_PTR f = check_x_frame (frame);
7510
7511 CHECK_STRING (color);
7512
7513 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7514 {
7515 Lisp_Object rgb[3];
7516
7517 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7518 | GetRValue (foo.pixel));
7519 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7520 | GetGValue (foo.pixel));
7521 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7522 | GetBValue (foo.pixel));
7523 return Flist (3, rgb);
7524 }
7525 else
7526 return Qnil;
7527 }
7528
7529 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7530 doc: /* Internal function called by `display-color-p', which see. */)
7531 (display)
7532 Lisp_Object display;
7533 {
7534 struct w32_display_info *dpyinfo = check_x_display_info (display);
7535
7536 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7537 return Qnil;
7538
7539 return Qt;
7540 }
7541
7542 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
7543 Sx_display_grayscale_p, 0, 1, 0,
7544 doc: /* Return t if the X display supports shades of gray.
7545 Note that color displays do support shades of gray.
7546 The optional argument DISPLAY specifies which display to ask about.
7547 DISPLAY should be either a frame or a display name (a string).
7548 If omitted or nil, that stands for the selected frame's display. */)
7549 (display)
7550 Lisp_Object display;
7551 {
7552 struct w32_display_info *dpyinfo = check_x_display_info (display);
7553
7554 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7555 return Qnil;
7556
7557 return Qt;
7558 }
7559
7560 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
7561 Sx_display_pixel_width, 0, 1, 0,
7562 doc: /* Returns the width in pixels of DISPLAY.
7563 The optional argument DISPLAY specifies which display to ask about.
7564 DISPLAY should be either a frame or a display name (a string).
7565 If omitted or nil, that stands for the selected frame's display. */)
7566 (display)
7567 Lisp_Object display;
7568 {
7569 struct w32_display_info *dpyinfo = check_x_display_info (display);
7570
7571 return make_number (dpyinfo->width);
7572 }
7573
7574 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7575 Sx_display_pixel_height, 0, 1, 0,
7576 doc: /* Returns the height in pixels of DISPLAY.
7577 The optional argument DISPLAY specifies which display to ask about.
7578 DISPLAY should be either a frame or a display name (a string).
7579 If omitted or nil, that stands for the selected frame's display. */)
7580 (display)
7581 Lisp_Object display;
7582 {
7583 struct w32_display_info *dpyinfo = check_x_display_info (display);
7584
7585 return make_number (dpyinfo->height);
7586 }
7587
7588 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7589 0, 1, 0,
7590 doc: /* Returns the number of bitplanes of DISPLAY.
7591 The optional argument DISPLAY specifies which display to ask about.
7592 DISPLAY should be either a frame or a display name (a string).
7593 If omitted or nil, that stands for the selected frame's display. */)
7594 (display)
7595 Lisp_Object display;
7596 {
7597 struct w32_display_info *dpyinfo = check_x_display_info (display);
7598
7599 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7600 }
7601
7602 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7603 0, 1, 0,
7604 doc: /* Returns the number of color cells of DISPLAY.
7605 The optional argument DISPLAY specifies which display to ask about.
7606 DISPLAY should be either a frame or a display name (a string).
7607 If omitted or nil, that stands for the selected frame's display. */)
7608 (display)
7609 Lisp_Object display;
7610 {
7611 struct w32_display_info *dpyinfo = check_x_display_info (display);
7612 HDC hdc;
7613 int cap;
7614
7615 hdc = GetDC (dpyinfo->root_window);
7616 if (dpyinfo->has_palette)
7617 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7618 else
7619 cap = GetDeviceCaps (hdc,NUMCOLORS);
7620
7621 if (cap < 0)
7622 cap = 1 << (dpyinfo->n_planes * dpyinfo->n_cbits);
7623
7624 ReleaseDC (dpyinfo->root_window, hdc);
7625
7626 return make_number (cap);
7627 }
7628
7629 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7630 Sx_server_max_request_size,
7631 0, 1, 0,
7632 doc: /* Returns the maximum request size of the server of DISPLAY.
7633 The optional argument DISPLAY specifies which display to ask about.
7634 DISPLAY should be either a frame or a display name (a string).
7635 If omitted or nil, that stands for the selected frame's display. */)
7636 (display)
7637 Lisp_Object display;
7638 {
7639 struct w32_display_info *dpyinfo = check_x_display_info (display);
7640
7641 return make_number (1);
7642 }
7643
7644 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7645 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
7646 The optional argument DISPLAY specifies which display to ask about.
7647 DISPLAY should be either a frame or a display name (a string).
7648 If omitted or nil, that stands for the selected frame's display. */)
7649 (display)
7650 Lisp_Object display;
7651 {
7652 return build_string ("Microsoft Corp.");
7653 }
7654
7655 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7656 doc: /* Returns the version numbers of the server of DISPLAY.
7657 The value is a list of three integers: the major and minor
7658 version numbers, and the vendor-specific release
7659 number. See also the function `x-server-vendor'.
7660
7661 The optional argument DISPLAY specifies which display to ask about.
7662 DISPLAY should be either a frame or a display name (a string).
7663 If omitted or nil, that stands for the selected frame's display. */)
7664 (display)
7665 Lisp_Object display;
7666 {
7667 return Fcons (make_number (w32_major_version),
7668 Fcons (make_number (w32_minor_version),
7669 Fcons (make_number (w32_build_number), Qnil)));
7670 }
7671
7672 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7673 doc: /* Returns the number of screens on the server of DISPLAY.
7674 The optional argument DISPLAY specifies which display to ask about.
7675 DISPLAY should be either a frame or a display name (a string).
7676 If omitted or nil, that stands for the selected frame's display. */)
7677 (display)
7678 Lisp_Object display;
7679 {
7680 return make_number (1);
7681 }
7682
7683 DEFUN ("x-display-mm-height", Fx_display_mm_height,
7684 Sx_display_mm_height, 0, 1, 0,
7685 doc: /* Returns the height in millimeters of DISPLAY.
7686 The optional argument DISPLAY specifies which display to ask about.
7687 DISPLAY should be either a frame or a display name (a string).
7688 If omitted or nil, that stands for the selected frame's display. */)
7689 (display)
7690 Lisp_Object display;
7691 {
7692 struct w32_display_info *dpyinfo = check_x_display_info (display);
7693 HDC hdc;
7694 int cap;
7695
7696 hdc = GetDC (dpyinfo->root_window);
7697
7698 cap = GetDeviceCaps (hdc, VERTSIZE);
7699
7700 ReleaseDC (dpyinfo->root_window, hdc);
7701
7702 return make_number (cap);
7703 }
7704
7705 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7706 doc: /* Returns the width in millimeters of DISPLAY.
7707 The optional argument DISPLAY specifies which display to ask about.
7708 DISPLAY should be either a frame or a display name (a string).
7709 If omitted or nil, that stands for the selected frame's display. */)
7710 (display)
7711 Lisp_Object display;
7712 {
7713 struct w32_display_info *dpyinfo = check_x_display_info (display);
7714
7715 HDC hdc;
7716 int cap;
7717
7718 hdc = GetDC (dpyinfo->root_window);
7719
7720 cap = GetDeviceCaps (hdc, HORZSIZE);
7721
7722 ReleaseDC (dpyinfo->root_window, hdc);
7723
7724 return make_number (cap);
7725 }
7726
7727 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7728 Sx_display_backing_store, 0, 1, 0,
7729 doc: /* Returns an indication of whether DISPLAY does backing store.
7730 The value may be `always', `when-mapped', or `not-useful'.
7731 The optional argument DISPLAY specifies which display to ask about.
7732 DISPLAY should be either a frame or a display name (a string).
7733 If omitted or nil, that stands for the selected frame's display. */)
7734 (display)
7735 Lisp_Object display;
7736 {
7737 return intern ("not-useful");
7738 }
7739
7740 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7741 Sx_display_visual_class, 0, 1, 0,
7742 doc: /* Returns the visual class of DISPLAY.
7743 The value is one of the symbols `static-gray', `gray-scale',
7744 `static-color', `pseudo-color', `true-color', or `direct-color'.
7745
7746 The optional argument DISPLAY specifies which display to ask about.
7747 DISPLAY should be either a frame or a display name (a string).
7748 If omitted or nil, that stands for the selected frame's display. */)
7749 (display)
7750 Lisp_Object display;
7751 {
7752 struct w32_display_info *dpyinfo = check_x_display_info (display);
7753 Lisp_Object result = Qnil;
7754
7755 if (dpyinfo->has_palette)
7756 result = intern ("pseudo-color");
7757 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
7758 result = intern ("static-grey");
7759 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
7760 result = intern ("static-color");
7761 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
7762 result = intern ("true-color");
7763
7764 return result;
7765 }
7766
7767 DEFUN ("x-display-save-under", Fx_display_save_under,
7768 Sx_display_save_under, 0, 1, 0,
7769 doc: /* Returns t if DISPLAY supports the save-under feature.
7770 The optional argument DISPLAY specifies which display to ask about.
7771 DISPLAY should be either a frame or a display name (a string).
7772 If omitted or nil, that stands for the selected frame's display. */)
7773 (display)
7774 Lisp_Object display;
7775 {
7776 return Qnil;
7777 }
7778 \f
7779 int
7780 x_pixel_width (f)
7781 register struct frame *f;
7782 {
7783 return PIXEL_WIDTH (f);
7784 }
7785
7786 int
7787 x_pixel_height (f)
7788 register struct frame *f;
7789 {
7790 return PIXEL_HEIGHT (f);
7791 }
7792
7793 int
7794 x_char_width (f)
7795 register struct frame *f;
7796 {
7797 return FONT_WIDTH (f->output_data.w32->font);
7798 }
7799
7800 int
7801 x_char_height (f)
7802 register struct frame *f;
7803 {
7804 return f->output_data.w32->line_height;
7805 }
7806
7807 int
7808 x_screen_planes (f)
7809 register struct frame *f;
7810 {
7811 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7812 }
7813 \f
7814 /* Return the display structure for the display named NAME.
7815 Open a new connection if necessary. */
7816
7817 struct w32_display_info *
7818 x_display_info_for_name (name)
7819 Lisp_Object name;
7820 {
7821 Lisp_Object names;
7822 struct w32_display_info *dpyinfo;
7823
7824 CHECK_STRING (name);
7825
7826 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7827 dpyinfo;
7828 dpyinfo = dpyinfo->next, names = XCDR (names))
7829 {
7830 Lisp_Object tem;
7831 tem = Fstring_equal (XCAR (XCAR (names)), name);
7832 if (!NILP (tem))
7833 return dpyinfo;
7834 }
7835
7836 /* Use this general default value to start with. */
7837 Vx_resource_name = Vinvocation_name;
7838
7839 validate_x_resource_name ();
7840
7841 dpyinfo = w32_term_init (name, (unsigned char *)0,
7842 (char *) XSTRING (Vx_resource_name)->data);
7843
7844 if (dpyinfo == 0)
7845 error ("Cannot connect to server %s", XSTRING (name)->data);
7846
7847 w32_in_use = 1;
7848 XSETFASTINT (Vwindow_system_version, 3);
7849
7850 return dpyinfo;
7851 }
7852
7853 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7854 1, 3, 0, doc: /* Open a connection to a server.
7855 DISPLAY is the name of the display to connect to.
7856 Optional second arg XRM-STRING is a string of resources in xrdb format.
7857 If the optional third arg MUST-SUCCEED is non-nil,
7858 terminate Emacs if we can't open the connection. */)
7859 (display, xrm_string, must_succeed)
7860 Lisp_Object display, xrm_string, must_succeed;
7861 {
7862 unsigned char *xrm_option;
7863 struct w32_display_info *dpyinfo;
7864
7865 /* If initialization has already been done, return now to avoid
7866 overwriting critical parts of one_w32_display_info. */
7867 if (w32_in_use)
7868 return Qnil;
7869
7870 CHECK_STRING (display);
7871 if (! NILP (xrm_string))
7872 CHECK_STRING (xrm_string);
7873
7874 if (! EQ (Vwindow_system, intern ("w32")))
7875 error ("Not using Microsoft Windows");
7876
7877 /* Allow color mapping to be defined externally; first look in user's
7878 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
7879 {
7880 Lisp_Object color_file;
7881 struct gcpro gcpro1;
7882
7883 color_file = build_string("~/rgb.txt");
7884
7885 GCPRO1 (color_file);
7886
7887 if (NILP (Ffile_readable_p (color_file)))
7888 color_file =
7889 Fexpand_file_name (build_string ("rgb.txt"),
7890 Fsymbol_value (intern ("data-directory")));
7891
7892 Vw32_color_map = Fw32_load_color_file (color_file);
7893
7894 UNGCPRO;
7895 }
7896 if (NILP (Vw32_color_map))
7897 Vw32_color_map = Fw32_default_color_map ();
7898
7899 if (! NILP (xrm_string))
7900 xrm_option = (unsigned char *) XSTRING (xrm_string)->data;
7901 else
7902 xrm_option = (unsigned char *) 0;
7903
7904 /* Use this general default value to start with. */
7905 /* First remove .exe suffix from invocation-name - it looks ugly. */
7906 {
7907 char basename[ MAX_PATH ], *str;
7908
7909 strcpy (basename, XSTRING (Vinvocation_name)->data);
7910 str = strrchr (basename, '.');
7911 if (str) *str = 0;
7912 Vinvocation_name = build_string (basename);
7913 }
7914 Vx_resource_name = Vinvocation_name;
7915
7916 validate_x_resource_name ();
7917
7918 /* This is what opens the connection and sets x_current_display.
7919 This also initializes many symbols, such as those used for input. */
7920 dpyinfo = w32_term_init (display, xrm_option,
7921 (char *) XSTRING (Vx_resource_name)->data);
7922
7923 if (dpyinfo == 0)
7924 {
7925 if (!NILP (must_succeed))
7926 fatal ("Cannot connect to server %s.\n",
7927 XSTRING (display)->data);
7928 else
7929 error ("Cannot connect to server %s", XSTRING (display)->data);
7930 }
7931
7932 w32_in_use = 1;
7933
7934 XSETFASTINT (Vwindow_system_version, 3);
7935 return Qnil;
7936 }
7937
7938 DEFUN ("x-close-connection", Fx_close_connection,
7939 Sx_close_connection, 1, 1, 0,
7940 doc: /* Close the connection to DISPLAY's server.
7941 For DISPLAY, specify either a frame or a display name (a string).
7942 If DISPLAY is nil, that stands for the selected frame's display. */)
7943 (display)
7944 Lisp_Object display;
7945 {
7946 struct w32_display_info *dpyinfo = check_x_display_info (display);
7947 int i;
7948
7949 if (dpyinfo->reference_count > 0)
7950 error ("Display still has frames on it");
7951
7952 BLOCK_INPUT;
7953 /* Free the fonts in the font table. */
7954 for (i = 0; i < dpyinfo->n_fonts; i++)
7955 if (dpyinfo->font_table[i].name)
7956 {
7957 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
7958 xfree (dpyinfo->font_table[i].full_name);
7959 xfree (dpyinfo->font_table[i].name);
7960 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
7961 }
7962 x_destroy_all_bitmaps (dpyinfo);
7963
7964 x_delete_display (dpyinfo);
7965 UNBLOCK_INPUT;
7966
7967 return Qnil;
7968 }
7969
7970 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
7971 doc: /* Return the list of display names that Emacs has connections to. */)
7972 ()
7973 {
7974 Lisp_Object tail, result;
7975
7976 result = Qnil;
7977 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
7978 result = Fcons (XCAR (XCAR (tail)), result);
7979
7980 return result;
7981 }
7982
7983 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7984 doc: /* This is a noop on W32 systems. */)
7985 (on, display)
7986 Lisp_Object display, on;
7987 {
7988 return Qnil;
7989 }
7990
7991 \f
7992 \f
7993 /***********************************************************************
7994 Image types
7995 ***********************************************************************/
7996
7997 /* Value is the number of elements of vector VECTOR. */
7998
7999 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
8000
8001 /* List of supported image types. Use define_image_type to add new
8002 types. Use lookup_image_type to find a type for a given symbol. */
8003
8004 static struct image_type *image_types;
8005
8006 /* The symbol `image' which is the car of the lists used to represent
8007 images in Lisp. */
8008
8009 extern Lisp_Object Qimage;
8010
8011 /* The symbol `xbm' which is used as the type symbol for XBM images. */
8012
8013 Lisp_Object Qxbm;
8014
8015 /* Keywords. */
8016
8017 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
8018 extern Lisp_Object QCdata;
8019 Lisp_Object QCtype, QCascent, QCmargin, QCrelief;
8020 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
8021 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
8022
8023 /* Other symbols. */
8024
8025 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
8026
8027 /* Time in seconds after which images should be removed from the cache
8028 if not displayed. */
8029
8030 Lisp_Object Vimage_cache_eviction_delay;
8031
8032 /* Function prototypes. */
8033
8034 static void define_image_type P_ ((struct image_type *type));
8035 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
8036 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
8037 static void x_laplace P_ ((struct frame *, struct image *));
8038 static void x_emboss P_ ((struct frame *, struct image *));
8039 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
8040 Lisp_Object));
8041
8042
8043 /* Define a new image type from TYPE. This adds a copy of TYPE to
8044 image_types and adds the symbol *TYPE->type to Vimage_types. */
8045
8046 static void
8047 define_image_type (type)
8048 struct image_type *type;
8049 {
8050 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
8051 The initialized data segment is read-only. */
8052 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
8053 bcopy (type, p, sizeof *p);
8054 p->next = image_types;
8055 image_types = p;
8056 Vimage_types = Fcons (*p->type, Vimage_types);
8057 }
8058
8059
8060 /* Look up image type SYMBOL, and return a pointer to its image_type
8061 structure. Value is null if SYMBOL is not a known image type. */
8062
8063 static INLINE struct image_type *
8064 lookup_image_type (symbol)
8065 Lisp_Object symbol;
8066 {
8067 struct image_type *type;
8068
8069 for (type = image_types; type; type = type->next)
8070 if (EQ (symbol, *type->type))
8071 break;
8072
8073 return type;
8074 }
8075
8076
8077 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
8078 valid image specification is a list whose car is the symbol
8079 `image', and whose rest is a property list. The property list must
8080 contain a value for key `:type'. That value must be the name of a
8081 supported image type. The rest of the property list depends on the
8082 image type. */
8083
8084 int
8085 valid_image_p (object)
8086 Lisp_Object object;
8087 {
8088 int valid_p = 0;
8089
8090 if (CONSP (object) && EQ (XCAR (object), Qimage))
8091 {
8092 Lisp_Object tem;
8093
8094 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
8095 if (EQ (XCAR (tem), QCtype))
8096 {
8097 tem = XCDR (tem);
8098 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
8099 {
8100 struct image_type *type;
8101 type = lookup_image_type (XCAR (tem));
8102 if (type)
8103 valid_p = type->valid_p (object);
8104 }
8105
8106 break;
8107 }
8108 }
8109
8110 return valid_p;
8111 }
8112
8113
8114 /* Log error message with format string FORMAT and argument ARG.
8115 Signaling an error, e.g. when an image cannot be loaded, is not a
8116 good idea because this would interrupt redisplay, and the error
8117 message display would lead to another redisplay. This function
8118 therefore simply displays a message. */
8119
8120 static void
8121 image_error (format, arg1, arg2)
8122 char *format;
8123 Lisp_Object arg1, arg2;
8124 {
8125 add_to_log (format, arg1, arg2);
8126 }
8127
8128
8129 \f
8130 /***********************************************************************
8131 Image specifications
8132 ***********************************************************************/
8133
8134 enum image_value_type
8135 {
8136 IMAGE_DONT_CHECK_VALUE_TYPE,
8137 IMAGE_STRING_VALUE,
8138 IMAGE_STRING_OR_NIL_VALUE,
8139 IMAGE_SYMBOL_VALUE,
8140 IMAGE_POSITIVE_INTEGER_VALUE,
8141 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
8142 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
8143 IMAGE_ASCENT_VALUE,
8144 IMAGE_INTEGER_VALUE,
8145 IMAGE_FUNCTION_VALUE,
8146 IMAGE_NUMBER_VALUE,
8147 IMAGE_BOOL_VALUE
8148 };
8149
8150 /* Structure used when parsing image specifications. */
8151
8152 struct image_keyword
8153 {
8154 /* Name of keyword. */
8155 char *name;
8156
8157 /* The type of value allowed. */
8158 enum image_value_type type;
8159
8160 /* Non-zero means key must be present. */
8161 int mandatory_p;
8162
8163 /* Used to recognize duplicate keywords in a property list. */
8164 int count;
8165
8166 /* The value that was found. */
8167 Lisp_Object value;
8168 };
8169
8170
8171 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
8172 int, Lisp_Object));
8173 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
8174
8175
8176 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
8177 has the format (image KEYWORD VALUE ...). One of the keyword/
8178 value pairs must be `:type TYPE'. KEYWORDS is a vector of
8179 image_keywords structures of size NKEYWORDS describing other
8180 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
8181
8182 static int
8183 parse_image_spec (spec, keywords, nkeywords, type)
8184 Lisp_Object spec;
8185 struct image_keyword *keywords;
8186 int nkeywords;
8187 Lisp_Object type;
8188 {
8189 int i;
8190 Lisp_Object plist;
8191
8192 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
8193 return 0;
8194
8195 plist = XCDR (spec);
8196 while (CONSP (plist))
8197 {
8198 Lisp_Object key, value;
8199
8200 /* First element of a pair must be a symbol. */
8201 key = XCAR (plist);
8202 plist = XCDR (plist);
8203 if (!SYMBOLP (key))
8204 return 0;
8205
8206 /* There must follow a value. */
8207 if (!CONSP (plist))
8208 return 0;
8209 value = XCAR (plist);
8210 plist = XCDR (plist);
8211
8212 /* Find key in KEYWORDS. Error if not found. */
8213 for (i = 0; i < nkeywords; ++i)
8214 if (strcmp (keywords[i].name, XSYMBOL (key)->name->data) == 0)
8215 break;
8216
8217 if (i == nkeywords)
8218 continue;
8219
8220 /* Record that we recognized the keyword. If a keywords
8221 was found more than once, it's an error. */
8222 keywords[i].value = value;
8223 ++keywords[i].count;
8224
8225 if (keywords[i].count > 1)
8226 return 0;
8227
8228 /* Check type of value against allowed type. */
8229 switch (keywords[i].type)
8230 {
8231 case IMAGE_STRING_VALUE:
8232 if (!STRINGP (value))
8233 return 0;
8234 break;
8235
8236 case IMAGE_STRING_OR_NIL_VALUE:
8237 if (!STRINGP (value) && !NILP (value))
8238 return 0;
8239 break;
8240
8241 case IMAGE_SYMBOL_VALUE:
8242 if (!SYMBOLP (value))
8243 return 0;
8244 break;
8245
8246 case IMAGE_POSITIVE_INTEGER_VALUE:
8247 if (!INTEGERP (value) || XINT (value) <= 0)
8248 return 0;
8249 break;
8250
8251 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
8252 if (INTEGERP (value) && XINT (value) >= 0)
8253 break;
8254 if (CONSP (value)
8255 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
8256 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
8257 break;
8258 return 0;
8259
8260 case IMAGE_ASCENT_VALUE:
8261 if (SYMBOLP (value) && EQ (value, Qcenter))
8262 break;
8263 else if (INTEGERP (value)
8264 && XINT (value) >= 0
8265 && XINT (value) <= 100)
8266 break;
8267 return 0;
8268
8269 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
8270 if (!INTEGERP (value) || XINT (value) < 0)
8271 return 0;
8272 break;
8273
8274 case IMAGE_DONT_CHECK_VALUE_TYPE:
8275 break;
8276
8277 case IMAGE_FUNCTION_VALUE:
8278 value = indirect_function (value);
8279 if (SUBRP (value)
8280 || COMPILEDP (value)
8281 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
8282 break;
8283 return 0;
8284
8285 case IMAGE_NUMBER_VALUE:
8286 if (!INTEGERP (value) && !FLOATP (value))
8287 return 0;
8288 break;
8289
8290 case IMAGE_INTEGER_VALUE:
8291 if (!INTEGERP (value))
8292 return 0;
8293 break;
8294
8295 case IMAGE_BOOL_VALUE:
8296 if (!NILP (value) && !EQ (value, Qt))
8297 return 0;
8298 break;
8299
8300 default:
8301 abort ();
8302 break;
8303 }
8304
8305 if (EQ (key, QCtype) && !EQ (type, value))
8306 return 0;
8307 }
8308
8309 /* Check that all mandatory fields are present. */
8310 for (i = 0; i < nkeywords; ++i)
8311 if (keywords[i].mandatory_p && keywords[i].count == 0)
8312 return 0;
8313
8314 return NILP (plist);
8315 }
8316
8317
8318 /* Return the value of KEY in image specification SPEC. Value is nil
8319 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
8320 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
8321
8322 static Lisp_Object
8323 image_spec_value (spec, key, found)
8324 Lisp_Object spec, key;
8325 int *found;
8326 {
8327 Lisp_Object tail;
8328
8329 xassert (valid_image_p (spec));
8330
8331 for (tail = XCDR (spec);
8332 CONSP (tail) && CONSP (XCDR (tail));
8333 tail = XCDR (XCDR (tail)))
8334 {
8335 if (EQ (XCAR (tail), key))
8336 {
8337 if (found)
8338 *found = 1;
8339 return XCAR (XCDR (tail));
8340 }
8341 }
8342
8343 if (found)
8344 *found = 0;
8345 return Qnil;
8346 }
8347
8348
8349
8350 \f
8351 /***********************************************************************
8352 Image type independent image structures
8353 ***********************************************************************/
8354
8355 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
8356 static void free_image P_ ((struct frame *f, struct image *img));
8357
8358
8359 /* Allocate and return a new image structure for image specification
8360 SPEC. SPEC has a hash value of HASH. */
8361
8362 static struct image *
8363 make_image (spec, hash)
8364 Lisp_Object spec;
8365 unsigned hash;
8366 {
8367 struct image *img = (struct image *) xmalloc (sizeof *img);
8368
8369 xassert (valid_image_p (spec));
8370 bzero (img, sizeof *img);
8371 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
8372 xassert (img->type != NULL);
8373 img->spec = spec;
8374 img->data.lisp_val = Qnil;
8375 img->ascent = DEFAULT_IMAGE_ASCENT;
8376 img->hash = hash;
8377 return img;
8378 }
8379
8380
8381 /* Free image IMG which was used on frame F, including its resources. */
8382
8383 static void
8384 free_image (f, img)
8385 struct frame *f;
8386 struct image *img;
8387 {
8388 if (img)
8389 {
8390 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8391
8392 /* Remove IMG from the hash table of its cache. */
8393 if (img->prev)
8394 img->prev->next = img->next;
8395 else
8396 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
8397
8398 if (img->next)
8399 img->next->prev = img->prev;
8400
8401 c->images[img->id] = NULL;
8402
8403 /* Free resources, then free IMG. */
8404 img->type->free (f, img);
8405 xfree (img);
8406 }
8407 }
8408
8409
8410 /* Prepare image IMG for display on frame F. Must be called before
8411 drawing an image. */
8412
8413 void
8414 prepare_image_for_display (f, img)
8415 struct frame *f;
8416 struct image *img;
8417 {
8418 EMACS_TIME t;
8419
8420 /* We're about to display IMG, so set its timestamp to `now'. */
8421 EMACS_GET_TIME (t);
8422 img->timestamp = EMACS_SECS (t);
8423
8424 /* If IMG doesn't have a pixmap yet, load it now, using the image
8425 type dependent loader function. */
8426 if (img->pixmap == 0 && !img->load_failed_p)
8427 img->load_failed_p = img->type->load (f, img) == 0;
8428 }
8429
8430
8431 /* Value is the number of pixels for the ascent of image IMG when
8432 drawn in face FACE. */
8433
8434 int
8435 image_ascent (img, face)
8436 struct image *img;
8437 struct face *face;
8438 {
8439 int height = img->height + img->vmargin;
8440 int ascent;
8441
8442 if (img->ascent == CENTERED_IMAGE_ASCENT)
8443 {
8444 if (face->font)
8445 ascent = height / 2 - (FONT_DESCENT(face->font)
8446 - FONT_BASE(face->font)) / 2;
8447 else
8448 ascent = height / 2;
8449 }
8450 else
8451 ascent = height * img->ascent / 100.0;
8452
8453 return ascent;
8454 }
8455
8456
8457 \f
8458 /* Image background colors. */
8459
8460 static unsigned long
8461 four_corners_best (ximg, width, height)
8462 XImage *ximg;
8463 unsigned long width, height;
8464 {
8465 #if 0 /* TODO: Image support. */
8466 unsigned long corners[4], best;
8467 int i, best_count;
8468
8469 /* Get the colors at the corners of ximg. */
8470 corners[0] = XGetPixel (ximg, 0, 0);
8471 corners[1] = XGetPixel (ximg, width - 1, 0);
8472 corners[2] = XGetPixel (ximg, width - 1, height - 1);
8473 corners[3] = XGetPixel (ximg, 0, height - 1);
8474
8475 /* Choose the most frequently found color as background. */
8476 for (i = best_count = 0; i < 4; ++i)
8477 {
8478 int j, n;
8479
8480 for (j = n = 0; j < 4; ++j)
8481 if (corners[i] == corners[j])
8482 ++n;
8483
8484 if (n > best_count)
8485 best = corners[i], best_count = n;
8486 }
8487
8488 return best;
8489 #else
8490 return 0;
8491 #endif
8492 }
8493
8494 /* Return the `background' field of IMG. If IMG doesn't have one yet,
8495 it is guessed heuristically. If non-zero, XIMG is an existing XImage
8496 object to use for the heuristic. */
8497
8498 unsigned long
8499 image_background (img, f, ximg)
8500 struct image *img;
8501 struct frame *f;
8502 XImage *ximg;
8503 {
8504 if (! img->background_valid)
8505 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8506 {
8507 #if 0 /* TODO: Image support. */
8508 int free_ximg = !ximg;
8509
8510 if (! ximg)
8511 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
8512 0, 0, img->width, img->height, ~0, ZPixmap);
8513
8514 img->background = four_corners_best (ximg, img->width, img->height);
8515
8516 if (free_ximg)
8517 XDestroyImage (ximg);
8518
8519 img->background_valid = 1;
8520 #endif
8521 }
8522
8523 return img->background;
8524 }
8525
8526 /* Return the `background_transparent' field of IMG. If IMG doesn't
8527 have one yet, it is guessed heuristically. If non-zero, MASK is an
8528 existing XImage object to use for the heuristic. */
8529
8530 int
8531 image_background_transparent (img, f, mask)
8532 struct image *img;
8533 struct frame *f;
8534 XImage *mask;
8535 {
8536 if (! img->background_transparent_valid)
8537 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8538 {
8539 #if 0 /* TODO: Image support. */
8540 if (img->mask)
8541 {
8542 int free_mask = !mask;
8543
8544 if (! mask)
8545 mask = XGetImage (FRAME_X_DISPLAY (f), img->mask,
8546 0, 0, img->width, img->height, ~0, ZPixmap);
8547
8548 img->background_transparent
8549 = !four_corners_best (mask, img->width, img->height);
8550
8551 if (free_mask)
8552 XDestroyImage (mask);
8553 }
8554 else
8555 #endif
8556 img->background_transparent = 0;
8557
8558 img->background_transparent_valid = 1;
8559 }
8560
8561 return img->background_transparent;
8562 }
8563
8564 \f
8565 /***********************************************************************
8566 Helper functions for X image types
8567 ***********************************************************************/
8568
8569 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
8570 int, int));
8571 static void x_clear_image P_ ((struct frame *f, struct image *img));
8572 static unsigned long x_alloc_image_color P_ ((struct frame *f,
8573 struct image *img,
8574 Lisp_Object color_name,
8575 unsigned long dflt));
8576
8577
8578 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
8579 free the pixmap if any. MASK_P non-zero means clear the mask
8580 pixmap if any. COLORS_P non-zero means free colors allocated for
8581 the image, if any. */
8582
8583 static void
8584 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
8585 struct frame *f;
8586 struct image *img;
8587 int pixmap_p, mask_p, colors_p;
8588 {
8589 #if 0 /* TODO: W32 image support */
8590 if (pixmap_p && img->pixmap)
8591 {
8592 XFreePixmap (FRAME_X_DISPLAY (f), img->pixmap);
8593 img->pixmap = None;
8594 img->background_valid = 0;
8595 }
8596
8597 if (mask_p && img->mask)
8598 {
8599 XFreePixmap (FRAME_X_DISPLAY (f), img->mask);
8600 img->mask = None;
8601 img->background_transparent_valid = 0;
8602 }
8603
8604 if (colors_p && img->ncolors)
8605 {
8606 x_free_colors (f, img->colors, img->ncolors);
8607 xfree (img->colors);
8608 img->colors = NULL;
8609 img->ncolors = 0;
8610 }
8611 #endif
8612 }
8613
8614 /* Free X resources of image IMG which is used on frame F. */
8615
8616 static void
8617 x_clear_image (f, img)
8618 struct frame *f;
8619 struct image *img;
8620 {
8621 #if 0 /* TODO: W32 image support */
8622
8623 if (img->pixmap)
8624 {
8625 BLOCK_INPUT;
8626 XFreePixmap (NULL, img->pixmap);
8627 img->pixmap = 0;
8628 UNBLOCK_INPUT;
8629 }
8630
8631 if (img->ncolors)
8632 {
8633 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8634
8635 /* If display has an immutable color map, freeing colors is not
8636 necessary and some servers don't allow it. So don't do it. */
8637 if (class != StaticColor
8638 && class != StaticGray
8639 && class != TrueColor)
8640 {
8641 Colormap cmap;
8642 BLOCK_INPUT;
8643 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8644 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8645 img->ncolors, 0);
8646 UNBLOCK_INPUT;
8647 }
8648
8649 xfree (img->colors);
8650 img->colors = NULL;
8651 img->ncolors = 0;
8652 }
8653 #endif
8654 }
8655
8656
8657 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8658 cannot be allocated, use DFLT. Add a newly allocated color to
8659 IMG->colors, so that it can be freed again. Value is the pixel
8660 color. */
8661
8662 static unsigned long
8663 x_alloc_image_color (f, img, color_name, dflt)
8664 struct frame *f;
8665 struct image *img;
8666 Lisp_Object color_name;
8667 unsigned long dflt;
8668 {
8669 #if 0 /* TODO: allocing colors. */
8670 XColor color;
8671 unsigned long result;
8672
8673 xassert (STRINGP (color_name));
8674
8675 if (w32_defined_color (f, XSTRING (color_name)->data, &color, 1))
8676 {
8677 /* This isn't called frequently so we get away with simply
8678 reallocating the color vector to the needed size, here. */
8679 ++img->ncolors;
8680 img->colors =
8681 (unsigned long *) xrealloc (img->colors,
8682 img->ncolors * sizeof *img->colors);
8683 img->colors[img->ncolors - 1] = color.pixel;
8684 result = color.pixel;
8685 }
8686 else
8687 result = dflt;
8688 return result;
8689 #endif
8690 return 0;
8691 }
8692
8693
8694 \f
8695 /***********************************************************************
8696 Image Cache
8697 ***********************************************************************/
8698
8699 static void cache_image P_ ((struct frame *f, struct image *img));
8700 static void postprocess_image P_ ((struct frame *, struct image *));
8701
8702
8703 /* Return a new, initialized image cache that is allocated from the
8704 heap. Call free_image_cache to free an image cache. */
8705
8706 struct image_cache *
8707 make_image_cache ()
8708 {
8709 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8710 int size;
8711
8712 bzero (c, sizeof *c);
8713 c->size = 50;
8714 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8715 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8716 c->buckets = (struct image **) xmalloc (size);
8717 bzero (c->buckets, size);
8718 return c;
8719 }
8720
8721
8722 /* Free image cache of frame F. Be aware that X frames share images
8723 caches. */
8724
8725 void
8726 free_image_cache (f)
8727 struct frame *f;
8728 {
8729 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8730 if (c)
8731 {
8732 int i;
8733
8734 /* Cache should not be referenced by any frame when freed. */
8735 xassert (c->refcount == 0);
8736
8737 for (i = 0; i < c->used; ++i)
8738 free_image (f, c->images[i]);
8739 xfree (c->images);
8740 xfree (c);
8741 xfree (c->buckets);
8742 FRAME_X_IMAGE_CACHE (f) = NULL;
8743 }
8744 }
8745
8746
8747 /* Clear image cache of frame F. FORCE_P non-zero means free all
8748 images. FORCE_P zero means clear only images that haven't been
8749 displayed for some time. Should be called from time to time to
8750 reduce the number of loaded images. If image-eviction-seconds is
8751 non-nil, this frees images in the cache which weren't displayed for
8752 at least that many seconds. */
8753
8754 void
8755 clear_image_cache (f, force_p)
8756 struct frame *f;
8757 int force_p;
8758 {
8759 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8760
8761 if (c && INTEGERP (Vimage_cache_eviction_delay))
8762 {
8763 EMACS_TIME t;
8764 unsigned long old;
8765 int i, any_freed_p = 0;
8766
8767 EMACS_GET_TIME (t);
8768 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8769
8770 for (i = 0; i < c->used; ++i)
8771 {
8772 struct image *img = c->images[i];
8773 if (img != NULL
8774 && (force_p
8775 || (img->timestamp > old)))
8776 {
8777 free_image (f, img);
8778 any_freed_p = 1;
8779 }
8780 }
8781
8782 /* We may be clearing the image cache because, for example,
8783 Emacs was iconified for a longer period of time. In that
8784 case, current matrices may still contain references to
8785 images freed above. So, clear these matrices. */
8786 if (any_freed_p)
8787 {
8788 clear_current_matrices (f);
8789 ++windows_or_buffers_changed;
8790 }
8791 }
8792 }
8793
8794
8795 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
8796 0, 1, 0,
8797 doc: /* Clear the image cache of FRAME.
8798 FRAME nil or omitted means use the selected frame.
8799 FRAME t means clear the image caches of all frames. */)
8800 (frame)
8801 Lisp_Object frame;
8802 {
8803 if (EQ (frame, Qt))
8804 {
8805 Lisp_Object tail;
8806
8807 FOR_EACH_FRAME (tail, frame)
8808 if (FRAME_W32_P (XFRAME (frame)))
8809 clear_image_cache (XFRAME (frame), 1);
8810 }
8811 else
8812 clear_image_cache (check_x_frame (frame), 1);
8813
8814 return Qnil;
8815 }
8816
8817
8818 /* Compute masks and transform image IMG on frame F, as specified
8819 by the image's specification, */
8820
8821 static void
8822 postprocess_image (f, img)
8823 struct frame *f;
8824 struct image *img;
8825 {
8826 #if 0 /* TODO: image support. */
8827 /* Manipulation of the image's mask. */
8828 if (img->pixmap)
8829 {
8830 Lisp_Object conversion, spec;
8831 Lisp_Object mask;
8832
8833 spec = img->spec;
8834
8835 /* `:heuristic-mask t'
8836 `:mask heuristic'
8837 means build a mask heuristically.
8838 `:heuristic-mask (R G B)'
8839 `:mask (heuristic (R G B))'
8840 means build a mask from color (R G B) in the
8841 image.
8842 `:mask nil'
8843 means remove a mask, if any. */
8844
8845 mask = image_spec_value (spec, QCheuristic_mask, NULL);
8846 if (!NILP (mask))
8847 x_build_heuristic_mask (f, img, mask);
8848 else
8849 {
8850 int found_p;
8851
8852 mask = image_spec_value (spec, QCmask, &found_p);
8853
8854 if (EQ (mask, Qheuristic))
8855 x_build_heuristic_mask (f, img, Qt);
8856 else if (CONSP (mask)
8857 && EQ (XCAR (mask), Qheuristic))
8858 {
8859 if (CONSP (XCDR (mask)))
8860 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
8861 else
8862 x_build_heuristic_mask (f, img, XCDR (mask));
8863 }
8864 else if (NILP (mask) && found_p && img->mask)
8865 {
8866 XFreePixmap (FRAME_X_DISPLAY (f), img->mask);
8867 img->mask = NULL;
8868 }
8869 }
8870
8871
8872 /* Should we apply an image transformation algorithm? */
8873 conversion = image_spec_value (spec, QCconversion, NULL);
8874 if (EQ (conversion, Qdisabled))
8875 x_disable_image (f, img);
8876 else if (EQ (conversion, Qlaplace))
8877 x_laplace (f, img);
8878 else if (EQ (conversion, Qemboss))
8879 x_emboss (f, img);
8880 else if (CONSP (conversion)
8881 && EQ (XCAR (conversion), Qedge_detection))
8882 {
8883 Lisp_Object tem;
8884 tem = XCDR (conversion);
8885 if (CONSP (tem))
8886 x_edge_detection (f, img,
8887 Fplist_get (tem, QCmatrix),
8888 Fplist_get (tem, QCcolor_adjustment));
8889 }
8890 }
8891 #endif
8892 }
8893
8894
8895 /* Return the id of image with Lisp specification SPEC on frame F.
8896 SPEC must be a valid Lisp image specification (see valid_image_p). */
8897
8898 int
8899 lookup_image (f, spec)
8900 struct frame *f;
8901 Lisp_Object spec;
8902 {
8903 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8904 struct image *img;
8905 int i;
8906 unsigned hash;
8907 struct gcpro gcpro1;
8908 EMACS_TIME now;
8909
8910 /* F must be a window-system frame, and SPEC must be a valid image
8911 specification. */
8912 xassert (FRAME_WINDOW_P (f));
8913 xassert (valid_image_p (spec));
8914
8915 GCPRO1 (spec);
8916
8917 /* Look up SPEC in the hash table of the image cache. */
8918 hash = sxhash (spec, 0);
8919 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
8920
8921 for (img = c->buckets[i]; img; img = img->next)
8922 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
8923 break;
8924
8925 /* If not found, create a new image and cache it. */
8926 if (img == NULL)
8927 {
8928 extern Lisp_Object Qpostscript;
8929
8930 BLOCK_INPUT;
8931 img = make_image (spec, hash);
8932 cache_image (f, img);
8933 img->load_failed_p = img->type->load (f, img) == 0;
8934
8935 /* If we can't load the image, and we don't have a width and
8936 height, use some arbitrary width and height so that we can
8937 draw a rectangle for it. */
8938 if (img->load_failed_p)
8939 {
8940 Lisp_Object value;
8941
8942 value = image_spec_value (spec, QCwidth, NULL);
8943 img->width = (INTEGERP (value)
8944 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
8945 value = image_spec_value (spec, QCheight, NULL);
8946 img->height = (INTEGERP (value)
8947 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
8948 }
8949 else
8950 {
8951 /* Handle image type independent image attributes
8952 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF',
8953 `:background COLOR'. */
8954 Lisp_Object ascent, margin, relief, bg;
8955
8956 ascent = image_spec_value (spec, QCascent, NULL);
8957 if (INTEGERP (ascent))
8958 img->ascent = XFASTINT (ascent);
8959 else if (EQ (ascent, Qcenter))
8960 img->ascent = CENTERED_IMAGE_ASCENT;
8961
8962 margin = image_spec_value (spec, QCmargin, NULL);
8963 if (INTEGERP (margin) && XINT (margin) >= 0)
8964 img->vmargin = img->hmargin = XFASTINT (margin);
8965 else if (CONSP (margin) && INTEGERP (XCAR (margin))
8966 && INTEGERP (XCDR (margin)))
8967 {
8968 if (XINT (XCAR (margin)) > 0)
8969 img->hmargin = XFASTINT (XCAR (margin));
8970 if (XINT (XCDR (margin)) > 0)
8971 img->vmargin = XFASTINT (XCDR (margin));
8972 }
8973
8974 relief = image_spec_value (spec, QCrelief, NULL);
8975 if (INTEGERP (relief))
8976 {
8977 img->relief = XINT (relief);
8978 img->hmargin += abs (img->relief);
8979 img->vmargin += abs (img->relief);
8980 }
8981
8982 if (! img->background_valid)
8983 {
8984 bg = image_spec_value (img->spec, QCbackground, NULL);
8985 if (!NILP (bg))
8986 {
8987 img->background
8988 = x_alloc_image_color (f, img, bg,
8989 FRAME_BACKGROUND_PIXEL (f));
8990 img->background_valid = 1;
8991 }
8992 }
8993
8994 /* Do image transformations and compute masks, unless we
8995 don't have the image yet. */
8996 if (!EQ (*img->type->type, Qpostscript))
8997 postprocess_image (f, img);
8998 }
8999
9000 UNBLOCK_INPUT;
9001 xassert (!interrupt_input_blocked);
9002 }
9003
9004 /* We're using IMG, so set its timestamp to `now'. */
9005 EMACS_GET_TIME (now);
9006 img->timestamp = EMACS_SECS (now);
9007
9008 UNGCPRO;
9009
9010 /* Value is the image id. */
9011 return img->id;
9012 }
9013
9014
9015 /* Cache image IMG in the image cache of frame F. */
9016
9017 static void
9018 cache_image (f, img)
9019 struct frame *f;
9020 struct image *img;
9021 {
9022 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9023 int i;
9024
9025 /* Find a free slot in c->images. */
9026 for (i = 0; i < c->used; ++i)
9027 if (c->images[i] == NULL)
9028 break;
9029
9030 /* If no free slot found, maybe enlarge c->images. */
9031 if (i == c->used && c->used == c->size)
9032 {
9033 c->size *= 2;
9034 c->images = (struct image **) xrealloc (c->images,
9035 c->size * sizeof *c->images);
9036 }
9037
9038 /* Add IMG to c->images, and assign IMG an id. */
9039 c->images[i] = img;
9040 img->id = i;
9041 if (i == c->used)
9042 ++c->used;
9043
9044 /* Add IMG to the cache's hash table. */
9045 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
9046 img->next = c->buckets[i];
9047 if (img->next)
9048 img->next->prev = img;
9049 img->prev = NULL;
9050 c->buckets[i] = img;
9051 }
9052
9053
9054 /* Call FN on every image in the image cache of frame F. Used to mark
9055 Lisp Objects in the image cache. */
9056
9057 void
9058 forall_images_in_image_cache (f, fn)
9059 struct frame *f;
9060 void (*fn) P_ ((struct image *img));
9061 {
9062 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
9063 {
9064 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9065 if (c)
9066 {
9067 int i;
9068 for (i = 0; i < c->used; ++i)
9069 if (c->images[i])
9070 fn (c->images[i]);
9071 }
9072 }
9073 }
9074
9075
9076 \f
9077 /***********************************************************************
9078 W32 support code
9079 ***********************************************************************/
9080
9081 #if 0 /* TODO: W32 specific image code. */
9082
9083 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
9084 XImage **, Pixmap *));
9085 static void x_destroy_x_image P_ ((XImage *));
9086 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
9087
9088
9089 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
9090 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
9091 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
9092 via xmalloc. Print error messages via image_error if an error
9093 occurs. Value is non-zero if successful. */
9094
9095 static int
9096 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
9097 struct frame *f;
9098 int width, height, depth;
9099 XImage **ximg;
9100 Pixmap *pixmap;
9101 {
9102 #if 0 /* TODO: Image support for W32 */
9103 Display *display = FRAME_W32_DISPLAY (f);
9104 Screen *screen = FRAME_X_SCREEN (f);
9105 Window window = FRAME_W32_WINDOW (f);
9106
9107 xassert (interrupt_input_blocked);
9108
9109 if (depth <= 0)
9110 depth = one_w32_display_info.n_cbits;
9111 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
9112 depth, ZPixmap, 0, NULL, width, height,
9113 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
9114 if (*ximg == NULL)
9115 {
9116 image_error ("Unable to allocate X image", Qnil, Qnil);
9117 return 0;
9118 }
9119
9120 /* Allocate image raster. */
9121 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
9122
9123 /* Allocate a pixmap of the same size. */
9124 *pixmap = XCreatePixmap (display, window, width, height, depth);
9125 if (*pixmap == 0)
9126 {
9127 x_destroy_x_image (*ximg);
9128 *ximg = NULL;
9129 image_error ("Unable to create X pixmap", Qnil, Qnil);
9130 return 0;
9131 }
9132 #endif
9133 return 1;
9134 }
9135
9136
9137 /* Destroy XImage XIMG. Free XIMG->data. */
9138
9139 static void
9140 x_destroy_x_image (ximg)
9141 XImage *ximg;
9142 {
9143 xassert (interrupt_input_blocked);
9144 if (ximg)
9145 {
9146 xfree (ximg->data);
9147 ximg->data = NULL;
9148 XDestroyImage (ximg);
9149 }
9150 }
9151
9152
9153 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
9154 are width and height of both the image and pixmap. */
9155
9156 static void
9157 x_put_x_image (f, ximg, pixmap, width, height)
9158 struct frame *f;
9159 XImage *ximg;
9160 Pixmap pixmap;
9161 {
9162 GC gc;
9163
9164 xassert (interrupt_input_blocked);
9165 gc = XCreateGC (NULL, pixmap, 0, NULL);
9166 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
9167 XFreeGC (NULL, gc);
9168 }
9169
9170 #endif
9171
9172 \f
9173 /***********************************************************************
9174 File Handling
9175 ***********************************************************************/
9176
9177 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
9178 static char *slurp_file P_ ((char *, int *));
9179
9180
9181 /* Find image file FILE. Look in data-directory, then
9182 x-bitmap-file-path. Value is the full name of the file found, or
9183 nil if not found. */
9184
9185 static Lisp_Object
9186 x_find_image_file (file)
9187 Lisp_Object file;
9188 {
9189 Lisp_Object file_found, search_path;
9190 struct gcpro gcpro1, gcpro2;
9191 int fd;
9192
9193 file_found = Qnil;
9194 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
9195 GCPRO2 (file_found, search_path);
9196
9197 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
9198 fd = openp (search_path, file, Qnil, &file_found, 0);
9199
9200 if (fd == -1)
9201 file_found = Qnil;
9202 else
9203 close (fd);
9204
9205 UNGCPRO;
9206 return file_found;
9207 }
9208
9209
9210 /* Read FILE into memory. Value is a pointer to a buffer allocated
9211 with xmalloc holding FILE's contents. Value is null if an error
9212 occurred. *SIZE is set to the size of the file. */
9213
9214 static char *
9215 slurp_file (file, size)
9216 char *file;
9217 int *size;
9218 {
9219 FILE *fp = NULL;
9220 char *buf = NULL;
9221 struct stat st;
9222
9223 if (stat (file, &st) == 0
9224 && (fp = fopen (file, "r")) != NULL
9225 && (buf = (char *) xmalloc (st.st_size),
9226 fread (buf, 1, st.st_size, fp) == st.st_size))
9227 {
9228 *size = st.st_size;
9229 fclose (fp);
9230 }
9231 else
9232 {
9233 if (fp)
9234 fclose (fp);
9235 if (buf)
9236 {
9237 xfree (buf);
9238 buf = NULL;
9239 }
9240 }
9241
9242 return buf;
9243 }
9244
9245
9246 \f
9247 /***********************************************************************
9248 XBM images
9249 ***********************************************************************/
9250
9251 static int xbm_load P_ ((struct frame *f, struct image *img));
9252 static int xbm_load_image_from_file P_ ((struct frame *f, struct image *img,
9253 Lisp_Object file));
9254 static int xbm_image_p P_ ((Lisp_Object object));
9255 static int xbm_read_bitmap_file_data P_ ((char *, int *, int *,
9256 unsigned char **));
9257
9258
9259 /* Indices of image specification fields in xbm_format, below. */
9260
9261 enum xbm_keyword_index
9262 {
9263 XBM_TYPE,
9264 XBM_FILE,
9265 XBM_WIDTH,
9266 XBM_HEIGHT,
9267 XBM_DATA,
9268 XBM_FOREGROUND,
9269 XBM_BACKGROUND,
9270 XBM_ASCENT,
9271 XBM_MARGIN,
9272 XBM_RELIEF,
9273 XBM_ALGORITHM,
9274 XBM_HEURISTIC_MASK,
9275 XBM_MASK,
9276 XBM_LAST
9277 };
9278
9279 /* Vector of image_keyword structures describing the format
9280 of valid XBM image specifications. */
9281
9282 static struct image_keyword xbm_format[XBM_LAST] =
9283 {
9284 {":type", IMAGE_SYMBOL_VALUE, 1},
9285 {":file", IMAGE_STRING_VALUE, 0},
9286 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9287 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9288 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9289 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
9290 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
9291 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9292 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9293 {":relief", IMAGE_INTEGER_VALUE, 0},
9294 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9295 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9296 };
9297
9298 /* Structure describing the image type XBM. */
9299
9300 static struct image_type xbm_type =
9301 {
9302 &Qxbm,
9303 xbm_image_p,
9304 xbm_load,
9305 x_clear_image,
9306 NULL
9307 };
9308
9309 /* Tokens returned from xbm_scan. */
9310
9311 enum xbm_token
9312 {
9313 XBM_TK_IDENT = 256,
9314 XBM_TK_NUMBER
9315 };
9316
9317
9318 /* Return non-zero if OBJECT is a valid XBM-type image specification.
9319 A valid specification is a list starting with the symbol `image'
9320 The rest of the list is a property list which must contain an
9321 entry `:type xbm..
9322
9323 If the specification specifies a file to load, it must contain
9324 an entry `:file FILENAME' where FILENAME is a string.
9325
9326 If the specification is for a bitmap loaded from memory it must
9327 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
9328 WIDTH and HEIGHT are integers > 0. DATA may be:
9329
9330 1. a string large enough to hold the bitmap data, i.e. it must
9331 have a size >= (WIDTH + 7) / 8 * HEIGHT
9332
9333 2. a bool-vector of size >= WIDTH * HEIGHT
9334
9335 3. a vector of strings or bool-vectors, one for each line of the
9336 bitmap.
9337
9338 Both the file and data forms may contain the additional entries
9339 `:background COLOR' and `:foreground COLOR'. If not present,
9340 foreground and background of the frame on which the image is
9341 displayed, is used. */
9342
9343 static int
9344 xbm_image_p (object)
9345 Lisp_Object object;
9346 {
9347 struct image_keyword kw[XBM_LAST];
9348
9349 bcopy (xbm_format, kw, sizeof kw);
9350 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
9351 return 0;
9352
9353 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
9354
9355 if (kw[XBM_FILE].count)
9356 {
9357 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
9358 return 0;
9359 }
9360 else
9361 {
9362 Lisp_Object data;
9363 int width, height;
9364
9365 /* Entries for `:width', `:height' and `:data' must be present. */
9366 if (!kw[XBM_WIDTH].count
9367 || !kw[XBM_HEIGHT].count
9368 || !kw[XBM_DATA].count)
9369 return 0;
9370
9371 data = kw[XBM_DATA].value;
9372 width = XFASTINT (kw[XBM_WIDTH].value);
9373 height = XFASTINT (kw[XBM_HEIGHT].value);
9374
9375 /* Check type of data, and width and height against contents of
9376 data. */
9377 if (VECTORP (data))
9378 {
9379 int i;
9380
9381 /* Number of elements of the vector must be >= height. */
9382 if (XVECTOR (data)->size < height)
9383 return 0;
9384
9385 /* Each string or bool-vector in data must be large enough
9386 for one line of the image. */
9387 for (i = 0; i < height; ++i)
9388 {
9389 Lisp_Object elt = XVECTOR (data)->contents[i];
9390
9391 if (STRINGP (elt))
9392 {
9393 if (XSTRING (elt)->size
9394 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
9395 return 0;
9396 }
9397 else if (BOOL_VECTOR_P (elt))
9398 {
9399 if (XBOOL_VECTOR (elt)->size < width)
9400 return 0;
9401 }
9402 else
9403 return 0;
9404 }
9405 }
9406 else if (STRINGP (data))
9407 {
9408 if (XSTRING (data)->size
9409 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
9410 return 0;
9411 }
9412 else if (BOOL_VECTOR_P (data))
9413 {
9414 if (XBOOL_VECTOR (data)->size < width * height)
9415 return 0;
9416 }
9417 else
9418 return 0;
9419 }
9420
9421 /* Baseline must be a value between 0 and 100 (a percentage). */
9422 if (kw[XBM_ASCENT].count
9423 && XFASTINT (kw[XBM_ASCENT].value) > 100)
9424 return 0;
9425
9426 return 1;
9427 }
9428
9429
9430 /* Scan a bitmap file. FP is the stream to read from. Value is
9431 either an enumerator from enum xbm_token, or a character for a
9432 single-character token, or 0 at end of file. If scanning an
9433 identifier, store the lexeme of the identifier in SVAL. If
9434 scanning a number, store its value in *IVAL. */
9435
9436 static int
9437 xbm_scan (s, end, sval, ival)
9438 char **s, *end;
9439 char *sval;
9440 int *ival;
9441 {
9442 int c;
9443
9444 loop:
9445
9446 /* Skip white space. */
9447 while (*s < end &&(c = *(*s)++, isspace (c)))
9448 ;
9449
9450 if (*s >= end)
9451 c = 0;
9452 else if (isdigit (c))
9453 {
9454 int value = 0, digit;
9455
9456 if (c == '0' && *s < end)
9457 {
9458 c = *(*s)++;
9459 if (c == 'x' || c == 'X')
9460 {
9461 while (*s < end)
9462 {
9463 c = *(*s)++;
9464 if (isdigit (c))
9465 digit = c - '0';
9466 else if (c >= 'a' && c <= 'f')
9467 digit = c - 'a' + 10;
9468 else if (c >= 'A' && c <= 'F')
9469 digit = c - 'A' + 10;
9470 else
9471 break;
9472 value = 16 * value + digit;
9473 }
9474 }
9475 else if (isdigit (c))
9476 {
9477 value = c - '0';
9478 while (*s < end
9479 && (c = *(*s)++, isdigit (c)))
9480 value = 8 * value + c - '0';
9481 }
9482 }
9483 else
9484 {
9485 value = c - '0';
9486 while (*s < end
9487 && (c = *(*s)++, isdigit (c)))
9488 value = 10 * value + c - '0';
9489 }
9490
9491 if (*s < end)
9492 *s = *s - 1;
9493 *ival = value;
9494 c = XBM_TK_NUMBER;
9495 }
9496 else if (isalpha (c) || c == '_')
9497 {
9498 *sval++ = c;
9499 while (*s < end
9500 && (c = *(*s)++, (isalnum (c) || c == '_')))
9501 *sval++ = c;
9502 *sval = 0;
9503 if (*s < end)
9504 *s = *s - 1;
9505 c = XBM_TK_IDENT;
9506 }
9507 else if (c == '/' && **s == '*')
9508 {
9509 /* C-style comment. */
9510 ++*s;
9511 while (**s && (**s != '*' || *(*s + 1) != '/'))
9512 ++*s;
9513 if (**s)
9514 {
9515 *s += 2;
9516 goto loop;
9517 }
9518 }
9519
9520 return c;
9521 }
9522
9523
9524 /* Replacement for XReadBitmapFileData which isn't available under old
9525 X versions. CONTENTS is a pointer to a buffer to parse; END is the
9526 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
9527 the image. Return in *DATA the bitmap data allocated with xmalloc.
9528 Value is non-zero if successful. DATA null means just test if
9529 CONTENTS looks like an in-memory XBM file. */
9530
9531 static int
9532 xbm_read_bitmap_data (contents, end, width, height, data)
9533 char *contents, *end;
9534 int *width, *height;
9535 unsigned char **data;
9536 {
9537 char *s = contents;
9538 char buffer[BUFSIZ];
9539 int padding_p = 0;
9540 int v10 = 0;
9541 int bytes_per_line, i, nbytes;
9542 unsigned char *p;
9543 int value;
9544 int LA1;
9545
9546 #define match() \
9547 LA1 = xbm_scan (contents, end, buffer, &value)
9548
9549 #define expect(TOKEN) \
9550 if (LA1 != (TOKEN)) \
9551 goto failure; \
9552 else \
9553 match ()
9554
9555 #define expect_ident(IDENT) \
9556 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
9557 match (); \
9558 else \
9559 goto failure
9560
9561 *width = *height = -1;
9562 if (data)
9563 *data = NULL;
9564 LA1 = xbm_scan (&s, end, buffer, &value);
9565
9566 /* Parse defines for width, height and hot-spots. */
9567 while (LA1 == '#')
9568 {
9569 match ();
9570 expect_ident ("define");
9571 expect (XBM_TK_IDENT);
9572
9573 if (LA1 == XBM_TK_NUMBER);
9574 {
9575 char *p = strrchr (buffer, '_');
9576 p = p ? p + 1 : buffer;
9577 if (strcmp (p, "width") == 0)
9578 *width = value;
9579 else if (strcmp (p, "height") == 0)
9580 *height = value;
9581 }
9582 expect (XBM_TK_NUMBER);
9583 }
9584
9585 if (*width < 0 || *height < 0)
9586 goto failure;
9587 else if (data == NULL)
9588 goto success;
9589
9590 /* Parse bits. Must start with `static'. */
9591 expect_ident ("static");
9592 if (LA1 == XBM_TK_IDENT)
9593 {
9594 if (strcmp (buffer, "unsigned") == 0)
9595 {
9596 match ();
9597 expect_ident ("char");
9598 }
9599 else if (strcmp (buffer, "short") == 0)
9600 {
9601 match ();
9602 v10 = 1;
9603 if (*width % 16 && *width % 16 < 9)
9604 padding_p = 1;
9605 }
9606 else if (strcmp (buffer, "char") == 0)
9607 match ();
9608 else
9609 goto failure;
9610 }
9611 else
9612 goto failure;
9613
9614 expect (XBM_TK_IDENT);
9615 expect ('[');
9616 expect (']');
9617 expect ('=');
9618 expect ('{');
9619
9620 bytes_per_line = (*width + 7) / 8 + padding_p;
9621 nbytes = bytes_per_line * *height;
9622 p = *data = (char *) xmalloc (nbytes);
9623
9624 if (v10)
9625 {
9626
9627 for (i = 0; i < nbytes; i += 2)
9628 {
9629 int val = value;
9630 expect (XBM_TK_NUMBER);
9631
9632 *p++ = val;
9633 if (!padding_p || ((i + 2) % bytes_per_line))
9634 *p++ = value >> 8;
9635
9636 if (LA1 == ',' || LA1 == '}')
9637 match ();
9638 else
9639 goto failure;
9640 }
9641 }
9642 else
9643 {
9644 for (i = 0; i < nbytes; ++i)
9645 {
9646 int val = value;
9647 expect (XBM_TK_NUMBER);
9648
9649 *p++ = val;
9650
9651 if (LA1 == ',' || LA1 == '}')
9652 match ();
9653 else
9654 goto failure;
9655 }
9656 }
9657
9658 success:
9659 return 1;
9660
9661 failure:
9662
9663 if (data && *data)
9664 {
9665 xfree (*data);
9666 *data = NULL;
9667 }
9668 return 0;
9669
9670 #undef match
9671 #undef expect
9672 #undef expect_ident
9673 }
9674
9675
9676 /* Load XBM image IMG which will be displayed on frame F from buffer
9677 CONTENTS. END is the end of the buffer. Value is non-zero if
9678 successful. */
9679
9680 static int
9681 xbm_load_image (f, img, contents, end)
9682 struct frame *f;
9683 struct image *img;
9684 char *contents, *end;
9685 {
9686 int rc;
9687 unsigned char *data;
9688 int success_p = 0;
9689
9690 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
9691 if (rc)
9692 {
9693 int depth = one_w32_display_info.n_cbits;
9694 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9695 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9696 Lisp_Object value;
9697
9698 xassert (img->width > 0 && img->height > 0);
9699
9700 /* Get foreground and background colors, maybe allocate colors. */
9701 value = image_spec_value (img->spec, QCforeground, NULL);
9702 if (!NILP (value))
9703 foreground = x_alloc_image_color (f, img, value, foreground);
9704 value = image_spec_value (img->spec, QCbackground, NULL);
9705 if (!NILP (value))
9706 {
9707 background = x_alloc_image_color (f, img, value, background);
9708 img->background = background;
9709 img->background_valid = 1;
9710 }
9711
9712 #if 0 /* TODO : Port image display to W32 */
9713 img->pixmap
9714 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
9715 FRAME_W32_WINDOW (f),
9716 data,
9717 img->width, img->height,
9718 foreground, background,
9719 depth);
9720 #endif
9721 xfree (data);
9722
9723 if (img->pixmap == 0)
9724 {
9725 x_clear_image (f, img);
9726 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
9727 }
9728 else
9729 success_p = 1;
9730 }
9731 else
9732 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
9733
9734 return success_p;
9735 }
9736
9737
9738 /* Value is non-zero if DATA looks like an in-memory XBM file. */
9739
9740 static int
9741 xbm_file_p (data)
9742 Lisp_Object data;
9743 {
9744 int w, h;
9745 return (STRINGP (data)
9746 && xbm_read_bitmap_data (XSTRING (data)->data,
9747 (XSTRING (data)->data
9748 + STRING_BYTES (XSTRING (data))),
9749 &w, &h, NULL));
9750 }
9751
9752
9753 /* Fill image IMG which is used on frame F with pixmap data. Value is
9754 non-zero if successful. */
9755
9756 static int
9757 xbm_load (f, img)
9758 struct frame *f;
9759 struct image *img;
9760 {
9761 int success_p = 0;
9762 Lisp_Object file_name;
9763
9764 xassert (xbm_image_p (img->spec));
9765
9766 /* If IMG->spec specifies a file name, create a non-file spec from it. */
9767 file_name = image_spec_value (img->spec, QCfile, NULL);
9768 if (STRINGP (file_name))
9769 {
9770 Lisp_Object file;
9771 char *contents;
9772 int size;
9773 struct gcpro gcpro1;
9774
9775 file = x_find_image_file (file_name);
9776 GCPRO1 (file);
9777 if (!STRINGP (file))
9778 {
9779 image_error ("Cannot find image file `%s'", file_name, Qnil);
9780 UNGCPRO;
9781 return 0;
9782 }
9783
9784 contents = slurp_file (XSTRING (file)->data, &size);
9785 if (contents == NULL)
9786 {
9787 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
9788 UNGCPRO;
9789 return 0;
9790 }
9791
9792 success_p = xbm_load_image (f, img, contents, contents + size);
9793 UNGCPRO;
9794 }
9795 else
9796 {
9797 struct image_keyword fmt[XBM_LAST];
9798 Lisp_Object data;
9799 int depth;
9800 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9801 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9802 char *bits;
9803 int parsed_p;
9804 int in_memory_file_p = 0;
9805
9806 /* See if data looks like an in-memory XBM file. */
9807 data = image_spec_value (img->spec, QCdata, NULL);
9808 in_memory_file_p = xbm_file_p (data);
9809
9810 /* Parse the list specification. */
9811 bcopy (xbm_format, fmt, sizeof fmt);
9812 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
9813 xassert (parsed_p);
9814
9815 /* Get specified width, and height. */
9816 if (!in_memory_file_p)
9817 {
9818 img->width = XFASTINT (fmt[XBM_WIDTH].value);
9819 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
9820 xassert (img->width > 0 && img->height > 0);
9821 }
9822 /* Get foreground and background colors, maybe allocate colors. */
9823 if (fmt[XBM_FOREGROUND].count
9824 && STRINGP (fmt[XBM_FOREGROUND].value))
9825 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
9826 foreground);
9827 if (fmt[XBM_BACKGROUND].count
9828 && STRINGP (fmt[XBM_BACKGROUND].value))
9829 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
9830 background);
9831
9832 if (in_memory_file_p)
9833 success_p = xbm_load_image (f, img, XSTRING (data)->data,
9834 (XSTRING (data)->data
9835 + STRING_BYTES (XSTRING (data))));
9836 else
9837 {
9838 if (VECTORP (data))
9839 {
9840 int i;
9841 char *p;
9842 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
9843
9844 p = bits = (char *) alloca (nbytes * img->height);
9845 for (i = 0; i < img->height; ++i, p += nbytes)
9846 {
9847 Lisp_Object line = XVECTOR (data)->contents[i];
9848 if (STRINGP (line))
9849 bcopy (XSTRING (line)->data, p, nbytes);
9850 else
9851 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
9852 }
9853 }
9854 else if (STRINGP (data))
9855 bits = XSTRING (data)->data;
9856 else
9857 bits = XBOOL_VECTOR (data)->data;
9858 #ifdef TODO /* image support. */
9859 /* Create the pixmap. */
9860 depth = one_w32_display_info.n_cbits;
9861 img->pixmap
9862 = XCreatePixmapFromBitmapData (FRAME_X_DISPLAY (f),
9863 FRAME_X_WINDOW (f),
9864 bits,
9865 img->width, img->height,
9866 foreground, background,
9867 depth);
9868 #endif
9869 if (img->pixmap)
9870 success_p = 1;
9871 else
9872 {
9873 image_error ("Unable to create pixmap for XBM image `%s'",
9874 img->spec, Qnil);
9875 x_clear_image (f, img);
9876 }
9877 }
9878 }
9879
9880 return success_p;
9881 }
9882
9883
9884 \f
9885 /***********************************************************************
9886 XPM images
9887 ***********************************************************************/
9888
9889 #if HAVE_XPM
9890
9891 static int xpm_image_p P_ ((Lisp_Object object));
9892 static int xpm_load P_ ((struct frame *f, struct image *img));
9893 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
9894
9895 #include "X11/xpm.h"
9896
9897 /* The symbol `xpm' identifying XPM-format images. */
9898
9899 Lisp_Object Qxpm;
9900
9901 /* Indices of image specification fields in xpm_format, below. */
9902
9903 enum xpm_keyword_index
9904 {
9905 XPM_TYPE,
9906 XPM_FILE,
9907 XPM_DATA,
9908 XPM_ASCENT,
9909 XPM_MARGIN,
9910 XPM_RELIEF,
9911 XPM_ALGORITHM,
9912 XPM_HEURISTIC_MASK,
9913 XPM_MASK,
9914 XPM_COLOR_SYMBOLS,
9915 XPM_BACKGROUND,
9916 XPM_LAST
9917 };
9918
9919 /* Vector of image_keyword structures describing the format
9920 of valid XPM image specifications. */
9921
9922 static struct image_keyword xpm_format[XPM_LAST] =
9923 {
9924 {":type", IMAGE_SYMBOL_VALUE, 1},
9925 {":file", IMAGE_STRING_VALUE, 0},
9926 {":data", IMAGE_STRING_VALUE, 0},
9927 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9928 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9929 {":relief", IMAGE_INTEGER_VALUE, 0},
9930 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9931 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9932 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9933 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9934 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9935 };
9936
9937 /* Structure describing the image type XBM. */
9938
9939 static struct image_type xpm_type =
9940 {
9941 &Qxpm,
9942 xpm_image_p,
9943 xpm_load,
9944 x_clear_image,
9945 NULL
9946 };
9947
9948
9949 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9950 for XPM images. Such a list must consist of conses whose car and
9951 cdr are strings. */
9952
9953 static int
9954 xpm_valid_color_symbols_p (color_symbols)
9955 Lisp_Object color_symbols;
9956 {
9957 while (CONSP (color_symbols))
9958 {
9959 Lisp_Object sym = XCAR (color_symbols);
9960 if (!CONSP (sym)
9961 || !STRINGP (XCAR (sym))
9962 || !STRINGP (XCDR (sym)))
9963 break;
9964 color_symbols = XCDR (color_symbols);
9965 }
9966
9967 return NILP (color_symbols);
9968 }
9969
9970
9971 /* Value is non-zero if OBJECT is a valid XPM image specification. */
9972
9973 static int
9974 xpm_image_p (object)
9975 Lisp_Object object;
9976 {
9977 struct image_keyword fmt[XPM_LAST];
9978 bcopy (xpm_format, fmt, sizeof fmt);
9979 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9980 /* Either `:file' or `:data' must be present. */
9981 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9982 /* Either no `:color-symbols' or it's a list of conses
9983 whose car and cdr are strings. */
9984 && (fmt[XPM_COLOR_SYMBOLS].count == 0
9985 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
9986 && (fmt[XPM_ASCENT].count == 0
9987 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
9988 }
9989
9990
9991 /* Load image IMG which will be displayed on frame F. Value is
9992 non-zero if successful. */
9993
9994 static int
9995 xpm_load (f, img)
9996 struct frame *f;
9997 struct image *img;
9998 {
9999 int rc, i;
10000 XpmAttributes attrs;
10001 Lisp_Object specified_file, color_symbols;
10002
10003 /* Configure the XPM lib. Use the visual of frame F. Allocate
10004 close colors. Return colors allocated. */
10005 bzero (&attrs, sizeof attrs);
10006 attrs.visual = FRAME_X_VISUAL (f);
10007 attrs.colormap = FRAME_X_COLORMAP (f);
10008 attrs.valuemask |= XpmVisual;
10009 attrs.valuemask |= XpmColormap;
10010 attrs.valuemask |= XpmReturnAllocPixels;
10011 #ifdef XpmAllocCloseColors
10012 attrs.alloc_close_colors = 1;
10013 attrs.valuemask |= XpmAllocCloseColors;
10014 #else
10015 attrs.closeness = 600;
10016 attrs.valuemask |= XpmCloseness;
10017 #endif
10018
10019 /* If image specification contains symbolic color definitions, add
10020 these to `attrs'. */
10021 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
10022 if (CONSP (color_symbols))
10023 {
10024 Lisp_Object tail;
10025 XpmColorSymbol *xpm_syms;
10026 int i, size;
10027
10028 attrs.valuemask |= XpmColorSymbols;
10029
10030 /* Count number of symbols. */
10031 attrs.numsymbols = 0;
10032 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
10033 ++attrs.numsymbols;
10034
10035 /* Allocate an XpmColorSymbol array. */
10036 size = attrs.numsymbols * sizeof *xpm_syms;
10037 xpm_syms = (XpmColorSymbol *) alloca (size);
10038 bzero (xpm_syms, size);
10039 attrs.colorsymbols = xpm_syms;
10040
10041 /* Fill the color symbol array. */
10042 for (tail = color_symbols, i = 0;
10043 CONSP (tail);
10044 ++i, tail = XCDR (tail))
10045 {
10046 Lisp_Object name = XCAR (XCAR (tail));
10047 Lisp_Object color = XCDR (XCAR (tail));
10048 xpm_syms[i].name = (char *) alloca (XSTRING (name)->size + 1);
10049 strcpy (xpm_syms[i].name, XSTRING (name)->data);
10050 xpm_syms[i].value = (char *) alloca (XSTRING (color)->size + 1);
10051 strcpy (xpm_syms[i].value, XSTRING (color)->data);
10052 }
10053 }
10054
10055 /* Create a pixmap for the image, either from a file, or from a
10056 string buffer containing data in the same format as an XPM file. */
10057 BLOCK_INPUT;
10058 specified_file = image_spec_value (img->spec, QCfile, NULL);
10059 if (STRINGP (specified_file))
10060 {
10061 Lisp_Object file = x_find_image_file (specified_file);
10062 if (!STRINGP (file))
10063 {
10064 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10065 UNBLOCK_INPUT;
10066 return 0;
10067 }
10068
10069 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
10070 XSTRING (file)->data, &img->pixmap, &img->mask,
10071 &attrs);
10072 }
10073 else
10074 {
10075 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
10076 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
10077 XSTRING (buffer)->data,
10078 &img->pixmap, &img->mask,
10079 &attrs);
10080 }
10081 UNBLOCK_INPUT;
10082
10083 if (rc == XpmSuccess)
10084 {
10085 /* Remember allocated colors. */
10086 img->ncolors = attrs.nalloc_pixels;
10087 img->colors = (unsigned long *) xmalloc (img->ncolors
10088 * sizeof *img->colors);
10089 for (i = 0; i < attrs.nalloc_pixels; ++i)
10090 img->colors[i] = attrs.alloc_pixels[i];
10091
10092 img->width = attrs.width;
10093 img->height = attrs.height;
10094 xassert (img->width > 0 && img->height > 0);
10095
10096 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
10097 BLOCK_INPUT;
10098 XpmFreeAttributes (&attrs);
10099 UNBLOCK_INPUT;
10100 }
10101 else
10102 {
10103 switch (rc)
10104 {
10105 case XpmOpenFailed:
10106 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
10107 break;
10108
10109 case XpmFileInvalid:
10110 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
10111 break;
10112
10113 case XpmNoMemory:
10114 image_error ("Out of memory (%s)", img->spec, Qnil);
10115 break;
10116
10117 case XpmColorFailed:
10118 image_error ("Color allocation error (%s)", img->spec, Qnil);
10119 break;
10120
10121 default:
10122 image_error ("Unknown error (%s)", img->spec, Qnil);
10123 break;
10124 }
10125 }
10126
10127 return rc == XpmSuccess;
10128 }
10129
10130 #endif /* HAVE_XPM != 0 */
10131
10132 \f
10133 #if 0 /* TODO : Color tables on W32. */
10134 /***********************************************************************
10135 Color table
10136 ***********************************************************************/
10137
10138 /* An entry in the color table mapping an RGB color to a pixel color. */
10139
10140 struct ct_color
10141 {
10142 int r, g, b;
10143 unsigned long pixel;
10144
10145 /* Next in color table collision list. */
10146 struct ct_color *next;
10147 };
10148
10149 /* The bucket vector size to use. Must be prime. */
10150
10151 #define CT_SIZE 101
10152
10153 /* Value is a hash of the RGB color given by R, G, and B. */
10154
10155 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
10156
10157 /* The color hash table. */
10158
10159 struct ct_color **ct_table;
10160
10161 /* Number of entries in the color table. */
10162
10163 int ct_colors_allocated;
10164
10165 /* Function prototypes. */
10166
10167 static void init_color_table P_ ((void));
10168 static void free_color_table P_ ((void));
10169 static unsigned long *colors_in_color_table P_ ((int *n));
10170 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
10171 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
10172
10173
10174 /* Initialize the color table. */
10175
10176 static void
10177 init_color_table ()
10178 {
10179 int size = CT_SIZE * sizeof (*ct_table);
10180 ct_table = (struct ct_color **) xmalloc (size);
10181 bzero (ct_table, size);
10182 ct_colors_allocated = 0;
10183 }
10184
10185
10186 /* Free memory associated with the color table. */
10187
10188 static void
10189 free_color_table ()
10190 {
10191 int i;
10192 struct ct_color *p, *next;
10193
10194 for (i = 0; i < CT_SIZE; ++i)
10195 for (p = ct_table[i]; p; p = next)
10196 {
10197 next = p->next;
10198 xfree (p);
10199 }
10200
10201 xfree (ct_table);
10202 ct_table = NULL;
10203 }
10204
10205
10206 /* Value is a pixel color for RGB color R, G, B on frame F. If an
10207 entry for that color already is in the color table, return the
10208 pixel color of that entry. Otherwise, allocate a new color for R,
10209 G, B, and make an entry in the color table. */
10210
10211 static unsigned long
10212 lookup_rgb_color (f, r, g, b)
10213 struct frame *f;
10214 int r, g, b;
10215 {
10216 unsigned hash = CT_HASH_RGB (r, g, b);
10217 int i = hash % CT_SIZE;
10218 struct ct_color *p;
10219
10220 for (p = ct_table[i]; p; p = p->next)
10221 if (p->r == r && p->g == g && p->b == b)
10222 break;
10223
10224 if (p == NULL)
10225 {
10226 COLORREF color;
10227 Colormap cmap;
10228 int rc;
10229
10230 color = PALETTERGB (r, g, b);
10231
10232 ++ct_colors_allocated;
10233
10234 p = (struct ct_color *) xmalloc (sizeof *p);
10235 p->r = r;
10236 p->g = g;
10237 p->b = b;
10238 p->pixel = color;
10239 p->next = ct_table[i];
10240 ct_table[i] = p;
10241 }
10242
10243 return p->pixel;
10244 }
10245
10246
10247 /* Look up pixel color PIXEL which is used on frame F in the color
10248 table. If not already present, allocate it. Value is PIXEL. */
10249
10250 static unsigned long
10251 lookup_pixel_color (f, pixel)
10252 struct frame *f;
10253 unsigned long pixel;
10254 {
10255 int i = pixel % CT_SIZE;
10256 struct ct_color *p;
10257
10258 for (p = ct_table[i]; p; p = p->next)
10259 if (p->pixel == pixel)
10260 break;
10261
10262 if (p == NULL)
10263 {
10264 XColor color;
10265 Colormap cmap;
10266 int rc;
10267
10268 BLOCK_INPUT;
10269
10270 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10271 color.pixel = pixel;
10272 XQueryColor (NULL, cmap, &color);
10273 rc = x_alloc_nearest_color (f, cmap, &color);
10274 UNBLOCK_INPUT;
10275
10276 if (rc)
10277 {
10278 ++ct_colors_allocated;
10279
10280 p = (struct ct_color *) xmalloc (sizeof *p);
10281 p->r = color.red;
10282 p->g = color.green;
10283 p->b = color.blue;
10284 p->pixel = pixel;
10285 p->next = ct_table[i];
10286 ct_table[i] = p;
10287 }
10288 else
10289 return FRAME_FOREGROUND_PIXEL (f);
10290 }
10291 return p->pixel;
10292 }
10293
10294
10295 /* Value is a vector of all pixel colors contained in the color table,
10296 allocated via xmalloc. Set *N to the number of colors. */
10297
10298 static unsigned long *
10299 colors_in_color_table (n)
10300 int *n;
10301 {
10302 int i, j;
10303 struct ct_color *p;
10304 unsigned long *colors;
10305
10306 if (ct_colors_allocated == 0)
10307 {
10308 *n = 0;
10309 colors = NULL;
10310 }
10311 else
10312 {
10313 colors = (unsigned long *) xmalloc (ct_colors_allocated
10314 * sizeof *colors);
10315 *n = ct_colors_allocated;
10316
10317 for (i = j = 0; i < CT_SIZE; ++i)
10318 for (p = ct_table[i]; p; p = p->next)
10319 colors[j++] = p->pixel;
10320 }
10321
10322 return colors;
10323 }
10324
10325 #endif /* TODO */
10326
10327 \f
10328 /***********************************************************************
10329 Algorithms
10330 ***********************************************************************/
10331 #if 0 /* TODO: image support. */
10332 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
10333 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
10334 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
10335
10336 /* Non-zero means draw a cross on images having `:conversion
10337 disabled'. */
10338
10339 int cross_disabled_images;
10340
10341 /* Edge detection matrices for different edge-detection
10342 strategies. */
10343
10344 static int emboss_matrix[9] = {
10345 /* x - 1 x x + 1 */
10346 2, -1, 0, /* y - 1 */
10347 -1, 0, 1, /* y */
10348 0, 1, -2 /* y + 1 */
10349 };
10350
10351 static int laplace_matrix[9] = {
10352 /* x - 1 x x + 1 */
10353 1, 0, 0, /* y - 1 */
10354 0, 0, 0, /* y */
10355 0, 0, -1 /* y + 1 */
10356 };
10357
10358 /* Value is the intensity of the color whose red/green/blue values
10359 are R, G, and B. */
10360
10361 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
10362
10363
10364 /* On frame F, return an array of XColor structures describing image
10365 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
10366 non-zero means also fill the red/green/blue members of the XColor
10367 structures. Value is a pointer to the array of XColors structures,
10368 allocated with xmalloc; it must be freed by the caller. */
10369
10370 static XColor *
10371 x_to_xcolors (f, img, rgb_p)
10372 struct frame *f;
10373 struct image *img;
10374 int rgb_p;
10375 {
10376 int x, y;
10377 XColor *colors, *p;
10378 XImage *ximg;
10379
10380 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
10381
10382 /* Get the X image IMG->pixmap. */
10383 ximg = XGetImage (FRAME_X_DISPLAY (f), img->pixmap,
10384 0, 0, img->width, img->height, ~0, ZPixmap);
10385
10386 /* Fill the `pixel' members of the XColor array. I wished there
10387 were an easy and portable way to circumvent XGetPixel. */
10388 p = colors;
10389 for (y = 0; y < img->height; ++y)
10390 {
10391 XColor *row = p;
10392
10393 for (x = 0; x < img->width; ++x, ++p)
10394 p->pixel = XGetPixel (ximg, x, y);
10395
10396 if (rgb_p)
10397 x_query_colors (f, row, img->width);
10398 }
10399
10400 XDestroyImage (ximg);
10401 return colors;
10402 }
10403
10404
10405 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
10406 RGB members are set. F is the frame on which this all happens.
10407 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
10408
10409 static void
10410 x_from_xcolors (f, img, colors)
10411 struct frame *f;
10412 struct image *img;
10413 XColor *colors;
10414 {
10415 int x, y;
10416 XImage *oimg;
10417 Pixmap pixmap;
10418 XColor *p;
10419
10420 init_color_table ();
10421
10422 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
10423 &oimg, &pixmap);
10424 p = colors;
10425 for (y = 0; y < img->height; ++y)
10426 for (x = 0; x < img->width; ++x, ++p)
10427 {
10428 unsigned long pixel;
10429 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
10430 XPutPixel (oimg, x, y, pixel);
10431 }
10432
10433 xfree (colors);
10434 x_clear_image_1 (f, img, 1, 0, 1);
10435
10436 x_put_x_image (f, oimg, pixmap, img->width, img->height);
10437 x_destroy_x_image (oimg);
10438 img->pixmap = pixmap;
10439 img->colors = colors_in_color_table (&img->ncolors);
10440 free_color_table ();
10441 }
10442
10443
10444 /* On frame F, perform edge-detection on image IMG.
10445
10446 MATRIX is a nine-element array specifying the transformation
10447 matrix. See emboss_matrix for an example.
10448
10449 COLOR_ADJUST is a color adjustment added to each pixel of the
10450 outgoing image. */
10451
10452 static void
10453 x_detect_edges (f, img, matrix, color_adjust)
10454 struct frame *f;
10455 struct image *img;
10456 int matrix[9], color_adjust;
10457 {
10458 XColor *colors = x_to_xcolors (f, img, 1);
10459 XColor *new, *p;
10460 int x, y, i, sum;
10461
10462 for (i = sum = 0; i < 9; ++i)
10463 sum += abs (matrix[i]);
10464
10465 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
10466
10467 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
10468
10469 for (y = 0; y < img->height; ++y)
10470 {
10471 p = COLOR (new, 0, y);
10472 p->red = p->green = p->blue = 0xffff/2;
10473 p = COLOR (new, img->width - 1, y);
10474 p->red = p->green = p->blue = 0xffff/2;
10475 }
10476
10477 for (x = 1; x < img->width - 1; ++x)
10478 {
10479 p = COLOR (new, x, 0);
10480 p->red = p->green = p->blue = 0xffff/2;
10481 p = COLOR (new, x, img->height - 1);
10482 p->red = p->green = p->blue = 0xffff/2;
10483 }
10484
10485 for (y = 1; y < img->height - 1; ++y)
10486 {
10487 p = COLOR (new, 1, y);
10488
10489 for (x = 1; x < img->width - 1; ++x, ++p)
10490 {
10491 int r, g, b, y1, x1;
10492
10493 r = g = b = i = 0;
10494 for (y1 = y - 1; y1 < y + 2; ++y1)
10495 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
10496 if (matrix[i])
10497 {
10498 XColor *t = COLOR (colors, x1, y1);
10499 r += matrix[i] * t->red;
10500 g += matrix[i] * t->green;
10501 b += matrix[i] * t->blue;
10502 }
10503
10504 r = (r / sum + color_adjust) & 0xffff;
10505 g = (g / sum + color_adjust) & 0xffff;
10506 b = (b / sum + color_adjust) & 0xffff;
10507 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
10508 }
10509 }
10510
10511 xfree (colors);
10512 x_from_xcolors (f, img, new);
10513
10514 #undef COLOR
10515 }
10516
10517
10518 /* Perform the pre-defined `emboss' edge-detection on image IMG
10519 on frame F. */
10520
10521 static void
10522 x_emboss (f, img)
10523 struct frame *f;
10524 struct image *img;
10525 {
10526 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
10527 }
10528
10529
10530 /* Transform image IMG which is used on frame F with a Laplace
10531 edge-detection algorithm. The result is an image that can be used
10532 to draw disabled buttons, for example. */
10533
10534 static void
10535 x_laplace (f, img)
10536 struct frame *f;
10537 struct image *img;
10538 {
10539 x_detect_edges (f, img, laplace_matrix, 45000);
10540 }
10541
10542
10543 /* Perform edge-detection on image IMG on frame F, with specified
10544 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
10545
10546 MATRIX must be either
10547
10548 - a list of at least 9 numbers in row-major form
10549 - a vector of at least 9 numbers
10550
10551 COLOR_ADJUST nil means use a default; otherwise it must be a
10552 number. */
10553
10554 static void
10555 x_edge_detection (f, img, matrix, color_adjust)
10556 struct frame *f;
10557 struct image *img;
10558 Lisp_Object matrix, color_adjust;
10559 {
10560 int i = 0;
10561 int trans[9];
10562
10563 if (CONSP (matrix))
10564 {
10565 for (i = 0;
10566 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
10567 ++i, matrix = XCDR (matrix))
10568 trans[i] = XFLOATINT (XCAR (matrix));
10569 }
10570 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
10571 {
10572 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
10573 trans[i] = XFLOATINT (AREF (matrix, i));
10574 }
10575
10576 if (NILP (color_adjust))
10577 color_adjust = make_number (0xffff / 2);
10578
10579 if (i == 9 && NUMBERP (color_adjust))
10580 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
10581 }
10582
10583
10584 /* Transform image IMG on frame F so that it looks disabled. */
10585
10586 static void
10587 x_disable_image (f, img)
10588 struct frame *f;
10589 struct image *img;
10590 {
10591 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
10592
10593 if (dpyinfo->n_planes >= 2)
10594 {
10595 /* Color (or grayscale). Convert to gray, and equalize. Just
10596 drawing such images with a stipple can look very odd, so
10597 we're using this method instead. */
10598 XColor *colors = x_to_xcolors (f, img, 1);
10599 XColor *p, *end;
10600 const int h = 15000;
10601 const int l = 30000;
10602
10603 for (p = colors, end = colors + img->width * img->height;
10604 p < end;
10605 ++p)
10606 {
10607 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
10608 int i2 = (0xffff - h - l) * i / 0xffff + l;
10609 p->red = p->green = p->blue = i2;
10610 }
10611
10612 x_from_xcolors (f, img, colors);
10613 }
10614
10615 /* Draw a cross over the disabled image, if we must or if we
10616 should. */
10617 if (dpyinfo->n_planes < 2 || cross_disabled_images)
10618 {
10619 Display *dpy = FRAME_X_DISPLAY (f);
10620 GC gc;
10621
10622 gc = XCreateGC (dpy, img->pixmap, 0, NULL);
10623 XSetForeground (dpy, gc, BLACK_PIX_DEFAULT (f));
10624 XDrawLine (dpy, img->pixmap, gc, 0, 0,
10625 img->width - 1, img->height - 1);
10626 XDrawLine (dpy, img->pixmap, gc, 0, img->height - 1,
10627 img->width - 1, 0);
10628 XFreeGC (dpy, gc);
10629
10630 if (img->mask)
10631 {
10632 gc = XCreateGC (dpy, img->mask, 0, NULL);
10633 XSetForeground (dpy, gc, WHITE_PIX_DEFAULT (f));
10634 XDrawLine (dpy, img->mask, gc, 0, 0,
10635 img->width - 1, img->height - 1);
10636 XDrawLine (dpy, img->mask, gc, 0, img->height - 1,
10637 img->width - 1, 0);
10638 XFreeGC (dpy, gc);
10639 }
10640 }
10641 }
10642
10643
10644 /* Build a mask for image IMG which is used on frame F. FILE is the
10645 name of an image file, for error messages. HOW determines how to
10646 determine the background color of IMG. If it is a list '(R G B)',
10647 with R, G, and B being integers >= 0, take that as the color of the
10648 background. Otherwise, determine the background color of IMG
10649 heuristically. Value is non-zero if successful. */
10650
10651 static int
10652 x_build_heuristic_mask (f, img, how)
10653 struct frame *f;
10654 struct image *img;
10655 Lisp_Object how;
10656 {
10657 Display *dpy = FRAME_W32_DISPLAY (f);
10658 XImage *ximg, *mask_img;
10659 int x, y, rc, use_img_background;
10660 unsigned long bg = 0;
10661
10662 if (img->mask)
10663 {
10664 XFreePixmap (FRAME_X_DISPLAY (f), img->mask);
10665 img->mask = None;
10666 img->background_transparent_valid = 0;
10667 }
10668
10669 /* Create an image and pixmap serving as mask. */
10670 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
10671 &mask_img, &img->mask);
10672 if (!rc)
10673 return 0;
10674
10675 /* Get the X image of IMG->pixmap. */
10676 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
10677 ~0, ZPixmap);
10678
10679 /* Determine the background color of ximg. If HOW is `(R G B)'
10680 take that as color. Otherwise, use the image's background color. */
10681 use_img_background = 1;
10682
10683 if (CONSP (how))
10684 {
10685 int rgb[3], i;
10686
10687 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
10688 {
10689 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
10690 how = XCDR (how);
10691 }
10692
10693 if (i == 3 && NILP (how))
10694 {
10695 char color_name[30];
10696 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
10697 bg = x_alloc_image_color (f, img, build_string (color_name), 0);
10698 use_img_background = 0;
10699 }
10700 }
10701
10702 if (use_img_background)
10703 bg = four_corners_best (ximg, img->width, img->height);
10704
10705 /* Set all bits in mask_img to 1 whose color in ximg is different
10706 from the background color bg. */
10707 for (y = 0; y < img->height; ++y)
10708 for (x = 0; x < img->width; ++x)
10709 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
10710
10711 /* Fill in the background_transparent field while we have the mask handy. */
10712 image_background_transparent (img, f, mask_img);
10713
10714 /* Put mask_img into img->mask. */
10715 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10716 x_destroy_x_image (mask_img);
10717 XDestroyImage (ximg);
10718
10719 return 1;
10720 }
10721 #endif /* TODO */
10722
10723 \f
10724 /***********************************************************************
10725 PBM (mono, gray, color)
10726 ***********************************************************************/
10727 #ifdef HAVE_PBM
10728
10729 static int pbm_image_p P_ ((Lisp_Object object));
10730 static int pbm_load P_ ((struct frame *f, struct image *img));
10731 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
10732
10733 /* The symbol `pbm' identifying images of this type. */
10734
10735 Lisp_Object Qpbm;
10736
10737 /* Indices of image specification fields in gs_format, below. */
10738
10739 enum pbm_keyword_index
10740 {
10741 PBM_TYPE,
10742 PBM_FILE,
10743 PBM_DATA,
10744 PBM_ASCENT,
10745 PBM_MARGIN,
10746 PBM_RELIEF,
10747 PBM_ALGORITHM,
10748 PBM_HEURISTIC_MASK,
10749 PBM_MASK,
10750 PBM_FOREGROUND,
10751 PBM_BACKGROUND,
10752 PBM_LAST
10753 };
10754
10755 /* Vector of image_keyword structures describing the format
10756 of valid user-defined image specifications. */
10757
10758 static struct image_keyword pbm_format[PBM_LAST] =
10759 {
10760 {":type", IMAGE_SYMBOL_VALUE, 1},
10761 {":file", IMAGE_STRING_VALUE, 0},
10762 {":data", IMAGE_STRING_VALUE, 0},
10763 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10764 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10765 {":relief", IMAGE_INTEGER_VALUE, 0},
10766 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10767 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10768 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10769 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
10770 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
10771 };
10772
10773 /* Structure describing the image type `pbm'. */
10774
10775 static struct image_type pbm_type =
10776 {
10777 &Qpbm,
10778 pbm_image_p,
10779 pbm_load,
10780 x_clear_image,
10781 NULL
10782 };
10783
10784
10785 /* Return non-zero if OBJECT is a valid PBM image specification. */
10786
10787 static int
10788 pbm_image_p (object)
10789 Lisp_Object object;
10790 {
10791 struct image_keyword fmt[PBM_LAST];
10792
10793 bcopy (pbm_format, fmt, sizeof fmt);
10794
10795 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
10796 || (fmt[PBM_ASCENT].count
10797 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
10798 return 0;
10799
10800 /* Must specify either :data or :file. */
10801 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
10802 }
10803
10804
10805 /* Scan a decimal number from *S and return it. Advance *S while
10806 reading the number. END is the end of the string. Value is -1 at
10807 end of input. */
10808
10809 static int
10810 pbm_scan_number (s, end)
10811 unsigned char **s, *end;
10812 {
10813 int c, val = -1;
10814
10815 while (*s < end)
10816 {
10817 /* Skip white-space. */
10818 while (*s < end && (c = *(*s)++, isspace (c)))
10819 ;
10820
10821 if (c == '#')
10822 {
10823 /* Skip comment to end of line. */
10824 while (*s < end && (c = *(*s)++, c != '\n'))
10825 ;
10826 }
10827 else if (isdigit (c))
10828 {
10829 /* Read decimal number. */
10830 val = c - '0';
10831 while (*s < end && (c = *(*s)++, isdigit (c)))
10832 val = 10 * val + c - '0';
10833 break;
10834 }
10835 else
10836 break;
10837 }
10838
10839 return val;
10840 }
10841
10842
10843 /* Read FILE into memory. Value is a pointer to a buffer allocated
10844 with xmalloc holding FILE's contents. Value is null if an error
10845 occured. *SIZE is set to the size of the file. */
10846
10847 static char *
10848 pbm_read_file (file, size)
10849 Lisp_Object file;
10850 int *size;
10851 {
10852 FILE *fp = NULL;
10853 char *buf = NULL;
10854 struct stat st;
10855
10856 if (stat (XSTRING (file)->data, &st) == 0
10857 && (fp = fopen (XSTRING (file)->data, "r")) != NULL
10858 && (buf = (char *) xmalloc (st.st_size),
10859 fread (buf, 1, st.st_size, fp) == st.st_size))
10860 {
10861 *size = st.st_size;
10862 fclose (fp);
10863 }
10864 else
10865 {
10866 if (fp)
10867 fclose (fp);
10868 if (buf)
10869 {
10870 xfree (buf);
10871 buf = NULL;
10872 }
10873 }
10874
10875 return buf;
10876 }
10877
10878
10879 /* Load PBM image IMG for use on frame F. */
10880
10881 static int
10882 pbm_load (f, img)
10883 struct frame *f;
10884 struct image *img;
10885 {
10886 int raw_p, x, y;
10887 int width, height, max_color_idx = 0;
10888 XImage *ximg;
10889 Lisp_Object file, specified_file;
10890 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
10891 struct gcpro gcpro1;
10892 unsigned char *contents = NULL;
10893 unsigned char *end, *p;
10894 int size;
10895
10896 specified_file = image_spec_value (img->spec, QCfile, NULL);
10897 file = Qnil;
10898 GCPRO1 (file);
10899
10900 if (STRINGP (specified_file))
10901 {
10902 file = x_find_image_file (specified_file);
10903 if (!STRINGP (file))
10904 {
10905 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10906 UNGCPRO;
10907 return 0;
10908 }
10909
10910 contents = slurp_file (XSTRING (file)->data, &size);
10911 if (contents == NULL)
10912 {
10913 image_error ("Error reading `%s'", file, Qnil);
10914 UNGCPRO;
10915 return 0;
10916 }
10917
10918 p = contents;
10919 end = contents + size;
10920 }
10921 else
10922 {
10923 Lisp_Object data;
10924 data = image_spec_value (img->spec, QCdata, NULL);
10925 p = XSTRING (data)->data;
10926 end = p + STRING_BYTES (XSTRING (data));
10927 }
10928
10929 /* Check magic number. */
10930 if (end - p < 2 || *p++ != 'P')
10931 {
10932 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10933 error:
10934 xfree (contents);
10935 UNGCPRO;
10936 return 0;
10937 }
10938
10939 switch (*p++)
10940 {
10941 case '1':
10942 raw_p = 0, type = PBM_MONO;
10943 break;
10944
10945 case '2':
10946 raw_p = 0, type = PBM_GRAY;
10947 break;
10948
10949 case '3':
10950 raw_p = 0, type = PBM_COLOR;
10951 break;
10952
10953 case '4':
10954 raw_p = 1, type = PBM_MONO;
10955 break;
10956
10957 case '5':
10958 raw_p = 1, type = PBM_GRAY;
10959 break;
10960
10961 case '6':
10962 raw_p = 1, type = PBM_COLOR;
10963 break;
10964
10965 default:
10966 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10967 goto error;
10968 }
10969
10970 /* Read width, height, maximum color-component. Characters
10971 starting with `#' up to the end of a line are ignored. */
10972 width = pbm_scan_number (&p, end);
10973 height = pbm_scan_number (&p, end);
10974
10975 if (type != PBM_MONO)
10976 {
10977 max_color_idx = pbm_scan_number (&p, end);
10978 if (raw_p && max_color_idx > 255)
10979 max_color_idx = 255;
10980 }
10981
10982 if (width < 0
10983 || height < 0
10984 || (type != PBM_MONO && max_color_idx < 0))
10985 goto error;
10986
10987 if (!x_create_x_image_and_pixmap (f, width, height, 0,
10988 &ximg, &img->pixmap))
10989 goto error;
10990
10991 /* Initialize the color hash table. */
10992 init_color_table ();
10993
10994 if (type == PBM_MONO)
10995 {
10996 int c = 0, g;
10997 struct image_keyword fmt[PBM_LAST];
10998 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
10999 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
11000
11001 /* Parse the image specification. */
11002 bcopy (pbm_format, fmt, sizeof fmt);
11003 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
11004
11005 /* Get foreground and background colors, maybe allocate colors. */
11006 if (fmt[PBM_FOREGROUND].count
11007 && STRINGP (fmt[PBM_FOREGROUND].value))
11008 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
11009 if (fmt[PBM_BACKGROUND].count
11010 && STRINGP (fmt[PBM_BACKGROUND].value))
11011 {
11012 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
11013 img->background = bg;
11014 img->background_valid = 1;
11015 }
11016
11017 for (y = 0; y < height; ++y)
11018 for (x = 0; x < width; ++x)
11019 {
11020 if (raw_p)
11021 {
11022 if ((x & 7) == 0)
11023 c = *p++;
11024 g = c & 0x80;
11025 c <<= 1;
11026 }
11027 else
11028 g = pbm_scan_number (&p, end);
11029
11030 XPutPixel (ximg, x, y, g ? fg : bg);
11031 }
11032 }
11033 else
11034 {
11035 for (y = 0; y < height; ++y)
11036 for (x = 0; x < width; ++x)
11037 {
11038 int r, g, b;
11039
11040 if (type == PBM_GRAY)
11041 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
11042 else if (raw_p)
11043 {
11044 r = *p++;
11045 g = *p++;
11046 b = *p++;
11047 }
11048 else
11049 {
11050 r = pbm_scan_number (&p, end);
11051 g = pbm_scan_number (&p, end);
11052 b = pbm_scan_number (&p, end);
11053 }
11054
11055 if (r < 0 || g < 0 || b < 0)
11056 {
11057 xfree (ximg->data);
11058 ximg->data = NULL;
11059 XDestroyImage (ximg);
11060 image_error ("Invalid pixel value in image `%s'",
11061 img->spec, Qnil);
11062 goto error;
11063 }
11064
11065 /* RGB values are now in the range 0..max_color_idx.
11066 Scale this to the range 0..0xffff supported by X. */
11067 r = (double) r * 65535 / max_color_idx;
11068 g = (double) g * 65535 / max_color_idx;
11069 b = (double) b * 65535 / max_color_idx;
11070 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
11071 }
11072 }
11073
11074 /* Store in IMG->colors the colors allocated for the image, and
11075 free the color table. */
11076 img->colors = colors_in_color_table (&img->ncolors);
11077 free_color_table ();
11078
11079 /* Maybe fill in the background field while we have ximg handy. */
11080 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11081 IMAGE_BACKGROUND (img, f, ximg);
11082
11083 /* Put the image into a pixmap. */
11084 x_put_x_image (f, ximg, img->pixmap, width, height);
11085 x_destroy_x_image (ximg);
11086
11087 img->width = width;
11088 img->height = height;
11089
11090 UNGCPRO;
11091 xfree (contents);
11092 return 1;
11093 }
11094 #endif /* HAVE_PBM */
11095
11096 \f
11097 /***********************************************************************
11098 PNG
11099 ***********************************************************************/
11100
11101 #if HAVE_PNG
11102
11103 #include <png.h>
11104
11105 /* Function prototypes. */
11106
11107 static int png_image_p P_ ((Lisp_Object object));
11108 static int png_load P_ ((struct frame *f, struct image *img));
11109
11110 /* The symbol `png' identifying images of this type. */
11111
11112 Lisp_Object Qpng;
11113
11114 /* Indices of image specification fields in png_format, below. */
11115
11116 enum png_keyword_index
11117 {
11118 PNG_TYPE,
11119 PNG_DATA,
11120 PNG_FILE,
11121 PNG_ASCENT,
11122 PNG_MARGIN,
11123 PNG_RELIEF,
11124 PNG_ALGORITHM,
11125 PNG_HEURISTIC_MASK,
11126 PNG_MASK,
11127 PNG_BACKGROUND,
11128 PNG_LAST
11129 };
11130
11131 /* Vector of image_keyword structures describing the format
11132 of valid user-defined image specifications. */
11133
11134 static struct image_keyword png_format[PNG_LAST] =
11135 {
11136 {":type", IMAGE_SYMBOL_VALUE, 1},
11137 {":data", IMAGE_STRING_VALUE, 0},
11138 {":file", IMAGE_STRING_VALUE, 0},
11139 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11140 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11141 {":relief", IMAGE_INTEGER_VALUE, 0},
11142 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11143 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11144 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11145 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11146 };
11147
11148 /* Structure describing the image type `png'. */
11149
11150 static struct image_type png_type =
11151 {
11152 &Qpng,
11153 png_image_p,
11154 png_load,
11155 x_clear_image,
11156 NULL
11157 };
11158
11159
11160 /* Return non-zero if OBJECT is a valid PNG image specification. */
11161
11162 static int
11163 png_image_p (object)
11164 Lisp_Object object;
11165 {
11166 struct image_keyword fmt[PNG_LAST];
11167 bcopy (png_format, fmt, sizeof fmt);
11168
11169 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
11170 || (fmt[PNG_ASCENT].count
11171 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
11172 return 0;
11173
11174 /* Must specify either the :data or :file keyword. */
11175 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
11176 }
11177
11178
11179 /* Error and warning handlers installed when the PNG library
11180 is initialized. */
11181
11182 static void
11183 my_png_error (png_ptr, msg)
11184 png_struct *png_ptr;
11185 char *msg;
11186 {
11187 xassert (png_ptr != NULL);
11188 image_error ("PNG error: %s", build_string (msg), Qnil);
11189 longjmp (png_ptr->jmpbuf, 1);
11190 }
11191
11192
11193 static void
11194 my_png_warning (png_ptr, msg)
11195 png_struct *png_ptr;
11196 char *msg;
11197 {
11198 xassert (png_ptr != NULL);
11199 image_error ("PNG warning: %s", build_string (msg), Qnil);
11200 }
11201
11202 /* Memory source for PNG decoding. */
11203
11204 struct png_memory_storage
11205 {
11206 unsigned char *bytes; /* The data */
11207 size_t len; /* How big is it? */
11208 int index; /* Where are we? */
11209 };
11210
11211
11212 /* Function set as reader function when reading PNG image from memory.
11213 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
11214 bytes from the input to DATA. */
11215
11216 static void
11217 png_read_from_memory (png_ptr, data, length)
11218 png_structp png_ptr;
11219 png_bytep data;
11220 png_size_t length;
11221 {
11222 struct png_memory_storage *tbr
11223 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
11224
11225 if (length > tbr->len - tbr->index)
11226 png_error (png_ptr, "Read error");
11227
11228 bcopy (tbr->bytes + tbr->index, data, length);
11229 tbr->index = tbr->index + length;
11230 }
11231
11232 /* Load PNG image IMG for use on frame F. Value is non-zero if
11233 successful. */
11234
11235 static int
11236 png_load (f, img)
11237 struct frame *f;
11238 struct image *img;
11239 {
11240 Lisp_Object file, specified_file;
11241 Lisp_Object specified_data;
11242 int x, y, i;
11243 XImage *ximg, *mask_img = NULL;
11244 struct gcpro gcpro1;
11245 png_struct *png_ptr = NULL;
11246 png_info *info_ptr = NULL, *end_info = NULL;
11247 FILE *volatile fp = NULL;
11248 png_byte sig[8];
11249 png_byte *volatile pixels = NULL;
11250 png_byte **volatile rows = NULL;
11251 png_uint_32 width, height;
11252 int bit_depth, color_type, interlace_type;
11253 png_byte channels;
11254 png_uint_32 row_bytes;
11255 int transparent_p;
11256 char *gamma_str;
11257 double screen_gamma, image_gamma;
11258 int intent;
11259 struct png_memory_storage tbr; /* Data to be read */
11260
11261 /* Find out what file to load. */
11262 specified_file = image_spec_value (img->spec, QCfile, NULL);
11263 specified_data = image_spec_value (img->spec, QCdata, NULL);
11264 file = Qnil;
11265 GCPRO1 (file);
11266
11267 if (NILP (specified_data))
11268 {
11269 file = x_find_image_file (specified_file);
11270 if (!STRINGP (file))
11271 {
11272 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11273 UNGCPRO;
11274 return 0;
11275 }
11276
11277 /* Open the image file. */
11278 fp = fopen (XSTRING (file)->data, "rb");
11279 if (!fp)
11280 {
11281 image_error ("Cannot open image file `%s'", file, Qnil);
11282 UNGCPRO;
11283 fclose (fp);
11284 return 0;
11285 }
11286
11287 /* Check PNG signature. */
11288 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
11289 || !png_check_sig (sig, sizeof sig))
11290 {
11291 image_error ("Not a PNG file:` %s'", file, Qnil);
11292 UNGCPRO;
11293 fclose (fp);
11294 return 0;
11295 }
11296 }
11297 else
11298 {
11299 /* Read from memory. */
11300 tbr.bytes = XSTRING (specified_data)->data;
11301 tbr.len = STRING_BYTES (XSTRING (specified_data));
11302 tbr.index = 0;
11303
11304 /* Check PNG signature. */
11305 if (tbr.len < sizeof sig
11306 || !png_check_sig (tbr.bytes, sizeof sig))
11307 {
11308 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
11309 UNGCPRO;
11310 return 0;
11311 }
11312
11313 /* Need to skip past the signature. */
11314 tbr.bytes += sizeof (sig);
11315 }
11316
11317 /* Initialize read and info structs for PNG lib. */
11318 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
11319 my_png_error, my_png_warning);
11320 if (!png_ptr)
11321 {
11322 if (fp) fclose (fp);
11323 UNGCPRO;
11324 return 0;
11325 }
11326
11327 info_ptr = png_create_info_struct (png_ptr);
11328 if (!info_ptr)
11329 {
11330 png_destroy_read_struct (&png_ptr, NULL, NULL);
11331 if (fp) fclose (fp);
11332 UNGCPRO;
11333 return 0;
11334 }
11335
11336 end_info = png_create_info_struct (png_ptr);
11337 if (!end_info)
11338 {
11339 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
11340 if (fp) fclose (fp);
11341 UNGCPRO;
11342 return 0;
11343 }
11344
11345 /* Set error jump-back. We come back here when the PNG library
11346 detects an error. */
11347 if (setjmp (png_ptr->jmpbuf))
11348 {
11349 error:
11350 if (png_ptr)
11351 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11352 xfree (pixels);
11353 xfree (rows);
11354 if (fp) fclose (fp);
11355 UNGCPRO;
11356 return 0;
11357 }
11358
11359 /* Read image info. */
11360 if (!NILP (specified_data))
11361 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
11362 else
11363 png_init_io (png_ptr, fp);
11364
11365 png_set_sig_bytes (png_ptr, sizeof sig);
11366 png_read_info (png_ptr, info_ptr);
11367 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
11368 &interlace_type, NULL, NULL);
11369
11370 /* If image contains simply transparency data, we prefer to
11371 construct a clipping mask. */
11372 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
11373 transparent_p = 1;
11374 else
11375 transparent_p = 0;
11376
11377 /* This function is easier to write if we only have to handle
11378 one data format: RGB or RGBA with 8 bits per channel. Let's
11379 transform other formats into that format. */
11380
11381 /* Strip more than 8 bits per channel. */
11382 if (bit_depth == 16)
11383 png_set_strip_16 (png_ptr);
11384
11385 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
11386 if available. */
11387 png_set_expand (png_ptr);
11388
11389 /* Convert grayscale images to RGB. */
11390 if (color_type == PNG_COLOR_TYPE_GRAY
11391 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
11392 png_set_gray_to_rgb (png_ptr);
11393
11394 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
11395 gamma_str = getenv ("SCREEN_GAMMA");
11396 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
11397
11398 /* Tell the PNG lib to handle gamma correction for us. */
11399
11400 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
11401 if (png_get_sRGB (png_ptr, info_ptr, &intent))
11402 /* There is a special chunk in the image specifying the gamma. */
11403 png_set_sRGB (png_ptr, info_ptr, intent);
11404 else
11405 #endif
11406 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
11407 /* Image contains gamma information. */
11408 png_set_gamma (png_ptr, screen_gamma, image_gamma);
11409 else
11410 /* Use a default of 0.5 for the image gamma. */
11411 png_set_gamma (png_ptr, screen_gamma, 0.5);
11412
11413 /* Handle alpha channel by combining the image with a background
11414 color. Do this only if a real alpha channel is supplied. For
11415 simple transparency, we prefer a clipping mask. */
11416 if (!transparent_p)
11417 {
11418 png_color_16 *image_background;
11419 Lisp_Object specified_bg
11420 = image_spec_value (img->spec, QCbackground, NULL);
11421
11422
11423 if (STRINGP (specified_bg))
11424 /* The user specified `:background', use that. */
11425 {
11426 COLORREF color;
11427 if (w32_defined_color (f, XSTRING (specified_bg)->data, &color, 0))
11428 {
11429 png_color_16 user_bg;
11430
11431 bzero (&user_bg, sizeof user_bg);
11432 user_bg.red = color.red;
11433 user_bg.green = color.green;
11434 user_bg.blue = color.blue;
11435
11436 png_set_background (png_ptr, &user_bg,
11437 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11438 }
11439 }
11440 else if (png_get_bKGD (png_ptr, info_ptr, &image_background))
11441 /* Image contains a background color with which to
11442 combine the image. */
11443 png_set_background (png_ptr, image_background,
11444 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
11445 else
11446 {
11447 /* Image does not contain a background color with which
11448 to combine the image data via an alpha channel. Use
11449 the frame's background instead. */
11450 XColor color;
11451 Colormap cmap;
11452 png_color_16 frame_background;
11453
11454 cmap = FRAME_X_COLORMAP (f);
11455 color.pixel = FRAME_BACKGROUND_PIXEL (f);
11456 x_query_color (f, &color);
11457
11458 bzero (&frame_background, sizeof frame_background);
11459 frame_background.red = color.red;
11460 frame_background.green = color.green;
11461 frame_background.blue = color.blue;
11462
11463 png_set_background (png_ptr, &frame_background,
11464 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11465 }
11466 }
11467
11468 /* Update info structure. */
11469 png_read_update_info (png_ptr, info_ptr);
11470
11471 /* Get number of channels. Valid values are 1 for grayscale images
11472 and images with a palette, 2 for grayscale images with transparency
11473 information (alpha channel), 3 for RGB images, and 4 for RGB
11474 images with alpha channel, i.e. RGBA. If conversions above were
11475 sufficient we should only have 3 or 4 channels here. */
11476 channels = png_get_channels (png_ptr, info_ptr);
11477 xassert (channels == 3 || channels == 4);
11478
11479 /* Number of bytes needed for one row of the image. */
11480 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
11481
11482 /* Allocate memory for the image. */
11483 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
11484 rows = (png_byte **) xmalloc (height * sizeof *rows);
11485 for (i = 0; i < height; ++i)
11486 rows[i] = pixels + i * row_bytes;
11487
11488 /* Read the entire image. */
11489 png_read_image (png_ptr, rows);
11490 png_read_end (png_ptr, info_ptr);
11491 if (fp)
11492 {
11493 fclose (fp);
11494 fp = NULL;
11495 }
11496
11497 /* Create the X image and pixmap. */
11498 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11499 &img->pixmap))
11500 goto error;
11501
11502 /* Create an image and pixmap serving as mask if the PNG image
11503 contains an alpha channel. */
11504 if (channels == 4
11505 && !transparent_p
11506 && !x_create_x_image_and_pixmap (f, width, height, 1,
11507 &mask_img, &img->mask))
11508 {
11509 x_destroy_x_image (ximg);
11510 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
11511 img->pixmap = 0;
11512 goto error;
11513 }
11514
11515 /* Fill the X image and mask from PNG data. */
11516 init_color_table ();
11517
11518 for (y = 0; y < height; ++y)
11519 {
11520 png_byte *p = rows[y];
11521
11522 for (x = 0; x < width; ++x)
11523 {
11524 unsigned r, g, b;
11525
11526 r = *p++ << 8;
11527 g = *p++ << 8;
11528 b = *p++ << 8;
11529 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
11530
11531 /* An alpha channel, aka mask channel, associates variable
11532 transparency with an image. Where other image formats
11533 support binary transparency---fully transparent or fully
11534 opaque---PNG allows up to 254 levels of partial transparency.
11535 The PNG library implements partial transparency by combining
11536 the image with a specified background color.
11537
11538 I'm not sure how to handle this here nicely: because the
11539 background on which the image is displayed may change, for
11540 real alpha channel support, it would be necessary to create
11541 a new image for each possible background.
11542
11543 What I'm doing now is that a mask is created if we have
11544 boolean transparency information. Otherwise I'm using
11545 the frame's background color to combine the image with. */
11546
11547 if (channels == 4)
11548 {
11549 if (mask_img)
11550 XPutPixel (mask_img, x, y, *p > 0);
11551 ++p;
11552 }
11553 }
11554 }
11555
11556 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11557 /* Set IMG's background color from the PNG image, unless the user
11558 overrode it. */
11559 {
11560 png_color_16 *bg;
11561 if (png_get_bKGD (png_ptr, info_ptr, &bg))
11562 {
11563 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
11564 img->background_valid = 1;
11565 }
11566 }
11567
11568 /* Remember colors allocated for this image. */
11569 img->colors = colors_in_color_table (&img->ncolors);
11570 free_color_table ();
11571
11572 /* Clean up. */
11573 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11574 xfree (rows);
11575 xfree (pixels);
11576
11577 img->width = width;
11578 img->height = height;
11579
11580 /* Maybe fill in the background field while we have ximg handy. */
11581 IMAGE_BACKGROUND (img, f, ximg);
11582
11583 /* Put the image into the pixmap, then free the X image and its buffer. */
11584 x_put_x_image (f, ximg, img->pixmap, width, height);
11585 x_destroy_x_image (ximg);
11586
11587 /* Same for the mask. */
11588 if (mask_img)
11589 {
11590 /* Fill in the background_transparent field while we have the mask
11591 handy. */
11592 image_background_transparent (img, f, mask_img);
11593
11594 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
11595 x_destroy_x_image (mask_img);
11596 }
11597
11598 UNGCPRO;
11599 return 1;
11600 }
11601
11602 #endif /* HAVE_PNG != 0 */
11603
11604
11605 \f
11606 /***********************************************************************
11607 JPEG
11608 ***********************************************************************/
11609
11610 #if HAVE_JPEG
11611
11612 /* Work around a warning about HAVE_STDLIB_H being redefined in
11613 jconfig.h. */
11614 #ifdef HAVE_STDLIB_H
11615 #define HAVE_STDLIB_H_1
11616 #undef HAVE_STDLIB_H
11617 #endif /* HAVE_STLIB_H */
11618
11619 #include <jpeglib.h>
11620 #include <jerror.h>
11621 #include <setjmp.h>
11622
11623 #ifdef HAVE_STLIB_H_1
11624 #define HAVE_STDLIB_H 1
11625 #endif
11626
11627 static int jpeg_image_p P_ ((Lisp_Object object));
11628 static int jpeg_load P_ ((struct frame *f, struct image *img));
11629
11630 /* The symbol `jpeg' identifying images of this type. */
11631
11632 Lisp_Object Qjpeg;
11633
11634 /* Indices of image specification fields in gs_format, below. */
11635
11636 enum jpeg_keyword_index
11637 {
11638 JPEG_TYPE,
11639 JPEG_DATA,
11640 JPEG_FILE,
11641 JPEG_ASCENT,
11642 JPEG_MARGIN,
11643 JPEG_RELIEF,
11644 JPEG_ALGORITHM,
11645 JPEG_HEURISTIC_MASK,
11646 JPEG_MASK,
11647 JPEG_BACKGROUND,
11648 JPEG_LAST
11649 };
11650
11651 /* Vector of image_keyword structures describing the format
11652 of valid user-defined image specifications. */
11653
11654 static struct image_keyword jpeg_format[JPEG_LAST] =
11655 {
11656 {":type", IMAGE_SYMBOL_VALUE, 1},
11657 {":data", IMAGE_STRING_VALUE, 0},
11658 {":file", IMAGE_STRING_VALUE, 0},
11659 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11660 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11661 {":relief", IMAGE_INTEGER_VALUE, 0},
11662 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11663 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11664 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11665 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11666 };
11667
11668 /* Structure describing the image type `jpeg'. */
11669
11670 static struct image_type jpeg_type =
11671 {
11672 &Qjpeg,
11673 jpeg_image_p,
11674 jpeg_load,
11675 x_clear_image,
11676 NULL
11677 };
11678
11679
11680 /* Return non-zero if OBJECT is a valid JPEG image specification. */
11681
11682 static int
11683 jpeg_image_p (object)
11684 Lisp_Object object;
11685 {
11686 struct image_keyword fmt[JPEG_LAST];
11687
11688 bcopy (jpeg_format, fmt, sizeof fmt);
11689
11690 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
11691 || (fmt[JPEG_ASCENT].count
11692 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
11693 return 0;
11694
11695 /* Must specify either the :data or :file keyword. */
11696 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
11697 }
11698
11699
11700 struct my_jpeg_error_mgr
11701 {
11702 struct jpeg_error_mgr pub;
11703 jmp_buf setjmp_buffer;
11704 };
11705
11706 static void
11707 my_error_exit (cinfo)
11708 j_common_ptr cinfo;
11709 {
11710 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
11711 longjmp (mgr->setjmp_buffer, 1);
11712 }
11713
11714 /* Init source method for JPEG data source manager. Called by
11715 jpeg_read_header() before any data is actually read. See
11716 libjpeg.doc from the JPEG lib distribution. */
11717
11718 static void
11719 our_init_source (cinfo)
11720 j_decompress_ptr cinfo;
11721 {
11722 }
11723
11724
11725 /* Fill input buffer method for JPEG data source manager. Called
11726 whenever more data is needed. We read the whole image in one step,
11727 so this only adds a fake end of input marker at the end. */
11728
11729 static boolean
11730 our_fill_input_buffer (cinfo)
11731 j_decompress_ptr cinfo;
11732 {
11733 /* Insert a fake EOI marker. */
11734 struct jpeg_source_mgr *src = cinfo->src;
11735 static JOCTET buffer[2];
11736
11737 buffer[0] = (JOCTET) 0xFF;
11738 buffer[1] = (JOCTET) JPEG_EOI;
11739
11740 src->next_input_byte = buffer;
11741 src->bytes_in_buffer = 2;
11742 return TRUE;
11743 }
11744
11745
11746 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
11747 is the JPEG data source manager. */
11748
11749 static void
11750 our_skip_input_data (cinfo, num_bytes)
11751 j_decompress_ptr cinfo;
11752 long num_bytes;
11753 {
11754 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
11755
11756 if (src)
11757 {
11758 if (num_bytes > src->bytes_in_buffer)
11759 ERREXIT (cinfo, JERR_INPUT_EOF);
11760
11761 src->bytes_in_buffer -= num_bytes;
11762 src->next_input_byte += num_bytes;
11763 }
11764 }
11765
11766
11767 /* Method to terminate data source. Called by
11768 jpeg_finish_decompress() after all data has been processed. */
11769
11770 static void
11771 our_term_source (cinfo)
11772 j_decompress_ptr cinfo;
11773 {
11774 }
11775
11776
11777 /* Set up the JPEG lib for reading an image from DATA which contains
11778 LEN bytes. CINFO is the decompression info structure created for
11779 reading the image. */
11780
11781 static void
11782 jpeg_memory_src (cinfo, data, len)
11783 j_decompress_ptr cinfo;
11784 JOCTET *data;
11785 unsigned int len;
11786 {
11787 struct jpeg_source_mgr *src;
11788
11789 if (cinfo->src == NULL)
11790 {
11791 /* First time for this JPEG object? */
11792 cinfo->src = (struct jpeg_source_mgr *)
11793 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
11794 sizeof (struct jpeg_source_mgr));
11795 src = (struct jpeg_source_mgr *) cinfo->src;
11796 src->next_input_byte = data;
11797 }
11798
11799 src = (struct jpeg_source_mgr *) cinfo->src;
11800 src->init_source = our_init_source;
11801 src->fill_input_buffer = our_fill_input_buffer;
11802 src->skip_input_data = our_skip_input_data;
11803 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
11804 src->term_source = our_term_source;
11805 src->bytes_in_buffer = len;
11806 src->next_input_byte = data;
11807 }
11808
11809
11810 /* Load image IMG for use on frame F. Patterned after example.c
11811 from the JPEG lib. */
11812
11813 static int
11814 jpeg_load (f, img)
11815 struct frame *f;
11816 struct image *img;
11817 {
11818 struct jpeg_decompress_struct cinfo;
11819 struct my_jpeg_error_mgr mgr;
11820 Lisp_Object file, specified_file;
11821 Lisp_Object specified_data;
11822 FILE * volatile fp = NULL;
11823 JSAMPARRAY buffer;
11824 int row_stride, x, y;
11825 XImage *ximg = NULL;
11826 int rc;
11827 unsigned long *colors;
11828 int width, height;
11829 struct gcpro gcpro1;
11830
11831 /* Open the JPEG file. */
11832 specified_file = image_spec_value (img->spec, QCfile, NULL);
11833 specified_data = image_spec_value (img->spec, QCdata, NULL);
11834 file = Qnil;
11835 GCPRO1 (file);
11836
11837 if (NILP (specified_data))
11838 {
11839 file = x_find_image_file (specified_file);
11840 if (!STRINGP (file))
11841 {
11842 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11843 UNGCPRO;
11844 return 0;
11845 }
11846
11847 fp = fopen (XSTRING (file)->data, "r");
11848 if (fp == NULL)
11849 {
11850 image_error ("Cannot open `%s'", file, Qnil);
11851 UNGCPRO;
11852 return 0;
11853 }
11854 }
11855
11856 /* Customize libjpeg's error handling to call my_error_exit when an
11857 error is detected. This function will perform a longjmp. */
11858 cinfo.err = jpeg_std_error (&mgr.pub);
11859 mgr.pub.error_exit = my_error_exit;
11860
11861 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
11862 {
11863 if (rc == 1)
11864 {
11865 /* Called from my_error_exit. Display a JPEG error. */
11866 char buffer[JMSG_LENGTH_MAX];
11867 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
11868 image_error ("Error reading JPEG image `%s': %s", img->spec,
11869 build_string (buffer));
11870 }
11871
11872 /* Close the input file and destroy the JPEG object. */
11873 if (fp)
11874 fclose (fp);
11875 jpeg_destroy_decompress (&cinfo);
11876
11877 /* If we already have an XImage, free that. */
11878 x_destroy_x_image (ximg);
11879
11880 /* Free pixmap and colors. */
11881 x_clear_image (f, img);
11882
11883 UNGCPRO;
11884 return 0;
11885 }
11886
11887 /* Create the JPEG decompression object. Let it read from fp.
11888 Read the JPEG image header. */
11889 jpeg_create_decompress (&cinfo);
11890
11891 if (NILP (specified_data))
11892 jpeg_stdio_src (&cinfo, fp);
11893 else
11894 jpeg_memory_src (&cinfo, XSTRING (specified_data)->data,
11895 STRING_BYTES (XSTRING (specified_data)));
11896
11897 jpeg_read_header (&cinfo, TRUE);
11898
11899 /* Customize decompression so that color quantization will be used.
11900 Start decompression. */
11901 cinfo.quantize_colors = TRUE;
11902 jpeg_start_decompress (&cinfo);
11903 width = img->width = cinfo.output_width;
11904 height = img->height = cinfo.output_height;
11905
11906 /* Create X image and pixmap. */
11907 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11908 &img->pixmap))
11909 longjmp (mgr.setjmp_buffer, 2);
11910
11911 /* Allocate colors. When color quantization is used,
11912 cinfo.actual_number_of_colors has been set with the number of
11913 colors generated, and cinfo.colormap is a two-dimensional array
11914 of color indices in the range 0..cinfo.actual_number_of_colors.
11915 No more than 255 colors will be generated. */
11916 {
11917 int i, ir, ig, ib;
11918
11919 if (cinfo.out_color_components > 2)
11920 ir = 0, ig = 1, ib = 2;
11921 else if (cinfo.out_color_components > 1)
11922 ir = 0, ig = 1, ib = 0;
11923 else
11924 ir = 0, ig = 0, ib = 0;
11925
11926 /* Use the color table mechanism because it handles colors that
11927 cannot be allocated nicely. Such colors will be replaced with
11928 a default color, and we don't have to care about which colors
11929 can be freed safely, and which can't. */
11930 init_color_table ();
11931 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
11932 * sizeof *colors);
11933
11934 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
11935 {
11936 /* Multiply RGB values with 255 because X expects RGB values
11937 in the range 0..0xffff. */
11938 int r = cinfo.colormap[ir][i] << 8;
11939 int g = cinfo.colormap[ig][i] << 8;
11940 int b = cinfo.colormap[ib][i] << 8;
11941 colors[i] = lookup_rgb_color (f, r, g, b);
11942 }
11943
11944 /* Remember those colors actually allocated. */
11945 img->colors = colors_in_color_table (&img->ncolors);
11946 free_color_table ();
11947 }
11948
11949 /* Read pixels. */
11950 row_stride = width * cinfo.output_components;
11951 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
11952 row_stride, 1);
11953 for (y = 0; y < height; ++y)
11954 {
11955 jpeg_read_scanlines (&cinfo, buffer, 1);
11956 for (x = 0; x < cinfo.output_width; ++x)
11957 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
11958 }
11959
11960 /* Clean up. */
11961 jpeg_finish_decompress (&cinfo);
11962 jpeg_destroy_decompress (&cinfo);
11963 if (fp)
11964 fclose (fp);
11965
11966 /* Maybe fill in the background field while we have ximg handy. */
11967 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11968 IMAGE_BACKGROUND (img, f, ximg);
11969
11970 /* Put the image into the pixmap. */
11971 x_put_x_image (f, ximg, img->pixmap, width, height);
11972 x_destroy_x_image (ximg);
11973 UNBLOCK_INPUT;
11974 UNGCPRO;
11975 return 1;
11976 }
11977
11978 #endif /* HAVE_JPEG */
11979
11980
11981 \f
11982 /***********************************************************************
11983 TIFF
11984 ***********************************************************************/
11985
11986 #if HAVE_TIFF
11987
11988 #include <tiffio.h>
11989
11990 static int tiff_image_p P_ ((Lisp_Object object));
11991 static int tiff_load P_ ((struct frame *f, struct image *img));
11992
11993 /* The symbol `tiff' identifying images of this type. */
11994
11995 Lisp_Object Qtiff;
11996
11997 /* Indices of image specification fields in tiff_format, below. */
11998
11999 enum tiff_keyword_index
12000 {
12001 TIFF_TYPE,
12002 TIFF_DATA,
12003 TIFF_FILE,
12004 TIFF_ASCENT,
12005 TIFF_MARGIN,
12006 TIFF_RELIEF,
12007 TIFF_ALGORITHM,
12008 TIFF_HEURISTIC_MASK,
12009 TIFF_MASK,
12010 TIFF_BACKGROUND,
12011 TIFF_LAST
12012 };
12013
12014 /* Vector of image_keyword structures describing the format
12015 of valid user-defined image specifications. */
12016
12017 static struct image_keyword tiff_format[TIFF_LAST] =
12018 {
12019 {":type", IMAGE_SYMBOL_VALUE, 1},
12020 {":data", IMAGE_STRING_VALUE, 0},
12021 {":file", IMAGE_STRING_VALUE, 0},
12022 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12023 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12024 {":relief", IMAGE_INTEGER_VALUE, 0},
12025 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12026 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12027 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12028 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12029 };
12030
12031 /* Structure describing the image type `tiff'. */
12032
12033 static struct image_type tiff_type =
12034 {
12035 &Qtiff,
12036 tiff_image_p,
12037 tiff_load,
12038 x_clear_image,
12039 NULL
12040 };
12041
12042
12043 /* Return non-zero if OBJECT is a valid TIFF image specification. */
12044
12045 static int
12046 tiff_image_p (object)
12047 Lisp_Object object;
12048 {
12049 struct image_keyword fmt[TIFF_LAST];
12050 bcopy (tiff_format, fmt, sizeof fmt);
12051
12052 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
12053 || (fmt[TIFF_ASCENT].count
12054 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
12055 return 0;
12056
12057 /* Must specify either the :data or :file keyword. */
12058 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
12059 }
12060
12061
12062 /* Reading from a memory buffer for TIFF images Based on the PNG
12063 memory source, but we have to provide a lot of extra functions.
12064 Blah.
12065
12066 We really only need to implement read and seek, but I am not
12067 convinced that the TIFF library is smart enough not to destroy
12068 itself if we only hand it the function pointers we need to
12069 override. */
12070
12071 typedef struct
12072 {
12073 unsigned char *bytes;
12074 size_t len;
12075 int index;
12076 }
12077 tiff_memory_source;
12078
12079 static size_t
12080 tiff_read_from_memory (data, buf, size)
12081 thandle_t data;
12082 tdata_t buf;
12083 tsize_t size;
12084 {
12085 tiff_memory_source *src = (tiff_memory_source *) data;
12086
12087 if (size > src->len - src->index)
12088 return (size_t) -1;
12089 bcopy (src->bytes + src->index, buf, size);
12090 src->index += size;
12091 return size;
12092 }
12093
12094 static size_t
12095 tiff_write_from_memory (data, buf, size)
12096 thandle_t data;
12097 tdata_t buf;
12098 tsize_t size;
12099 {
12100 return (size_t) -1;
12101 }
12102
12103 static toff_t
12104 tiff_seek_in_memory (data, off, whence)
12105 thandle_t data;
12106 toff_t off;
12107 int whence;
12108 {
12109 tiff_memory_source *src = (tiff_memory_source *) data;
12110 int idx;
12111
12112 switch (whence)
12113 {
12114 case SEEK_SET: /* Go from beginning of source. */
12115 idx = off;
12116 break;
12117
12118 case SEEK_END: /* Go from end of source. */
12119 idx = src->len + off;
12120 break;
12121
12122 case SEEK_CUR: /* Go from current position. */
12123 idx = src->index + off;
12124 break;
12125
12126 default: /* Invalid `whence'. */
12127 return -1;
12128 }
12129
12130 if (idx > src->len || idx < 0)
12131 return -1;
12132
12133 src->index = idx;
12134 return src->index;
12135 }
12136
12137 static int
12138 tiff_close_memory (data)
12139 thandle_t data;
12140 {
12141 /* NOOP */
12142 return 0;
12143 }
12144
12145 static int
12146 tiff_mmap_memory (data, pbase, psize)
12147 thandle_t data;
12148 tdata_t *pbase;
12149 toff_t *psize;
12150 {
12151 /* It is already _IN_ memory. */
12152 return 0;
12153 }
12154
12155 static void
12156 tiff_unmap_memory (data, base, size)
12157 thandle_t data;
12158 tdata_t base;
12159 toff_t size;
12160 {
12161 /* We don't need to do this. */
12162 }
12163
12164 static toff_t
12165 tiff_size_of_memory (data)
12166 thandle_t data;
12167 {
12168 return ((tiff_memory_source *) data)->len;
12169 }
12170
12171
12172 static void
12173 tiff_error_handler (title, format, ap)
12174 const char *title, *format;
12175 va_list ap;
12176 {
12177 char buf[512];
12178 int len;
12179
12180 len = sprintf (buf, "TIFF error: %s ", title);
12181 vsprintf (buf + len, format, ap);
12182 add_to_log (buf, Qnil, Qnil);
12183 }
12184
12185
12186 static void
12187 tiff_warning_handler (title, format, ap)
12188 const char *title, *format;
12189 va_list ap;
12190 {
12191 char buf[512];
12192 int len;
12193
12194 len = sprintf (buf, "TIFF warning: %s ", title);
12195 vsprintf (buf + len, format, ap);
12196 add_to_log (buf, Qnil, Qnil);
12197 }
12198
12199
12200 /* Load TIFF image IMG for use on frame F. Value is non-zero if
12201 successful. */
12202
12203 static int
12204 tiff_load (f, img)
12205 struct frame *f;
12206 struct image *img;
12207 {
12208 Lisp_Object file, specified_file;
12209 Lisp_Object specified_data;
12210 TIFF *tiff;
12211 int width, height, x, y;
12212 uint32 *buf;
12213 int rc;
12214 XImage *ximg;
12215 struct gcpro gcpro1;
12216 tiff_memory_source memsrc;
12217
12218 specified_file = image_spec_value (img->spec, QCfile, NULL);
12219 specified_data = image_spec_value (img->spec, QCdata, NULL);
12220 file = Qnil;
12221 GCPRO1 (file);
12222
12223 TIFFSetErrorHandler (tiff_error_handler);
12224 TIFFSetWarningHandler (tiff_warning_handler);
12225
12226 if (NILP (specified_data))
12227 {
12228 /* Read from a file */
12229 file = x_find_image_file (specified_file);
12230 if (!STRINGP (file))
12231 {
12232 image_error ("Cannot find image file `%s'", file, Qnil);
12233 UNGCPRO;
12234 return 0;
12235 }
12236
12237 /* Try to open the image file. */
12238 tiff = TIFFOpen (XSTRING (file)->data, "r");
12239 if (tiff == NULL)
12240 {
12241 image_error ("Cannot open `%s'", file, Qnil);
12242 UNGCPRO;
12243 return 0;
12244 }
12245 }
12246 else
12247 {
12248 /* Memory source! */
12249 memsrc.bytes = XSTRING (specified_data)->data;
12250 memsrc.len = STRING_BYTES (XSTRING (specified_data));
12251 memsrc.index = 0;
12252
12253 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
12254 (TIFFReadWriteProc) tiff_read_from_memory,
12255 (TIFFReadWriteProc) tiff_write_from_memory,
12256 tiff_seek_in_memory,
12257 tiff_close_memory,
12258 tiff_size_of_memory,
12259 tiff_mmap_memory,
12260 tiff_unmap_memory);
12261
12262 if (!tiff)
12263 {
12264 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
12265 UNGCPRO;
12266 return 0;
12267 }
12268 }
12269
12270 /* Get width and height of the image, and allocate a raster buffer
12271 of width x height 32-bit values. */
12272 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
12273 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
12274 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
12275
12276 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
12277 TIFFClose (tiff);
12278 if (!rc)
12279 {
12280 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
12281 xfree (buf);
12282 UNGCPRO;
12283 return 0;
12284 }
12285
12286 /* Create the X image and pixmap. */
12287 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12288 {
12289 xfree (buf);
12290 UNGCPRO;
12291 return 0;
12292 }
12293
12294 /* Initialize the color table. */
12295 init_color_table ();
12296
12297 /* Process the pixel raster. Origin is in the lower-left corner. */
12298 for (y = 0; y < height; ++y)
12299 {
12300 uint32 *row = buf + y * width;
12301
12302 for (x = 0; x < width; ++x)
12303 {
12304 uint32 abgr = row[x];
12305 int r = TIFFGetR (abgr) << 8;
12306 int g = TIFFGetG (abgr) << 8;
12307 int b = TIFFGetB (abgr) << 8;
12308 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
12309 }
12310 }
12311
12312 /* Remember the colors allocated for the image. Free the color table. */
12313 img->colors = colors_in_color_table (&img->ncolors);
12314 free_color_table ();
12315
12316 img->width = width;
12317 img->height = height;
12318
12319 /* Maybe fill in the background field while we have ximg handy. */
12320 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12321 IMAGE_BACKGROUND (img, f, ximg);
12322
12323 /* Put the image into the pixmap, then free the X image and its buffer. */
12324 x_put_x_image (f, ximg, img->pixmap, width, height);
12325 x_destroy_x_image (ximg);
12326 xfree (buf);
12327
12328 UNGCPRO;
12329 return 1;
12330 }
12331
12332 #endif /* HAVE_TIFF != 0 */
12333
12334
12335 \f
12336 /***********************************************************************
12337 GIF
12338 ***********************************************************************/
12339
12340 #if HAVE_GIF
12341
12342 #include <gif_lib.h>
12343
12344 static int gif_image_p P_ ((Lisp_Object object));
12345 static int gif_load P_ ((struct frame *f, struct image *img));
12346
12347 /* The symbol `gif' identifying images of this type. */
12348
12349 Lisp_Object Qgif;
12350
12351 /* Indices of image specification fields in gif_format, below. */
12352
12353 enum gif_keyword_index
12354 {
12355 GIF_TYPE,
12356 GIF_DATA,
12357 GIF_FILE,
12358 GIF_ASCENT,
12359 GIF_MARGIN,
12360 GIF_RELIEF,
12361 GIF_ALGORITHM,
12362 GIF_HEURISTIC_MASK,
12363 GIF_MASK,
12364 GIF_IMAGE,
12365 GIF_BACKGROUND,
12366 GIF_LAST
12367 };
12368
12369 /* Vector of image_keyword structures describing the format
12370 of valid user-defined image specifications. */
12371
12372 static struct image_keyword gif_format[GIF_LAST] =
12373 {
12374 {":type", IMAGE_SYMBOL_VALUE, 1},
12375 {":data", IMAGE_STRING_VALUE, 0},
12376 {":file", IMAGE_STRING_VALUE, 0},
12377 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12378 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12379 {":relief", IMAGE_INTEGER_VALUE, 0},
12380 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12381 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12382 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12383 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12384 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12385 };
12386
12387 /* Structure describing the image type `gif'. */
12388
12389 static struct image_type gif_type =
12390 {
12391 &Qgif,
12392 gif_image_p,
12393 gif_load,
12394 x_clear_image,
12395 NULL
12396 };
12397
12398 /* Return non-zero if OBJECT is a valid GIF image specification. */
12399
12400 static int
12401 gif_image_p (object)
12402 Lisp_Object object;
12403 {
12404 struct image_keyword fmt[GIF_LAST];
12405 bcopy (gif_format, fmt, sizeof fmt);
12406
12407 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
12408 || (fmt[GIF_ASCENT].count
12409 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
12410 return 0;
12411
12412 /* Must specify either the :data or :file keyword. */
12413 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
12414 }
12415
12416 /* Reading a GIF image from memory
12417 Based on the PNG memory stuff to a certain extent. */
12418
12419 typedef struct
12420 {
12421 unsigned char *bytes;
12422 size_t len;
12423 int index;
12424 }
12425 gif_memory_source;
12426
12427 /* Make the current memory source available to gif_read_from_memory.
12428 It's done this way because not all versions of libungif support
12429 a UserData field in the GifFileType structure. */
12430 static gif_memory_source *current_gif_memory_src;
12431
12432 static int
12433 gif_read_from_memory (file, buf, len)
12434 GifFileType *file;
12435 GifByteType *buf;
12436 int len;
12437 {
12438 gif_memory_source *src = current_gif_memory_src;
12439
12440 if (len > src->len - src->index)
12441 return -1;
12442
12443 bcopy (src->bytes + src->index, buf, len);
12444 src->index += len;
12445 return len;
12446 }
12447
12448
12449 /* Load GIF image IMG for use on frame F. Value is non-zero if
12450 successful. */
12451
12452 static int
12453 gif_load (f, img)
12454 struct frame *f;
12455 struct image *img;
12456 {
12457 Lisp_Object file, specified_file;
12458 Lisp_Object specified_data;
12459 int rc, width, height, x, y, i;
12460 XImage *ximg;
12461 ColorMapObject *gif_color_map;
12462 unsigned long pixel_colors[256];
12463 GifFileType *gif;
12464 struct gcpro gcpro1;
12465 Lisp_Object image;
12466 int ino, image_left, image_top, image_width, image_height;
12467 gif_memory_source memsrc;
12468 unsigned char *raster;
12469
12470 specified_file = image_spec_value (img->spec, QCfile, NULL);
12471 specified_data = image_spec_value (img->spec, QCdata, NULL);
12472 file = Qnil;
12473 GCPRO1 (file);
12474
12475 if (NILP (specified_data))
12476 {
12477 file = x_find_image_file (specified_file);
12478 if (!STRINGP (file))
12479 {
12480 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12481 UNGCPRO;
12482 return 0;
12483 }
12484
12485 /* Open the GIF file. */
12486 gif = DGifOpenFileName (XSTRING (file)->data);
12487 if (gif == NULL)
12488 {
12489 image_error ("Cannot open `%s'", file, Qnil);
12490 UNGCPRO;
12491 return 0;
12492 }
12493 }
12494 else
12495 {
12496 /* Read from memory! */
12497 current_gif_memory_src = &memsrc;
12498 memsrc.bytes = XSTRING (specified_data)->data;
12499 memsrc.len = STRING_BYTES (XSTRING (specified_data));
12500 memsrc.index = 0;
12501
12502 gif = DGifOpen(&memsrc, gif_read_from_memory);
12503 if (!gif)
12504 {
12505 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
12506 UNGCPRO;
12507 return 0;
12508 }
12509 }
12510
12511 /* Read entire contents. */
12512 rc = DGifSlurp (gif);
12513 if (rc == GIF_ERROR)
12514 {
12515 image_error ("Error reading `%s'", img->spec, Qnil);
12516 DGifCloseFile (gif);
12517 UNGCPRO;
12518 return 0;
12519 }
12520
12521 image = image_spec_value (img->spec, QCindex, NULL);
12522 ino = INTEGERP (image) ? XFASTINT (image) : 0;
12523 if (ino >= gif->ImageCount)
12524 {
12525 image_error ("Invalid image number `%s' in image `%s'",
12526 image, img->spec);
12527 DGifCloseFile (gif);
12528 UNGCPRO;
12529 return 0;
12530 }
12531
12532 width = img->width = gif->SWidth;
12533 height = img->height = gif->SHeight;
12534
12535 /* Create the X image and pixmap. */
12536 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12537 {
12538 DGifCloseFile (gif);
12539 UNGCPRO;
12540 return 0;
12541 }
12542
12543 /* Allocate colors. */
12544 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
12545 if (!gif_color_map)
12546 gif_color_map = gif->SColorMap;
12547 init_color_table ();
12548 bzero (pixel_colors, sizeof pixel_colors);
12549
12550 for (i = 0; i < gif_color_map->ColorCount; ++i)
12551 {
12552 int r = gif_color_map->Colors[i].Red << 8;
12553 int g = gif_color_map->Colors[i].Green << 8;
12554 int b = gif_color_map->Colors[i].Blue << 8;
12555 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
12556 }
12557
12558 img->colors = colors_in_color_table (&img->ncolors);
12559 free_color_table ();
12560
12561 /* Clear the part of the screen image that are not covered by
12562 the image from the GIF file. Full animated GIF support
12563 requires more than can be done here (see the gif89 spec,
12564 disposal methods). Let's simply assume that the part
12565 not covered by a sub-image is in the frame's background color. */
12566 image_top = gif->SavedImages[ino].ImageDesc.Top;
12567 image_left = gif->SavedImages[ino].ImageDesc.Left;
12568 image_width = gif->SavedImages[ino].ImageDesc.Width;
12569 image_height = gif->SavedImages[ino].ImageDesc.Height;
12570
12571 for (y = 0; y < image_top; ++y)
12572 for (x = 0; x < width; ++x)
12573 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12574
12575 for (y = image_top + image_height; y < height; ++y)
12576 for (x = 0; x < width; ++x)
12577 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12578
12579 for (y = image_top; y < image_top + image_height; ++y)
12580 {
12581 for (x = 0; x < image_left; ++x)
12582 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12583 for (x = image_left + image_width; x < width; ++x)
12584 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12585 }
12586
12587 /* Read the GIF image into the X image. We use a local variable
12588 `raster' here because RasterBits below is a char *, and invites
12589 problems with bytes >= 0x80. */
12590 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
12591
12592 if (gif->SavedImages[ino].ImageDesc.Interlace)
12593 {
12594 static int interlace_start[] = {0, 4, 2, 1};
12595 static int interlace_increment[] = {8, 8, 4, 2};
12596 int pass;
12597 int row = interlace_start[0];
12598
12599 pass = 0;
12600
12601 for (y = 0; y < image_height; y++)
12602 {
12603 if (row >= image_height)
12604 {
12605 row = interlace_start[++pass];
12606 while (row >= image_height)
12607 row = interlace_start[++pass];
12608 }
12609
12610 for (x = 0; x < image_width; x++)
12611 {
12612 int i = raster[(y * image_width) + x];
12613 XPutPixel (ximg, x + image_left, row + image_top,
12614 pixel_colors[i]);
12615 }
12616
12617 row += interlace_increment[pass];
12618 }
12619 }
12620 else
12621 {
12622 for (y = 0; y < image_height; ++y)
12623 for (x = 0; x < image_width; ++x)
12624 {
12625 int i = raster[y* image_width + x];
12626 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
12627 }
12628 }
12629
12630 DGifCloseFile (gif);
12631
12632 /* Maybe fill in the background field while we have ximg handy. */
12633 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12634 IMAGE_BACKGROUND (img, f, ximg);
12635
12636 /* Put the image into the pixmap, then free the X image and its buffer. */
12637 x_put_x_image (f, ximg, img->pixmap, width, height);
12638 x_destroy_x_image (ximg);
12639
12640 UNGCPRO;
12641 return 1;
12642 }
12643
12644 #endif /* HAVE_GIF != 0 */
12645
12646
12647 \f
12648 /***********************************************************************
12649 Ghostscript
12650 ***********************************************************************/
12651
12652 Lisp_Object Qpostscript;
12653
12654 #ifdef HAVE_GHOSTSCRIPT
12655 static int gs_image_p P_ ((Lisp_Object object));
12656 static int gs_load P_ ((struct frame *f, struct image *img));
12657 static void gs_clear_image P_ ((struct frame *f, struct image *img));
12658
12659 /* The symbol `postscript' identifying images of this type. */
12660
12661 /* Keyword symbols. */
12662
12663 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12664
12665 /* Indices of image specification fields in gs_format, below. */
12666
12667 enum gs_keyword_index
12668 {
12669 GS_TYPE,
12670 GS_PT_WIDTH,
12671 GS_PT_HEIGHT,
12672 GS_FILE,
12673 GS_LOADER,
12674 GS_BOUNDING_BOX,
12675 GS_ASCENT,
12676 GS_MARGIN,
12677 GS_RELIEF,
12678 GS_ALGORITHM,
12679 GS_HEURISTIC_MASK,
12680 GS_MASK,
12681 GS_BACKGROUND,
12682 GS_LAST
12683 };
12684
12685 /* Vector of image_keyword structures describing the format
12686 of valid user-defined image specifications. */
12687
12688 static struct image_keyword gs_format[GS_LAST] =
12689 {
12690 {":type", IMAGE_SYMBOL_VALUE, 1},
12691 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12692 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12693 {":file", IMAGE_STRING_VALUE, 1},
12694 {":loader", IMAGE_FUNCTION_VALUE, 0},
12695 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
12696 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12697 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12698 {":relief", IMAGE_INTEGER_VALUE, 0},
12699 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12700 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12701 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12702 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12703 };
12704
12705 /* Structure describing the image type `ghostscript'. */
12706
12707 static struct image_type gs_type =
12708 {
12709 &Qpostscript,
12710 gs_image_p,
12711 gs_load,
12712 gs_clear_image,
12713 NULL
12714 };
12715
12716
12717 /* Free X resources of Ghostscript image IMG which is used on frame F. */
12718
12719 static void
12720 gs_clear_image (f, img)
12721 struct frame *f;
12722 struct image *img;
12723 {
12724 /* IMG->data.ptr_val may contain a recorded colormap. */
12725 xfree (img->data.ptr_val);
12726 x_clear_image (f, img);
12727 }
12728
12729
12730 /* Return non-zero if OBJECT is a valid Ghostscript image
12731 specification. */
12732
12733 static int
12734 gs_image_p (object)
12735 Lisp_Object object;
12736 {
12737 struct image_keyword fmt[GS_LAST];
12738 Lisp_Object tem;
12739 int i;
12740
12741 bcopy (gs_format, fmt, sizeof fmt);
12742
12743 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
12744 || (fmt[GS_ASCENT].count
12745 && XFASTINT (fmt[GS_ASCENT].value) > 100))
12746 return 0;
12747
12748 /* Bounding box must be a list or vector containing 4 integers. */
12749 tem = fmt[GS_BOUNDING_BOX].value;
12750 if (CONSP (tem))
12751 {
12752 for (i = 0; i < 4; ++i, tem = XCDR (tem))
12753 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
12754 return 0;
12755 if (!NILP (tem))
12756 return 0;
12757 }
12758 else if (VECTORP (tem))
12759 {
12760 if (XVECTOR (tem)->size != 4)
12761 return 0;
12762 for (i = 0; i < 4; ++i)
12763 if (!INTEGERP (XVECTOR (tem)->contents[i]))
12764 return 0;
12765 }
12766 else
12767 return 0;
12768
12769 return 1;
12770 }
12771
12772
12773 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
12774 if successful. */
12775
12776 static int
12777 gs_load (f, img)
12778 struct frame *f;
12779 struct image *img;
12780 {
12781 char buffer[100];
12782 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
12783 struct gcpro gcpro1, gcpro2;
12784 Lisp_Object frame;
12785 double in_width, in_height;
12786 Lisp_Object pixel_colors = Qnil;
12787
12788 /* Compute pixel size of pixmap needed from the given size in the
12789 image specification. Sizes in the specification are in pt. 1 pt
12790 = 1/72 in, xdpi and ydpi are stored in the frame's X display
12791 info. */
12792 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
12793 in_width = XFASTINT (pt_width) / 72.0;
12794 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
12795 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
12796 in_height = XFASTINT (pt_height) / 72.0;
12797 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
12798
12799 /* Create the pixmap. */
12800 BLOCK_INPUT;
12801 xassert (img->pixmap == 0);
12802 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12803 img->width, img->height,
12804 one_w32_display_info.n_cbits);
12805 UNBLOCK_INPUT;
12806
12807 if (!img->pixmap)
12808 {
12809 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
12810 return 0;
12811 }
12812
12813 /* Call the loader to fill the pixmap. It returns a process object
12814 if successful. We do not record_unwind_protect here because
12815 other places in redisplay like calling window scroll functions
12816 don't either. Let the Lisp loader use `unwind-protect' instead. */
12817 GCPRO2 (window_and_pixmap_id, pixel_colors);
12818
12819 sprintf (buffer, "%lu %lu",
12820 (unsigned long) FRAME_W32_WINDOW (f),
12821 (unsigned long) img->pixmap);
12822 window_and_pixmap_id = build_string (buffer);
12823
12824 sprintf (buffer, "%lu %lu",
12825 FRAME_FOREGROUND_PIXEL (f),
12826 FRAME_BACKGROUND_PIXEL (f));
12827 pixel_colors = build_string (buffer);
12828
12829 XSETFRAME (frame, f);
12830 loader = image_spec_value (img->spec, QCloader, NULL);
12831 if (NILP (loader))
12832 loader = intern ("gs-load-image");
12833
12834 img->data.lisp_val = call6 (loader, frame, img->spec,
12835 make_number (img->width),
12836 make_number (img->height),
12837 window_and_pixmap_id,
12838 pixel_colors);
12839 UNGCPRO;
12840 return PROCESSP (img->data.lisp_val);
12841 }
12842
12843
12844 /* Kill the Ghostscript process that was started to fill PIXMAP on
12845 frame F. Called from XTread_socket when receiving an event
12846 telling Emacs that Ghostscript has finished drawing. */
12847
12848 void
12849 x_kill_gs_process (pixmap, f)
12850 Pixmap pixmap;
12851 struct frame *f;
12852 {
12853 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
12854 int class, i;
12855 struct image *img;
12856
12857 /* Find the image containing PIXMAP. */
12858 for (i = 0; i < c->used; ++i)
12859 if (c->images[i]->pixmap == pixmap)
12860 break;
12861
12862 /* Should someone in between have cleared the image cache, for
12863 instance, give up. */
12864 if (i == c->used)
12865 return;
12866
12867 /* Kill the GS process. We should have found PIXMAP in the image
12868 cache and its image should contain a process object. */
12869 img = c->images[i];
12870 xassert (PROCESSP (img->data.lisp_val));
12871 Fkill_process (img->data.lisp_val, Qnil);
12872 img->data.lisp_val = Qnil;
12873
12874 /* On displays with a mutable colormap, figure out the colors
12875 allocated for the image by looking at the pixels of an XImage for
12876 img->pixmap. */
12877 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
12878 if (class != StaticColor && class != StaticGray && class != TrueColor)
12879 {
12880 XImage *ximg;
12881
12882 BLOCK_INPUT;
12883
12884 /* Try to get an XImage for img->pixmep. */
12885 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
12886 0, 0, img->width, img->height, ~0, ZPixmap);
12887 if (ximg)
12888 {
12889 int x, y;
12890
12891 /* Initialize the color table. */
12892 init_color_table ();
12893
12894 /* For each pixel of the image, look its color up in the
12895 color table. After having done so, the color table will
12896 contain an entry for each color used by the image. */
12897 for (y = 0; y < img->height; ++y)
12898 for (x = 0; x < img->width; ++x)
12899 {
12900 unsigned long pixel = XGetPixel (ximg, x, y);
12901 lookup_pixel_color (f, pixel);
12902 }
12903
12904 /* Record colors in the image. Free color table and XImage. */
12905 img->colors = colors_in_color_table (&img->ncolors);
12906 free_color_table ();
12907 XDestroyImage (ximg);
12908
12909 #if 0 /* This doesn't seem to be the case. If we free the colors
12910 here, we get a BadAccess later in x_clear_image when
12911 freeing the colors. */
12912 /* We have allocated colors once, but Ghostscript has also
12913 allocated colors on behalf of us. So, to get the
12914 reference counts right, free them once. */
12915 if (img->ncolors)
12916 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
12917 img->colors, img->ncolors, 0);
12918 #endif
12919 }
12920 else
12921 image_error ("Cannot get X image of `%s'; colors will not be freed",
12922 img->spec, Qnil);
12923
12924 UNBLOCK_INPUT;
12925 }
12926
12927 /* Now that we have the pixmap, compute mask and transform the
12928 image if requested. */
12929 BLOCK_INPUT;
12930 postprocess_image (f, img);
12931 UNBLOCK_INPUT;
12932 }
12933
12934 #endif /* HAVE_GHOSTSCRIPT */
12935
12936 \f
12937 /***********************************************************************
12938 Window properties
12939 ***********************************************************************/
12940
12941 DEFUN ("x-change-window-property", Fx_change_window_property,
12942 Sx_change_window_property, 2, 3, 0,
12943 doc: /* Change window property PROP to VALUE on the X window of FRAME.
12944 PROP and VALUE must be strings. FRAME nil or omitted means use the
12945 selected frame. Value is VALUE. */)
12946 (prop, value, frame)
12947 Lisp_Object frame, prop, value;
12948 {
12949 #if 0 /* TODO : port window properties to W32 */
12950 struct frame *f = check_x_frame (frame);
12951 Atom prop_atom;
12952
12953 CHECK_STRING (prop);
12954 CHECK_STRING (value);
12955
12956 BLOCK_INPUT;
12957 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12958 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12959 prop_atom, XA_STRING, 8, PropModeReplace,
12960 XSTRING (value)->data, XSTRING (value)->size);
12961
12962 /* Make sure the property is set when we return. */
12963 XFlush (FRAME_W32_DISPLAY (f));
12964 UNBLOCK_INPUT;
12965
12966 #endif /* TODO */
12967
12968 return value;
12969 }
12970
12971
12972 DEFUN ("x-delete-window-property", Fx_delete_window_property,
12973 Sx_delete_window_property, 1, 2, 0,
12974 doc: /* Remove window property PROP from X window of FRAME.
12975 FRAME nil or omitted means use the selected frame. Value is PROP. */)
12976 (prop, frame)
12977 Lisp_Object prop, frame;
12978 {
12979 #if 0 /* TODO : port window properties to W32 */
12980
12981 struct frame *f = check_x_frame (frame);
12982 Atom prop_atom;
12983
12984 CHECK_STRING (prop);
12985 BLOCK_INPUT;
12986 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
12987 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
12988
12989 /* Make sure the property is removed when we return. */
12990 XFlush (FRAME_W32_DISPLAY (f));
12991 UNBLOCK_INPUT;
12992 #endif /* TODO */
12993
12994 return prop;
12995 }
12996
12997
12998 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
12999 1, 2, 0,
13000 doc: /* Value is the value of window property PROP on FRAME.
13001 If FRAME is nil or omitted, use the selected frame. Value is nil
13002 if FRAME hasn't a property with name PROP or if PROP has no string
13003 value. */)
13004 (prop, frame)
13005 Lisp_Object prop, frame;
13006 {
13007 #if 0 /* TODO : port window properties to W32 */
13008
13009 struct frame *f = check_x_frame (frame);
13010 Atom prop_atom;
13011 int rc;
13012 Lisp_Object prop_value = Qnil;
13013 char *tmp_data = NULL;
13014 Atom actual_type;
13015 int actual_format;
13016 unsigned long actual_size, bytes_remaining;
13017
13018 CHECK_STRING (prop);
13019 BLOCK_INPUT;
13020 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
13021 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13022 prop_atom, 0, 0, False, XA_STRING,
13023 &actual_type, &actual_format, &actual_size,
13024 &bytes_remaining, (unsigned char **) &tmp_data);
13025 if (rc == Success)
13026 {
13027 int size = bytes_remaining;
13028
13029 XFree (tmp_data);
13030 tmp_data = NULL;
13031
13032 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13033 prop_atom, 0, bytes_remaining,
13034 False, XA_STRING,
13035 &actual_type, &actual_format,
13036 &actual_size, &bytes_remaining,
13037 (unsigned char **) &tmp_data);
13038 if (rc == Success)
13039 prop_value = make_string (tmp_data, size);
13040
13041 XFree (tmp_data);
13042 }
13043
13044 UNBLOCK_INPUT;
13045
13046 return prop_value;
13047
13048 #endif /* TODO */
13049 return Qnil;
13050 }
13051
13052
13053 \f
13054 /***********************************************************************
13055 Busy cursor
13056 ***********************************************************************/
13057
13058 /* If non-null, an asynchronous timer that, when it expires, displays
13059 an hourglass cursor on all frames. */
13060
13061 static struct atimer *hourglass_atimer;
13062
13063 /* Non-zero means an hourglass cursor is currently shown. */
13064
13065 static int hourglass_shown_p;
13066
13067 /* Number of seconds to wait before displaying an hourglass cursor. */
13068
13069 static Lisp_Object Vhourglass_delay;
13070
13071 /* Default number of seconds to wait before displaying an hourglass
13072 cursor. */
13073
13074 #define DEFAULT_HOURGLASS_DELAY 1
13075
13076 /* Function prototypes. */
13077
13078 static void show_hourglass P_ ((struct atimer *));
13079 static void hide_hourglass P_ ((void));
13080
13081
13082 /* Cancel a currently active hourglass timer, and start a new one. */
13083
13084 void
13085 start_hourglass ()
13086 {
13087 #if 0 /* TODO: cursor shape changes. */
13088 EMACS_TIME delay;
13089 int secs, usecs = 0;
13090
13091 cancel_hourglass ();
13092
13093 if (INTEGERP (Vhourglass_delay)
13094 && XINT (Vhourglass_delay) > 0)
13095 secs = XFASTINT (Vhourglass_delay);
13096 else if (FLOATP (Vhourglass_delay)
13097 && XFLOAT_DATA (Vhourglass_delay) > 0)
13098 {
13099 Lisp_Object tem;
13100 tem = Ftruncate (Vhourglass_delay, Qnil);
13101 secs = XFASTINT (tem);
13102 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
13103 }
13104 else
13105 secs = DEFAULT_HOURGLASS_DELAY;
13106
13107 EMACS_SET_SECS_USECS (delay, secs, usecs);
13108 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
13109 show_hourglass, NULL);
13110 #endif
13111 }
13112
13113
13114 /* Cancel the hourglass cursor timer if active, hide an hourglass
13115 cursor if shown. */
13116
13117 void
13118 cancel_hourglass ()
13119 {
13120 if (hourglass_atimer)
13121 {
13122 cancel_atimer (hourglass_atimer);
13123 hourglass_atimer = NULL;
13124 }
13125
13126 if (hourglass_shown_p)
13127 hide_hourglass ();
13128 }
13129
13130
13131 /* Timer function of hourglass_atimer. TIMER is equal to
13132 hourglass_atimer.
13133
13134 Display an hourglass cursor on all frames by mapping the frames'
13135 hourglass_window. Set the hourglass_p flag in the frames'
13136 output_data.x structure to indicate that an hourglass cursor is
13137 shown on the frames. */
13138
13139 static void
13140 show_hourglass (timer)
13141 struct atimer *timer;
13142 {
13143 #if 0 /* TODO: cursor shape changes. */
13144 /* The timer implementation will cancel this timer automatically
13145 after this function has run. Set hourglass_atimer to null
13146 so that we know the timer doesn't have to be canceled. */
13147 hourglass_atimer = NULL;
13148
13149 if (!hourglass_shown_p)
13150 {
13151 Lisp_Object rest, frame;
13152
13153 BLOCK_INPUT;
13154
13155 FOR_EACH_FRAME (rest, frame)
13156 if (FRAME_W32_P (XFRAME (frame)))
13157 {
13158 struct frame *f = XFRAME (frame);
13159
13160 f->output_data.w32->hourglass_p = 1;
13161
13162 if (!f->output_data.w32->hourglass_window)
13163 {
13164 unsigned long mask = CWCursor;
13165 XSetWindowAttributes attrs;
13166
13167 attrs.cursor = f->output_data.w32->hourglass_cursor;
13168
13169 f->output_data.w32->hourglass_window
13170 = XCreateWindow (FRAME_X_DISPLAY (f),
13171 FRAME_OUTER_WINDOW (f),
13172 0, 0, 32000, 32000, 0, 0,
13173 InputOnly,
13174 CopyFromParent,
13175 mask, &attrs);
13176 }
13177
13178 XMapRaised (FRAME_X_DISPLAY (f),
13179 f->output_data.w32->hourglass_window);
13180 XFlush (FRAME_X_DISPLAY (f));
13181 }
13182
13183 hourglass_shown_p = 1;
13184 UNBLOCK_INPUT;
13185 }
13186 #endif
13187 }
13188
13189
13190 /* Hide the hourglass cursor on all frames, if it is currently shown. */
13191
13192 static void
13193 hide_hourglass ()
13194 {
13195 #if 0 /* TODO: cursor shape changes. */
13196 if (hourglass_shown_p)
13197 {
13198 Lisp_Object rest, frame;
13199
13200 BLOCK_INPUT;
13201 FOR_EACH_FRAME (rest, frame)
13202 {
13203 struct frame *f = XFRAME (frame);
13204
13205 if (FRAME_W32_P (f)
13206 /* Watch out for newly created frames. */
13207 && f->output_data.x->hourglass_window)
13208 {
13209 XUnmapWindow (FRAME_X_DISPLAY (f),
13210 f->output_data.x->hourglass_window);
13211 /* Sync here because XTread_socket looks at the
13212 hourglass_p flag that is reset to zero below. */
13213 XSync (FRAME_X_DISPLAY (f), False);
13214 f->output_data.x->hourglass_p = 0;
13215 }
13216 }
13217
13218 hourglass_shown_p = 0;
13219 UNBLOCK_INPUT;
13220 }
13221 #endif
13222 }
13223
13224
13225 \f
13226 /***********************************************************************
13227 Tool tips
13228 ***********************************************************************/
13229
13230 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
13231 Lisp_Object, Lisp_Object));
13232 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
13233 Lisp_Object, int, int, int *, int *));
13234
13235 /* The frame of a currently visible tooltip. */
13236
13237 Lisp_Object tip_frame;
13238
13239 /* If non-nil, a timer started that hides the last tooltip when it
13240 fires. */
13241
13242 Lisp_Object tip_timer;
13243 Window tip_window;
13244
13245 /* If non-nil, a vector of 3 elements containing the last args
13246 with which x-show-tip was called. See there. */
13247
13248 Lisp_Object last_show_tip_args;
13249
13250 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
13251
13252 Lisp_Object Vx_max_tooltip_size;
13253
13254
13255 static Lisp_Object
13256 unwind_create_tip_frame (frame)
13257 Lisp_Object frame;
13258 {
13259 Lisp_Object deleted;
13260
13261 deleted = unwind_create_frame (frame);
13262 if (EQ (deleted, Qt))
13263 {
13264 tip_window = NULL;
13265 tip_frame = Qnil;
13266 }
13267
13268 return deleted;
13269 }
13270
13271
13272 /* Create a frame for a tooltip on the display described by DPYINFO.
13273 PARMS is a list of frame parameters. TEXT is the string to
13274 display in the tip frame. Value is the frame.
13275
13276 Note that functions called here, esp. x_default_parameter can
13277 signal errors, for instance when a specified color name is
13278 undefined. We have to make sure that we're in a consistent state
13279 when this happens. */
13280
13281 static Lisp_Object
13282 x_create_tip_frame (dpyinfo, parms, text)
13283 struct w32_display_info *dpyinfo;
13284 Lisp_Object parms, text;
13285 {
13286 struct frame *f;
13287 Lisp_Object frame, tem;
13288 Lisp_Object name;
13289 long window_prompting = 0;
13290 int width, height;
13291 int count = BINDING_STACK_SIZE ();
13292 struct gcpro gcpro1, gcpro2, gcpro3;
13293 struct kboard *kb;
13294 int face_change_count_before = face_change_count;
13295 Lisp_Object buffer;
13296 struct buffer *old_buffer;
13297
13298 check_w32 ();
13299
13300 /* Use this general default value to start with until we know if
13301 this frame has a specified name. */
13302 Vx_resource_name = Vinvocation_name;
13303
13304 #ifdef MULTI_KBOARD
13305 kb = dpyinfo->kboard;
13306 #else
13307 kb = &the_only_kboard;
13308 #endif
13309
13310 /* Get the name of the frame to use for resource lookup. */
13311 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
13312 if (!STRINGP (name)
13313 && !EQ (name, Qunbound)
13314 && !NILP (name))
13315 error ("Invalid frame name--not a string or nil");
13316 Vx_resource_name = name;
13317
13318 frame = Qnil;
13319 GCPRO3 (parms, name, frame);
13320 /* Make a frame without minibuffer nor mode-line. */
13321 f = make_frame (0);
13322 f->wants_modeline = 0;
13323 XSETFRAME (frame, f);
13324
13325 buffer = Fget_buffer_create (build_string (" *tip*"));
13326 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
13327 old_buffer = current_buffer;
13328 set_buffer_internal_1 (XBUFFER (buffer));
13329 current_buffer->truncate_lines = Qnil;
13330 Ferase_buffer ();
13331 Finsert (1, &text);
13332 set_buffer_internal_1 (old_buffer);
13333
13334 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
13335 record_unwind_protect (unwind_create_tip_frame, frame);
13336
13337 /* By setting the output method, we're essentially saying that
13338 the frame is live, as per FRAME_LIVE_P. If we get a signal
13339 from this point on, x_destroy_window might screw up reference
13340 counts etc. */
13341 f->output_method = output_w32;
13342 f->output_data.w32 =
13343 (struct w32_output *) xmalloc (sizeof (struct w32_output));
13344 bzero (f->output_data.w32, sizeof (struct w32_output));
13345
13346 FRAME_FONTSET (f) = -1;
13347 f->icon_name = Qnil;
13348
13349 #if 0 /* GLYPH_DEBUG TODO: image support. */
13350 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
13351 dpyinfo_refcount = dpyinfo->reference_count;
13352 #endif /* GLYPH_DEBUG */
13353 #ifdef MULTI_KBOARD
13354 FRAME_KBOARD (f) = kb;
13355 #endif
13356 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13357 f->output_data.w32->explicit_parent = 0;
13358
13359 /* Set the name; the functions to which we pass f expect the name to
13360 be set. */
13361 if (EQ (name, Qunbound) || NILP (name))
13362 {
13363 f->name = build_string (dpyinfo->w32_id_name);
13364 f->explicit_name = 0;
13365 }
13366 else
13367 {
13368 f->name = name;
13369 f->explicit_name = 1;
13370 /* use the frame's title when getting resources for this frame. */
13371 specbind (Qx_resource_name, name);
13372 }
13373
13374 /* Extract the window parameters from the supplied values
13375 that are needed to determine window geometry. */
13376 {
13377 Lisp_Object font;
13378
13379 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
13380
13381 BLOCK_INPUT;
13382 /* First, try whatever font the caller has specified. */
13383 if (STRINGP (font))
13384 {
13385 tem = Fquery_fontset (font, Qnil);
13386 if (STRINGP (tem))
13387 font = x_new_fontset (f, XSTRING (tem)->data);
13388 else
13389 font = x_new_font (f, XSTRING (font)->data);
13390 }
13391
13392 /* Try out a font which we hope has bold and italic variations. */
13393 if (!STRINGP (font))
13394 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
13395 if (! STRINGP (font))
13396 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
13397 /* If those didn't work, look for something which will at least work. */
13398 if (! STRINGP (font))
13399 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
13400 UNBLOCK_INPUT;
13401 if (! STRINGP (font))
13402 font = build_string ("Fixedsys");
13403
13404 x_default_parameter (f, parms, Qfont, font,
13405 "font", "Font", RES_TYPE_STRING);
13406 }
13407
13408 x_default_parameter (f, parms, Qborder_width, make_number (2),
13409 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
13410 /* This defaults to 2 in order to match xterm. We recognize either
13411 internalBorderWidth or internalBorder (which is what xterm calls
13412 it). */
13413 if (NILP (Fassq (Qinternal_border_width, parms)))
13414 {
13415 Lisp_Object value;
13416
13417 value = w32_get_arg (parms, Qinternal_border_width,
13418 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
13419 if (! EQ (value, Qunbound))
13420 parms = Fcons (Fcons (Qinternal_border_width, value),
13421 parms);
13422 }
13423 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
13424 "internalBorderWidth", "internalBorderWidth",
13425 RES_TYPE_NUMBER);
13426
13427 /* Also do the stuff which must be set before the window exists. */
13428 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
13429 "foreground", "Foreground", RES_TYPE_STRING);
13430 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
13431 "background", "Background", RES_TYPE_STRING);
13432 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
13433 "pointerColor", "Foreground", RES_TYPE_STRING);
13434 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
13435 "cursorColor", "Foreground", RES_TYPE_STRING);
13436 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
13437 "borderColor", "BorderColor", RES_TYPE_STRING);
13438
13439 /* Init faces before x_default_parameter is called for scroll-bar
13440 parameters because that function calls x_set_scroll_bar_width,
13441 which calls change_frame_size, which calls Fset_window_buffer,
13442 which runs hooks, which call Fvertical_motion. At the end, we
13443 end up in init_iterator with a null face cache, which should not
13444 happen. */
13445 init_frame_faces (f);
13446
13447 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
13448 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13449
13450 window_prompting = x_figure_window_size (f, parms);
13451
13452 /* No fringes on tip frame. */
13453 f->output_data.w32->fringes_extra = 0;
13454 f->output_data.w32->fringe_cols = 0;
13455 f->output_data.w32->left_fringe_width = 0;
13456 f->output_data.w32->right_fringe_width = 0;
13457
13458 if (window_prompting & XNegative)
13459 {
13460 if (window_prompting & YNegative)
13461 f->output_data.w32->win_gravity = SouthEastGravity;
13462 else
13463 f->output_data.w32->win_gravity = NorthEastGravity;
13464 }
13465 else
13466 {
13467 if (window_prompting & YNegative)
13468 f->output_data.w32->win_gravity = SouthWestGravity;
13469 else
13470 f->output_data.w32->win_gravity = NorthWestGravity;
13471 }
13472
13473 f->output_data.w32->size_hint_flags = window_prompting;
13474
13475 BLOCK_INPUT;
13476 my_create_tip_window (f);
13477 UNBLOCK_INPUT;
13478
13479 x_make_gc (f);
13480
13481 x_default_parameter (f, parms, Qauto_raise, Qnil,
13482 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13483 x_default_parameter (f, parms, Qauto_lower, Qnil,
13484 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13485 x_default_parameter (f, parms, Qcursor_type, Qbox,
13486 "cursorType", "CursorType", RES_TYPE_SYMBOL);
13487
13488 /* Dimensions, especially f->height, must be done via change_frame_size.
13489 Change will not be effected unless different from the current
13490 f->height. */
13491 width = f->width;
13492 height = f->height;
13493 f->height = 0;
13494 SET_FRAME_WIDTH (f, 0);
13495 change_frame_size (f, height, width, 1, 0, 0);
13496
13497 /* Set up faces after all frame parameters are known. This call
13498 also merges in face attributes specified for new frames.
13499
13500 Frame parameters may be changed if .Xdefaults contains
13501 specifications for the default font. For example, if there is an
13502 `Emacs.default.attributeBackground: pink', the `background-color'
13503 attribute of the frame get's set, which let's the internal border
13504 of the tooltip frame appear in pink. Prevent this. */
13505 {
13506 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
13507
13508 /* Set tip_frame here, so that */
13509 tip_frame = frame;
13510 call1 (Qface_set_after_frame_default, frame);
13511
13512 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
13513 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
13514 Qnil));
13515 }
13516
13517 f->no_split = 1;
13518
13519 UNGCPRO;
13520
13521 /* It is now ok to make the frame official even if we get an error
13522 below. And the frame needs to be on Vframe_list or making it
13523 visible won't work. */
13524 Vframe_list = Fcons (frame, Vframe_list);
13525
13526 /* Now that the frame is official, it counts as a reference to
13527 its display. */
13528 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
13529
13530 /* Setting attributes of faces of the tooltip frame from resources
13531 and similar will increment face_change_count, which leads to the
13532 clearing of all current matrices. Since this isn't necessary
13533 here, avoid it by resetting face_change_count to the value it
13534 had before we created the tip frame. */
13535 face_change_count = face_change_count_before;
13536
13537 /* Discard the unwind_protect. */
13538 return unbind_to (count, frame);
13539 }
13540
13541
13542 /* Compute where to display tip frame F. PARMS is the list of frame
13543 parameters for F. DX and DY are specified offsets from the current
13544 location of the mouse. WIDTH and HEIGHT are the width and height
13545 of the tooltip. Return coordinates relative to the root window of
13546 the display in *ROOT_X, and *ROOT_Y. */
13547
13548 static void
13549 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
13550 struct frame *f;
13551 Lisp_Object parms, dx, dy;
13552 int width, height;
13553 int *root_x, *root_y;
13554 {
13555 Lisp_Object left, top;
13556
13557 /* User-specified position? */
13558 left = Fcdr (Fassq (Qleft, parms));
13559 top = Fcdr (Fassq (Qtop, parms));
13560
13561 /* Move the tooltip window where the mouse pointer is. Resize and
13562 show it. */
13563 if (!INTEGERP (left) || !INTEGERP (top))
13564 {
13565 POINT pt;
13566
13567 BLOCK_INPUT;
13568 GetCursorPos (&pt);
13569 *root_x = pt.x;
13570 *root_y = pt.y;
13571 UNBLOCK_INPUT;
13572 }
13573
13574 if (INTEGERP (top))
13575 *root_y = XINT (top);
13576 else if (*root_y + XINT (dy) - height < 0)
13577 *root_y -= XINT (dy);
13578 else
13579 {
13580 *root_y -= height;
13581 *root_y += XINT (dy);
13582 }
13583
13584 if (INTEGERP (left))
13585 *root_x = XINT (left);
13586 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
13587 /* It fits to the right of the pointer. */
13588 *root_x += XINT (dx);
13589 else if (width + XINT (dx) <= *root_x)
13590 /* It fits to the left of the pointer. */
13591 *root_x -= width + XINT (dx);
13592 else
13593 /* Put it left justified on the screen -- it ought to fit that way. */
13594 *root_x = 0;
13595 }
13596
13597
13598 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
13599 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
13600 A tooltip window is a small window displaying a string.
13601
13602 FRAME nil or omitted means use the selected frame.
13603
13604 PARMS is an optional list of frame parameters which can be
13605 used to change the tooltip's appearance.
13606
13607 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
13608 means use the default timeout of 5 seconds.
13609
13610 If the list of frame parameters PARAMS contains a `left' parameter,
13611 the tooltip is displayed at that x-position. Otherwise it is
13612 displayed at the mouse position, with offset DX added (default is 5 if
13613 DX isn't specified). Likewise for the y-position; if a `top' frame
13614 parameter is specified, it determines the y-position of the tooltip
13615 window, otherwise it is displayed at the mouse position, with offset
13616 DY added (default is -10).
13617
13618 A tooltip's maximum size is specified by `x-max-tooltip-size'.
13619 Text larger than the specified size is clipped. */)
13620 (string, frame, parms, timeout, dx, dy)
13621 Lisp_Object string, frame, parms, timeout, dx, dy;
13622 {
13623 struct frame *f;
13624 struct window *w;
13625 int root_x, root_y;
13626 struct buffer *old_buffer;
13627 struct text_pos pos;
13628 int i, width, height;
13629 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
13630 int old_windows_or_buffers_changed = windows_or_buffers_changed;
13631 int count = BINDING_STACK_SIZE ();
13632
13633 specbind (Qinhibit_redisplay, Qt);
13634
13635 GCPRO4 (string, parms, frame, timeout);
13636
13637 CHECK_STRING (string);
13638 f = check_x_frame (frame);
13639 if (NILP (timeout))
13640 timeout = make_number (5);
13641 else
13642 CHECK_NATNUM (timeout);
13643
13644 if (NILP (dx))
13645 dx = make_number (5);
13646 else
13647 CHECK_NUMBER (dx);
13648
13649 if (NILP (dy))
13650 dy = make_number (-10);
13651 else
13652 CHECK_NUMBER (dy);
13653
13654 if (NILP (last_show_tip_args))
13655 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
13656
13657 if (!NILP (tip_frame))
13658 {
13659 Lisp_Object last_string = AREF (last_show_tip_args, 0);
13660 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
13661 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
13662
13663 if (EQ (frame, last_frame)
13664 && !NILP (Fequal (last_string, string))
13665 && !NILP (Fequal (last_parms, parms)))
13666 {
13667 struct frame *f = XFRAME (tip_frame);
13668
13669 /* Only DX and DY have changed. */
13670 if (!NILP (tip_timer))
13671 {
13672 Lisp_Object timer = tip_timer;
13673 tip_timer = Qnil;
13674 call1 (Qcancel_timer, timer);
13675 }
13676
13677 BLOCK_INPUT;
13678 compute_tip_xy (f, parms, dx, dy, PIXEL_WIDTH (f),
13679 PIXEL_HEIGHT (f), &root_x, &root_y);
13680 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13681 root_x, root_y, 0, 0,
13682 SWP_NOSIZE | SWP_NOACTIVATE);
13683 UNBLOCK_INPUT;
13684 goto start_timer;
13685 }
13686 }
13687
13688 /* Hide a previous tip, if any. */
13689 Fx_hide_tip ();
13690
13691 ASET (last_show_tip_args, 0, string);
13692 ASET (last_show_tip_args, 1, frame);
13693 ASET (last_show_tip_args, 2, parms);
13694
13695 /* Add default values to frame parameters. */
13696 if (NILP (Fassq (Qname, parms)))
13697 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
13698 if (NILP (Fassq (Qinternal_border_width, parms)))
13699 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
13700 if (NILP (Fassq (Qborder_width, parms)))
13701 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
13702 if (NILP (Fassq (Qborder_color, parms)))
13703 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
13704 if (NILP (Fassq (Qbackground_color, parms)))
13705 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
13706 parms);
13707
13708 /* Block input until the tip has been fully drawn, to avoid crashes
13709 when drawing tips in menus. */
13710 BLOCK_INPUT;
13711
13712 /* Create a frame for the tooltip, and record it in the global
13713 variable tip_frame. */
13714 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
13715 f = XFRAME (frame);
13716
13717 /* Set up the frame's root window. */
13718 w = XWINDOW (FRAME_ROOT_WINDOW (f));
13719 w->left = w->top = make_number (0);
13720
13721 if (CONSP (Vx_max_tooltip_size)
13722 && INTEGERP (XCAR (Vx_max_tooltip_size))
13723 && XINT (XCAR (Vx_max_tooltip_size)) > 0
13724 && INTEGERP (XCDR (Vx_max_tooltip_size))
13725 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
13726 {
13727 w->width = XCAR (Vx_max_tooltip_size);
13728 w->height = XCDR (Vx_max_tooltip_size);
13729 }
13730 else
13731 {
13732 w->width = make_number (80);
13733 w->height = make_number (40);
13734 }
13735
13736 f->window_width = XINT (w->width);
13737 adjust_glyphs (f);
13738 w->pseudo_window_p = 1;
13739
13740 /* Display the tooltip text in a temporary buffer. */
13741 old_buffer = current_buffer;
13742 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
13743 current_buffer->truncate_lines = Qnil;
13744 clear_glyph_matrix (w->desired_matrix);
13745 clear_glyph_matrix (w->current_matrix);
13746 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
13747 try_window (FRAME_ROOT_WINDOW (f), pos);
13748
13749 /* Compute width and height of the tooltip. */
13750 width = height = 0;
13751 for (i = 0; i < w->desired_matrix->nrows; ++i)
13752 {
13753 struct glyph_row *row = &w->desired_matrix->rows[i];
13754 struct glyph *last;
13755 int row_width;
13756
13757 /* Stop at the first empty row at the end. */
13758 if (!row->enabled_p || !row->displays_text_p)
13759 break;
13760
13761 /* Let the row go over the full width of the frame. */
13762 row->full_width_p = 1;
13763
13764 #ifdef TODO /* Investigate why some fonts need more width than is
13765 calculated for some tooltips. */
13766 /* There's a glyph at the end of rows that is use to place
13767 the cursor there. Don't include the width of this glyph. */
13768 if (row->used[TEXT_AREA])
13769 {
13770 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
13771 row_width = row->pixel_width - last->pixel_width;
13772 }
13773 else
13774 #endif
13775 row_width = row->pixel_width;
13776
13777 /* TODO: find why tips do not draw along baseline as instructed. */
13778 height += row->height;
13779 width = max (width, row_width);
13780 }
13781
13782 /* Add the frame's internal border to the width and height the X
13783 window should have. */
13784 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
13785 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
13786
13787 /* Move the tooltip window where the mouse pointer is. Resize and
13788 show it. */
13789 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
13790
13791 {
13792 /* Adjust Window size to take border into account. */
13793 RECT rect;
13794 rect.left = rect.top = 0;
13795 rect.right = width;
13796 rect.bottom = height;
13797 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
13798 FRAME_EXTERNAL_MENU_BAR (f));
13799
13800 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13801 root_x, root_y, rect.right - rect.left,
13802 rect.bottom - rect.top, SWP_NOACTIVATE);
13803
13804 /* Let redisplay know that we have made the frame visible already. */
13805 f->async_visible = 1;
13806
13807 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
13808 }
13809
13810 /* Draw into the window. */
13811 w->must_be_updated_p = 1;
13812 update_single_window (w, 1);
13813
13814 UNBLOCK_INPUT;
13815
13816 /* Restore original current buffer. */
13817 set_buffer_internal_1 (old_buffer);
13818 windows_or_buffers_changed = old_windows_or_buffers_changed;
13819
13820 start_timer:
13821 /* Let the tip disappear after timeout seconds. */
13822 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
13823 intern ("x-hide-tip"));
13824
13825 UNGCPRO;
13826 return unbind_to (count, Qnil);
13827 }
13828
13829
13830 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
13831 doc: /* Hide the current tooltip window, if there is any.
13832 Value is t if tooltip was open, nil otherwise. */)
13833 ()
13834 {
13835 int count;
13836 Lisp_Object deleted, frame, timer;
13837 struct gcpro gcpro1, gcpro2;
13838
13839 /* Return quickly if nothing to do. */
13840 if (NILP (tip_timer) && NILP (tip_frame))
13841 return Qnil;
13842
13843 frame = tip_frame;
13844 timer = tip_timer;
13845 GCPRO2 (frame, timer);
13846 tip_frame = tip_timer = deleted = Qnil;
13847
13848 count = BINDING_STACK_SIZE ();
13849 specbind (Qinhibit_redisplay, Qt);
13850 specbind (Qinhibit_quit, Qt);
13851
13852 if (!NILP (timer))
13853 call1 (Qcancel_timer, timer);
13854
13855 if (FRAMEP (frame))
13856 {
13857 Fdelete_frame (frame, Qnil);
13858 deleted = Qt;
13859 }
13860
13861 UNGCPRO;
13862 return unbind_to (count, deleted);
13863 }
13864
13865
13866 \f
13867 /***********************************************************************
13868 File selection dialog
13869 ***********************************************************************/
13870
13871 extern Lisp_Object Qfile_name_history;
13872
13873 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
13874 doc: /* Read file name, prompting with PROMPT in directory DIR.
13875 Use a file selection dialog.
13876 Select DEFAULT-FILENAME in the dialog's file selection box, if
13877 specified. Ensure that file exists if MUSTMATCH is non-nil. */)
13878 (prompt, dir, default_filename, mustmatch)
13879 Lisp_Object prompt, dir, default_filename, mustmatch;
13880 {
13881 struct frame *f = SELECTED_FRAME ();
13882 Lisp_Object file = Qnil;
13883 int count = specpdl_ptr - specpdl;
13884 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
13885 char filename[MAX_PATH + 1];
13886 char init_dir[MAX_PATH + 1];
13887 int use_dialog_p = 1;
13888
13889 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
13890 CHECK_STRING (prompt);
13891 CHECK_STRING (dir);
13892
13893 /* Create the dialog with PROMPT as title, using DIR as initial
13894 directory and using "*" as pattern. */
13895 dir = Fexpand_file_name (dir, Qnil);
13896 strncpy (init_dir, XSTRING (dir)->data, MAX_PATH);
13897 init_dir[MAX_PATH] = '\0';
13898 unixtodos_filename (init_dir);
13899
13900 if (STRINGP (default_filename))
13901 {
13902 char *file_name_only;
13903 char *full_path_name = XSTRING (default_filename)->data;
13904
13905 unixtodos_filename (full_path_name);
13906
13907 file_name_only = strrchr (full_path_name, '\\');
13908 if (!file_name_only)
13909 file_name_only = full_path_name;
13910 else
13911 {
13912 file_name_only++;
13913
13914 /* If default_file_name is a directory, don't use the open
13915 file dialog, as it does not support selecting
13916 directories. */
13917 if (!(*file_name_only))
13918 use_dialog_p = 0;
13919 }
13920
13921 strncpy (filename, file_name_only, MAX_PATH);
13922 filename[MAX_PATH] = '\0';
13923 }
13924 else
13925 filename[0] = '\0';
13926
13927 if (use_dialog_p)
13928 {
13929 OPENFILENAME file_details;
13930
13931 /* Prevent redisplay. */
13932 specbind (Qinhibit_redisplay, Qt);
13933 BLOCK_INPUT;
13934
13935 bzero (&file_details, sizeof (file_details));
13936 file_details.lStructSize = sizeof (file_details);
13937 file_details.hwndOwner = FRAME_W32_WINDOW (f);
13938 /* Undocumented Bug in Common File Dialog:
13939 If a filter is not specified, shell links are not resolved. */
13940 file_details.lpstrFilter = "ALL Files (*.*)\0*.*\0\0";
13941 file_details.lpstrFile = filename;
13942 file_details.nMaxFile = sizeof (filename);
13943 file_details.lpstrInitialDir = init_dir;
13944 file_details.lpstrTitle = XSTRING (prompt)->data;
13945 file_details.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
13946
13947 if (!NILP (mustmatch))
13948 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
13949
13950 if (GetOpenFileName (&file_details))
13951 {
13952 dostounix_filename (filename);
13953 file = build_string (filename);
13954 }
13955 else
13956 file = Qnil;
13957
13958 UNBLOCK_INPUT;
13959 file = unbind_to (count, file);
13960 }
13961 /* Open File dialog will not allow folders to be selected, so resort
13962 to minibuffer completing reads for directories. */
13963 else
13964 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
13965 dir, mustmatch, dir, Qfile_name_history,
13966 default_filename, Qnil);
13967
13968 UNGCPRO;
13969
13970 /* Make "Cancel" equivalent to C-g. */
13971 if (NILP (file))
13972 Fsignal (Qquit, Qnil);
13973
13974 return unbind_to (count, file);
13975 }
13976
13977
13978 \f
13979 /***********************************************************************
13980 w32 specialized functions
13981 ***********************************************************************/
13982
13983 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
13984 doc: /* Select a font using the W32 font dialog.
13985 Returns an X font string corresponding to the selection. */)
13986 (frame, include_proportional)
13987 Lisp_Object frame, include_proportional;
13988 {
13989 FRAME_PTR f = check_x_frame (frame);
13990 CHOOSEFONT cf;
13991 LOGFONT lf;
13992 TEXTMETRIC tm;
13993 HDC hdc;
13994 HANDLE oldobj;
13995 char buf[100];
13996
13997 bzero (&cf, sizeof (cf));
13998 bzero (&lf, sizeof (lf));
13999
14000 cf.lStructSize = sizeof (cf);
14001 cf.hwndOwner = FRAME_W32_WINDOW (f);
14002 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
14003
14004 /* Unless include_proportional is non-nil, limit the selection to
14005 monospaced fonts. */
14006 if (NILP (include_proportional))
14007 cf.Flags |= CF_FIXEDPITCHONLY;
14008
14009 cf.lpLogFont = &lf;
14010
14011 /* Initialize as much of the font details as we can from the current
14012 default font. */
14013 hdc = GetDC (FRAME_W32_WINDOW (f));
14014 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
14015 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
14016 if (GetTextMetrics (hdc, &tm))
14017 {
14018 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
14019 lf.lfWeight = tm.tmWeight;
14020 lf.lfItalic = tm.tmItalic;
14021 lf.lfUnderline = tm.tmUnderlined;
14022 lf.lfStrikeOut = tm.tmStruckOut;
14023 lf.lfCharSet = tm.tmCharSet;
14024 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
14025 }
14026 SelectObject (hdc, oldobj);
14027 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
14028
14029 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
14030 return Qnil;
14031
14032 return build_string (buf);
14033 }
14034
14035 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
14036 Sw32_send_sys_command, 1, 2, 0,
14037 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
14038 Some useful values for command are #xf030 to maximise frame (#xf020
14039 to minimize), #xf120 to restore frame to original size, and #xf100
14040 to activate the menubar for keyboard access. #xf140 activates the
14041 screen saver if defined.
14042
14043 If optional parameter FRAME is not specified, use selected frame. */)
14044 (command, frame)
14045 Lisp_Object command, frame;
14046 {
14047 FRAME_PTR f = check_x_frame (frame);
14048
14049 CHECK_NUMBER (command);
14050
14051 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
14052
14053 return Qnil;
14054 }
14055
14056 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
14057 doc: /* Get Windows to perform OPERATION on DOCUMENT.
14058 This is a wrapper around the ShellExecute system function, which
14059 invokes the application registered to handle OPERATION for DOCUMENT.
14060 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
14061 nil for the default action), and DOCUMENT is typically the name of a
14062 document file or URL, but can also be a program executable to run or
14063 a directory to open in the Windows Explorer.
14064
14065 If DOCUMENT is a program executable, PARAMETERS can be a string
14066 containing command line parameters, but otherwise should be nil.
14067
14068 SHOW-FLAG can be used to control whether the invoked application is hidden
14069 or minimized. If SHOW-FLAG is nil, the application is displayed normally,
14070 otherwise it is an integer representing a ShowWindow flag:
14071
14072 0 - start hidden
14073 1 - start normally
14074 3 - start maximized
14075 6 - start minimized */)
14076 (operation, document, parameters, show_flag)
14077 Lisp_Object operation, document, parameters, show_flag;
14078 {
14079 Lisp_Object current_dir;
14080
14081 CHECK_STRING (document);
14082
14083 /* Encode filename and current directory. */
14084 current_dir = ENCODE_FILE (current_buffer->directory);
14085 document = ENCODE_FILE (document);
14086 if ((int) ShellExecute (NULL,
14087 (STRINGP (operation) ?
14088 XSTRING (operation)->data : NULL),
14089 XSTRING (document)->data,
14090 (STRINGP (parameters) ?
14091 XSTRING (parameters)->data : NULL),
14092 XSTRING (current_dir)->data,
14093 (INTEGERP (show_flag) ?
14094 XINT (show_flag) : SW_SHOWDEFAULT))
14095 > 32)
14096 return Qt;
14097 error ("ShellExecute failed: %s", w32_strerror (0));
14098 }
14099
14100 /* Lookup virtual keycode from string representing the name of a
14101 non-ascii keystroke into the corresponding virtual key, using
14102 lispy_function_keys. */
14103 static int
14104 lookup_vk_code (char *key)
14105 {
14106 int i;
14107
14108 for (i = 0; i < 256; i++)
14109 if (lispy_function_keys[i] != 0
14110 && strcmp (lispy_function_keys[i], key) == 0)
14111 return i;
14112
14113 return -1;
14114 }
14115
14116 /* Convert a one-element vector style key sequence to a hot key
14117 definition. */
14118 static int
14119 w32_parse_hot_key (key)
14120 Lisp_Object key;
14121 {
14122 /* Copied from Fdefine_key and store_in_keymap. */
14123 register Lisp_Object c;
14124 int vk_code;
14125 int lisp_modifiers;
14126 int w32_modifiers;
14127 struct gcpro gcpro1;
14128
14129 CHECK_VECTOR (key);
14130
14131 if (XFASTINT (Flength (key)) != 1)
14132 return Qnil;
14133
14134 GCPRO1 (key);
14135
14136 c = Faref (key, make_number (0));
14137
14138 if (CONSP (c) && lucid_event_type_list_p (c))
14139 c = Fevent_convert_list (c);
14140
14141 UNGCPRO;
14142
14143 if (! INTEGERP (c) && ! SYMBOLP (c))
14144 error ("Key definition is invalid");
14145
14146 /* Work out the base key and the modifiers. */
14147 if (SYMBOLP (c))
14148 {
14149 c = parse_modifiers (c);
14150 lisp_modifiers = Fcar (Fcdr (c));
14151 c = Fcar (c);
14152 if (!SYMBOLP (c))
14153 abort ();
14154 vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
14155 }
14156 else if (INTEGERP (c))
14157 {
14158 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
14159 /* Many ascii characters are their own virtual key code. */
14160 vk_code = XINT (c) & CHARACTERBITS;
14161 }
14162
14163 if (vk_code < 0 || vk_code > 255)
14164 return Qnil;
14165
14166 if ((lisp_modifiers & meta_modifier) != 0
14167 && !NILP (Vw32_alt_is_meta))
14168 lisp_modifiers |= alt_modifier;
14169
14170 /* Supply defs missing from mingw32. */
14171 #ifndef MOD_ALT
14172 #define MOD_ALT 0x0001
14173 #define MOD_CONTROL 0x0002
14174 #define MOD_SHIFT 0x0004
14175 #define MOD_WIN 0x0008
14176 #endif
14177
14178 /* Convert lisp modifiers to Windows hot-key form. */
14179 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
14180 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
14181 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
14182 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
14183
14184 return HOTKEY (vk_code, w32_modifiers);
14185 }
14186
14187 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
14188 Sw32_register_hot_key, 1, 1, 0,
14189 doc: /* Register KEY as a hot-key combination.
14190 Certain key combinations like Alt-Tab are reserved for system use on
14191 Windows, and therefore are normally intercepted by the system. However,
14192 most of these key combinations can be received by registering them as
14193 hot-keys, overriding their special meaning.
14194
14195 KEY must be a one element key definition in vector form that would be
14196 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
14197 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
14198 is always interpreted as the Windows modifier keys.
14199
14200 The return value is the hotkey-id if registered, otherwise nil. */)
14201 (key)
14202 Lisp_Object key;
14203 {
14204 key = w32_parse_hot_key (key);
14205
14206 if (NILP (Fmemq (key, w32_grabbed_keys)))
14207 {
14208 /* Reuse an empty slot if possible. */
14209 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
14210
14211 /* Safe to add new key to list, even if we have focus. */
14212 if (NILP (item))
14213 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
14214 else
14215 XSETCAR (item, key);
14216
14217 /* Notify input thread about new hot-key definition, so that it
14218 takes effect without needing to switch focus. */
14219 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
14220 (WPARAM) key, 0);
14221 }
14222
14223 return key;
14224 }
14225
14226 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
14227 Sw32_unregister_hot_key, 1, 1, 0,
14228 doc: /* Unregister HOTKEY as a hot-key combination. */)
14229 (key)
14230 Lisp_Object key;
14231 {
14232 Lisp_Object item;
14233
14234 if (!INTEGERP (key))
14235 key = w32_parse_hot_key (key);
14236
14237 item = Fmemq (key, w32_grabbed_keys);
14238
14239 if (!NILP (item))
14240 {
14241 /* Notify input thread about hot-key definition being removed, so
14242 that it takes effect without needing focus switch. */
14243 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
14244 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
14245 {
14246 MSG msg;
14247 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14248 }
14249 return Qt;
14250 }
14251 return Qnil;
14252 }
14253
14254 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
14255 Sw32_registered_hot_keys, 0, 0, 0,
14256 doc: /* Return list of registered hot-key IDs. */)
14257 ()
14258 {
14259 return Fcopy_sequence (w32_grabbed_keys);
14260 }
14261
14262 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
14263 Sw32_reconstruct_hot_key, 1, 1, 0,
14264 doc: /* Convert hot-key ID to a lisp key combination. */)
14265 (hotkeyid)
14266 Lisp_Object hotkeyid;
14267 {
14268 int vk_code, w32_modifiers;
14269 Lisp_Object key;
14270
14271 CHECK_NUMBER (hotkeyid);
14272
14273 vk_code = HOTKEY_VK_CODE (hotkeyid);
14274 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
14275
14276 if (lispy_function_keys[vk_code])
14277 key = intern (lispy_function_keys[vk_code]);
14278 else
14279 key = make_number (vk_code);
14280
14281 key = Fcons (key, Qnil);
14282 if (w32_modifiers & MOD_SHIFT)
14283 key = Fcons (Qshift, key);
14284 if (w32_modifiers & MOD_CONTROL)
14285 key = Fcons (Qctrl, key);
14286 if (w32_modifiers & MOD_ALT)
14287 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
14288 if (w32_modifiers & MOD_WIN)
14289 key = Fcons (Qhyper, key);
14290
14291 return key;
14292 }
14293
14294 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
14295 Sw32_toggle_lock_key, 1, 2, 0,
14296 doc: /* Toggle the state of the lock key KEY.
14297 KEY can be `capslock', `kp-numlock', or `scroll'.
14298 If the optional parameter NEW-STATE is a number, then the state of KEY
14299 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
14300 (key, new_state)
14301 Lisp_Object key, new_state;
14302 {
14303 int vk_code;
14304
14305 if (EQ (key, intern ("capslock")))
14306 vk_code = VK_CAPITAL;
14307 else if (EQ (key, intern ("kp-numlock")))
14308 vk_code = VK_NUMLOCK;
14309 else if (EQ (key, intern ("scroll")))
14310 vk_code = VK_SCROLL;
14311 else
14312 return Qnil;
14313
14314 if (!dwWindowsThreadId)
14315 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
14316
14317 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
14318 (WPARAM) vk_code, (LPARAM) new_state))
14319 {
14320 MSG msg;
14321 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14322 return make_number (msg.wParam);
14323 }
14324 return Qnil;
14325 }
14326 \f
14327 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
14328 doc: /* Return storage information about the file system FILENAME is on.
14329 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
14330 storage of the file system, FREE is the free storage, and AVAIL is the
14331 storage available to a non-superuser. All 3 numbers are in bytes.
14332 If the underlying system call fails, value is nil. */)
14333 (filename)
14334 Lisp_Object filename;
14335 {
14336 Lisp_Object encoded, value;
14337
14338 CHECK_STRING (filename);
14339 filename = Fexpand_file_name (filename, Qnil);
14340 encoded = ENCODE_FILE (filename);
14341
14342 value = Qnil;
14343
14344 /* Determining the required information on Windows turns out, sadly,
14345 to be more involved than one would hope. The original Win32 api
14346 call for this will return bogus information on some systems, but we
14347 must dynamically probe for the replacement api, since that was
14348 added rather late on. */
14349 {
14350 HMODULE hKernel = GetModuleHandle ("kernel32");
14351 BOOL (*pfn_GetDiskFreeSpaceEx)
14352 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
14353 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
14354
14355 /* On Windows, we may need to specify the root directory of the
14356 volume holding FILENAME. */
14357 char rootname[MAX_PATH];
14358 char *name = XSTRING (encoded)->data;
14359
14360 /* find the root name of the volume if given */
14361 if (isalpha (name[0]) && name[1] == ':')
14362 {
14363 rootname[0] = name[0];
14364 rootname[1] = name[1];
14365 rootname[2] = '\\';
14366 rootname[3] = 0;
14367 }
14368 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
14369 {
14370 char *str = rootname;
14371 int slashes = 4;
14372 do
14373 {
14374 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
14375 break;
14376 *str++ = *name++;
14377 }
14378 while ( *name );
14379
14380 *str++ = '\\';
14381 *str = 0;
14382 }
14383
14384 if (pfn_GetDiskFreeSpaceEx)
14385 {
14386 LARGE_INTEGER availbytes;
14387 LARGE_INTEGER freebytes;
14388 LARGE_INTEGER totalbytes;
14389
14390 if (pfn_GetDiskFreeSpaceEx(rootname,
14391 &availbytes,
14392 &totalbytes,
14393 &freebytes))
14394 value = list3 (make_float ((double) totalbytes.QuadPart),
14395 make_float ((double) freebytes.QuadPart),
14396 make_float ((double) availbytes.QuadPart));
14397 }
14398 else
14399 {
14400 DWORD sectors_per_cluster;
14401 DWORD bytes_per_sector;
14402 DWORD free_clusters;
14403 DWORD total_clusters;
14404
14405 if (GetDiskFreeSpace(rootname,
14406 &sectors_per_cluster,
14407 &bytes_per_sector,
14408 &free_clusters,
14409 &total_clusters))
14410 value = list3 (make_float ((double) total_clusters
14411 * sectors_per_cluster * bytes_per_sector),
14412 make_float ((double) free_clusters
14413 * sectors_per_cluster * bytes_per_sector),
14414 make_float ((double) free_clusters
14415 * sectors_per_cluster * bytes_per_sector));
14416 }
14417 }
14418
14419 return value;
14420 }
14421 \f
14422 /***********************************************************************
14423 Initialization
14424 ***********************************************************************/
14425
14426 void
14427 syms_of_w32fns ()
14428 {
14429 HMODULE user32_lib = GetModuleHandle ("user32.dll");
14430
14431 /* This is zero if not using MS-Windows. */
14432 w32_in_use = 0;
14433
14434 /* TrackMouseEvent not available in all versions of Windows, so must load
14435 it dynamically. Do it once, here, instead of every time it is used. */
14436 track_mouse_event_fn = GetProcAddress (user32_lib, "TrackMouseEvent");
14437 track_mouse_window = NULL;
14438
14439 /* The section below is built by the lisp expression at the top of the file,
14440 just above where these variables are declared. */
14441 /*&&& init symbols here &&&*/
14442 Qauto_raise = intern ("auto-raise");
14443 staticpro (&Qauto_raise);
14444 Qauto_lower = intern ("auto-lower");
14445 staticpro (&Qauto_lower);
14446 Qbar = intern ("bar");
14447 staticpro (&Qbar);
14448 Qborder_color = intern ("border-color");
14449 staticpro (&Qborder_color);
14450 Qborder_width = intern ("border-width");
14451 staticpro (&Qborder_width);
14452 Qbox = intern ("box");
14453 staticpro (&Qbox);
14454 Qcursor_color = intern ("cursor-color");
14455 staticpro (&Qcursor_color);
14456 Qcursor_type = intern ("cursor-type");
14457 staticpro (&Qcursor_type);
14458 Qgeometry = intern ("geometry");
14459 staticpro (&Qgeometry);
14460 Qicon_left = intern ("icon-left");
14461 staticpro (&Qicon_left);
14462 Qicon_top = intern ("icon-top");
14463 staticpro (&Qicon_top);
14464 Qicon_type = intern ("icon-type");
14465 staticpro (&Qicon_type);
14466 Qicon_name = intern ("icon-name");
14467 staticpro (&Qicon_name);
14468 Qinternal_border_width = intern ("internal-border-width");
14469 staticpro (&Qinternal_border_width);
14470 Qleft = intern ("left");
14471 staticpro (&Qleft);
14472 Qright = intern ("right");
14473 staticpro (&Qright);
14474 Qmouse_color = intern ("mouse-color");
14475 staticpro (&Qmouse_color);
14476 Qnone = intern ("none");
14477 staticpro (&Qnone);
14478 Qparent_id = intern ("parent-id");
14479 staticpro (&Qparent_id);
14480 Qscroll_bar_width = intern ("scroll-bar-width");
14481 staticpro (&Qscroll_bar_width);
14482 Qsuppress_icon = intern ("suppress-icon");
14483 staticpro (&Qsuppress_icon);
14484 Qundefined_color = intern ("undefined-color");
14485 staticpro (&Qundefined_color);
14486 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
14487 staticpro (&Qvertical_scroll_bars);
14488 Qvisibility = intern ("visibility");
14489 staticpro (&Qvisibility);
14490 Qwindow_id = intern ("window-id");
14491 staticpro (&Qwindow_id);
14492 Qx_frame_parameter = intern ("x-frame-parameter");
14493 staticpro (&Qx_frame_parameter);
14494 Qx_resource_name = intern ("x-resource-name");
14495 staticpro (&Qx_resource_name);
14496 Quser_position = intern ("user-position");
14497 staticpro (&Quser_position);
14498 Quser_size = intern ("user-size");
14499 staticpro (&Quser_size);
14500 Qscreen_gamma = intern ("screen-gamma");
14501 staticpro (&Qscreen_gamma);
14502 Qline_spacing = intern ("line-spacing");
14503 staticpro (&Qline_spacing);
14504 Qcenter = intern ("center");
14505 staticpro (&Qcenter);
14506 Qcancel_timer = intern ("cancel-timer");
14507 staticpro (&Qcancel_timer);
14508 /* This is the end of symbol initialization. */
14509
14510 Qhyper = intern ("hyper");
14511 staticpro (&Qhyper);
14512 Qsuper = intern ("super");
14513 staticpro (&Qsuper);
14514 Qmeta = intern ("meta");
14515 staticpro (&Qmeta);
14516 Qalt = intern ("alt");
14517 staticpro (&Qalt);
14518 Qctrl = intern ("ctrl");
14519 staticpro (&Qctrl);
14520 Qcontrol = intern ("control");
14521 staticpro (&Qcontrol);
14522 Qshift = intern ("shift");
14523 staticpro (&Qshift);
14524
14525 /* Text property `display' should be nonsticky by default. */
14526 Vtext_property_default_nonsticky
14527 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
14528
14529
14530 Qlaplace = intern ("laplace");
14531 staticpro (&Qlaplace);
14532 Qemboss = intern ("emboss");
14533 staticpro (&Qemboss);
14534 Qedge_detection = intern ("edge-detection");
14535 staticpro (&Qedge_detection);
14536 Qheuristic = intern ("heuristic");
14537 staticpro (&Qheuristic);
14538 QCmatrix = intern (":matrix");
14539 staticpro (&QCmatrix);
14540 QCcolor_adjustment = intern (":color-adjustment");
14541 staticpro (&QCcolor_adjustment);
14542 QCmask = intern (":mask");
14543 staticpro (&QCmask);
14544
14545 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
14546 staticpro (&Qface_set_after_frame_default);
14547
14548 Fput (Qundefined_color, Qerror_conditions,
14549 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
14550 Fput (Qundefined_color, Qerror_message,
14551 build_string ("Undefined color"));
14552
14553 staticpro (&w32_grabbed_keys);
14554 w32_grabbed_keys = Qnil;
14555
14556 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
14557 doc: /* An array of color name mappings for windows. */);
14558 Vw32_color_map = Qnil;
14559
14560 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
14561 doc: /* Non-nil if alt key presses are passed on to Windows.
14562 When non-nil, for example, alt pressed and released and then space will
14563 open the System menu. When nil, Emacs silently swallows alt key events. */);
14564 Vw32_pass_alt_to_system = Qnil;
14565
14566 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
14567 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
14568 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
14569 Vw32_alt_is_meta = Qt;
14570
14571 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
14572 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
14573 XSETINT (Vw32_quit_key, 0);
14574
14575 DEFVAR_LISP ("w32-pass-lwindow-to-system",
14576 &Vw32_pass_lwindow_to_system,
14577 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
14578 When non-nil, the Start menu is opened by tapping the key. */);
14579 Vw32_pass_lwindow_to_system = Qt;
14580
14581 DEFVAR_LISP ("w32-pass-rwindow-to-system",
14582 &Vw32_pass_rwindow_to_system,
14583 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
14584 When non-nil, the Start menu is opened by tapping the key. */);
14585 Vw32_pass_rwindow_to_system = Qt;
14586
14587 DEFVAR_INT ("w32-phantom-key-code",
14588 &Vw32_phantom_key_code,
14589 doc: /* Virtual key code used to generate \"phantom\" key presses.
14590 Value is a number between 0 and 255.
14591
14592 Phantom key presses are generated in order to stop the system from
14593 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
14594 `w32-pass-rwindow-to-system' is nil. */);
14595 /* Although 255 is technically not a valid key code, it works and
14596 means that this hack won't interfere with any real key code. */
14597 Vw32_phantom_key_code = 255;
14598
14599 DEFVAR_LISP ("w32-enable-num-lock",
14600 &Vw32_enable_num_lock,
14601 doc: /* Non-nil if Num Lock should act normally.
14602 Set to nil to see Num Lock as the key `kp-numlock'. */);
14603 Vw32_enable_num_lock = Qt;
14604
14605 DEFVAR_LISP ("w32-enable-caps-lock",
14606 &Vw32_enable_caps_lock,
14607 doc: /* Non-nil if Caps Lock should act normally.
14608 Set to nil to see Caps Lock as the key `capslock'. */);
14609 Vw32_enable_caps_lock = Qt;
14610
14611 DEFVAR_LISP ("w32-scroll-lock-modifier",
14612 &Vw32_scroll_lock_modifier,
14613 doc: /* Modifier to use for the Scroll Lock on state.
14614 The value can be hyper, super, meta, alt, control or shift for the
14615 respective modifier, or nil to see Scroll Lock as the key `scroll'.
14616 Any other value will cause the key to be ignored. */);
14617 Vw32_scroll_lock_modifier = Qt;
14618
14619 DEFVAR_LISP ("w32-lwindow-modifier",
14620 &Vw32_lwindow_modifier,
14621 doc: /* Modifier to use for the left \"Windows\" key.
14622 The value can be hyper, super, meta, alt, control or shift for the
14623 respective modifier, or nil to appear as the key `lwindow'.
14624 Any other value will cause the key to be ignored. */);
14625 Vw32_lwindow_modifier = Qnil;
14626
14627 DEFVAR_LISP ("w32-rwindow-modifier",
14628 &Vw32_rwindow_modifier,
14629 doc: /* Modifier to use for the right \"Windows\" key.
14630 The value can be hyper, super, meta, alt, control or shift for the
14631 respective modifier, or nil to appear as the key `rwindow'.
14632 Any other value will cause the key to be ignored. */);
14633 Vw32_rwindow_modifier = Qnil;
14634
14635 DEFVAR_LISP ("w32-apps-modifier",
14636 &Vw32_apps_modifier,
14637 doc: /* Modifier to use for the \"Apps\" key.
14638 The value can be hyper, super, meta, alt, control or shift for the
14639 respective modifier, or nil to appear as the key `apps'.
14640 Any other value will cause the key to be ignored. */);
14641 Vw32_apps_modifier = Qnil;
14642
14643 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
14644 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
14645 w32_enable_synthesized_fonts = 0;
14646
14647 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
14648 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
14649 Vw32_enable_palette = Qt;
14650
14651 DEFVAR_INT ("w32-mouse-button-tolerance",
14652 &Vw32_mouse_button_tolerance,
14653 doc: /* Analogue of double click interval for faking middle mouse events.
14654 The value is the minimum time in milliseconds that must elapse between
14655 left/right button down events before they are considered distinct events.
14656 If both mouse buttons are depressed within this interval, a middle mouse
14657 button down event is generated instead. */);
14658 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
14659
14660 DEFVAR_INT ("w32-mouse-move-interval",
14661 &Vw32_mouse_move_interval,
14662 doc: /* Minimum interval between mouse move events.
14663 The value is the minimum time in milliseconds that must elapse between
14664 successive mouse move (or scroll bar drag) events before they are
14665 reported as lisp events. */);
14666 XSETINT (Vw32_mouse_move_interval, 0);
14667
14668 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
14669 &w32_pass_extra_mouse_buttons_to_system,
14670 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
14671 Recent versions of Windows support mice with up to five buttons.
14672 Since most applications don't support these extra buttons, most mouse
14673 drivers will allow you to map them to functions at the system level.
14674 If this variable is non-nil, Emacs will pass them on, allowing the
14675 system to handle them. */);
14676 w32_pass_extra_mouse_buttons_to_system = 0;
14677
14678 init_x_parm_symbols ();
14679
14680 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
14681 doc: /* List of directories to search for bitmap files for w32. */);
14682 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
14683
14684 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
14685 doc: /* The shape of the pointer when over text.
14686 Changing the value does not affect existing frames
14687 unless you set the mouse color. */);
14688 Vx_pointer_shape = Qnil;
14689
14690 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
14691 doc: /* The name Emacs uses to look up resources; for internal use only.
14692 `x-get-resource' uses this as the first component of the instance name
14693 when requesting resource values.
14694 Emacs initially sets `x-resource-name' to the name under which Emacs
14695 was invoked, or to the value specified with the `-name' or `-rn'
14696 switches, if present. */);
14697 Vx_resource_name = Qnil;
14698
14699 Vx_nontext_pointer_shape = Qnil;
14700
14701 Vx_mode_pointer_shape = Qnil;
14702
14703 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
14704 doc: /* The shape of the pointer when Emacs is busy.
14705 This variable takes effect when you create a new frame
14706 or when you set the mouse color. */);
14707 Vx_hourglass_pointer_shape = Qnil;
14708
14709 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
14710 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
14711 display_hourglass_p = 1;
14712
14713 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
14714 doc: /* *Seconds to wait before displaying an hourglass pointer.
14715 Value must be an integer or float. */);
14716 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
14717
14718 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
14719 &Vx_sensitive_text_pointer_shape,
14720 doc: /* The shape of the pointer when over mouse-sensitive text.
14721 This variable takes effect when you create a new frame
14722 or when you set the mouse color. */);
14723 Vx_sensitive_text_pointer_shape = Qnil;
14724
14725 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
14726 &Vx_window_horizontal_drag_shape,
14727 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
14728 This variable takes effect when you create a new frame
14729 or when you set the mouse color. */);
14730 Vx_window_horizontal_drag_shape = Qnil;
14731
14732 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
14733 doc: /* A string indicating the foreground color of the cursor box. */);
14734 Vx_cursor_fore_pixel = Qnil;
14735
14736 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
14737 doc: /* Maximum size for tooltips.
14738 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
14739 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
14740
14741 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
14742 doc: /* Non-nil if no window manager is in use.
14743 Emacs doesn't try to figure this out; this is always nil
14744 unless you set it to something else. */);
14745 /* We don't have any way to find this out, so set it to nil
14746 and maybe the user would like to set it to t. */
14747 Vx_no_window_manager = Qnil;
14748
14749 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
14750 &Vx_pixel_size_width_font_regexp,
14751 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
14752
14753 Since Emacs gets width of a font matching with this regexp from
14754 PIXEL_SIZE field of the name, font finding mechanism gets faster for
14755 such a font. This is especially effective for such large fonts as
14756 Chinese, Japanese, and Korean. */);
14757 Vx_pixel_size_width_font_regexp = Qnil;
14758
14759 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
14760 doc: /* Time after which cached images are removed from the cache.
14761 When an image has not been displayed this many seconds, remove it
14762 from the image cache. Value must be an integer or nil with nil
14763 meaning don't clear the cache. */);
14764 Vimage_cache_eviction_delay = make_number (30 * 60);
14765
14766 DEFVAR_LISP ("w32-bdf-filename-alist",
14767 &Vw32_bdf_filename_alist,
14768 doc: /* List of bdf fonts and their corresponding filenames. */);
14769 Vw32_bdf_filename_alist = Qnil;
14770
14771 DEFVAR_BOOL ("w32-strict-fontnames",
14772 &w32_strict_fontnames,
14773 doc: /* Non-nil means only use fonts that are exact matches for those requested.
14774 Default is nil, which allows old fontnames that are not XLFD compliant,
14775 and allows third-party CJK display to work by specifying false charset
14776 fields to trick Emacs into translating to Big5, SJIS etc.
14777 Setting this to t will prevent wrong fonts being selected when
14778 fontsets are automatically created. */);
14779 w32_strict_fontnames = 0;
14780
14781 DEFVAR_BOOL ("w32-strict-painting",
14782 &w32_strict_painting,
14783 doc: /* Non-nil means use strict rules for repainting frames.
14784 Set this to nil to get the old behaviour for repainting; this should
14785 only be necessary if the default setting causes problems. */);
14786 w32_strict_painting = 1;
14787
14788 DEFVAR_LISP ("w32-charset-info-alist",
14789 &Vw32_charset_info_alist,
14790 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
14791 Each entry should be of the form:
14792
14793 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
14794
14795 where CHARSET_NAME is a string used in font names to identify the charset,
14796 WINDOWS_CHARSET is a symbol that can be one of:
14797 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
14798 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
14799 w32-charset-chinesebig5,
14800 #ifdef JOHAB_CHARSET
14801 w32-charset-johab, w32-charset-hebrew,
14802 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
14803 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
14804 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
14805 #endif
14806 #ifdef UNICODE_CHARSET
14807 w32-charset-unicode,
14808 #endif
14809 or w32-charset-oem.
14810 CODEPAGE should be an integer specifying the codepage that should be used
14811 to display the character set, t to do no translation and output as Unicode,
14812 or nil to do no translation and output as 8 bit (or multibyte on far-east
14813 versions of Windows) characters. */);
14814 Vw32_charset_info_alist = Qnil;
14815
14816 staticpro (&Qw32_charset_ansi);
14817 Qw32_charset_ansi = intern ("w32-charset-ansi");
14818 staticpro (&Qw32_charset_symbol);
14819 Qw32_charset_symbol = intern ("w32-charset-symbol");
14820 staticpro (&Qw32_charset_shiftjis);
14821 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
14822 staticpro (&Qw32_charset_hangeul);
14823 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
14824 staticpro (&Qw32_charset_chinesebig5);
14825 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
14826 staticpro (&Qw32_charset_gb2312);
14827 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
14828 staticpro (&Qw32_charset_oem);
14829 Qw32_charset_oem = intern ("w32-charset-oem");
14830
14831 #ifdef JOHAB_CHARSET
14832 {
14833 static int w32_extra_charsets_defined = 1;
14834 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
14835 doc: /* Internal variable. */);
14836
14837 staticpro (&Qw32_charset_johab);
14838 Qw32_charset_johab = intern ("w32-charset-johab");
14839 staticpro (&Qw32_charset_easteurope);
14840 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
14841 staticpro (&Qw32_charset_turkish);
14842 Qw32_charset_turkish = intern ("w32-charset-turkish");
14843 staticpro (&Qw32_charset_baltic);
14844 Qw32_charset_baltic = intern ("w32-charset-baltic");
14845 staticpro (&Qw32_charset_russian);
14846 Qw32_charset_russian = intern ("w32-charset-russian");
14847 staticpro (&Qw32_charset_arabic);
14848 Qw32_charset_arabic = intern ("w32-charset-arabic");
14849 staticpro (&Qw32_charset_greek);
14850 Qw32_charset_greek = intern ("w32-charset-greek");
14851 staticpro (&Qw32_charset_hebrew);
14852 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
14853 staticpro (&Qw32_charset_vietnamese);
14854 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
14855 staticpro (&Qw32_charset_thai);
14856 Qw32_charset_thai = intern ("w32-charset-thai");
14857 staticpro (&Qw32_charset_mac);
14858 Qw32_charset_mac = intern ("w32-charset-mac");
14859 }
14860 #endif
14861
14862 #ifdef UNICODE_CHARSET
14863 {
14864 static int w32_unicode_charset_defined = 1;
14865 DEFVAR_BOOL ("w32-unicode-charset-defined",
14866 &w32_unicode_charset_defined,
14867 doc: /* Internal variable. */);
14868
14869 staticpro (&Qw32_charset_unicode);
14870 Qw32_charset_unicode = intern ("w32-charset-unicode");
14871 #endif
14872
14873 defsubr (&Sx_get_resource);
14874 #if 0 /* TODO: Port to W32 */
14875 defsubr (&Sx_change_window_property);
14876 defsubr (&Sx_delete_window_property);
14877 defsubr (&Sx_window_property);
14878 #endif
14879 defsubr (&Sxw_display_color_p);
14880 defsubr (&Sx_display_grayscale_p);
14881 defsubr (&Sxw_color_defined_p);
14882 defsubr (&Sxw_color_values);
14883 defsubr (&Sx_server_max_request_size);
14884 defsubr (&Sx_server_vendor);
14885 defsubr (&Sx_server_version);
14886 defsubr (&Sx_display_pixel_width);
14887 defsubr (&Sx_display_pixel_height);
14888 defsubr (&Sx_display_mm_width);
14889 defsubr (&Sx_display_mm_height);
14890 defsubr (&Sx_display_screens);
14891 defsubr (&Sx_display_planes);
14892 defsubr (&Sx_display_color_cells);
14893 defsubr (&Sx_display_visual_class);
14894 defsubr (&Sx_display_backing_store);
14895 defsubr (&Sx_display_save_under);
14896 defsubr (&Sx_parse_geometry);
14897 defsubr (&Sx_create_frame);
14898 defsubr (&Sx_open_connection);
14899 defsubr (&Sx_close_connection);
14900 defsubr (&Sx_display_list);
14901 defsubr (&Sx_synchronize);
14902
14903 /* W32 specific functions */
14904
14905 defsubr (&Sw32_focus_frame);
14906 defsubr (&Sw32_select_font);
14907 defsubr (&Sw32_define_rgb_color);
14908 defsubr (&Sw32_default_color_map);
14909 defsubr (&Sw32_load_color_file);
14910 defsubr (&Sw32_send_sys_command);
14911 defsubr (&Sw32_shell_execute);
14912 defsubr (&Sw32_register_hot_key);
14913 defsubr (&Sw32_unregister_hot_key);
14914 defsubr (&Sw32_registered_hot_keys);
14915 defsubr (&Sw32_reconstruct_hot_key);
14916 defsubr (&Sw32_toggle_lock_key);
14917 defsubr (&Sw32_find_bdf_fonts);
14918
14919 defsubr (&Sfile_system_info);
14920
14921 /* Setting callback functions for fontset handler. */
14922 get_font_info_func = w32_get_font_info;
14923
14924 #if 0 /* This function pointer doesn't seem to be used anywhere.
14925 And the pointer assigned has the wrong type, anyway. */
14926 list_fonts_func = w32_list_fonts;
14927 #endif
14928
14929 load_font_func = w32_load_font;
14930 find_ccl_program_func = w32_find_ccl_program;
14931 query_font_func = w32_query_font;
14932 set_frame_fontset_func = x_set_font;
14933 check_window_system_func = check_w32;
14934
14935 #if 0 /* TODO Image support for W32 */
14936 /* Images. */
14937 Qxbm = intern ("xbm");
14938 staticpro (&Qxbm);
14939 QCtype = intern (":type");
14940 staticpro (&QCtype);
14941 QCconversion = intern (":conversion");
14942 staticpro (&QCconversion);
14943 QCheuristic_mask = intern (":heuristic-mask");
14944 staticpro (&QCheuristic_mask);
14945 QCcolor_symbols = intern (":color-symbols");
14946 staticpro (&QCcolor_symbols);
14947 QCascent = intern (":ascent");
14948 staticpro (&QCascent);
14949 QCmargin = intern (":margin");
14950 staticpro (&QCmargin);
14951 QCrelief = intern (":relief");
14952 staticpro (&QCrelief);
14953 Qpostscript = intern ("postscript");
14954 staticpro (&Qpostscript);
14955 QCloader = intern (":loader");
14956 staticpro (&QCloader);
14957 QCbounding_box = intern (":bounding-box");
14958 staticpro (&QCbounding_box);
14959 QCpt_width = intern (":pt-width");
14960 staticpro (&QCpt_width);
14961 QCpt_height = intern (":pt-height");
14962 staticpro (&QCpt_height);
14963 QCindex = intern (":index");
14964 staticpro (&QCindex);
14965 Qpbm = intern ("pbm");
14966 staticpro (&Qpbm);
14967
14968 #if HAVE_XPM
14969 Qxpm = intern ("xpm");
14970 staticpro (&Qxpm);
14971 #endif
14972
14973 #if HAVE_JPEG
14974 Qjpeg = intern ("jpeg");
14975 staticpro (&Qjpeg);
14976 #endif
14977
14978 #if HAVE_TIFF
14979 Qtiff = intern ("tiff");
14980 staticpro (&Qtiff);
14981 #endif
14982
14983 #if HAVE_GIF
14984 Qgif = intern ("gif");
14985 staticpro (&Qgif);
14986 #endif
14987
14988 #if HAVE_PNG
14989 Qpng = intern ("png");
14990 staticpro (&Qpng);
14991 #endif
14992
14993 defsubr (&Sclear_image_cache);
14994
14995 #if GLYPH_DEBUG
14996 defsubr (&Simagep);
14997 defsubr (&Slookup_image);
14998 #endif
14999 #endif /* TODO */
15000
15001 hourglass_atimer = NULL;
15002 hourglass_shown_p = 0;
15003 defsubr (&Sx_show_tip);
15004 defsubr (&Sx_hide_tip);
15005 tip_timer = Qnil;
15006 staticpro (&tip_timer);
15007 tip_frame = Qnil;
15008 staticpro (&tip_frame);
15009
15010 last_show_tip_args = Qnil;
15011 staticpro (&last_show_tip_args);
15012
15013 defsubr (&Sx_file_dialog);
15014 }
15015
15016
15017 void
15018 init_xfns ()
15019 {
15020 image_types = NULL;
15021 Vimage_types = Qnil;
15022
15023 #if 0 /* TODO : Image support for W32 */
15024 define_image_type (&xbm_type);
15025 define_image_type (&gs_type);
15026 define_image_type (&pbm_type);
15027
15028 #if HAVE_XPM
15029 define_image_type (&xpm_type);
15030 #endif
15031
15032 #if HAVE_JPEG
15033 define_image_type (&jpeg_type);
15034 #endif
15035
15036 #if HAVE_TIFF
15037 define_image_type (&tiff_type);
15038 #endif
15039
15040 #if HAVE_GIF
15041 define_image_type (&gif_type);
15042 #endif
15043
15044 #if HAVE_PNG
15045 define_image_type (&png_type);
15046 #endif
15047 #endif /* TODO */
15048 }
15049
15050 #undef abort
15051
15052 void
15053 w32_abort()
15054 {
15055 int button;
15056 button = MessageBox (NULL,
15057 "A fatal error has occurred!\n\n"
15058 "Select Abort to exit, Retry to debug, Ignore to continue",
15059 "Emacs Abort Dialog",
15060 MB_ICONEXCLAMATION | MB_TASKMODAL
15061 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
15062 switch (button)
15063 {
15064 case IDRETRY:
15065 DebugBreak ();
15066 break;
15067 case IDIGNORE:
15068 break;
15069 case IDABORT:
15070 default:
15071 abort ();
15072 break;
15073 }
15074 }
15075
15076 /* For convenience when debugging. */
15077 int
15078 w32_last_error()
15079 {
15080 return GetLastError ();
15081 }