Fix last change.
[bpt/emacs.git] / 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
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 "frame.h"
36 #include "window.h"
37 #include "buffer.h"
38 #include "fontset.h"
39 #include "intervals.h"
40 #include "keyboard.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "w32heap.h"
44 #include "termhooks.h"
45 #include "coding.h"
46 #include "ccl.h"
47 #include "systime.h"
48
49 #include "bitmaps/gray.xbm"
50
51 #include <commdlg.h>
52 #include <shellapi.h>
53 #include <ctype.h>
54
55 #define max(a, b) ((a) > (b) ? (a) : (b))
56
57 extern void free_frame_menubar ();
58 extern double atof ();
59 extern int w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state);
60 extern int quit_char;
61
62 /* A definition of XColor for non-X frames. */
63 #ifndef HAVE_X_WINDOWS
64 typedef struct {
65 unsigned long pixel;
66 unsigned short red, green, blue;
67 char flags;
68 char pad;
69 } XColor;
70 #endif
71
72 extern char *lispy_function_keys[];
73
74 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
75 it, and including `bitmaps/gray' more than once is a problem when
76 config.h defines `static' as an empty replacement string. */
77
78 int gray_bitmap_width = gray_width;
79 int gray_bitmap_height = gray_height;
80 unsigned char *gray_bitmap_bits = gray_bits;
81
82 /* The colormap for converting color names to RGB values */
83 Lisp_Object Vw32_color_map;
84
85 /* Non nil if alt key presses are passed on to Windows. */
86 Lisp_Object Vw32_pass_alt_to_system;
87
88 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
89 to alt_modifier. */
90 Lisp_Object Vw32_alt_is_meta;
91
92 /* If non-zero, the windows virtual key code for an alternative quit key. */
93 Lisp_Object Vw32_quit_key;
94
95 /* Non nil if left window key events are passed on to Windows (this only
96 affects whether "tapping" the key opens the Start menu). */
97 Lisp_Object Vw32_pass_lwindow_to_system;
98
99 /* Non nil if right window key events are passed on to Windows (this
100 only affects whether "tapping" the key opens the Start menu). */
101 Lisp_Object Vw32_pass_rwindow_to_system;
102
103 /* Virtual key code used to generate "phantom" key presses in order
104 to stop system from acting on Windows key events. */
105 Lisp_Object Vw32_phantom_key_code;
106
107 /* Modifier associated with the left "Windows" key, or nil to act as a
108 normal key. */
109 Lisp_Object Vw32_lwindow_modifier;
110
111 /* Modifier associated with the right "Windows" key, or nil to act as a
112 normal key. */
113 Lisp_Object Vw32_rwindow_modifier;
114
115 /* Modifier associated with the "Apps" key, or nil to act as a normal
116 key. */
117 Lisp_Object Vw32_apps_modifier;
118
119 /* Value is nil if Num Lock acts as a function key. */
120 Lisp_Object Vw32_enable_num_lock;
121
122 /* Value is nil if Caps Lock acts as a function key. */
123 Lisp_Object Vw32_enable_caps_lock;
124
125 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
126 Lisp_Object Vw32_scroll_lock_modifier;
127
128 /* Switch to control whether we inhibit requests for synthesized bold
129 and italic versions of fonts. */
130 Lisp_Object Vw32_enable_synthesized_fonts;
131
132 /* Enable palette management. */
133 Lisp_Object Vw32_enable_palette;
134
135 /* Control how close left/right button down events must be to
136 be converted to a middle button down event. */
137 Lisp_Object Vw32_mouse_button_tolerance;
138
139 /* Minimum interval between mouse movement (and scroll bar drag)
140 events that are passed on to the event loop. */
141 Lisp_Object Vw32_mouse_move_interval;
142
143 /* The name we're using in resource queries. */
144 Lisp_Object Vx_resource_name;
145
146 /* Non nil if no window manager is in use. */
147 Lisp_Object Vx_no_window_manager;
148
149 /* Non-zero means we're allowed to display a busy cursor. */
150
151 int display_busy_cursor_p;
152
153 /* The background and shape of the mouse pointer, and shape when not
154 over text or in the modeline. */
155
156 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
157 Lisp_Object Vx_busy_pointer_shape;
158
159 /* The shape when over mouse-sensitive text. */
160
161 Lisp_Object Vx_sensitive_text_pointer_shape;
162
163 /* Color of chars displayed in cursor box. */
164
165 Lisp_Object Vx_cursor_fore_pixel;
166
167 /* Nonzero if using Windows. */
168
169 static int w32_in_use;
170
171 /* Search path for bitmap files. */
172
173 Lisp_Object Vx_bitmap_file_path;
174
175 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
176
177 Lisp_Object Vx_pixel_size_width_font_regexp;
178
179 /* Alist of bdf fonts and the files that define them. */
180 Lisp_Object Vw32_bdf_filename_alist;
181
182 Lisp_Object Vw32_system_coding_system;
183
184 /* A flag to control whether fonts are matched strictly or not. */
185 int w32_strict_fontnames;
186
187 /* A flag to control whether we should only repaint if GetUpdateRect
188 indicates there is an update region. */
189 int w32_strict_painting;
190
191 /* Associative list linking character set strings to Windows codepages. */
192 Lisp_Object Vw32_charset_info_alist;
193
194 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
195 #ifndef VIETNAMESE_CHARSET
196 #define VIETNAMESE_CHARSET 163
197 #endif
198
199
200 /* Evaluate this expression to rebuild the section of syms_of_w32fns
201 that initializes and staticpros the symbols declared below. Note
202 that Emacs 18 has a bug that keeps C-x C-e from being able to
203 evaluate this expression.
204
205 (progn
206 ;; Accumulate a list of the symbols we want to initialize from the
207 ;; declarations at the top of the file.
208 (goto-char (point-min))
209 (search-forward "/\*&&& symbols declared here &&&*\/\n")
210 (let (symbol-list)
211 (while (looking-at "Lisp_Object \\(Q[a-z_]+\\)")
212 (setq symbol-list
213 (cons (buffer-substring (match-beginning 1) (match-end 1))
214 symbol-list))
215 (forward-line 1))
216 (setq symbol-list (nreverse symbol-list))
217 ;; Delete the section of syms_of_... where we initialize the symbols.
218 (search-forward "\n /\*&&& init symbols here &&&*\/\n")
219 (let ((start (point)))
220 (while (looking-at "^ Q")
221 (forward-line 2))
222 (kill-region start (point)))
223 ;; Write a new symbol initialization section.
224 (while symbol-list
225 (insert (format " %s = intern (\"" (car symbol-list)))
226 (let ((start (point)))
227 (insert (substring (car symbol-list) 1))
228 (subst-char-in-region start (point) ?_ ?-))
229 (insert (format "\");\n staticpro (&%s);\n" (car symbol-list)))
230 (setq symbol-list (cdr symbol-list)))))
231
232 */
233
234 /*&&& symbols declared here &&&*/
235 Lisp_Object Qauto_raise;
236 Lisp_Object Qauto_lower;
237 Lisp_Object Qbar;
238 Lisp_Object Qborder_color;
239 Lisp_Object Qborder_width;
240 Lisp_Object Qbox;
241 Lisp_Object Qcursor_color;
242 Lisp_Object Qcursor_type;
243 Lisp_Object Qgeometry;
244 Lisp_Object Qicon_left;
245 Lisp_Object Qicon_top;
246 Lisp_Object Qicon_type;
247 Lisp_Object Qicon_name;
248 Lisp_Object Qinternal_border_width;
249 Lisp_Object Qleft;
250 Lisp_Object Qright;
251 Lisp_Object Qmouse_color;
252 Lisp_Object Qnone;
253 Lisp_Object Qparent_id;
254 Lisp_Object Qscroll_bar_width;
255 Lisp_Object Qsuppress_icon;
256 Lisp_Object Qundefined_color;
257 Lisp_Object Qvertical_scroll_bars;
258 Lisp_Object Qvisibility;
259 Lisp_Object Qwindow_id;
260 Lisp_Object Qx_frame_parameter;
261 Lisp_Object Qx_resource_name;
262 Lisp_Object Quser_position;
263 Lisp_Object Quser_size;
264 Lisp_Object Qscreen_gamma;
265 Lisp_Object Qline_spacing;
266 Lisp_Object Qcenter;
267 Lisp_Object Qhyper;
268 Lisp_Object Qsuper;
269 Lisp_Object Qmeta;
270 Lisp_Object Qalt;
271 Lisp_Object Qctrl;
272 Lisp_Object Qcontrol;
273 Lisp_Object Qshift;
274
275 Lisp_Object Qw32_charset_ansi;
276 Lisp_Object Qw32_charset_default;
277 Lisp_Object Qw32_charset_symbol;
278 Lisp_Object Qw32_charset_shiftjis;
279 Lisp_Object Qw32_charset_hangeul;
280 Lisp_Object Qw32_charset_gb2312;
281 Lisp_Object Qw32_charset_chinesebig5;
282 Lisp_Object Qw32_charset_oem;
283
284 #ifndef JOHAB_CHARSET
285 #define JOHAB_CHARSET 130
286 #endif
287 #ifdef JOHAB_CHARSET
288 Lisp_Object Qw32_charset_easteurope;
289 Lisp_Object Qw32_charset_turkish;
290 Lisp_Object Qw32_charset_baltic;
291 Lisp_Object Qw32_charset_russian;
292 Lisp_Object Qw32_charset_arabic;
293 Lisp_Object Qw32_charset_greek;
294 Lisp_Object Qw32_charset_hebrew;
295 Lisp_Object Qw32_charset_vietnamese;
296 Lisp_Object Qw32_charset_thai;
297 Lisp_Object Qw32_charset_johab;
298 Lisp_Object Qw32_charset_mac;
299 #endif
300
301 #ifdef UNICODE_CHARSET
302 Lisp_Object Qw32_charset_unicode;
303 #endif
304
305 extern Lisp_Object Qtop;
306 extern Lisp_Object Qdisplay;
307 extern Lisp_Object Qtool_bar_lines;
308
309 /* State variables for emulating a three button mouse. */
310 #define LMOUSE 1
311 #define MMOUSE 2
312 #define RMOUSE 4
313
314 static int button_state = 0;
315 static W32Msg saved_mouse_button_msg;
316 static unsigned mouse_button_timer; /* non-zero when timer is active */
317 static W32Msg saved_mouse_move_msg;
318 static unsigned mouse_move_timer;
319
320 /* W95 mousewheel handler */
321 unsigned int msh_mousewheel = 0;
322
323 #define MOUSE_BUTTON_ID 1
324 #define MOUSE_MOVE_ID 2
325
326 /* The below are defined in frame.c. */
327
328 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
329 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
330 extern Lisp_Object Qtool_bar_lines;
331
332 extern Lisp_Object Vwindow_system_version;
333
334 Lisp_Object Qface_set_after_frame_default;
335
336 /* From w32term.c. */
337 extern Lisp_Object Vw32_num_mouse_buttons;
338 extern Lisp_Object Vw32_recognize_altgr;
339
340 \f
341 /* Error if we are not connected to MS-Windows. */
342 void
343 check_w32 ()
344 {
345 if (! w32_in_use)
346 error ("MS-Windows not in use or not initialized");
347 }
348
349 /* Nonzero if we can use mouse menus.
350 You should not call this unless HAVE_MENUS is defined. */
351
352 int
353 have_menus_p ()
354 {
355 return w32_in_use;
356 }
357
358 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
359 and checking validity for W32. */
360
361 FRAME_PTR
362 check_x_frame (frame)
363 Lisp_Object frame;
364 {
365 FRAME_PTR f;
366
367 if (NILP (frame))
368 frame = selected_frame;
369 CHECK_LIVE_FRAME (frame, 0);
370 f = XFRAME (frame);
371 if (! FRAME_W32_P (f))
372 error ("non-w32 frame used");
373 return f;
374 }
375
376 /* Let the user specify an display with a frame.
377 nil stands for the selected frame--or, if that is not a w32 frame,
378 the first display on the list. */
379
380 static struct w32_display_info *
381 check_x_display_info (frame)
382 Lisp_Object frame;
383 {
384 if (NILP (frame))
385 {
386 struct frame *sf = XFRAME (selected_frame);
387
388 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
389 return FRAME_W32_DISPLAY_INFO (sf);
390 else
391 return &one_w32_display_info;
392 }
393 else if (STRINGP (frame))
394 return x_display_info_for_name (frame);
395 else
396 {
397 FRAME_PTR f;
398
399 CHECK_LIVE_FRAME (frame, 0);
400 f = XFRAME (frame);
401 if (! FRAME_W32_P (f))
402 error ("non-w32 frame used");
403 return FRAME_W32_DISPLAY_INFO (f);
404 }
405 }
406 \f
407 /* Return the Emacs frame-object corresponding to an w32 window.
408 It could be the frame's main window or an icon window. */
409
410 /* This function can be called during GC, so use GC_xxx type test macros. */
411
412 struct frame *
413 x_window_to_frame (dpyinfo, wdesc)
414 struct w32_display_info *dpyinfo;
415 HWND wdesc;
416 {
417 Lisp_Object tail, frame;
418 struct frame *f;
419
420 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
421 {
422 frame = XCAR (tail);
423 if (!GC_FRAMEP (frame))
424 continue;
425 f = XFRAME (frame);
426 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
427 continue;
428 if (f->output_data.w32->busy_window == wdesc)
429 return f;
430
431 /* TODO: Check tooltips when supported. */
432 if (FRAME_W32_WINDOW (f) == wdesc)
433 return f;
434 }
435 return 0;
436 }
437
438 \f
439
440 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
441 id, which is just an int that this section returns. Bitmaps are
442 reference counted so they can be shared among frames.
443
444 Bitmap indices are guaranteed to be > 0, so a negative number can
445 be used to indicate no bitmap.
446
447 If you use x_create_bitmap_from_data, then you must keep track of
448 the bitmaps yourself. That is, creating a bitmap from the same
449 data more than once will not be caught. */
450
451
452 /* Functions to access the contents of a bitmap, given an id. */
453
454 int
455 x_bitmap_height (f, id)
456 FRAME_PTR f;
457 int id;
458 {
459 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
460 }
461
462 int
463 x_bitmap_width (f, id)
464 FRAME_PTR f;
465 int id;
466 {
467 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
468 }
469
470 int
471 x_bitmap_pixmap (f, id)
472 FRAME_PTR f;
473 int id;
474 {
475 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
476 }
477
478
479 /* Allocate a new bitmap record. Returns index of new record. */
480
481 static int
482 x_allocate_bitmap_record (f)
483 FRAME_PTR f;
484 {
485 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
486 int i;
487
488 if (dpyinfo->bitmaps == NULL)
489 {
490 dpyinfo->bitmaps_size = 10;
491 dpyinfo->bitmaps
492 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
493 dpyinfo->bitmaps_last = 1;
494 return 1;
495 }
496
497 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
498 return ++dpyinfo->bitmaps_last;
499
500 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
501 if (dpyinfo->bitmaps[i].refcount == 0)
502 return i + 1;
503
504 dpyinfo->bitmaps_size *= 2;
505 dpyinfo->bitmaps
506 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
507 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
508 return ++dpyinfo->bitmaps_last;
509 }
510
511 /* Add one reference to the reference count of the bitmap with id ID. */
512
513 void
514 x_reference_bitmap (f, id)
515 FRAME_PTR f;
516 int id;
517 {
518 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
519 }
520
521 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
522
523 int
524 x_create_bitmap_from_data (f, bits, width, height)
525 struct frame *f;
526 char *bits;
527 unsigned int width, height;
528 {
529 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
530 Pixmap bitmap;
531 int id;
532
533 bitmap = CreateBitmap (width, height,
534 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
535 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
536 bits);
537
538 if (! bitmap)
539 return -1;
540
541 id = x_allocate_bitmap_record (f);
542 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
543 dpyinfo->bitmaps[id - 1].file = NULL;
544 dpyinfo->bitmaps[id - 1].hinst = NULL;
545 dpyinfo->bitmaps[id - 1].refcount = 1;
546 dpyinfo->bitmaps[id - 1].depth = 1;
547 dpyinfo->bitmaps[id - 1].height = height;
548 dpyinfo->bitmaps[id - 1].width = width;
549
550 return id;
551 }
552
553 /* Create bitmap from file FILE for frame F. */
554
555 int
556 x_create_bitmap_from_file (f, file)
557 struct frame *f;
558 Lisp_Object file;
559 {
560 return -1;
561 #if 0 /* TODO : bitmap support */
562 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
563 unsigned int width, height;
564 HBITMAP bitmap;
565 int xhot, yhot, result, id;
566 Lisp_Object found;
567 int fd;
568 char *filename;
569 HINSTANCE hinst;
570
571 /* Look for an existing bitmap with the same name. */
572 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
573 {
574 if (dpyinfo->bitmaps[id].refcount
575 && dpyinfo->bitmaps[id].file
576 && !strcmp (dpyinfo->bitmaps[id].file, (char *) XSTRING (file)->data))
577 {
578 ++dpyinfo->bitmaps[id].refcount;
579 return id + 1;
580 }
581 }
582
583 /* Search bitmap-file-path for the file, if appropriate. */
584 fd = openp (Vx_bitmap_file_path, file, "", &found, 0);
585 if (fd < 0)
586 return -1;
587 emacs_close (fd);
588
589 filename = (char *) XSTRING (found)->data;
590
591 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
592
593 if (hinst == NULL)
594 return -1;
595
596
597 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
598 filename, &width, &height, &bitmap, &xhot, &yhot);
599 if (result != BitmapSuccess)
600 return -1;
601
602 id = x_allocate_bitmap_record (f);
603 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
604 dpyinfo->bitmaps[id - 1].refcount = 1;
605 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (XSTRING (file)->size + 1);
606 dpyinfo->bitmaps[id - 1].depth = 1;
607 dpyinfo->bitmaps[id - 1].height = height;
608 dpyinfo->bitmaps[id - 1].width = width;
609 strcpy (dpyinfo->bitmaps[id - 1].file, XSTRING (file)->data);
610
611 return id;
612 #endif /* TODO */
613 }
614
615 /* Remove reference to bitmap with id number ID. */
616
617 void
618 x_destroy_bitmap (f, id)
619 FRAME_PTR f;
620 int id;
621 {
622 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
623
624 if (id > 0)
625 {
626 --dpyinfo->bitmaps[id - 1].refcount;
627 if (dpyinfo->bitmaps[id - 1].refcount == 0)
628 {
629 BLOCK_INPUT;
630 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
631 if (dpyinfo->bitmaps[id - 1].file)
632 {
633 xfree (dpyinfo->bitmaps[id - 1].file);
634 dpyinfo->bitmaps[id - 1].file = NULL;
635 }
636 UNBLOCK_INPUT;
637 }
638 }
639 }
640
641 /* Free all the bitmaps for the display specified by DPYINFO. */
642
643 static void
644 x_destroy_all_bitmaps (dpyinfo)
645 struct w32_display_info *dpyinfo;
646 {
647 int i;
648 for (i = 0; i < dpyinfo->bitmaps_last; i++)
649 if (dpyinfo->bitmaps[i].refcount > 0)
650 {
651 DeleteObject (dpyinfo->bitmaps[i].pixmap);
652 if (dpyinfo->bitmaps[i].file)
653 xfree (dpyinfo->bitmaps[i].file);
654 }
655 dpyinfo->bitmaps_last = 0;
656 }
657 \f
658 /* Connect the frame-parameter names for W32 frames
659 to the ways of passing the parameter values to the window system.
660
661 The name of a parameter, as a Lisp symbol,
662 has an `x-frame-parameter' property which is an integer in Lisp
663 but can be interpreted as an `enum x_frame_parm' in C. */
664
665 enum x_frame_parm
666 {
667 X_PARM_FOREGROUND_COLOR,
668 X_PARM_BACKGROUND_COLOR,
669 X_PARM_MOUSE_COLOR,
670 X_PARM_CURSOR_COLOR,
671 X_PARM_BORDER_COLOR,
672 X_PARM_ICON_TYPE,
673 X_PARM_FONT,
674 X_PARM_BORDER_WIDTH,
675 X_PARM_INTERNAL_BORDER_WIDTH,
676 X_PARM_NAME,
677 X_PARM_AUTORAISE,
678 X_PARM_AUTOLOWER,
679 X_PARM_VERT_SCROLL_BAR,
680 X_PARM_VISIBILITY,
681 X_PARM_MENU_BAR_LINES
682 };
683
684
685 struct x_frame_parm_table
686 {
687 char *name;
688 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
689 };
690
691 /* TODO: Native Input Method support; see x_create_im. */
692 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
693 static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
694 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
695 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
696 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
697 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
698 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
699 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
700 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
701 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
702 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
703 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
704 Lisp_Object));
705 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
706 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
707 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
708 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
709 Lisp_Object));
710 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
711 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
712 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
713 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
714 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
715 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
716 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
717
718 static struct x_frame_parm_table x_frame_parms[] =
719 {
720 "auto-raise", x_set_autoraise,
721 "auto-lower", x_set_autolower,
722 "background-color", x_set_background_color,
723 "border-color", x_set_border_color,
724 "border-width", x_set_border_width,
725 "cursor-color", x_set_cursor_color,
726 "cursor-type", x_set_cursor_type,
727 "font", x_set_font,
728 "foreground-color", x_set_foreground_color,
729 "icon-name", x_set_icon_name,
730 "icon-type", x_set_icon_type,
731 "internal-border-width", x_set_internal_border_width,
732 "menu-bar-lines", x_set_menu_bar_lines,
733 "mouse-color", x_set_mouse_color,
734 "name", x_explicitly_set_name,
735 "scroll-bar-width", x_set_scroll_bar_width,
736 "title", x_set_title,
737 "unsplittable", x_set_unsplittable,
738 "vertical-scroll-bars", x_set_vertical_scroll_bars,
739 "visibility", x_set_visibility,
740 "tool-bar-lines", x_set_tool_bar_lines,
741 "screen-gamma", x_set_screen_gamma,
742 "line-spacing", x_set_line_spacing
743 };
744
745 /* Attach the `x-frame-parameter' properties to
746 the Lisp symbol names of parameters relevant to W32. */
747
748 void
749 init_x_parm_symbols ()
750 {
751 int i;
752
753 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
754 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
755 make_number (i));
756 }
757 \f
758 /* Change the parameters of frame F as specified by ALIST.
759 If a parameter is not specially recognized, do nothing;
760 otherwise call the `x_set_...' function for that parameter. */
761
762 void
763 x_set_frame_parameters (f, alist)
764 FRAME_PTR f;
765 Lisp_Object alist;
766 {
767 Lisp_Object tail;
768
769 /* If both of these parameters are present, it's more efficient to
770 set them both at once. So we wait until we've looked at the
771 entire list before we set them. */
772 int width, height;
773
774 /* Same here. */
775 Lisp_Object left, top;
776
777 /* Same with these. */
778 Lisp_Object icon_left, icon_top;
779
780 /* Record in these vectors all the parms specified. */
781 Lisp_Object *parms;
782 Lisp_Object *values;
783 int i, p;
784 int left_no_change = 0, top_no_change = 0;
785 int icon_left_no_change = 0, icon_top_no_change = 0;
786
787 struct gcpro gcpro1, gcpro2;
788
789 i = 0;
790 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
791 i++;
792
793 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
794 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
795
796 /* Extract parm names and values into those vectors. */
797
798 i = 0;
799 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
800 {
801 Lisp_Object elt;
802
803 elt = Fcar (tail);
804 parms[i] = Fcar (elt);
805 values[i] = Fcdr (elt);
806 i++;
807 }
808 /* TAIL and ALIST are not used again below here. */
809 alist = tail = Qnil;
810
811 GCPRO2 (*parms, *values);
812 gcpro1.nvars = i;
813 gcpro2.nvars = i;
814
815 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
816 because their values appear in VALUES and strings are not valid. */
817 top = left = Qunbound;
818 icon_left = icon_top = Qunbound;
819
820 /* Provide default values for HEIGHT and WIDTH. */
821 if (FRAME_NEW_WIDTH (f))
822 width = FRAME_NEW_WIDTH (f);
823 else
824 width = FRAME_WIDTH (f);
825
826 if (FRAME_NEW_HEIGHT (f))
827 height = FRAME_NEW_HEIGHT (f);
828 else
829 height = FRAME_HEIGHT (f);
830
831 /* Process foreground_color and background_color before anything else.
832 They are independent of other properties, but other properties (e.g.,
833 cursor_color) are dependent upon them. */
834 for (p = 0; p < i; p++)
835 {
836 Lisp_Object prop, val;
837
838 prop = parms[p];
839 val = values[p];
840 if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
841 {
842 register Lisp_Object param_index, old_value;
843
844 param_index = Fget (prop, Qx_frame_parameter);
845 old_value = get_frame_param (f, prop);
846 store_frame_param (f, prop, val);
847 if (NATNUMP (param_index)
848 && (XFASTINT (param_index)
849 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
850 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
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) || EQ (prop, Qbackground_color))
875 /* Processed above. */
876 continue;
877 else
878 {
879 register Lisp_Object param_index, old_value;
880
881 param_index = Fget (prop, Qx_frame_parameter);
882 old_value = get_frame_param (f, prop);
883 store_frame_param (f, prop, val);
884 if (NATNUMP (param_index)
885 && (XFASTINT (param_index)
886 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
887 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
888 }
889 }
890
891 /* Don't die if just one of these was set. */
892 if (EQ (left, Qunbound))
893 {
894 left_no_change = 1;
895 if (f->output_data.w32->left_pos < 0)
896 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
897 else
898 XSETINT (left, f->output_data.w32->left_pos);
899 }
900 if (EQ (top, Qunbound))
901 {
902 top_no_change = 1;
903 if (f->output_data.w32->top_pos < 0)
904 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
905 else
906 XSETINT (top, f->output_data.w32->top_pos);
907 }
908
909 /* If one of the icon positions was not set, preserve or default it. */
910 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
911 {
912 icon_left_no_change = 1;
913 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
914 if (NILP (icon_left))
915 XSETINT (icon_left, 0);
916 }
917 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
918 {
919 icon_top_no_change = 1;
920 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
921 if (NILP (icon_top))
922 XSETINT (icon_top, 0);
923 }
924
925 /* Don't set these parameters unless they've been explicitly
926 specified. The window might be mapped or resized while we're in
927 this function, and we don't want to override that unless the lisp
928 code has asked for it.
929
930 Don't set these parameters unless they actually differ from the
931 window's current parameters; the window may not actually exist
932 yet. */
933 {
934 Lisp_Object frame;
935
936 check_frame_size (f, &height, &width);
937
938 XSETFRAME (frame, f);
939
940 if (width != FRAME_WIDTH (f)
941 || height != FRAME_HEIGHT (f)
942 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
943 Fset_frame_size (frame, make_number (width), make_number (height));
944
945 if ((!NILP (left) || !NILP (top))
946 && ! (left_no_change && top_no_change)
947 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
948 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
949 {
950 int leftpos = 0;
951 int toppos = 0;
952
953 /* Record the signs. */
954 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
955 if (EQ (left, Qminus))
956 f->output_data.w32->size_hint_flags |= XNegative;
957 else if (INTEGERP (left))
958 {
959 leftpos = XINT (left);
960 if (leftpos < 0)
961 f->output_data.w32->size_hint_flags |= XNegative;
962 }
963 else if (CONSP (left) && EQ (XCAR (left), Qminus)
964 && CONSP (XCDR (left))
965 && INTEGERP (XCAR (XCDR (left))))
966 {
967 leftpos = - XINT (XCAR (XCDR (left)));
968 f->output_data.w32->size_hint_flags |= XNegative;
969 }
970 else if (CONSP (left) && EQ (XCAR (left), Qplus)
971 && CONSP (XCDR (left))
972 && INTEGERP (XCAR (XCDR (left))))
973 {
974 leftpos = XINT (XCAR (XCDR (left)));
975 }
976
977 if (EQ (top, Qminus))
978 f->output_data.w32->size_hint_flags |= YNegative;
979 else if (INTEGERP (top))
980 {
981 toppos = XINT (top);
982 if (toppos < 0)
983 f->output_data.w32->size_hint_flags |= YNegative;
984 }
985 else if (CONSP (top) && EQ (XCAR (top), Qminus)
986 && CONSP (XCDR (top))
987 && INTEGERP (XCAR (XCDR (top))))
988 {
989 toppos = - XINT (XCAR (XCDR (top)));
990 f->output_data.w32->size_hint_flags |= YNegative;
991 }
992 else if (CONSP (top) && EQ (XCAR (top), Qplus)
993 && CONSP (XCDR (top))
994 && INTEGERP (XCAR (XCDR (top))))
995 {
996 toppos = XINT (XCAR (XCDR (top)));
997 }
998
999
1000 /* Store the numeric value of the position. */
1001 f->output_data.w32->top_pos = toppos;
1002 f->output_data.w32->left_pos = leftpos;
1003
1004 f->output_data.w32->win_gravity = NorthWestGravity;
1005
1006 /* Actually set that position, and convert to absolute. */
1007 x_set_offset (f, leftpos, toppos, -1);
1008 }
1009
1010 if ((!NILP (icon_left) || !NILP (icon_top))
1011 && ! (icon_left_no_change && icon_top_no_change))
1012 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1013 }
1014
1015 UNGCPRO;
1016 }
1017
1018 /* Store the screen positions of frame F into XPTR and YPTR.
1019 These are the positions of the containing window manager window,
1020 not Emacs's own window. */
1021
1022 void
1023 x_real_positions (f, xptr, yptr)
1024 FRAME_PTR f;
1025 int *xptr, *yptr;
1026 {
1027 POINT pt;
1028
1029 {
1030 RECT rect;
1031
1032 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1033 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1034
1035 pt.x = rect.left;
1036 pt.y = rect.top;
1037 }
1038
1039 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1040
1041 *xptr = pt.x;
1042 *yptr = pt.y;
1043 }
1044
1045 /* Insert a description of internally-recorded parameters of frame X
1046 into the parameter alist *ALISTPTR that is to be given to the user.
1047 Only parameters that are specific to W32
1048 and whose values are not correctly recorded in the frame's
1049 param_alist need to be considered here. */
1050
1051 void
1052 x_report_frame_params (f, alistptr)
1053 struct frame *f;
1054 Lisp_Object *alistptr;
1055 {
1056 char buf[16];
1057 Lisp_Object tem;
1058
1059 /* Represent negative positions (off the top or left screen edge)
1060 in a way that Fmodify_frame_parameters will understand correctly. */
1061 XSETINT (tem, f->output_data.w32->left_pos);
1062 if (f->output_data.w32->left_pos >= 0)
1063 store_in_alist (alistptr, Qleft, tem);
1064 else
1065 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1066
1067 XSETINT (tem, f->output_data.w32->top_pos);
1068 if (f->output_data.w32->top_pos >= 0)
1069 store_in_alist (alistptr, Qtop, tem);
1070 else
1071 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1072
1073 store_in_alist (alistptr, Qborder_width,
1074 make_number (f->output_data.w32->border_width));
1075 store_in_alist (alistptr, Qinternal_border_width,
1076 make_number (f->output_data.w32->internal_border_width));
1077 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1078 store_in_alist (alistptr, Qwindow_id,
1079 build_string (buf));
1080 store_in_alist (alistptr, Qicon_name, f->icon_name);
1081 FRAME_SAMPLE_VISIBILITY (f);
1082 store_in_alist (alistptr, Qvisibility,
1083 (FRAME_VISIBLE_P (f) ? Qt
1084 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1085 store_in_alist (alistptr, Qdisplay,
1086 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1087 }
1088 \f
1089
1090 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color, Sw32_define_rgb_color, 4, 4, 0,
1091 "Convert RGB numbers to a windows color reference and associate with NAME (a string).\n\
1092 This adds or updates a named color to w32-color-map, making it available for use.\n\
1093 The original entry's RGB ref is returned, or nil if the entry is new.")
1094 (red, green, blue, name)
1095 Lisp_Object red, green, blue, name;
1096 {
1097 Lisp_Object rgb;
1098 Lisp_Object oldrgb = Qnil;
1099 Lisp_Object entry;
1100
1101 CHECK_NUMBER (red, 0);
1102 CHECK_NUMBER (green, 0);
1103 CHECK_NUMBER (blue, 0);
1104 CHECK_STRING (name, 0);
1105
1106 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1107
1108 BLOCK_INPUT;
1109
1110 /* replace existing entry in w32-color-map or add new entry. */
1111 entry = Fassoc (name, Vw32_color_map);
1112 if (NILP (entry))
1113 {
1114 entry = Fcons (name, rgb);
1115 Vw32_color_map = Fcons (entry, Vw32_color_map);
1116 }
1117 else
1118 {
1119 oldrgb = Fcdr (entry);
1120 Fsetcdr (entry, rgb);
1121 }
1122
1123 UNBLOCK_INPUT;
1124
1125 return (oldrgb);
1126 }
1127
1128 DEFUN ("w32-load-color-file", Fw32_load_color_file, Sw32_load_color_file, 1, 1, 0,
1129 "Create an alist of color entries from an external file (ie. rgb.txt).\n\
1130 Assign this value to w32-color-map to replace the existing color map.\n\
1131 \
1132 The file should define one named RGB color per line like so:\
1133 R G B name\n\
1134 where R,G,B are numbers between 0 and 255 and name is an arbitrary string.")
1135 (filename)
1136 Lisp_Object filename;
1137 {
1138 FILE *fp;
1139 Lisp_Object cmap = Qnil;
1140 Lisp_Object abspath;
1141
1142 CHECK_STRING (filename, 0);
1143 abspath = Fexpand_file_name (filename, Qnil);
1144
1145 fp = fopen (XSTRING (filename)->data, "rt");
1146 if (fp)
1147 {
1148 char buf[512];
1149 int red, green, blue;
1150 int num;
1151
1152 BLOCK_INPUT;
1153
1154 while (fgets (buf, sizeof (buf), fp) != NULL) {
1155 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1156 {
1157 char *name = buf + num;
1158 num = strlen (name) - 1;
1159 if (name[num] == '\n')
1160 name[num] = 0;
1161 cmap = Fcons (Fcons (build_string (name),
1162 make_number (RGB (red, green, blue))),
1163 cmap);
1164 }
1165 }
1166 fclose (fp);
1167
1168 UNBLOCK_INPUT;
1169 }
1170
1171 return cmap;
1172 }
1173
1174 /* The default colors for the w32 color map */
1175 typedef struct colormap_t
1176 {
1177 char *name;
1178 COLORREF colorref;
1179 } colormap_t;
1180
1181 colormap_t w32_color_map[] =
1182 {
1183 {"snow" , PALETTERGB (255,250,250)},
1184 {"ghost white" , PALETTERGB (248,248,255)},
1185 {"GhostWhite" , PALETTERGB (248,248,255)},
1186 {"white smoke" , PALETTERGB (245,245,245)},
1187 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1188 {"gainsboro" , PALETTERGB (220,220,220)},
1189 {"floral white" , PALETTERGB (255,250,240)},
1190 {"FloralWhite" , PALETTERGB (255,250,240)},
1191 {"old lace" , PALETTERGB (253,245,230)},
1192 {"OldLace" , PALETTERGB (253,245,230)},
1193 {"linen" , PALETTERGB (250,240,230)},
1194 {"antique white" , PALETTERGB (250,235,215)},
1195 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1196 {"papaya whip" , PALETTERGB (255,239,213)},
1197 {"PapayaWhip" , PALETTERGB (255,239,213)},
1198 {"blanched almond" , PALETTERGB (255,235,205)},
1199 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1200 {"bisque" , PALETTERGB (255,228,196)},
1201 {"peach puff" , PALETTERGB (255,218,185)},
1202 {"PeachPuff" , PALETTERGB (255,218,185)},
1203 {"navajo white" , PALETTERGB (255,222,173)},
1204 {"NavajoWhite" , PALETTERGB (255,222,173)},
1205 {"moccasin" , PALETTERGB (255,228,181)},
1206 {"cornsilk" , PALETTERGB (255,248,220)},
1207 {"ivory" , PALETTERGB (255,255,240)},
1208 {"lemon chiffon" , PALETTERGB (255,250,205)},
1209 {"LemonChiffon" , PALETTERGB (255,250,205)},
1210 {"seashell" , PALETTERGB (255,245,238)},
1211 {"honeydew" , PALETTERGB (240,255,240)},
1212 {"mint cream" , PALETTERGB (245,255,250)},
1213 {"MintCream" , PALETTERGB (245,255,250)},
1214 {"azure" , PALETTERGB (240,255,255)},
1215 {"alice blue" , PALETTERGB (240,248,255)},
1216 {"AliceBlue" , PALETTERGB (240,248,255)},
1217 {"lavender" , PALETTERGB (230,230,250)},
1218 {"lavender blush" , PALETTERGB (255,240,245)},
1219 {"LavenderBlush" , PALETTERGB (255,240,245)},
1220 {"misty rose" , PALETTERGB (255,228,225)},
1221 {"MistyRose" , PALETTERGB (255,228,225)},
1222 {"white" , PALETTERGB (255,255,255)},
1223 {"black" , PALETTERGB ( 0, 0, 0)},
1224 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1225 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1226 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1227 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1228 {"dim gray" , PALETTERGB (105,105,105)},
1229 {"DimGray" , PALETTERGB (105,105,105)},
1230 {"dim grey" , PALETTERGB (105,105,105)},
1231 {"DimGrey" , PALETTERGB (105,105,105)},
1232 {"slate gray" , PALETTERGB (112,128,144)},
1233 {"SlateGray" , PALETTERGB (112,128,144)},
1234 {"slate grey" , PALETTERGB (112,128,144)},
1235 {"SlateGrey" , PALETTERGB (112,128,144)},
1236 {"light slate gray" , PALETTERGB (119,136,153)},
1237 {"LightSlateGray" , PALETTERGB (119,136,153)},
1238 {"light slate grey" , PALETTERGB (119,136,153)},
1239 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1240 {"gray" , PALETTERGB (190,190,190)},
1241 {"grey" , PALETTERGB (190,190,190)},
1242 {"light grey" , PALETTERGB (211,211,211)},
1243 {"LightGrey" , PALETTERGB (211,211,211)},
1244 {"light gray" , PALETTERGB (211,211,211)},
1245 {"LightGray" , PALETTERGB (211,211,211)},
1246 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1247 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1248 {"navy" , PALETTERGB ( 0, 0,128)},
1249 {"navy blue" , PALETTERGB ( 0, 0,128)},
1250 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1251 {"cornflower blue" , PALETTERGB (100,149,237)},
1252 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1253 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1254 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1255 {"slate blue" , PALETTERGB (106, 90,205)},
1256 {"SlateBlue" , PALETTERGB (106, 90,205)},
1257 {"medium slate blue" , PALETTERGB (123,104,238)},
1258 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1259 {"light slate blue" , PALETTERGB (132,112,255)},
1260 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1261 {"medium blue" , PALETTERGB ( 0, 0,205)},
1262 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1263 {"royal blue" , PALETTERGB ( 65,105,225)},
1264 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1265 {"blue" , PALETTERGB ( 0, 0,255)},
1266 {"dodger blue" , PALETTERGB ( 30,144,255)},
1267 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1268 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1269 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1270 {"sky blue" , PALETTERGB (135,206,235)},
1271 {"SkyBlue" , PALETTERGB (135,206,235)},
1272 {"light sky blue" , PALETTERGB (135,206,250)},
1273 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1274 {"steel blue" , PALETTERGB ( 70,130,180)},
1275 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1276 {"light steel blue" , PALETTERGB (176,196,222)},
1277 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1278 {"light blue" , PALETTERGB (173,216,230)},
1279 {"LightBlue" , PALETTERGB (173,216,230)},
1280 {"powder blue" , PALETTERGB (176,224,230)},
1281 {"PowderBlue" , PALETTERGB (176,224,230)},
1282 {"pale turquoise" , PALETTERGB (175,238,238)},
1283 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1284 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1285 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1286 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1287 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1288 {"turquoise" , PALETTERGB ( 64,224,208)},
1289 {"cyan" , PALETTERGB ( 0,255,255)},
1290 {"light cyan" , PALETTERGB (224,255,255)},
1291 {"LightCyan" , PALETTERGB (224,255,255)},
1292 {"cadet blue" , PALETTERGB ( 95,158,160)},
1293 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1294 {"medium aquamarine" , PALETTERGB (102,205,170)},
1295 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1296 {"aquamarine" , PALETTERGB (127,255,212)},
1297 {"dark green" , PALETTERGB ( 0,100, 0)},
1298 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1299 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1300 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1301 {"dark sea green" , PALETTERGB (143,188,143)},
1302 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1303 {"sea green" , PALETTERGB ( 46,139, 87)},
1304 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1305 {"medium sea green" , PALETTERGB ( 60,179,113)},
1306 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1307 {"light sea green" , PALETTERGB ( 32,178,170)},
1308 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1309 {"pale green" , PALETTERGB (152,251,152)},
1310 {"PaleGreen" , PALETTERGB (152,251,152)},
1311 {"spring green" , PALETTERGB ( 0,255,127)},
1312 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1313 {"lawn green" , PALETTERGB (124,252, 0)},
1314 {"LawnGreen" , PALETTERGB (124,252, 0)},
1315 {"green" , PALETTERGB ( 0,255, 0)},
1316 {"chartreuse" , PALETTERGB (127,255, 0)},
1317 {"medium spring green" , PALETTERGB ( 0,250,154)},
1318 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1319 {"green yellow" , PALETTERGB (173,255, 47)},
1320 {"GreenYellow" , PALETTERGB (173,255, 47)},
1321 {"lime green" , PALETTERGB ( 50,205, 50)},
1322 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1323 {"yellow green" , PALETTERGB (154,205, 50)},
1324 {"YellowGreen" , PALETTERGB (154,205, 50)},
1325 {"forest green" , PALETTERGB ( 34,139, 34)},
1326 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1327 {"olive drab" , PALETTERGB (107,142, 35)},
1328 {"OliveDrab" , PALETTERGB (107,142, 35)},
1329 {"dark khaki" , PALETTERGB (189,183,107)},
1330 {"DarkKhaki" , PALETTERGB (189,183,107)},
1331 {"khaki" , PALETTERGB (240,230,140)},
1332 {"pale goldenrod" , PALETTERGB (238,232,170)},
1333 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1334 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1335 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1336 {"light yellow" , PALETTERGB (255,255,224)},
1337 {"LightYellow" , PALETTERGB (255,255,224)},
1338 {"yellow" , PALETTERGB (255,255, 0)},
1339 {"gold" , PALETTERGB (255,215, 0)},
1340 {"light goldenrod" , PALETTERGB (238,221,130)},
1341 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1342 {"goldenrod" , PALETTERGB (218,165, 32)},
1343 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1344 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1345 {"rosy brown" , PALETTERGB (188,143,143)},
1346 {"RosyBrown" , PALETTERGB (188,143,143)},
1347 {"indian red" , PALETTERGB (205, 92, 92)},
1348 {"IndianRed" , PALETTERGB (205, 92, 92)},
1349 {"saddle brown" , PALETTERGB (139, 69, 19)},
1350 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1351 {"sienna" , PALETTERGB (160, 82, 45)},
1352 {"peru" , PALETTERGB (205,133, 63)},
1353 {"burlywood" , PALETTERGB (222,184,135)},
1354 {"beige" , PALETTERGB (245,245,220)},
1355 {"wheat" , PALETTERGB (245,222,179)},
1356 {"sandy brown" , PALETTERGB (244,164, 96)},
1357 {"SandyBrown" , PALETTERGB (244,164, 96)},
1358 {"tan" , PALETTERGB (210,180,140)},
1359 {"chocolate" , PALETTERGB (210,105, 30)},
1360 {"firebrick" , PALETTERGB (178,34, 34)},
1361 {"brown" , PALETTERGB (165,42, 42)},
1362 {"dark salmon" , PALETTERGB (233,150,122)},
1363 {"DarkSalmon" , PALETTERGB (233,150,122)},
1364 {"salmon" , PALETTERGB (250,128,114)},
1365 {"light salmon" , PALETTERGB (255,160,122)},
1366 {"LightSalmon" , PALETTERGB (255,160,122)},
1367 {"orange" , PALETTERGB (255,165, 0)},
1368 {"dark orange" , PALETTERGB (255,140, 0)},
1369 {"DarkOrange" , PALETTERGB (255,140, 0)},
1370 {"coral" , PALETTERGB (255,127, 80)},
1371 {"light coral" , PALETTERGB (240,128,128)},
1372 {"LightCoral" , PALETTERGB (240,128,128)},
1373 {"tomato" , PALETTERGB (255, 99, 71)},
1374 {"orange red" , PALETTERGB (255, 69, 0)},
1375 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1376 {"red" , PALETTERGB (255, 0, 0)},
1377 {"hot pink" , PALETTERGB (255,105,180)},
1378 {"HotPink" , PALETTERGB (255,105,180)},
1379 {"deep pink" , PALETTERGB (255, 20,147)},
1380 {"DeepPink" , PALETTERGB (255, 20,147)},
1381 {"pink" , PALETTERGB (255,192,203)},
1382 {"light pink" , PALETTERGB (255,182,193)},
1383 {"LightPink" , PALETTERGB (255,182,193)},
1384 {"pale violet red" , PALETTERGB (219,112,147)},
1385 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1386 {"maroon" , PALETTERGB (176, 48, 96)},
1387 {"medium violet red" , PALETTERGB (199, 21,133)},
1388 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1389 {"violet red" , PALETTERGB (208, 32,144)},
1390 {"VioletRed" , PALETTERGB (208, 32,144)},
1391 {"magenta" , PALETTERGB (255, 0,255)},
1392 {"violet" , PALETTERGB (238,130,238)},
1393 {"plum" , PALETTERGB (221,160,221)},
1394 {"orchid" , PALETTERGB (218,112,214)},
1395 {"medium orchid" , PALETTERGB (186, 85,211)},
1396 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1397 {"dark orchid" , PALETTERGB (153, 50,204)},
1398 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1399 {"dark violet" , PALETTERGB (148, 0,211)},
1400 {"DarkViolet" , PALETTERGB (148, 0,211)},
1401 {"blue violet" , PALETTERGB (138, 43,226)},
1402 {"BlueViolet" , PALETTERGB (138, 43,226)},
1403 {"purple" , PALETTERGB (160, 32,240)},
1404 {"medium purple" , PALETTERGB (147,112,219)},
1405 {"MediumPurple" , PALETTERGB (147,112,219)},
1406 {"thistle" , PALETTERGB (216,191,216)},
1407 {"gray0" , PALETTERGB ( 0, 0, 0)},
1408 {"grey0" , PALETTERGB ( 0, 0, 0)},
1409 {"dark grey" , PALETTERGB (169,169,169)},
1410 {"DarkGrey" , PALETTERGB (169,169,169)},
1411 {"dark gray" , PALETTERGB (169,169,169)},
1412 {"DarkGray" , PALETTERGB (169,169,169)},
1413 {"dark blue" , PALETTERGB ( 0, 0,139)},
1414 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1415 {"dark cyan" , PALETTERGB ( 0,139,139)},
1416 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1417 {"dark magenta" , PALETTERGB (139, 0,139)},
1418 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1419 {"dark red" , PALETTERGB (139, 0, 0)},
1420 {"DarkRed" , PALETTERGB (139, 0, 0)},
1421 {"light green" , PALETTERGB (144,238,144)},
1422 {"LightGreen" , PALETTERGB (144,238,144)},
1423 };
1424
1425 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1426 0, 0, 0, "Return the default color map.")
1427 ()
1428 {
1429 int i;
1430 colormap_t *pc = w32_color_map;
1431 Lisp_Object cmap;
1432
1433 BLOCK_INPUT;
1434
1435 cmap = Qnil;
1436
1437 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1438 pc++, i++)
1439 cmap = Fcons (Fcons (build_string (pc->name),
1440 make_number (pc->colorref)),
1441 cmap);
1442
1443 UNBLOCK_INPUT;
1444
1445 return (cmap);
1446 }
1447
1448 Lisp_Object
1449 w32_to_x_color (rgb)
1450 Lisp_Object rgb;
1451 {
1452 Lisp_Object color;
1453
1454 CHECK_NUMBER (rgb, 0);
1455
1456 BLOCK_INPUT;
1457
1458 color = Frassq (rgb, Vw32_color_map);
1459
1460 UNBLOCK_INPUT;
1461
1462 if (!NILP (color))
1463 return (Fcar (color));
1464 else
1465 return Qnil;
1466 }
1467
1468 COLORREF
1469 w32_color_map_lookup (colorname)
1470 char *colorname;
1471 {
1472 Lisp_Object tail, ret = Qnil;
1473
1474 BLOCK_INPUT;
1475
1476 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1477 {
1478 register Lisp_Object elt, tem;
1479
1480 elt = Fcar (tail);
1481 if (!CONSP (elt)) continue;
1482
1483 tem = Fcar (elt);
1484
1485 if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
1486 {
1487 ret = XUINT (Fcdr (elt));
1488 break;
1489 }
1490
1491 QUIT;
1492 }
1493
1494
1495 UNBLOCK_INPUT;
1496
1497 return ret;
1498 }
1499
1500 COLORREF
1501 x_to_w32_color (colorname)
1502 char * colorname;
1503 {
1504 register Lisp_Object tail, ret = Qnil;
1505
1506 BLOCK_INPUT;
1507
1508 if (colorname[0] == '#')
1509 {
1510 /* Could be an old-style RGB Device specification. */
1511 char *color;
1512 int size;
1513 color = colorname + 1;
1514
1515 size = strlen(color);
1516 if (size == 3 || size == 6 || size == 9 || size == 12)
1517 {
1518 UINT colorval;
1519 int i, pos;
1520 pos = 0;
1521 size /= 3;
1522 colorval = 0;
1523
1524 for (i = 0; i < 3; i++)
1525 {
1526 char *end;
1527 char t;
1528 unsigned long value;
1529
1530 /* The check for 'x' in the following conditional takes into
1531 account the fact that strtol allows a "0x" in front of
1532 our numbers, and we don't. */
1533 if (!isxdigit(color[0]) || color[1] == 'x')
1534 break;
1535 t = color[size];
1536 color[size] = '\0';
1537 value = strtoul(color, &end, 16);
1538 color[size] = t;
1539 if (errno == ERANGE || end - color != size)
1540 break;
1541 switch (size)
1542 {
1543 case 1:
1544 value = value * 0x10;
1545 break;
1546 case 2:
1547 break;
1548 case 3:
1549 value /= 0x10;
1550 break;
1551 case 4:
1552 value /= 0x100;
1553 break;
1554 }
1555 colorval |= (value << pos);
1556 pos += 0x8;
1557 if (i == 2)
1558 {
1559 UNBLOCK_INPUT;
1560 return (colorval);
1561 }
1562 color = end;
1563 }
1564 }
1565 }
1566 else if (strnicmp(colorname, "rgb:", 4) == 0)
1567 {
1568 char *color;
1569 UINT colorval;
1570 int i, pos;
1571 pos = 0;
1572
1573 colorval = 0;
1574 color = colorname + 4;
1575 for (i = 0; i < 3; i++)
1576 {
1577 char *end;
1578 unsigned long value;
1579
1580 /* The check for 'x' in the following conditional takes into
1581 account the fact that strtol allows a "0x" in front of
1582 our numbers, and we don't. */
1583 if (!isxdigit(color[0]) || color[1] == 'x')
1584 break;
1585 value = strtoul(color, &end, 16);
1586 if (errno == ERANGE)
1587 break;
1588 switch (end - color)
1589 {
1590 case 1:
1591 value = value * 0x10 + value;
1592 break;
1593 case 2:
1594 break;
1595 case 3:
1596 value /= 0x10;
1597 break;
1598 case 4:
1599 value /= 0x100;
1600 break;
1601 default:
1602 value = ULONG_MAX;
1603 }
1604 if (value == ULONG_MAX)
1605 break;
1606 colorval |= (value << pos);
1607 pos += 0x8;
1608 if (i == 2)
1609 {
1610 if (*end != '\0')
1611 break;
1612 UNBLOCK_INPUT;
1613 return (colorval);
1614 }
1615 if (*end != '/')
1616 break;
1617 color = end + 1;
1618 }
1619 }
1620 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1621 {
1622 /* This is an RGB Intensity specification. */
1623 char *color;
1624 UINT colorval;
1625 int i, pos;
1626 pos = 0;
1627
1628 colorval = 0;
1629 color = colorname + 5;
1630 for (i = 0; i < 3; i++)
1631 {
1632 char *end;
1633 double value;
1634 UINT val;
1635
1636 value = strtod(color, &end);
1637 if (errno == ERANGE)
1638 break;
1639 if (value < 0.0 || value > 1.0)
1640 break;
1641 val = (UINT)(0x100 * value);
1642 /* We used 0x100 instead of 0xFF to give an continuous
1643 range between 0.0 and 1.0 inclusive. The next statement
1644 fixes the 1.0 case. */
1645 if (val == 0x100)
1646 val = 0xFF;
1647 colorval |= (val << pos);
1648 pos += 0x8;
1649 if (i == 2)
1650 {
1651 if (*end != '\0')
1652 break;
1653 UNBLOCK_INPUT;
1654 return (colorval);
1655 }
1656 if (*end != '/')
1657 break;
1658 color = end + 1;
1659 }
1660 }
1661 /* I am not going to attempt to handle any of the CIE color schemes
1662 or TekHVC, since I don't know the algorithms for conversion to
1663 RGB. */
1664
1665 /* If we fail to lookup the color name in w32_color_map, then check the
1666 colorname to see if it can be crudely approximated: If the X color
1667 ends in a number (e.g., "darkseagreen2"), strip the number and
1668 return the result of looking up the base color name. */
1669 ret = w32_color_map_lookup (colorname);
1670 if (NILP (ret))
1671 {
1672 int len = strlen (colorname);
1673
1674 if (isdigit (colorname[len - 1]))
1675 {
1676 char *ptr, *approx = alloca (len);
1677
1678 strcpy (approx, colorname);
1679 ptr = &approx[len - 1];
1680 while (ptr > approx && isdigit (*ptr))
1681 *ptr-- = '\0';
1682
1683 ret = w32_color_map_lookup (approx);
1684 }
1685 }
1686
1687 UNBLOCK_INPUT;
1688 return ret;
1689 }
1690
1691
1692 void
1693 w32_regenerate_palette (FRAME_PTR f)
1694 {
1695 struct w32_palette_entry * list;
1696 LOGPALETTE * log_palette;
1697 HPALETTE new_palette;
1698 int i;
1699
1700 /* don't bother trying to create palette if not supported */
1701 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1702 return;
1703
1704 log_palette = (LOGPALETTE *)
1705 alloca (sizeof (LOGPALETTE) +
1706 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1707 log_palette->palVersion = 0x300;
1708 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1709
1710 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1711 for (i = 0;
1712 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1713 i++, list = list->next)
1714 log_palette->palPalEntry[i] = list->entry;
1715
1716 new_palette = CreatePalette (log_palette);
1717
1718 enter_crit ();
1719
1720 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1721 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1722 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1723
1724 /* Realize display palette and garbage all frames. */
1725 release_frame_dc (f, get_frame_dc (f));
1726
1727 leave_crit ();
1728 }
1729
1730 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1731 #define SET_W32_COLOR(pe, color) \
1732 do \
1733 { \
1734 pe.peRed = GetRValue (color); \
1735 pe.peGreen = GetGValue (color); \
1736 pe.peBlue = GetBValue (color); \
1737 pe.peFlags = 0; \
1738 } while (0)
1739
1740 #if 0
1741 /* Keep these around in case we ever want to track color usage. */
1742 void
1743 w32_map_color (FRAME_PTR f, COLORREF color)
1744 {
1745 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1746
1747 if (NILP (Vw32_enable_palette))
1748 return;
1749
1750 /* check if color is already mapped */
1751 while (list)
1752 {
1753 if (W32_COLOR (list->entry) == color)
1754 {
1755 ++list->refcount;
1756 return;
1757 }
1758 list = list->next;
1759 }
1760
1761 /* not already mapped, so add to list and recreate Windows palette */
1762 list = (struct w32_palette_entry *)
1763 xmalloc (sizeof (struct w32_palette_entry));
1764 SET_W32_COLOR (list->entry, color);
1765 list->refcount = 1;
1766 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1767 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1768 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1769
1770 /* set flag that palette must be regenerated */
1771 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1772 }
1773
1774 void
1775 w32_unmap_color (FRAME_PTR f, COLORREF color)
1776 {
1777 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1778 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1779
1780 if (NILP (Vw32_enable_palette))
1781 return;
1782
1783 /* check if color is already mapped */
1784 while (list)
1785 {
1786 if (W32_COLOR (list->entry) == color)
1787 {
1788 if (--list->refcount == 0)
1789 {
1790 *prev = list->next;
1791 xfree (list);
1792 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1793 break;
1794 }
1795 else
1796 return;
1797 }
1798 prev = &list->next;
1799 list = list->next;
1800 }
1801
1802 /* set flag that palette must be regenerated */
1803 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1804 }
1805 #endif
1806
1807
1808 /* Gamma-correct COLOR on frame F. */
1809
1810 void
1811 gamma_correct (f, color)
1812 struct frame *f;
1813 COLORREF *color;
1814 {
1815 if (f->gamma)
1816 {
1817 *color = PALETTERGB (
1818 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1819 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1820 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1821 }
1822 }
1823
1824
1825 /* Decide if color named COLOR is valid for the display associated with
1826 the selected frame; if so, return the rgb values in COLOR_DEF.
1827 If ALLOC is nonzero, allocate a new colormap cell. */
1828
1829 int
1830 w32_defined_color (f, color, color_def, alloc)
1831 FRAME_PTR f;
1832 char *color;
1833 XColor *color_def;
1834 int alloc;
1835 {
1836 register Lisp_Object tem;
1837 COLORREF w32_color_ref;
1838
1839 tem = x_to_w32_color (color);
1840
1841 if (!NILP (tem))
1842 {
1843 if (f)
1844 {
1845 /* Apply gamma correction. */
1846 w32_color_ref = XUINT (tem);
1847 gamma_correct (f, &w32_color_ref);
1848 XSETINT (tem, w32_color_ref);
1849 }
1850
1851 /* Map this color to the palette if it is enabled. */
1852 if (!NILP (Vw32_enable_palette))
1853 {
1854 struct w32_palette_entry * entry =
1855 one_w32_display_info.color_list;
1856 struct w32_palette_entry ** prev =
1857 &one_w32_display_info.color_list;
1858
1859 /* check if color is already mapped */
1860 while (entry)
1861 {
1862 if (W32_COLOR (entry->entry) == XUINT (tem))
1863 break;
1864 prev = &entry->next;
1865 entry = entry->next;
1866 }
1867
1868 if (entry == NULL && alloc)
1869 {
1870 /* not already mapped, so add to list */
1871 entry = (struct w32_palette_entry *)
1872 xmalloc (sizeof (struct w32_palette_entry));
1873 SET_W32_COLOR (entry->entry, XUINT (tem));
1874 entry->next = NULL;
1875 *prev = entry;
1876 one_w32_display_info.num_colors++;
1877
1878 /* set flag that palette must be regenerated */
1879 one_w32_display_info.regen_palette = TRUE;
1880 }
1881 }
1882 /* Ensure COLORREF value is snapped to nearest color in (default)
1883 palette by simulating the PALETTERGB macro. This works whether
1884 or not the display device has a palette. */
1885 w32_color_ref = XUINT (tem) | 0x2000000;
1886
1887 color_def->pixel = w32_color_ref;
1888 color_def->red = GetRValue (w32_color_ref);
1889 color_def->green = GetGValue (w32_color_ref);
1890 color_def->blue = GetBValue (w32_color_ref);
1891
1892 return 1;
1893 }
1894 else
1895 {
1896 return 0;
1897 }
1898 }
1899
1900 /* Given a string ARG naming a color, compute a pixel value from it
1901 suitable for screen F.
1902 If F is not a color screen, return DEF (default) regardless of what
1903 ARG says. */
1904
1905 int
1906 x_decode_color (f, arg, def)
1907 FRAME_PTR f;
1908 Lisp_Object arg;
1909 int def;
1910 {
1911 XColor cdef;
1912
1913 CHECK_STRING (arg, 0);
1914
1915 if (strcmp (XSTRING (arg)->data, "black") == 0)
1916 return BLACK_PIX_DEFAULT (f);
1917 else if (strcmp (XSTRING (arg)->data, "white") == 0)
1918 return WHITE_PIX_DEFAULT (f);
1919
1920 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1921 return def;
1922
1923 /* w32_defined_color is responsible for coping with failures
1924 by looking for a near-miss. */
1925 if (w32_defined_color (f, XSTRING (arg)->data, &cdef, 1))
1926 return cdef.pixel;
1927
1928 /* defined_color failed; return an ultimate default. */
1929 return def;
1930 }
1931 \f
1932 /* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
1933 the previous value of that parameter, NEW_VALUE is the new value. */
1934
1935 static void
1936 x_set_line_spacing (f, new_value, old_value)
1937 struct frame *f;
1938 Lisp_Object new_value, old_value;
1939 {
1940 if (NILP (new_value))
1941 f->extra_line_spacing = 0;
1942 else if (NATNUMP (new_value))
1943 f->extra_line_spacing = XFASTINT (new_value);
1944 else
1945 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
1946 Fcons (new_value, Qnil)));
1947 if (FRAME_VISIBLE_P (f))
1948 redraw_frame (f);
1949 }
1950
1951
1952 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
1953 the previous value of that parameter, NEW_VALUE is the new value. */
1954
1955 static void
1956 x_set_screen_gamma (f, new_value, old_value)
1957 struct frame *f;
1958 Lisp_Object new_value, old_value;
1959 {
1960 if (NILP (new_value))
1961 f->gamma = 0;
1962 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
1963 /* The value 0.4545 is the normal viewing gamma. */
1964 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
1965 else
1966 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
1967 Fcons (new_value, Qnil)));
1968
1969 clear_face_cache (0);
1970 }
1971
1972
1973 /* Functions called only from `x_set_frame_param'
1974 to set individual parameters.
1975
1976 If FRAME_W32_WINDOW (f) is 0,
1977 the frame is being created and its window does not exist yet.
1978 In that case, just record the parameter's new value
1979 in the standard place; do not attempt to change the window. */
1980
1981 void
1982 x_set_foreground_color (f, arg, oldval)
1983 struct frame *f;
1984 Lisp_Object arg, oldval;
1985 {
1986 FRAME_FOREGROUND_PIXEL (f)
1987 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1988
1989 if (FRAME_W32_WINDOW (f) != 0)
1990 {
1991 update_face_from_frame_parameter (f, Qforeground_color, arg);
1992 if (FRAME_VISIBLE_P (f))
1993 redraw_frame (f);
1994 }
1995 }
1996
1997 void
1998 x_set_background_color (f, arg, oldval)
1999 struct frame *f;
2000 Lisp_Object arg, oldval;
2001 {
2002 FRAME_BACKGROUND_PIXEL (f)
2003 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2004
2005 if (FRAME_W32_WINDOW (f) != 0)
2006 {
2007 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2008 FRAME_BACKGROUND_PIXEL (f));
2009
2010 update_face_from_frame_parameter (f, Qbackground_color, arg);
2011
2012 if (FRAME_VISIBLE_P (f))
2013 redraw_frame (f);
2014 }
2015 }
2016
2017 void
2018 x_set_mouse_color (f, arg, oldval)
2019 struct frame *f;
2020 Lisp_Object arg, oldval;
2021 {
2022 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2023 int count;
2024 int mask_color;
2025
2026 if (!EQ (Qnil, arg))
2027 f->output_data.w32->mouse_pixel
2028 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2029 mask_color = FRAME_BACKGROUND_PIXEL (f);
2030
2031 /* Don't let pointers be invisible. */
2032 if (mask_color == f->output_data.w32->mouse_pixel
2033 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2034 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2035
2036 #if 0 /* TODO : cursor changes */
2037 BLOCK_INPUT;
2038
2039 /* It's not okay to crash if the user selects a screwy cursor. */
2040 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2041
2042 if (!EQ (Qnil, Vx_pointer_shape))
2043 {
2044 CHECK_NUMBER (Vx_pointer_shape, 0);
2045 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2046 }
2047 else
2048 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2049 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2050
2051 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2052 {
2053 CHECK_NUMBER (Vx_nontext_pointer_shape, 0);
2054 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2055 XINT (Vx_nontext_pointer_shape));
2056 }
2057 else
2058 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2059 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2060
2061 if (!EQ (Qnil, Vx_busy_pointer_shape))
2062 {
2063 CHECK_NUMBER (Vx_busy_pointer_shape, 0);
2064 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2065 XINT (Vx_busy_pointer_shape));
2066 }
2067 else
2068 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2069 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2070
2071 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2072 if (!EQ (Qnil, Vx_mode_pointer_shape))
2073 {
2074 CHECK_NUMBER (Vx_mode_pointer_shape, 0);
2075 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2076 XINT (Vx_mode_pointer_shape));
2077 }
2078 else
2079 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2080 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2081
2082 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2083 {
2084 CHECK_NUMBER (Vx_sensitive_text_pointer_shape, 0);
2085 cross_cursor
2086 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2087 XINT (Vx_sensitive_text_pointer_shape));
2088 }
2089 else
2090 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2091
2092 /* Check and report errors with the above calls. */
2093 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2094 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2095
2096 {
2097 XColor fore_color, back_color;
2098
2099 fore_color.pixel = f->output_data.w32->mouse_pixel;
2100 back_color.pixel = mask_color;
2101 XQueryColor (FRAME_W32_DISPLAY (f),
2102 DefaultColormap (FRAME_W32_DISPLAY (f),
2103 DefaultScreen (FRAME_W32_DISPLAY (f))),
2104 &fore_color);
2105 XQueryColor (FRAME_W32_DISPLAY (f),
2106 DefaultColormap (FRAME_W32_DISPLAY (f),
2107 DefaultScreen (FRAME_W32_DISPLAY (f))),
2108 &back_color);
2109 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2110 &fore_color, &back_color);
2111 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2112 &fore_color, &back_color);
2113 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2114 &fore_color, &back_color);
2115 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2116 &fore_color, &back_color);
2117 XRecolorCursor (FRAME_W32_DISPLAY (f), busy_cursor,
2118 &fore_color, &back_color);
2119 }
2120
2121 if (FRAME_W32_WINDOW (f) != 0)
2122 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2123
2124 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2125 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2126 f->output_data.w32->text_cursor = cursor;
2127
2128 if (nontext_cursor != f->output_data.w32->nontext_cursor
2129 && f->output_data.w32->nontext_cursor != 0)
2130 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2131 f->output_data.w32->nontext_cursor = nontext_cursor;
2132
2133 if (busy_cursor != f->output_data.w32->busy_cursor
2134 && f->output_data.w32->busy_cursor != 0)
2135 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->busy_cursor);
2136 f->output_data.w32->busy_cursor = busy_cursor;
2137
2138 if (mode_cursor != f->output_data.w32->modeline_cursor
2139 && f->output_data.w32->modeline_cursor != 0)
2140 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2141 f->output_data.w32->modeline_cursor = mode_cursor;
2142
2143 if (cross_cursor != f->output_data.w32->cross_cursor
2144 && f->output_data.w32->cross_cursor != 0)
2145 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2146 f->output_data.w32->cross_cursor = cross_cursor;
2147
2148 XFlush (FRAME_W32_DISPLAY (f));
2149 UNBLOCK_INPUT;
2150
2151 update_face_from_frame_parameter (f, Qmouse_color, arg);
2152 #endif /* TODO */
2153 }
2154
2155 /* Defined in w32term.c. */
2156 void x_update_cursor (struct frame *f, int on_p);
2157
2158 void
2159 x_set_cursor_color (f, arg, oldval)
2160 struct frame *f;
2161 Lisp_Object arg, oldval;
2162 {
2163 unsigned long fore_pixel, pixel;
2164
2165 if (!NILP (Vx_cursor_fore_pixel))
2166 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2167 WHITE_PIX_DEFAULT (f));
2168 else
2169 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2170
2171 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2172
2173 /* Make sure that the cursor color differs from the background color. */
2174 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2175 {
2176 pixel = f->output_data.w32->mouse_pixel;
2177 if (pixel == fore_pixel)
2178 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2179 }
2180
2181 FRAME_FOREGROUND_PIXEL (f) = fore_pixel;
2182 f->output_data.w32->cursor_pixel = pixel;
2183
2184 if (FRAME_W32_WINDOW (f) != 0)
2185 {
2186 if (FRAME_VISIBLE_P (f))
2187 {
2188 x_update_cursor (f, 0);
2189 x_update_cursor (f, 1);
2190 }
2191 }
2192
2193 update_face_from_frame_parameter (f, Qcursor_color, arg);
2194 }
2195
2196 /* Set the border-color of frame F to pixel value PIX.
2197 Note that this does not fully take effect if done before
2198 F has an window. */
2199 void
2200 x_set_border_pixel (f, pix)
2201 struct frame *f;
2202 int pix;
2203 {
2204 f->output_data.w32->border_pixel = pix;
2205
2206 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2207 {
2208 if (FRAME_VISIBLE_P (f))
2209 redraw_frame (f);
2210 }
2211 }
2212
2213 /* Set the border-color of frame F to value described by ARG.
2214 ARG can be a string naming a color.
2215 The border-color is used for the border that is drawn by the server.
2216 Note that this does not fully take effect if done before
2217 F has a window; it must be redone when the window is created. */
2218
2219 void
2220 x_set_border_color (f, arg, oldval)
2221 struct frame *f;
2222 Lisp_Object arg, oldval;
2223 {
2224 int pix;
2225
2226 CHECK_STRING (arg, 0);
2227 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2228 x_set_border_pixel (f, pix);
2229 update_face_from_frame_parameter (f, Qborder_color, arg);
2230 }
2231
2232 /* Value is the internal representation of the specified cursor type
2233 ARG. If type is BAR_CURSOR, return in *WIDTH the specified width
2234 of the bar cursor. */
2235
2236 enum text_cursor_kinds
2237 x_specified_cursor_type (arg, width)
2238 Lisp_Object arg;
2239 int *width;
2240 {
2241 enum text_cursor_kinds type;
2242
2243 if (EQ (arg, Qbar))
2244 {
2245 type = BAR_CURSOR;
2246 *width = 2;
2247 }
2248 else if (CONSP (arg)
2249 && EQ (XCAR (arg), Qbar)
2250 && INTEGERP (XCDR (arg))
2251 && XINT (XCDR (arg)) >= 0)
2252 {
2253 type = BAR_CURSOR;
2254 *width = XINT (XCDR (arg));
2255 }
2256 else if (NILP (arg))
2257 type = NO_CURSOR;
2258 else
2259 /* Treat anything unknown as "box cursor".
2260 It was bad to signal an error; people have trouble fixing
2261 .Xdefaults with Emacs, when it has something bad in it. */
2262 type = FILLED_BOX_CURSOR;
2263
2264 return type;
2265 }
2266
2267 void
2268 x_set_cursor_type (f, arg, oldval)
2269 FRAME_PTR f;
2270 Lisp_Object arg, oldval;
2271 {
2272 int width;
2273
2274 FRAME_DESIRED_CURSOR (f) = x_specified_cursor_type (arg, &width);
2275 f->output_data.w32->cursor_width = width;
2276
2277 /* Make sure the cursor gets redrawn. This is overkill, but how
2278 often do people change cursor types? */
2279 update_mode_lines++;
2280 }
2281 \f
2282 void
2283 x_set_icon_type (f, arg, oldval)
2284 struct frame *f;
2285 Lisp_Object arg, oldval;
2286 {
2287 int result;
2288
2289 if (NILP (arg) && NILP (oldval))
2290 return;
2291
2292 if (STRINGP (arg) && STRINGP (oldval)
2293 && EQ (Fstring_equal (oldval, arg), Qt))
2294 return;
2295
2296 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2297 return;
2298
2299 BLOCK_INPUT;
2300
2301 result = x_bitmap_icon (f, arg);
2302 if (result)
2303 {
2304 UNBLOCK_INPUT;
2305 error ("No icon window available");
2306 }
2307
2308 UNBLOCK_INPUT;
2309 }
2310
2311 /* Return non-nil if frame F wants a bitmap icon. */
2312
2313 Lisp_Object
2314 x_icon_type (f)
2315 FRAME_PTR f;
2316 {
2317 Lisp_Object tem;
2318
2319 tem = assq_no_quit (Qicon_type, f->param_alist);
2320 if (CONSP (tem))
2321 return XCDR (tem);
2322 else
2323 return Qnil;
2324 }
2325
2326 void
2327 x_set_icon_name (f, arg, oldval)
2328 struct frame *f;
2329 Lisp_Object arg, oldval;
2330 {
2331 int result;
2332
2333 if (STRINGP (arg))
2334 {
2335 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2336 return;
2337 }
2338 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2339 return;
2340
2341 f->icon_name = arg;
2342
2343 #if 0
2344 if (f->output_data.w32->icon_bitmap != 0)
2345 return;
2346
2347 BLOCK_INPUT;
2348
2349 result = x_text_icon (f,
2350 (char *) XSTRING ((!NILP (f->icon_name)
2351 ? f->icon_name
2352 : !NILP (f->title)
2353 ? f->title
2354 : f->name))->data);
2355
2356 if (result)
2357 {
2358 UNBLOCK_INPUT;
2359 error ("No icon window available");
2360 }
2361
2362 /* If the window was unmapped (and its icon was mapped),
2363 the new icon is not mapped, so map the window in its stead. */
2364 if (FRAME_VISIBLE_P (f))
2365 {
2366 #ifdef USE_X_TOOLKIT
2367 XtPopup (f->output_data.w32->widget, XtGrabNone);
2368 #endif
2369 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2370 }
2371
2372 XFlush (FRAME_W32_DISPLAY (f));
2373 UNBLOCK_INPUT;
2374 #endif
2375 }
2376
2377 extern Lisp_Object x_new_font ();
2378 extern Lisp_Object x_new_fontset();
2379
2380 void
2381 x_set_font (f, arg, oldval)
2382 struct frame *f;
2383 Lisp_Object arg, oldval;
2384 {
2385 Lisp_Object result;
2386 Lisp_Object fontset_name;
2387 Lisp_Object frame;
2388
2389 CHECK_STRING (arg, 1);
2390
2391 fontset_name = Fquery_fontset (arg, Qnil);
2392
2393 BLOCK_INPUT;
2394 result = (STRINGP (fontset_name)
2395 ? x_new_fontset (f, XSTRING (fontset_name)->data)
2396 : x_new_font (f, XSTRING (arg)->data));
2397 UNBLOCK_INPUT;
2398
2399 if (EQ (result, Qnil))
2400 error ("Font `%s' is not defined", XSTRING (arg)->data);
2401 else if (EQ (result, Qt))
2402 error ("The characters of the given font have varying widths");
2403 else if (STRINGP (result))
2404 {
2405 store_frame_param (f, Qfont, result);
2406 recompute_basic_faces (f);
2407 }
2408 else
2409 abort ();
2410
2411 do_pending_window_change (0);
2412
2413 /* Don't call `face-set-after-frame-default' when faces haven't been
2414 initialized yet. This is the case when called from
2415 Fx_create_frame. In that case, the X widget or window doesn't
2416 exist either, and we can end up in x_report_frame_params with a
2417 null widget which gives a segfault. */
2418 if (FRAME_FACE_CACHE (f))
2419 {
2420 XSETFRAME (frame, f);
2421 call1 (Qface_set_after_frame_default, frame);
2422 }
2423 }
2424
2425 void
2426 x_set_border_width (f, arg, oldval)
2427 struct frame *f;
2428 Lisp_Object arg, oldval;
2429 {
2430 CHECK_NUMBER (arg, 0);
2431
2432 if (XINT (arg) == f->output_data.w32->border_width)
2433 return;
2434
2435 if (FRAME_W32_WINDOW (f) != 0)
2436 error ("Cannot change the border width of a window");
2437
2438 f->output_data.w32->border_width = XINT (arg);
2439 }
2440
2441 void
2442 x_set_internal_border_width (f, arg, oldval)
2443 struct frame *f;
2444 Lisp_Object arg, oldval;
2445 {
2446 int old = f->output_data.w32->internal_border_width;
2447
2448 CHECK_NUMBER (arg, 0);
2449 f->output_data.w32->internal_border_width = XINT (arg);
2450 if (f->output_data.w32->internal_border_width < 0)
2451 f->output_data.w32->internal_border_width = 0;
2452
2453 if (f->output_data.w32->internal_border_width == old)
2454 return;
2455
2456 if (FRAME_W32_WINDOW (f) != 0)
2457 {
2458 x_set_window_size (f, 0, f->width, f->height);
2459 SET_FRAME_GARBAGED (f);
2460 do_pending_window_change (0);
2461 }
2462 }
2463
2464 void
2465 x_set_visibility (f, value, oldval)
2466 struct frame *f;
2467 Lisp_Object value, oldval;
2468 {
2469 Lisp_Object frame;
2470 XSETFRAME (frame, f);
2471
2472 if (NILP (value))
2473 Fmake_frame_invisible (frame, Qt);
2474 else if (EQ (value, Qicon))
2475 Ficonify_frame (frame);
2476 else
2477 Fmake_frame_visible (frame);
2478 }
2479
2480 \f
2481 /* Change window heights in windows rooted in WINDOW by N lines. */
2482
2483 static void
2484 x_change_window_heights (window, n)
2485 Lisp_Object window;
2486 int n;
2487 {
2488 struct window *w = XWINDOW (window);
2489
2490 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2491 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2492
2493 if (INTEGERP (w->orig_top))
2494 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2495 if (INTEGERP (w->orig_height))
2496 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2497
2498 /* Handle just the top child in a vertical split. */
2499 if (!NILP (w->vchild))
2500 x_change_window_heights (w->vchild, n);
2501
2502 /* Adjust all children in a horizontal split. */
2503 for (window = w->hchild; !NILP (window); window = w->next)
2504 {
2505 w = XWINDOW (window);
2506 x_change_window_heights (window, n);
2507 }
2508 }
2509
2510 void
2511 x_set_menu_bar_lines (f, value, oldval)
2512 struct frame *f;
2513 Lisp_Object value, oldval;
2514 {
2515 int nlines;
2516 int olines = FRAME_MENU_BAR_LINES (f);
2517
2518 /* Right now, menu bars don't work properly in minibuf-only frames;
2519 most of the commands try to apply themselves to the minibuffer
2520 frame itself, and get an error because you can't switch buffers
2521 in or split the minibuffer window. */
2522 if (FRAME_MINIBUF_ONLY_P (f))
2523 return;
2524
2525 if (INTEGERP (value))
2526 nlines = XINT (value);
2527 else
2528 nlines = 0;
2529
2530 FRAME_MENU_BAR_LINES (f) = 0;
2531 if (nlines)
2532 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2533 else
2534 {
2535 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2536 free_frame_menubar (f);
2537 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2538
2539 /* Adjust the frame size so that the client (text) dimensions
2540 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2541 set correctly. */
2542 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2543 do_pending_window_change (0);
2544 }
2545 adjust_glyphs (f);
2546 }
2547
2548
2549 /* Set the number of lines used for the tool bar of frame F to VALUE.
2550 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2551 is the old number of tool bar lines. This function changes the
2552 height of all windows on frame F to match the new tool bar height.
2553 The frame's height doesn't change. */
2554
2555 void
2556 x_set_tool_bar_lines (f, value, oldval)
2557 struct frame *f;
2558 Lisp_Object value, oldval;
2559 {
2560 int delta, nlines, root_height;
2561 Lisp_Object root_window;
2562
2563 /* Use VALUE only if an integer >= 0. */
2564 if (INTEGERP (value) && XINT (value) >= 0)
2565 nlines = XFASTINT (value);
2566 else
2567 nlines = 0;
2568
2569 /* Make sure we redisplay all windows in this frame. */
2570 ++windows_or_buffers_changed;
2571
2572 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2573
2574 /* Don't resize the tool-bar to more than we have room for. */
2575 root_window = FRAME_ROOT_WINDOW (f);
2576 root_height = XINT (XWINDOW (root_window)->height);
2577 if (root_height - delta < 1)
2578 {
2579 delta = root_height - 1;
2580 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2581 }
2582
2583 FRAME_TOOL_BAR_LINES (f) = nlines;
2584 x_change_window_heights (root_window, delta);
2585 adjust_glyphs (f);
2586
2587 /* We also have to make sure that the internal border at the top of
2588 the frame, below the menu bar or tool bar, is redrawn when the
2589 tool bar disappears. This is so because the internal border is
2590 below the tool bar if one is displayed, but is below the menu bar
2591 if there isn't a tool bar. The tool bar draws into the area
2592 below the menu bar. */
2593 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2594 {
2595 updating_frame = f;
2596 clear_frame ();
2597 clear_current_matrices (f);
2598 updating_frame = NULL;
2599 }
2600
2601 /* If the tool bar gets smaller, the internal border below it
2602 has to be cleared. It was formerly part of the display
2603 of the larger tool bar, and updating windows won't clear it. */
2604 if (delta < 0)
2605 {
2606 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2607 int width = PIXEL_WIDTH (f);
2608 int y = nlines * CANON_Y_UNIT (f);
2609
2610 BLOCK_INPUT;
2611 {
2612 HDC hdc = get_frame_dc (f);
2613 w32_clear_area (f, hdc, 0, y, width, height);
2614 release_frame_dc (f, hdc);
2615 }
2616 UNBLOCK_INPUT;
2617 }
2618 }
2619
2620
2621 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2622 w32_id_name.
2623
2624 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2625 name; if NAME is a string, set F's name to NAME and set
2626 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2627
2628 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2629 suggesting a new name, which lisp code should override; if
2630 F->explicit_name is set, ignore the new name; otherwise, set it. */
2631
2632 void
2633 x_set_name (f, name, explicit)
2634 struct frame *f;
2635 Lisp_Object name;
2636 int explicit;
2637 {
2638 /* Make sure that requests from lisp code override requests from
2639 Emacs redisplay code. */
2640 if (explicit)
2641 {
2642 /* If we're switching from explicit to implicit, we had better
2643 update the mode lines and thereby update the title. */
2644 if (f->explicit_name && NILP (name))
2645 update_mode_lines = 1;
2646
2647 f->explicit_name = ! NILP (name);
2648 }
2649 else if (f->explicit_name)
2650 return;
2651
2652 /* If NAME is nil, set the name to the w32_id_name. */
2653 if (NILP (name))
2654 {
2655 /* Check for no change needed in this very common case
2656 before we do any consing. */
2657 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2658 XSTRING (f->name)->data))
2659 return;
2660 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2661 }
2662 else
2663 CHECK_STRING (name, 0);
2664
2665 /* Don't change the name if it's already NAME. */
2666 if (! NILP (Fstring_equal (name, f->name)))
2667 return;
2668
2669 f->name = name;
2670
2671 /* For setting the frame title, the title parameter should override
2672 the name parameter. */
2673 if (! NILP (f->title))
2674 name = f->title;
2675
2676 if (FRAME_W32_WINDOW (f))
2677 {
2678 if (STRING_MULTIBYTE (name))
2679 name = ENCODE_SYSTEM (name);
2680
2681 BLOCK_INPUT;
2682 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2683 UNBLOCK_INPUT;
2684 }
2685 }
2686
2687 /* This function should be called when the user's lisp code has
2688 specified a name for the frame; the name will override any set by the
2689 redisplay code. */
2690 void
2691 x_explicitly_set_name (f, arg, oldval)
2692 FRAME_PTR f;
2693 Lisp_Object arg, oldval;
2694 {
2695 x_set_name (f, arg, 1);
2696 }
2697
2698 /* This function should be called by Emacs redisplay code to set the
2699 name; names set this way will never override names set by the user's
2700 lisp code. */
2701 void
2702 x_implicitly_set_name (f, arg, oldval)
2703 FRAME_PTR f;
2704 Lisp_Object arg, oldval;
2705 {
2706 x_set_name (f, arg, 0);
2707 }
2708 \f
2709 /* Change the title of frame F to NAME.
2710 If NAME is nil, use the frame name as the title.
2711
2712 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2713 name; if NAME is a string, set F's name to NAME and set
2714 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2715
2716 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2717 suggesting a new name, which lisp code should override; if
2718 F->explicit_name is set, ignore the new name; otherwise, set it. */
2719
2720 void
2721 x_set_title (f, name, old_name)
2722 struct frame *f;
2723 Lisp_Object name, old_name;
2724 {
2725 /* Don't change the title if it's already NAME. */
2726 if (EQ (name, f->title))
2727 return;
2728
2729 update_mode_lines = 1;
2730
2731 f->title = name;
2732
2733 if (NILP (name))
2734 name = f->name;
2735
2736 if (FRAME_W32_WINDOW (f))
2737 {
2738 if (STRING_MULTIBYTE (name))
2739 name = ENCODE_SYSTEM (name);
2740
2741 BLOCK_INPUT;
2742 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2743 UNBLOCK_INPUT;
2744 }
2745 }
2746 \f
2747 void
2748 x_set_autoraise (f, arg, oldval)
2749 struct frame *f;
2750 Lisp_Object arg, oldval;
2751 {
2752 f->auto_raise = !EQ (Qnil, arg);
2753 }
2754
2755 void
2756 x_set_autolower (f, arg, oldval)
2757 struct frame *f;
2758 Lisp_Object arg, oldval;
2759 {
2760 f->auto_lower = !EQ (Qnil, arg);
2761 }
2762
2763 void
2764 x_set_unsplittable (f, arg, oldval)
2765 struct frame *f;
2766 Lisp_Object arg, oldval;
2767 {
2768 f->no_split = !NILP (arg);
2769 }
2770
2771 void
2772 x_set_vertical_scroll_bars (f, arg, oldval)
2773 struct frame *f;
2774 Lisp_Object arg, oldval;
2775 {
2776 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2777 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2778 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2779 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2780 {
2781 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2782 vertical_scroll_bar_none :
2783 /* Put scroll bars on the right by default, as is conventional
2784 on MS-Windows. */
2785 EQ (Qleft, arg)
2786 ? vertical_scroll_bar_left
2787 : vertical_scroll_bar_right;
2788
2789 /* We set this parameter before creating the window for the
2790 frame, so we can get the geometry right from the start.
2791 However, if the window hasn't been created yet, we shouldn't
2792 call x_set_window_size. */
2793 if (FRAME_W32_WINDOW (f))
2794 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2795 do_pending_window_change (0);
2796 }
2797 }
2798
2799 void
2800 x_set_scroll_bar_width (f, arg, oldval)
2801 struct frame *f;
2802 Lisp_Object arg, oldval;
2803 {
2804 int wid = FONT_WIDTH (f->output_data.w32->font);
2805
2806 if (NILP (arg))
2807 {
2808 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2809 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2810 wid - 1) / wid;
2811 if (FRAME_W32_WINDOW (f))
2812 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2813 do_pending_window_change (0);
2814 }
2815 else if (INTEGERP (arg) && XINT (arg) > 0
2816 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2817 {
2818 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2819 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2820 + wid-1) / wid;
2821 if (FRAME_W32_WINDOW (f))
2822 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2823 do_pending_window_change (0);
2824 }
2825 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2826 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2827 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2828 }
2829 \f
2830 /* Subroutines of creating an frame. */
2831
2832 /* Make sure that Vx_resource_name is set to a reasonable value.
2833 Fix it up, or set it to `emacs' if it is too hopeless. */
2834
2835 static void
2836 validate_x_resource_name ()
2837 {
2838 int len = 0;
2839 /* Number of valid characters in the resource name. */
2840 int good_count = 0;
2841 /* Number of invalid characters in the resource name. */
2842 int bad_count = 0;
2843 Lisp_Object new;
2844 int i;
2845
2846 if (STRINGP (Vx_resource_name))
2847 {
2848 unsigned char *p = XSTRING (Vx_resource_name)->data;
2849 int i;
2850
2851 len = STRING_BYTES (XSTRING (Vx_resource_name));
2852
2853 /* Only letters, digits, - and _ are valid in resource names.
2854 Count the valid characters and count the invalid ones. */
2855 for (i = 0; i < len; i++)
2856 {
2857 int c = p[i];
2858 if (! ((c >= 'a' && c <= 'z')
2859 || (c >= 'A' && c <= 'Z')
2860 || (c >= '0' && c <= '9')
2861 || c == '-' || c == '_'))
2862 bad_count++;
2863 else
2864 good_count++;
2865 }
2866 }
2867 else
2868 /* Not a string => completely invalid. */
2869 bad_count = 5, good_count = 0;
2870
2871 /* If name is valid already, return. */
2872 if (bad_count == 0)
2873 return;
2874
2875 /* If name is entirely invalid, or nearly so, use `emacs'. */
2876 if (good_count == 0
2877 || (good_count == 1 && bad_count > 0))
2878 {
2879 Vx_resource_name = build_string ("emacs");
2880 return;
2881 }
2882
2883 /* Name is partly valid. Copy it and replace the invalid characters
2884 with underscores. */
2885
2886 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2887
2888 for (i = 0; i < len; i++)
2889 {
2890 int c = XSTRING (new)->data[i];
2891 if (! ((c >= 'a' && c <= 'z')
2892 || (c >= 'A' && c <= 'Z')
2893 || (c >= '0' && c <= '9')
2894 || c == '-' || c == '_'))
2895 XSTRING (new)->data[i] = '_';
2896 }
2897 }
2898
2899
2900 extern char *x_get_string_resource ();
2901
2902 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2903 "Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.\n\
2904 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the\n\
2905 class, where INSTANCE is the name under which Emacs was invoked, or\n\
2906 the name specified by the `-name' or `-rn' command-line arguments.\n\
2907 \n\
2908 The optional arguments COMPONENT and SUBCLASS add to the key and the\n\
2909 class, respectively. You must specify both of them or neither.\n\
2910 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'\n\
2911 and the class is `Emacs.CLASS.SUBCLASS'.")
2912 (attribute, class, component, subclass)
2913 Lisp_Object attribute, class, component, subclass;
2914 {
2915 register char *value;
2916 char *name_key;
2917 char *class_key;
2918
2919 CHECK_STRING (attribute, 0);
2920 CHECK_STRING (class, 0);
2921
2922 if (!NILP (component))
2923 CHECK_STRING (component, 1);
2924 if (!NILP (subclass))
2925 CHECK_STRING (subclass, 2);
2926 if (NILP (component) != NILP (subclass))
2927 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
2928
2929 validate_x_resource_name ();
2930
2931 /* Allocate space for the components, the dots which separate them,
2932 and the final '\0'. Make them big enough for the worst case. */
2933 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vx_resource_name))
2934 + (STRINGP (component)
2935 ? STRING_BYTES (XSTRING (component)) : 0)
2936 + STRING_BYTES (XSTRING (attribute))
2937 + 3);
2938
2939 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2940 + STRING_BYTES (XSTRING (class))
2941 + (STRINGP (subclass)
2942 ? STRING_BYTES (XSTRING (subclass)) : 0)
2943 + 3);
2944
2945 /* Start with emacs.FRAMENAME for the name (the specific one)
2946 and with `Emacs' for the class key (the general one). */
2947 strcpy (name_key, XSTRING (Vx_resource_name)->data);
2948 strcpy (class_key, EMACS_CLASS);
2949
2950 strcat (class_key, ".");
2951 strcat (class_key, XSTRING (class)->data);
2952
2953 if (!NILP (component))
2954 {
2955 strcat (class_key, ".");
2956 strcat (class_key, XSTRING (subclass)->data);
2957
2958 strcat (name_key, ".");
2959 strcat (name_key, XSTRING (component)->data);
2960 }
2961
2962 strcat (name_key, ".");
2963 strcat (name_key, XSTRING (attribute)->data);
2964
2965 value = x_get_string_resource (Qnil,
2966 name_key, class_key);
2967
2968 if (value != (char *) 0)
2969 return build_string (value);
2970 else
2971 return Qnil;
2972 }
2973
2974 /* Used when C code wants a resource value. */
2975
2976 char *
2977 x_get_resource_string (attribute, class)
2978 char *attribute, *class;
2979 {
2980 char *name_key;
2981 char *class_key;
2982 struct frame *sf = SELECTED_FRAME ();
2983
2984 /* Allocate space for the components, the dots which separate them,
2985 and the final '\0'. */
2986 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vinvocation_name))
2987 + strlen (attribute) + 2);
2988 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2989 + strlen (class) + 2);
2990
2991 sprintf (name_key, "%s.%s",
2992 XSTRING (Vinvocation_name)->data,
2993 attribute);
2994 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
2995
2996 return x_get_string_resource (sf, name_key, class_key);
2997 }
2998
2999 /* Types we might convert a resource string into. */
3000 enum resource_types
3001 {
3002 RES_TYPE_NUMBER,
3003 RES_TYPE_FLOAT,
3004 RES_TYPE_BOOLEAN,
3005 RES_TYPE_STRING,
3006 RES_TYPE_SYMBOL
3007 };
3008
3009 /* Return the value of parameter PARAM.
3010
3011 First search ALIST, then Vdefault_frame_alist, then the X defaults
3012 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3013
3014 Convert the resource to the type specified by desired_type.
3015
3016 If no default is specified, return Qunbound. If you call
3017 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3018 and don't let it get stored in any Lisp-visible variables! */
3019
3020 static Lisp_Object
3021 w32_get_arg (alist, param, attribute, class, type)
3022 Lisp_Object alist, param;
3023 char *attribute;
3024 char *class;
3025 enum resource_types type;
3026 {
3027 register Lisp_Object tem;
3028
3029 tem = Fassq (param, alist);
3030 if (EQ (tem, Qnil))
3031 tem = Fassq (param, Vdefault_frame_alist);
3032 if (EQ (tem, Qnil))
3033 {
3034
3035 if (attribute)
3036 {
3037 tem = Fx_get_resource (build_string (attribute),
3038 build_string (class),
3039 Qnil, Qnil);
3040
3041 if (NILP (tem))
3042 return Qunbound;
3043
3044 switch (type)
3045 {
3046 case RES_TYPE_NUMBER:
3047 return make_number (atoi (XSTRING (tem)->data));
3048
3049 case RES_TYPE_FLOAT:
3050 return make_float (atof (XSTRING (tem)->data));
3051
3052 case RES_TYPE_BOOLEAN:
3053 tem = Fdowncase (tem);
3054 if (!strcmp (XSTRING (tem)->data, "on")
3055 || !strcmp (XSTRING (tem)->data, "true"))
3056 return Qt;
3057 else
3058 return Qnil;
3059
3060 case RES_TYPE_STRING:
3061 return tem;
3062
3063 case RES_TYPE_SYMBOL:
3064 /* As a special case, we map the values `true' and `on'
3065 to Qt, and `false' and `off' to Qnil. */
3066 {
3067 Lisp_Object lower;
3068 lower = Fdowncase (tem);
3069 if (!strcmp (XSTRING (lower)->data, "on")
3070 || !strcmp (XSTRING (lower)->data, "true"))
3071 return Qt;
3072 else if (!strcmp (XSTRING (lower)->data, "off")
3073 || !strcmp (XSTRING (lower)->data, "false"))
3074 return Qnil;
3075 else
3076 return Fintern (tem, Qnil);
3077 }
3078
3079 default:
3080 abort ();
3081 }
3082 }
3083 else
3084 return Qunbound;
3085 }
3086 return Fcdr (tem);
3087 }
3088
3089 /* Record in frame F the specified or default value according to ALIST
3090 of the parameter named PROP (a Lisp symbol).
3091 If no value is specified for PROP, look for an X default for XPROP
3092 on the frame named NAME.
3093 If that is not found either, use the value DEFLT. */
3094
3095 static Lisp_Object
3096 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3097 struct frame *f;
3098 Lisp_Object alist;
3099 Lisp_Object prop;
3100 Lisp_Object deflt;
3101 char *xprop;
3102 char *xclass;
3103 enum resource_types type;
3104 {
3105 Lisp_Object tem;
3106
3107 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3108 if (EQ (tem, Qunbound))
3109 tem = deflt;
3110 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3111 return tem;
3112 }
3113 \f
3114 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3115 "Parse an X-style geometry string STRING.\n\
3116 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).\n\
3117 The properties returned may include `top', `left', `height', and `width'.\n\
3118 The value of `left' or `top' may be an integer,\n\
3119 or a list (+ N) meaning N pixels relative to top/left corner,\n\
3120 or a list (- N) meaning -N pixels relative to bottom/right corner.")
3121 (string)
3122 Lisp_Object string;
3123 {
3124 int geometry, x, y;
3125 unsigned int width, height;
3126 Lisp_Object result;
3127
3128 CHECK_STRING (string, 0);
3129
3130 geometry = XParseGeometry ((char *) XSTRING (string)->data,
3131 &x, &y, &width, &height);
3132
3133 result = Qnil;
3134 if (geometry & XValue)
3135 {
3136 Lisp_Object element;
3137
3138 if (x >= 0 && (geometry & XNegative))
3139 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3140 else if (x < 0 && ! (geometry & XNegative))
3141 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3142 else
3143 element = Fcons (Qleft, make_number (x));
3144 result = Fcons (element, result);
3145 }
3146
3147 if (geometry & YValue)
3148 {
3149 Lisp_Object element;
3150
3151 if (y >= 0 && (geometry & YNegative))
3152 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3153 else if (y < 0 && ! (geometry & YNegative))
3154 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3155 else
3156 element = Fcons (Qtop, make_number (y));
3157 result = Fcons (element, result);
3158 }
3159
3160 if (geometry & WidthValue)
3161 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3162 if (geometry & HeightValue)
3163 result = Fcons (Fcons (Qheight, make_number (height)), result);
3164
3165 return result;
3166 }
3167
3168 /* Calculate the desired size and position of this window,
3169 and return the flags saying which aspects were specified.
3170
3171 This function does not make the coordinates positive. */
3172
3173 #define DEFAULT_ROWS 40
3174 #define DEFAULT_COLS 80
3175
3176 static int
3177 x_figure_window_size (f, parms)
3178 struct frame *f;
3179 Lisp_Object parms;
3180 {
3181 register Lisp_Object tem0, tem1, tem2;
3182 long window_prompting = 0;
3183
3184 /* Default values if we fall through.
3185 Actually, if that happens we should get
3186 window manager prompting. */
3187 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3188 f->height = DEFAULT_ROWS;
3189 /* Window managers expect that if program-specified
3190 positions are not (0,0), they're intentional, not defaults. */
3191 f->output_data.w32->top_pos = 0;
3192 f->output_data.w32->left_pos = 0;
3193
3194 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3195 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3196 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3197 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3198 {
3199 if (!EQ (tem0, Qunbound))
3200 {
3201 CHECK_NUMBER (tem0, 0);
3202 f->height = XINT (tem0);
3203 }
3204 if (!EQ (tem1, Qunbound))
3205 {
3206 CHECK_NUMBER (tem1, 0);
3207 SET_FRAME_WIDTH (f, XINT (tem1));
3208 }
3209 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3210 window_prompting |= USSize;
3211 else
3212 window_prompting |= PSize;
3213 }
3214
3215 f->output_data.w32->vertical_scroll_bar_extra
3216 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3217 ? 0
3218 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3219 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3220 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3221 f->output_data.w32->flags_areas_extra
3222 = FRAME_FLAGS_AREA_WIDTH (f);
3223 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3224 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3225
3226 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3227 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3228 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3229 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3230 {
3231 if (EQ (tem0, Qminus))
3232 {
3233 f->output_data.w32->top_pos = 0;
3234 window_prompting |= YNegative;
3235 }
3236 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3237 && CONSP (XCDR (tem0))
3238 && INTEGERP (XCAR (XCDR (tem0))))
3239 {
3240 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3241 window_prompting |= YNegative;
3242 }
3243 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3244 && CONSP (XCDR (tem0))
3245 && INTEGERP (XCAR (XCDR (tem0))))
3246 {
3247 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3248 }
3249 else if (EQ (tem0, Qunbound))
3250 f->output_data.w32->top_pos = 0;
3251 else
3252 {
3253 CHECK_NUMBER (tem0, 0);
3254 f->output_data.w32->top_pos = XINT (tem0);
3255 if (f->output_data.w32->top_pos < 0)
3256 window_prompting |= YNegative;
3257 }
3258
3259 if (EQ (tem1, Qminus))
3260 {
3261 f->output_data.w32->left_pos = 0;
3262 window_prompting |= XNegative;
3263 }
3264 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3265 && CONSP (XCDR (tem1))
3266 && INTEGERP (XCAR (XCDR (tem1))))
3267 {
3268 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3269 window_prompting |= XNegative;
3270 }
3271 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3272 && CONSP (XCDR (tem1))
3273 && INTEGERP (XCAR (XCDR (tem1))))
3274 {
3275 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3276 }
3277 else if (EQ (tem1, Qunbound))
3278 f->output_data.w32->left_pos = 0;
3279 else
3280 {
3281 CHECK_NUMBER (tem1, 0);
3282 f->output_data.w32->left_pos = XINT (tem1);
3283 if (f->output_data.w32->left_pos < 0)
3284 window_prompting |= XNegative;
3285 }
3286
3287 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3288 window_prompting |= USPosition;
3289 else
3290 window_prompting |= PPosition;
3291 }
3292
3293 return window_prompting;
3294 }
3295
3296 \f
3297
3298 extern LRESULT CALLBACK w32_wnd_proc ();
3299
3300 BOOL
3301 w32_init_class (hinst)
3302 HINSTANCE hinst;
3303 {
3304 WNDCLASS wc;
3305
3306 wc.style = CS_HREDRAW | CS_VREDRAW;
3307 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3308 wc.cbClsExtra = 0;
3309 wc.cbWndExtra = WND_EXTRA_BYTES;
3310 wc.hInstance = hinst;
3311 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3312 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3313 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3314 wc.lpszMenuName = NULL;
3315 wc.lpszClassName = EMACS_CLASS;
3316
3317 return (RegisterClass (&wc));
3318 }
3319
3320 HWND
3321 w32_createscrollbar (f, bar)
3322 struct frame *f;
3323 struct scroll_bar * bar;
3324 {
3325 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3326 /* Position and size of scroll bar. */
3327 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3328 XINT(bar->top),
3329 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3330 XINT(bar->height),
3331 FRAME_W32_WINDOW (f),
3332 NULL,
3333 hinst,
3334 NULL));
3335 }
3336
3337 void
3338 w32_createwindow (f)
3339 struct frame *f;
3340 {
3341 HWND hwnd;
3342 RECT rect;
3343
3344 rect.left = rect.top = 0;
3345 rect.right = PIXEL_WIDTH (f);
3346 rect.bottom = PIXEL_HEIGHT (f);
3347
3348 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3349 FRAME_EXTERNAL_MENU_BAR (f));
3350
3351 /* Do first time app init */
3352
3353 if (!hprevinst)
3354 {
3355 w32_init_class (hinst);
3356 }
3357
3358 FRAME_W32_WINDOW (f) = hwnd
3359 = CreateWindow (EMACS_CLASS,
3360 f->namebuf,
3361 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3362 f->output_data.w32->left_pos,
3363 f->output_data.w32->top_pos,
3364 rect.right - rect.left,
3365 rect.bottom - rect.top,
3366 NULL,
3367 NULL,
3368 hinst,
3369 NULL);
3370
3371 if (hwnd)
3372 {
3373 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3374 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3375 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3376 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3377 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3378
3379 /* Enable drag-n-drop. */
3380 DragAcceptFiles (hwnd, TRUE);
3381
3382 /* Do this to discard the default setting specified by our parent. */
3383 ShowWindow (hwnd, SW_HIDE);
3384 }
3385 }
3386
3387 void
3388 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3389 W32Msg * wmsg;
3390 HWND hwnd;
3391 UINT msg;
3392 WPARAM wParam;
3393 LPARAM lParam;
3394 {
3395 wmsg->msg.hwnd = hwnd;
3396 wmsg->msg.message = msg;
3397 wmsg->msg.wParam = wParam;
3398 wmsg->msg.lParam = lParam;
3399 wmsg->msg.time = GetMessageTime ();
3400
3401 post_msg (wmsg);
3402 }
3403
3404 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3405 between left and right keys as advertised. We test for this
3406 support dynamically, and set a flag when the support is absent. If
3407 absent, we keep track of the left and right control and alt keys
3408 ourselves. This is particularly necessary on keyboards that rely
3409 upon the AltGr key, which is represented as having the left control
3410 and right alt keys pressed. For these keyboards, we need to know
3411 when the left alt key has been pressed in addition to the AltGr key
3412 so that we can properly support M-AltGr-key sequences (such as M-@
3413 on Swedish keyboards). */
3414
3415 #define EMACS_LCONTROL 0
3416 #define EMACS_RCONTROL 1
3417 #define EMACS_LMENU 2
3418 #define EMACS_RMENU 3
3419
3420 static int modifiers[4];
3421 static int modifiers_recorded;
3422 static int modifier_key_support_tested;
3423
3424 static void
3425 test_modifier_support (unsigned int wparam)
3426 {
3427 unsigned int l, r;
3428
3429 if (wparam != VK_CONTROL && wparam != VK_MENU)
3430 return;
3431 if (wparam == VK_CONTROL)
3432 {
3433 l = VK_LCONTROL;
3434 r = VK_RCONTROL;
3435 }
3436 else
3437 {
3438 l = VK_LMENU;
3439 r = VK_RMENU;
3440 }
3441 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3442 modifiers_recorded = 1;
3443 else
3444 modifiers_recorded = 0;
3445 modifier_key_support_tested = 1;
3446 }
3447
3448 static void
3449 record_keydown (unsigned int wparam, unsigned int lparam)
3450 {
3451 int i;
3452
3453 if (!modifier_key_support_tested)
3454 test_modifier_support (wparam);
3455
3456 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3457 return;
3458
3459 if (wparam == VK_CONTROL)
3460 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3461 else
3462 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3463
3464 modifiers[i] = 1;
3465 }
3466
3467 static void
3468 record_keyup (unsigned int wparam, unsigned int lparam)
3469 {
3470 int i;
3471
3472 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3473 return;
3474
3475 if (wparam == VK_CONTROL)
3476 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3477 else
3478 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3479
3480 modifiers[i] = 0;
3481 }
3482
3483 /* Emacs can lose focus while a modifier key has been pressed. When
3484 it regains focus, be conservative and clear all modifiers since
3485 we cannot reconstruct the left and right modifier state. */
3486 static void
3487 reset_modifiers ()
3488 {
3489 SHORT ctrl, alt;
3490
3491 if (GetFocus () == NULL)
3492 /* Emacs doesn't have keyboard focus. Do nothing. */
3493 return;
3494
3495 ctrl = GetAsyncKeyState (VK_CONTROL);
3496 alt = GetAsyncKeyState (VK_MENU);
3497
3498 if (!(ctrl & 0x08000))
3499 /* Clear any recorded control modifier state. */
3500 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3501
3502 if (!(alt & 0x08000))
3503 /* Clear any recorded alt modifier state. */
3504 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3505
3506 /* Update the state of all modifier keys, because modifiers used in
3507 hot-key combinations can get stuck on if Emacs loses focus as a
3508 result of a hot-key being pressed. */
3509 {
3510 BYTE keystate[256];
3511
3512 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3513
3514 GetKeyboardState (keystate);
3515 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3516 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3517 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3518 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3519 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3520 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3521 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3522 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3523 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3524 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3525 SetKeyboardState (keystate);
3526 }
3527 }
3528
3529 /* Synchronize modifier state with what is reported with the current
3530 keystroke. Even if we cannot distinguish between left and right
3531 modifier keys, we know that, if no modifiers are set, then neither
3532 the left or right modifier should be set. */
3533 static void
3534 sync_modifiers ()
3535 {
3536 if (!modifiers_recorded)
3537 return;
3538
3539 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3540 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3541
3542 if (!(GetKeyState (VK_MENU) & 0x8000))
3543 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3544 }
3545
3546 static int
3547 modifier_set (int vkey)
3548 {
3549 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3550 return (GetKeyState (vkey) & 0x1);
3551 if (!modifiers_recorded)
3552 return (GetKeyState (vkey) & 0x8000);
3553
3554 switch (vkey)
3555 {
3556 case VK_LCONTROL:
3557 return modifiers[EMACS_LCONTROL];
3558 case VK_RCONTROL:
3559 return modifiers[EMACS_RCONTROL];
3560 case VK_LMENU:
3561 return modifiers[EMACS_LMENU];
3562 case VK_RMENU:
3563 return modifiers[EMACS_RMENU];
3564 }
3565 return (GetKeyState (vkey) & 0x8000);
3566 }
3567
3568 /* Convert between the modifier bits W32 uses and the modifier bits
3569 Emacs uses. */
3570
3571 unsigned int
3572 w32_key_to_modifier (int key)
3573 {
3574 Lisp_Object key_mapping;
3575
3576 switch (key)
3577 {
3578 case VK_LWIN:
3579 key_mapping = Vw32_lwindow_modifier;
3580 break;
3581 case VK_RWIN:
3582 key_mapping = Vw32_rwindow_modifier;
3583 break;
3584 case VK_APPS:
3585 key_mapping = Vw32_apps_modifier;
3586 break;
3587 case VK_SCROLL:
3588 key_mapping = Vw32_scroll_lock_modifier;
3589 break;
3590 default:
3591 key_mapping = Qnil;
3592 }
3593
3594 /* NB. This code runs in the input thread, asychronously to the lisp
3595 thread, so we must be careful to ensure access to lisp data is
3596 thread-safe. The following code is safe because the modifier
3597 variable values are updated atomically from lisp and symbols are
3598 not relocated by GC. Also, we don't have to worry about seeing GC
3599 markbits here. */
3600 if (EQ (key_mapping, Qhyper))
3601 return hyper_modifier;
3602 if (EQ (key_mapping, Qsuper))
3603 return super_modifier;
3604 if (EQ (key_mapping, Qmeta))
3605 return meta_modifier;
3606 if (EQ (key_mapping, Qalt))
3607 return alt_modifier;
3608 if (EQ (key_mapping, Qctrl))
3609 return ctrl_modifier;
3610 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3611 return ctrl_modifier;
3612 if (EQ (key_mapping, Qshift))
3613 return shift_modifier;
3614
3615 /* Don't generate any modifier if not explicitly requested. */
3616 return 0;
3617 }
3618
3619 unsigned int
3620 w32_get_modifiers ()
3621 {
3622 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3623 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3624 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3625 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3626 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3627 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3628 (modifier_set (VK_MENU) ?
3629 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3630 }
3631
3632 /* We map the VK_* modifiers into console modifier constants
3633 so that we can use the same routines to handle both console
3634 and window input. */
3635
3636 static int
3637 construct_console_modifiers ()
3638 {
3639 int mods;
3640
3641 mods = 0;
3642 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3643 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3644 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3645 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3646 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3647 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3648 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3649 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3650 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3651 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3652 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3653
3654 return mods;
3655 }
3656
3657 static int
3658 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3659 {
3660 int mods;
3661
3662 /* Convert to emacs modifiers. */
3663 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3664
3665 return mods;
3666 }
3667
3668 unsigned int
3669 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3670 {
3671 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3672 return virt_key;
3673
3674 if (virt_key == VK_RETURN)
3675 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3676
3677 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3678 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3679
3680 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3681 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3682
3683 if (virt_key == VK_CLEAR)
3684 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3685
3686 return virt_key;
3687 }
3688
3689 /* List of special key combinations which w32 would normally capture,
3690 but emacs should grab instead. Not directly visible to lisp, to
3691 simplify synchronization. Each item is an integer encoding a virtual
3692 key code and modifier combination to capture. */
3693 Lisp_Object w32_grabbed_keys;
3694
3695 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3696 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3697 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3698 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3699
3700 /* Register hot-keys for reserved key combinations when Emacs has
3701 keyboard focus, since this is the only way Emacs can receive key
3702 combinations like Alt-Tab which are used by the system. */
3703
3704 static void
3705 register_hot_keys (hwnd)
3706 HWND hwnd;
3707 {
3708 Lisp_Object keylist;
3709
3710 /* Use GC_CONSP, since we are called asynchronously. */
3711 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3712 {
3713 Lisp_Object key = XCAR (keylist);
3714
3715 /* Deleted entries get set to nil. */
3716 if (!INTEGERP (key))
3717 continue;
3718
3719 RegisterHotKey (hwnd, HOTKEY_ID (key),
3720 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3721 }
3722 }
3723
3724 static void
3725 unregister_hot_keys (hwnd)
3726 HWND hwnd;
3727 {
3728 Lisp_Object keylist;
3729
3730 /* Use GC_CONSP, since we are called asynchronously. */
3731 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3732 {
3733 Lisp_Object key = XCAR (keylist);
3734
3735 if (!INTEGERP (key))
3736 continue;
3737
3738 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3739 }
3740 }
3741
3742 /* Main message dispatch loop. */
3743
3744 static void
3745 w32_msg_pump (deferred_msg * msg_buf)
3746 {
3747 MSG msg;
3748 int result;
3749 HWND focus_window;
3750
3751 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3752
3753 while (GetMessage (&msg, NULL, 0, 0))
3754 {
3755 if (msg.hwnd == NULL)
3756 {
3757 switch (msg.message)
3758 {
3759 case WM_NULL:
3760 /* Produced by complete_deferred_msg; just ignore. */
3761 break;
3762 case WM_EMACS_CREATEWINDOW:
3763 w32_createwindow ((struct frame *) msg.wParam);
3764 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3765 abort ();
3766 break;
3767 case WM_EMACS_SETLOCALE:
3768 SetThreadLocale (msg.wParam);
3769 /* Reply is not expected. */
3770 break;
3771 case WM_EMACS_SETKEYBOARDLAYOUT:
3772 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3773 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3774 result, 0))
3775 abort ();
3776 break;
3777 case WM_EMACS_REGISTER_HOT_KEY:
3778 focus_window = GetFocus ();
3779 if (focus_window != NULL)
3780 RegisterHotKey (focus_window,
3781 HOTKEY_ID (msg.wParam),
3782 HOTKEY_MODIFIERS (msg.wParam),
3783 HOTKEY_VK_CODE (msg.wParam));
3784 /* Reply is not expected. */
3785 break;
3786 case WM_EMACS_UNREGISTER_HOT_KEY:
3787 focus_window = GetFocus ();
3788 if (focus_window != NULL)
3789 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3790 /* Mark item as erased. NB: this code must be
3791 thread-safe. The next line is okay because the cons
3792 cell is never made into garbage and is not relocated by
3793 GC. */
3794 XCAR ((Lisp_Object) msg.lParam) = Qnil;
3795 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3796 abort ();
3797 break;
3798 case WM_EMACS_TOGGLE_LOCK_KEY:
3799 {
3800 int vk_code = (int) msg.wParam;
3801 int cur_state = (GetKeyState (vk_code) & 1);
3802 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3803
3804 /* NB: This code must be thread-safe. It is safe to
3805 call NILP because symbols are not relocated by GC,
3806 and pointer here is not touched by GC (so the markbit
3807 can't be set). Numbers are safe because they are
3808 immediate values. */
3809 if (NILP (new_state)
3810 || (NUMBERP (new_state)
3811 && (XUINT (new_state)) & 1 != cur_state))
3812 {
3813 one_w32_display_info.faked_key = vk_code;
3814
3815 keybd_event ((BYTE) vk_code,
3816 (BYTE) MapVirtualKey (vk_code, 0),
3817 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3818 keybd_event ((BYTE) vk_code,
3819 (BYTE) MapVirtualKey (vk_code, 0),
3820 KEYEVENTF_EXTENDEDKEY | 0, 0);
3821 keybd_event ((BYTE) vk_code,
3822 (BYTE) MapVirtualKey (vk_code, 0),
3823 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3824 cur_state = !cur_state;
3825 }
3826 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3827 cur_state, 0))
3828 abort ();
3829 }
3830 break;
3831 default:
3832 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3833 }
3834 }
3835 else
3836 {
3837 DispatchMessage (&msg);
3838 }
3839
3840 /* Exit nested loop when our deferred message has completed. */
3841 if (msg_buf->completed)
3842 break;
3843 }
3844 }
3845
3846 deferred_msg * deferred_msg_head;
3847
3848 static deferred_msg *
3849 find_deferred_msg (HWND hwnd, UINT msg)
3850 {
3851 deferred_msg * item;
3852
3853 /* Don't actually need synchronization for read access, since
3854 modification of single pointer is always atomic. */
3855 /* enter_crit (); */
3856
3857 for (item = deferred_msg_head; item != NULL; item = item->next)
3858 if (item->w32msg.msg.hwnd == hwnd
3859 && item->w32msg.msg.message == msg)
3860 break;
3861
3862 /* leave_crit (); */
3863
3864 return item;
3865 }
3866
3867 static LRESULT
3868 send_deferred_msg (deferred_msg * msg_buf,
3869 HWND hwnd,
3870 UINT msg,
3871 WPARAM wParam,
3872 LPARAM lParam)
3873 {
3874 /* Only input thread can send deferred messages. */
3875 if (GetCurrentThreadId () != dwWindowsThreadId)
3876 abort ();
3877
3878 /* It is an error to send a message that is already deferred. */
3879 if (find_deferred_msg (hwnd, msg) != NULL)
3880 abort ();
3881
3882 /* Enforced synchronization is not needed because this is the only
3883 function that alters deferred_msg_head, and the following critical
3884 section is guaranteed to only be serially reentered (since only the
3885 input thread can call us). */
3886
3887 /* enter_crit (); */
3888
3889 msg_buf->completed = 0;
3890 msg_buf->next = deferred_msg_head;
3891 deferred_msg_head = msg_buf;
3892 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3893
3894 /* leave_crit (); */
3895
3896 /* Start a new nested message loop to process other messages until
3897 this one is completed. */
3898 w32_msg_pump (msg_buf);
3899
3900 deferred_msg_head = msg_buf->next;
3901
3902 return msg_buf->result;
3903 }
3904
3905 void
3906 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3907 {
3908 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3909
3910 if (msg_buf == NULL)
3911 /* Message may have been cancelled, so don't abort(). */
3912 return;
3913
3914 msg_buf->result = result;
3915 msg_buf->completed = 1;
3916
3917 /* Ensure input thread is woken so it notices the completion. */
3918 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3919 }
3920
3921 void
3922 cancel_all_deferred_msgs ()
3923 {
3924 deferred_msg * item;
3925
3926 /* Don't actually need synchronization for read access, since
3927 modification of single pointer is always atomic. */
3928 /* enter_crit (); */
3929
3930 for (item = deferred_msg_head; item != NULL; item = item->next)
3931 {
3932 item->result = 0;
3933 item->completed = 1;
3934 }
3935
3936 /* leave_crit (); */
3937
3938 /* Ensure input thread is woken so it notices the completion. */
3939 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3940 }
3941
3942 DWORD
3943 w32_msg_worker (dw)
3944 DWORD dw;
3945 {
3946 MSG msg;
3947 deferred_msg dummy_buf;
3948
3949 /* Ensure our message queue is created */
3950
3951 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3952
3953 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3954 abort ();
3955
3956 memset (&dummy_buf, 0, sizeof (dummy_buf));
3957 dummy_buf.w32msg.msg.hwnd = NULL;
3958 dummy_buf.w32msg.msg.message = WM_NULL;
3959
3960 /* This is the inital message loop which should only exit when the
3961 application quits. */
3962 w32_msg_pump (&dummy_buf);
3963
3964 return 0;
3965 }
3966
3967 static void
3968 post_character_message (hwnd, msg, wParam, lParam, modifiers)
3969 HWND hwnd;
3970 UINT msg;
3971 WPARAM wParam;
3972 LPARAM lParam;
3973 DWORD modifiers;
3974
3975 {
3976 W32Msg wmsg;
3977
3978 wmsg.dwModifiers = modifiers;
3979
3980 /* Detect quit_char and set quit-flag directly. Note that we
3981 still need to post a message to ensure the main thread will be
3982 woken up if blocked in sys_select(), but we do NOT want to post
3983 the quit_char message itself (because it will usually be as if
3984 the user had typed quit_char twice). Instead, we post a dummy
3985 message that has no particular effect. */
3986 {
3987 int c = wParam;
3988 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
3989 c = make_ctrl_char (c) & 0377;
3990 if (c == quit_char
3991 || (wmsg.dwModifiers == 0 &&
3992 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
3993 {
3994 Vquit_flag = Qt;
3995
3996 /* The choice of message is somewhat arbitrary, as long as
3997 the main thread handler just ignores it. */
3998 msg = WM_NULL;
3999
4000 /* Interrupt any blocking system calls. */
4001 signal_quit ();
4002
4003 /* As a safety precaution, forcibly complete any deferred
4004 messages. This is a kludge, but I don't see any particularly
4005 clean way to handle the situation where a deferred message is
4006 "dropped" in the lisp thread, and will thus never be
4007 completed, eg. by the user trying to activate the menubar
4008 when the lisp thread is busy, and then typing C-g when the
4009 menubar doesn't open promptly (with the result that the
4010 menubar never responds at all because the deferred
4011 WM_INITMENU message is never completed). Another problem
4012 situation is when the lisp thread calls SendMessage (to send
4013 a window manager command) when a message has been deferred;
4014 the lisp thread gets blocked indefinitely waiting for the
4015 deferred message to be completed, which itself is waiting for
4016 the lisp thread to respond.
4017
4018 Note that we don't want to block the input thread waiting for
4019 a reponse from the lisp thread (although that would at least
4020 solve the deadlock problem above), because we want to be able
4021 to receive C-g to interrupt the lisp thread. */
4022 cancel_all_deferred_msgs ();
4023 }
4024 }
4025
4026 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4027 }
4028
4029 /* Main window procedure */
4030
4031 LRESULT CALLBACK
4032 w32_wnd_proc (hwnd, msg, wParam, lParam)
4033 HWND hwnd;
4034 UINT msg;
4035 WPARAM wParam;
4036 LPARAM lParam;
4037 {
4038 struct frame *f;
4039 struct w32_display_info *dpyinfo = &one_w32_display_info;
4040 W32Msg wmsg;
4041 int windows_translate;
4042 int key;
4043
4044 /* Note that it is okay to call x_window_to_frame, even though we are
4045 not running in the main lisp thread, because frame deletion
4046 requires the lisp thread to synchronize with this thread. Thus, if
4047 a frame struct is returned, it can be used without concern that the
4048 lisp thread might make it disappear while we are using it.
4049
4050 NB. Walking the frame list in this thread is safe (as long as
4051 writes of Lisp_Object slots are atomic, which they are on Windows).
4052 Although delete-frame can destructively modify the frame list while
4053 we are walking it, a garbage collection cannot occur until after
4054 delete-frame has synchronized with this thread.
4055
4056 It is also safe to use functions that make GDI calls, such as
4057 w32_clear_rect, because these functions must obtain a DC handle
4058 from the frame struct using get_frame_dc which is thread-aware. */
4059
4060 switch (msg)
4061 {
4062 case WM_ERASEBKGND:
4063 f = x_window_to_frame (dpyinfo, hwnd);
4064 if (f)
4065 {
4066 HDC hdc = get_frame_dc (f);
4067 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4068 w32_clear_rect (f, hdc, &wmsg.rect);
4069 release_frame_dc (f, hdc);
4070
4071 #if defined (W32_DEBUG_DISPLAY)
4072 DebPrint (("WM_ERASEBKGND: erasing %d,%d-%d,%d\n",
4073 wmsg.rect.left, wmsg.rect.top, wmsg.rect.right,
4074 wmsg.rect.bottom));
4075 #endif /* W32_DEBUG_DISPLAY */
4076 }
4077 return 1;
4078 case WM_PALETTECHANGED:
4079 /* ignore our own changes */
4080 if ((HWND)wParam != hwnd)
4081 {
4082 f = x_window_to_frame (dpyinfo, hwnd);
4083 if (f)
4084 /* get_frame_dc will realize our palette and force all
4085 frames to be redrawn if needed. */
4086 release_frame_dc (f, get_frame_dc (f));
4087 }
4088 return 0;
4089 case WM_PAINT:
4090 {
4091 PAINTSTRUCT paintStruct;
4092 RECT update_rect;
4093
4094 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4095 fails. Apparently this can happen under some
4096 circumstances. */
4097 if (!w32_strict_painting || GetUpdateRect (hwnd, &update_rect, FALSE))
4098 {
4099 enter_crit ();
4100 BeginPaint (hwnd, &paintStruct);
4101
4102 if (w32_strict_painting)
4103 /* The rectangles returned by GetUpdateRect and BeginPaint
4104 do not always match. GetUpdateRect seems to be the
4105 more reliable of the two. */
4106 wmsg.rect = update_rect;
4107 else
4108 wmsg.rect = paintStruct.rcPaint;
4109
4110 #if defined (W32_DEBUG_DISPLAY)
4111 DebPrint (("WM_PAINT: painting %d,%d-%d,%d\n", wmsg.rect.left,
4112 wmsg.rect.top, wmsg.rect.right, wmsg.rect.bottom));
4113 DebPrint (("WM_PAINT: update region is %d,%d-%d,%d\n",
4114 update_rect.left, update_rect.top,
4115 update_rect.right, update_rect.bottom));
4116 #endif
4117 EndPaint (hwnd, &paintStruct);
4118 leave_crit ();
4119
4120 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4121
4122 return 0;
4123 }
4124
4125 /* If GetUpdateRect returns 0 (meaning there is no update
4126 region), assume the whole window needs to be repainted. */
4127 GetClientRect(hwnd, &wmsg.rect);
4128 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4129 return 0;
4130 }
4131
4132 case WM_INPUTLANGCHANGE:
4133 /* Inform lisp thread of keyboard layout changes. */
4134 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4135
4136 /* Clear dead keys in the keyboard state; for simplicity only
4137 preserve modifier key states. */
4138 {
4139 int i;
4140 BYTE keystate[256];
4141
4142 GetKeyboardState (keystate);
4143 for (i = 0; i < 256; i++)
4144 if (1
4145 && i != VK_SHIFT
4146 && i != VK_LSHIFT
4147 && i != VK_RSHIFT
4148 && i != VK_CAPITAL
4149 && i != VK_NUMLOCK
4150 && i != VK_SCROLL
4151 && i != VK_CONTROL
4152 && i != VK_LCONTROL
4153 && i != VK_RCONTROL
4154 && i != VK_MENU
4155 && i != VK_LMENU
4156 && i != VK_RMENU
4157 && i != VK_LWIN
4158 && i != VK_RWIN)
4159 keystate[i] = 0;
4160 SetKeyboardState (keystate);
4161 }
4162 goto dflt;
4163
4164 case WM_HOTKEY:
4165 /* Synchronize hot keys with normal input. */
4166 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4167 return (0);
4168
4169 case WM_KEYUP:
4170 case WM_SYSKEYUP:
4171 record_keyup (wParam, lParam);
4172 goto dflt;
4173
4174 case WM_KEYDOWN:
4175 case WM_SYSKEYDOWN:
4176 /* Ignore keystrokes we fake ourself; see below. */
4177 if (dpyinfo->faked_key == wParam)
4178 {
4179 dpyinfo->faked_key = 0;
4180 /* Make sure TranslateMessage sees them though (as long as
4181 they don't produce WM_CHAR messages). This ensures that
4182 indicator lights are toggled promptly on Windows 9x, for
4183 example. */
4184 if (lispy_function_keys[wParam] != 0)
4185 {
4186 windows_translate = 1;
4187 goto translate;
4188 }
4189 return 0;
4190 }
4191
4192 /* Synchronize modifiers with current keystroke. */
4193 sync_modifiers ();
4194 record_keydown (wParam, lParam);
4195 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4196
4197 windows_translate = 0;
4198
4199 switch (wParam)
4200 {
4201 case VK_LWIN:
4202 if (NILP (Vw32_pass_lwindow_to_system))
4203 {
4204 /* Prevent system from acting on keyup (which opens the
4205 Start menu if no other key was pressed) by simulating a
4206 press of Space which we will ignore. */
4207 if (GetAsyncKeyState (wParam) & 1)
4208 {
4209 if (NUMBERP (Vw32_phantom_key_code))
4210 key = XUINT (Vw32_phantom_key_code) & 255;
4211 else
4212 key = VK_SPACE;
4213 dpyinfo->faked_key = key;
4214 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4215 }
4216 }
4217 if (!NILP (Vw32_lwindow_modifier))
4218 return 0;
4219 break;
4220 case VK_RWIN:
4221 if (NILP (Vw32_pass_rwindow_to_system))
4222 {
4223 if (GetAsyncKeyState (wParam) & 1)
4224 {
4225 if (NUMBERP (Vw32_phantom_key_code))
4226 key = XUINT (Vw32_phantom_key_code) & 255;
4227 else
4228 key = VK_SPACE;
4229 dpyinfo->faked_key = key;
4230 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4231 }
4232 }
4233 if (!NILP (Vw32_rwindow_modifier))
4234 return 0;
4235 break;
4236 case VK_APPS:
4237 if (!NILP (Vw32_apps_modifier))
4238 return 0;
4239 break;
4240 case VK_MENU:
4241 if (NILP (Vw32_pass_alt_to_system))
4242 /* Prevent DefWindowProc from activating the menu bar if an
4243 Alt key is pressed and released by itself. */
4244 return 0;
4245 windows_translate = 1;
4246 break;
4247 case VK_CAPITAL:
4248 /* Decide whether to treat as modifier or function key. */
4249 if (NILP (Vw32_enable_caps_lock))
4250 goto disable_lock_key;
4251 windows_translate = 1;
4252 break;
4253 case VK_NUMLOCK:
4254 /* Decide whether to treat as modifier or function key. */
4255 if (NILP (Vw32_enable_num_lock))
4256 goto disable_lock_key;
4257 windows_translate = 1;
4258 break;
4259 case VK_SCROLL:
4260 /* Decide whether to treat as modifier or function key. */
4261 if (NILP (Vw32_scroll_lock_modifier))
4262 goto disable_lock_key;
4263 windows_translate = 1;
4264 break;
4265 disable_lock_key:
4266 /* Ensure the appropriate lock key state (and indicator light)
4267 remains in the same state. We do this by faking another
4268 press of the relevant key. Apparently, this really is the
4269 only way to toggle the state of the indicator lights. */
4270 dpyinfo->faked_key = wParam;
4271 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4272 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4273 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4274 KEYEVENTF_EXTENDEDKEY | 0, 0);
4275 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4276 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4277 /* Ensure indicator lights are updated promptly on Windows 9x
4278 (TranslateMessage apparently does this), after forwarding
4279 input event. */
4280 post_character_message (hwnd, msg, wParam, lParam,
4281 w32_get_key_modifiers (wParam, lParam));
4282 windows_translate = 1;
4283 break;
4284 case VK_CONTROL:
4285 case VK_SHIFT:
4286 case VK_PROCESSKEY: /* Generated by IME. */
4287 windows_translate = 1;
4288 break;
4289 case VK_CANCEL:
4290 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4291 which is confusing for purposes of key binding; convert
4292 VK_CANCEL events into VK_PAUSE events. */
4293 wParam = VK_PAUSE;
4294 break;
4295 case VK_PAUSE:
4296 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4297 for purposes of key binding; convert these back into
4298 VK_NUMLOCK events, at least when we want to see NumLock key
4299 presses. (Note that there is never any possibility that
4300 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4301 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4302 wParam = VK_NUMLOCK;
4303 break;
4304 default:
4305 /* If not defined as a function key, change it to a WM_CHAR message. */
4306 if (lispy_function_keys[wParam] == 0)
4307 {
4308 DWORD modifiers = construct_console_modifiers ();
4309
4310 if (!NILP (Vw32_recognize_altgr)
4311 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4312 {
4313 /* Always let TranslateMessage handle AltGr key chords;
4314 for some reason, ToAscii doesn't always process AltGr
4315 chords correctly. */
4316 windows_translate = 1;
4317 }
4318 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4319 {
4320 /* Handle key chords including any modifiers other
4321 than shift directly, in order to preserve as much
4322 modifier information as possible. */
4323 if ('A' <= wParam && wParam <= 'Z')
4324 {
4325 /* Don't translate modified alphabetic keystrokes,
4326 so the user doesn't need to constantly switch
4327 layout to type control or meta keystrokes when
4328 the normal layout translates alphabetic
4329 characters to non-ascii characters. */
4330 if (!modifier_set (VK_SHIFT))
4331 wParam += ('a' - 'A');
4332 msg = WM_CHAR;
4333 }
4334 else
4335 {
4336 /* Try to handle other keystrokes by determining the
4337 base character (ie. translating the base key plus
4338 shift modifier). */
4339 int add;
4340 int isdead = 0;
4341 KEY_EVENT_RECORD key;
4342
4343 key.bKeyDown = TRUE;
4344 key.wRepeatCount = 1;
4345 key.wVirtualKeyCode = wParam;
4346 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4347 key.uChar.AsciiChar = 0;
4348 key.dwControlKeyState = modifiers;
4349
4350 add = w32_kbd_patch_key (&key);
4351 /* 0 means an unrecognised keycode, negative means
4352 dead key. Ignore both. */
4353 while (--add >= 0)
4354 {
4355 /* Forward asciified character sequence. */
4356 post_character_message
4357 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4358 w32_get_key_modifiers (wParam, lParam));
4359 w32_kbd_patch_key (&key);
4360 }
4361 return 0;
4362 }
4363 }
4364 else
4365 {
4366 /* Let TranslateMessage handle everything else. */
4367 windows_translate = 1;
4368 }
4369 }
4370 }
4371
4372 translate:
4373 if (windows_translate)
4374 {
4375 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4376
4377 windows_msg.time = GetMessageTime ();
4378 TranslateMessage (&windows_msg);
4379 goto dflt;
4380 }
4381
4382 /* Fall through */
4383
4384 case WM_SYSCHAR:
4385 case WM_CHAR:
4386 post_character_message (hwnd, msg, wParam, lParam,
4387 w32_get_key_modifiers (wParam, lParam));
4388 break;
4389
4390 /* Simulate middle mouse button events when left and right buttons
4391 are used together, but only if user has two button mouse. */
4392 case WM_LBUTTONDOWN:
4393 case WM_RBUTTONDOWN:
4394 if (XINT (Vw32_num_mouse_buttons) > 2)
4395 goto handle_plain_button;
4396
4397 {
4398 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4399 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4400
4401 if (button_state & this)
4402 return 0;
4403
4404 if (button_state == 0)
4405 SetCapture (hwnd);
4406
4407 button_state |= this;
4408
4409 if (button_state & other)
4410 {
4411 if (mouse_button_timer)
4412 {
4413 KillTimer (hwnd, mouse_button_timer);
4414 mouse_button_timer = 0;
4415
4416 /* Generate middle mouse event instead. */
4417 msg = WM_MBUTTONDOWN;
4418 button_state |= MMOUSE;
4419 }
4420 else if (button_state & MMOUSE)
4421 {
4422 /* Ignore button event if we've already generated a
4423 middle mouse down event. This happens if the
4424 user releases and press one of the two buttons
4425 after we've faked a middle mouse event. */
4426 return 0;
4427 }
4428 else
4429 {
4430 /* Flush out saved message. */
4431 post_msg (&saved_mouse_button_msg);
4432 }
4433 wmsg.dwModifiers = w32_get_modifiers ();
4434 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4435
4436 /* Clear message buffer. */
4437 saved_mouse_button_msg.msg.hwnd = 0;
4438 }
4439 else
4440 {
4441 /* Hold onto message for now. */
4442 mouse_button_timer =
4443 SetTimer (hwnd, MOUSE_BUTTON_ID,
4444 XINT (Vw32_mouse_button_tolerance), NULL);
4445 saved_mouse_button_msg.msg.hwnd = hwnd;
4446 saved_mouse_button_msg.msg.message = msg;
4447 saved_mouse_button_msg.msg.wParam = wParam;
4448 saved_mouse_button_msg.msg.lParam = lParam;
4449 saved_mouse_button_msg.msg.time = GetMessageTime ();
4450 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4451 }
4452 }
4453 return 0;
4454
4455 case WM_LBUTTONUP:
4456 case WM_RBUTTONUP:
4457 if (XINT (Vw32_num_mouse_buttons) > 2)
4458 goto handle_plain_button;
4459
4460 {
4461 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4462 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4463
4464 if ((button_state & this) == 0)
4465 return 0;
4466
4467 button_state &= ~this;
4468
4469 if (button_state & MMOUSE)
4470 {
4471 /* Only generate event when second button is released. */
4472 if ((button_state & other) == 0)
4473 {
4474 msg = WM_MBUTTONUP;
4475 button_state &= ~MMOUSE;
4476
4477 if (button_state) abort ();
4478 }
4479 else
4480 return 0;
4481 }
4482 else
4483 {
4484 /* Flush out saved message if necessary. */
4485 if (saved_mouse_button_msg.msg.hwnd)
4486 {
4487 post_msg (&saved_mouse_button_msg);
4488 }
4489 }
4490 wmsg.dwModifiers = w32_get_modifiers ();
4491 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4492
4493 /* Always clear message buffer and cancel timer. */
4494 saved_mouse_button_msg.msg.hwnd = 0;
4495 KillTimer (hwnd, mouse_button_timer);
4496 mouse_button_timer = 0;
4497
4498 if (button_state == 0)
4499 ReleaseCapture ();
4500 }
4501 return 0;
4502
4503 case WM_MBUTTONDOWN:
4504 case WM_MBUTTONUP:
4505 handle_plain_button:
4506 {
4507 BOOL up;
4508 int button;
4509
4510 if (parse_button (msg, &button, &up))
4511 {
4512 if (up) ReleaseCapture ();
4513 else SetCapture (hwnd);
4514 button = (button == 0) ? LMOUSE :
4515 ((button == 1) ? MMOUSE : RMOUSE);
4516 if (up)
4517 button_state &= ~button;
4518 else
4519 button_state |= button;
4520 }
4521 }
4522
4523 wmsg.dwModifiers = w32_get_modifiers ();
4524 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4525 return 0;
4526
4527 case WM_VSCROLL:
4528 case WM_MOUSEMOVE:
4529 if (XINT (Vw32_mouse_move_interval) <= 0
4530 || (msg == WM_MOUSEMOVE && button_state == 0))
4531 {
4532 wmsg.dwModifiers = w32_get_modifiers ();
4533 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4534 return 0;
4535 }
4536
4537 /* Hang onto mouse move and scroll messages for a bit, to avoid
4538 sending such events to Emacs faster than it can process them.
4539 If we get more events before the timer from the first message
4540 expires, we just replace the first message. */
4541
4542 if (saved_mouse_move_msg.msg.hwnd == 0)
4543 mouse_move_timer =
4544 SetTimer (hwnd, MOUSE_MOVE_ID,
4545 XINT (Vw32_mouse_move_interval), NULL);
4546
4547 /* Hold onto message for now. */
4548 saved_mouse_move_msg.msg.hwnd = hwnd;
4549 saved_mouse_move_msg.msg.message = msg;
4550 saved_mouse_move_msg.msg.wParam = wParam;
4551 saved_mouse_move_msg.msg.lParam = lParam;
4552 saved_mouse_move_msg.msg.time = GetMessageTime ();
4553 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4554
4555 return 0;
4556
4557 case WM_MOUSEWHEEL:
4558 wmsg.dwModifiers = w32_get_modifiers ();
4559 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4560 return 0;
4561
4562 case WM_DROPFILES:
4563 wmsg.dwModifiers = w32_get_modifiers ();
4564 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4565 return 0;
4566
4567 case WM_TIMER:
4568 /* Flush out saved messages if necessary. */
4569 if (wParam == mouse_button_timer)
4570 {
4571 if (saved_mouse_button_msg.msg.hwnd)
4572 {
4573 post_msg (&saved_mouse_button_msg);
4574 saved_mouse_button_msg.msg.hwnd = 0;
4575 }
4576 KillTimer (hwnd, mouse_button_timer);
4577 mouse_button_timer = 0;
4578 }
4579 else if (wParam == mouse_move_timer)
4580 {
4581 if (saved_mouse_move_msg.msg.hwnd)
4582 {
4583 post_msg (&saved_mouse_move_msg);
4584 saved_mouse_move_msg.msg.hwnd = 0;
4585 }
4586 KillTimer (hwnd, mouse_move_timer);
4587 mouse_move_timer = 0;
4588 }
4589 return 0;
4590
4591 case WM_NCACTIVATE:
4592 /* Windows doesn't send us focus messages when putting up and
4593 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4594 The only indication we get that something happened is receiving
4595 this message afterwards. So this is a good time to reset our
4596 keyboard modifiers' state. */
4597 reset_modifiers ();
4598 goto dflt;
4599
4600 case WM_INITMENU:
4601 button_state = 0;
4602 ReleaseCapture ();
4603 /* We must ensure menu bar is fully constructed and up to date
4604 before allowing user interaction with it. To achieve this
4605 we send this message to the lisp thread and wait for a
4606 reply (whose value is not actually needed) to indicate that
4607 the menu bar is now ready for use, so we can now return.
4608
4609 To remain responsive in the meantime, we enter a nested message
4610 loop that can process all other messages.
4611
4612 However, we skip all this if the message results from calling
4613 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4614 thread a message because it is blocked on us at this point. We
4615 set menubar_active before calling TrackPopupMenu to indicate
4616 this (there is no possibility of confusion with real menubar
4617 being active). */
4618
4619 f = x_window_to_frame (dpyinfo, hwnd);
4620 if (f
4621 && (f->output_data.w32->menubar_active
4622 /* We can receive this message even in the absence of a
4623 menubar (ie. when the system menu is activated) - in this
4624 case we do NOT want to forward the message, otherwise it
4625 will cause the menubar to suddenly appear when the user
4626 had requested it to be turned off! */
4627 || f->output_data.w32->menubar_widget == NULL))
4628 return 0;
4629
4630 {
4631 deferred_msg msg_buf;
4632
4633 /* Detect if message has already been deferred; in this case
4634 we cannot return any sensible value to ignore this. */
4635 if (find_deferred_msg (hwnd, msg) != NULL)
4636 abort ();
4637
4638 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4639 }
4640
4641 case WM_EXITMENULOOP:
4642 f = x_window_to_frame (dpyinfo, hwnd);
4643
4644 /* Indicate that menubar can be modified again. */
4645 if (f)
4646 f->output_data.w32->menubar_active = 0;
4647 goto dflt;
4648
4649 case WM_MENUSELECT:
4650 wmsg.dwModifiers = w32_get_modifiers ();
4651 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4652 return 0;
4653
4654 case WM_MEASUREITEM:
4655 f = x_window_to_frame (dpyinfo, hwnd);
4656 if (f)
4657 {
4658 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4659
4660 if (pMis->CtlType == ODT_MENU)
4661 {
4662 /* Work out dimensions for popup menu titles. */
4663 char * title = (char *) pMis->itemData;
4664 HDC hdc = GetDC (hwnd);
4665 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4666 LOGFONT menu_logfont;
4667 HFONT old_font;
4668 SIZE size;
4669
4670 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4671 menu_logfont.lfWeight = FW_BOLD;
4672 menu_font = CreateFontIndirect (&menu_logfont);
4673 old_font = SelectObject (hdc, menu_font);
4674
4675 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4676 if (title)
4677 {
4678 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4679 pMis->itemWidth = size.cx;
4680 if (pMis->itemHeight < size.cy)
4681 pMis->itemHeight = size.cy;
4682 }
4683 else
4684 pMis->itemWidth = 0;
4685
4686 SelectObject (hdc, old_font);
4687 DeleteObject (menu_font);
4688 ReleaseDC (hwnd, hdc);
4689 return TRUE;
4690 }
4691 }
4692 return 0;
4693
4694 case WM_DRAWITEM:
4695 f = x_window_to_frame (dpyinfo, hwnd);
4696 if (f)
4697 {
4698 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4699
4700 if (pDis->CtlType == ODT_MENU)
4701 {
4702 /* Draw popup menu title. */
4703 char * title = (char *) pDis->itemData;
4704 if (title)
4705 {
4706 HDC hdc = pDis->hDC;
4707 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4708 LOGFONT menu_logfont;
4709 HFONT old_font;
4710
4711 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4712 menu_logfont.lfWeight = FW_BOLD;
4713 menu_font = CreateFontIndirect (&menu_logfont);
4714 old_font = SelectObject (hdc, menu_font);
4715
4716 /* Always draw title as if not selected. */
4717 ExtTextOut (hdc,
4718 pDis->rcItem.left
4719 + GetSystemMetrics (SM_CXMENUCHECK),
4720 pDis->rcItem.top,
4721 ETO_OPAQUE, &pDis->rcItem,
4722 title, strlen (title), NULL);
4723
4724 SelectObject (hdc, old_font);
4725 DeleteObject (menu_font);
4726 }
4727 return TRUE;
4728 }
4729 }
4730 return 0;
4731
4732 #if 0
4733 /* Still not right - can't distinguish between clicks in the
4734 client area of the frame from clicks forwarded from the scroll
4735 bars - may have to hook WM_NCHITTEST to remember the mouse
4736 position and then check if it is in the client area ourselves. */
4737 case WM_MOUSEACTIVATE:
4738 /* Discard the mouse click that activates a frame, allowing the
4739 user to click anywhere without changing point (or worse!).
4740 Don't eat mouse clicks on scrollbars though!! */
4741 if (LOWORD (lParam) == HTCLIENT )
4742 return MA_ACTIVATEANDEAT;
4743 goto dflt;
4744 #endif
4745
4746 case WM_ACTIVATEAPP:
4747 case WM_ACTIVATE:
4748 case WM_WINDOWPOSCHANGED:
4749 case WM_SHOWWINDOW:
4750 /* Inform lisp thread that a frame might have just been obscured
4751 or exposed, so should recheck visibility of all frames. */
4752 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4753 goto dflt;
4754
4755 case WM_SETFOCUS:
4756 dpyinfo->faked_key = 0;
4757 reset_modifiers ();
4758 register_hot_keys (hwnd);
4759 goto command;
4760 case WM_KILLFOCUS:
4761 unregister_hot_keys (hwnd);
4762 button_state = 0;
4763 ReleaseCapture ();
4764 case WM_MOVE:
4765 case WM_SIZE:
4766 case WM_COMMAND:
4767 command:
4768 wmsg.dwModifiers = w32_get_modifiers ();
4769 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4770 goto dflt;
4771
4772 case WM_CLOSE:
4773 wmsg.dwModifiers = w32_get_modifiers ();
4774 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4775 return 0;
4776
4777 case WM_WINDOWPOSCHANGING:
4778 {
4779 WINDOWPLACEMENT wp;
4780 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4781
4782 wp.length = sizeof (WINDOWPLACEMENT);
4783 GetWindowPlacement (hwnd, &wp);
4784
4785 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4786 {
4787 RECT rect;
4788 int wdiff;
4789 int hdiff;
4790 DWORD font_width;
4791 DWORD line_height;
4792 DWORD internal_border;
4793 DWORD scrollbar_extra;
4794 RECT wr;
4795
4796 wp.length = sizeof(wp);
4797 GetWindowRect (hwnd, &wr);
4798
4799 enter_crit ();
4800
4801 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4802 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4803 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4804 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
4805
4806 leave_crit ();
4807
4808 memset (&rect, 0, sizeof (rect));
4809 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4810 GetMenu (hwnd) != NULL);
4811
4812 /* Force width and height of client area to be exact
4813 multiples of the character cell dimensions. */
4814 wdiff = (lppos->cx - (rect.right - rect.left)
4815 - 2 * internal_border - scrollbar_extra)
4816 % font_width;
4817 hdiff = (lppos->cy - (rect.bottom - rect.top)
4818 - 2 * internal_border)
4819 % line_height;
4820
4821 if (wdiff || hdiff)
4822 {
4823 /* For right/bottom sizing we can just fix the sizes.
4824 However for top/left sizing we will need to fix the X
4825 and Y positions as well. */
4826
4827 lppos->cx -= wdiff;
4828 lppos->cy -= hdiff;
4829
4830 if (wp.showCmd != SW_SHOWMAXIMIZED
4831 && (lppos->flags & SWP_NOMOVE) == 0)
4832 {
4833 if (lppos->x != wr.left || lppos->y != wr.top)
4834 {
4835 lppos->x += wdiff;
4836 lppos->y += hdiff;
4837 }
4838 else
4839 {
4840 lppos->flags |= SWP_NOMOVE;
4841 }
4842 }
4843
4844 return 0;
4845 }
4846 }
4847 }
4848
4849 goto dflt;
4850
4851 case WM_GETMINMAXINFO:
4852 /* Hack to correct bug that allows Emacs frames to be resized
4853 below the Minimum Tracking Size. */
4854 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
4855 return 0;
4856
4857 case WM_EMACS_CREATESCROLLBAR:
4858 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
4859 (struct scroll_bar *) lParam);
4860
4861 case WM_EMACS_SHOWWINDOW:
4862 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4863
4864 case WM_EMACS_SETFOREGROUND:
4865 {
4866 HWND foreground_window;
4867 DWORD foreground_thread, retval;
4868
4869 /* On NT 5.0, and apparently Windows 98, it is necessary to
4870 attach to the thread that currently has focus in order to
4871 pull the focus away from it. */
4872 foreground_window = GetForegroundWindow ();
4873 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4874 if (!foreground_window
4875 || foreground_thread == GetCurrentThreadId ()
4876 || !AttachThreadInput (GetCurrentThreadId (),
4877 foreground_thread, TRUE))
4878 foreground_thread = 0;
4879
4880 retval = SetForegroundWindow ((HWND) wParam);
4881
4882 /* Detach from the previous foreground thread. */
4883 if (foreground_thread)
4884 AttachThreadInput (GetCurrentThreadId (),
4885 foreground_thread, FALSE);
4886
4887 return retval;
4888 }
4889
4890 case WM_EMACS_SETWINDOWPOS:
4891 {
4892 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4893 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4894 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4895 }
4896
4897 case WM_EMACS_DESTROYWINDOW:
4898 DragAcceptFiles ((HWND) wParam, FALSE);
4899 return DestroyWindow ((HWND) wParam);
4900
4901 case WM_EMACS_TRACKPOPUPMENU:
4902 {
4903 UINT flags;
4904 POINT *pos;
4905 int retval;
4906 pos = (POINT *)lParam;
4907 flags = TPM_CENTERALIGN;
4908 if (button_state & LMOUSE)
4909 flags |= TPM_LEFTBUTTON;
4910 else if (button_state & RMOUSE)
4911 flags |= TPM_RIGHTBUTTON;
4912
4913 /* Remember we did a SetCapture on the initial mouse down event,
4914 so for safety, we make sure the capture is cancelled now. */
4915 ReleaseCapture ();
4916 button_state = 0;
4917
4918 /* Use menubar_active to indicate that WM_INITMENU is from
4919 TrackPopupMenu below, and should be ignored. */
4920 f = x_window_to_frame (dpyinfo, hwnd);
4921 if (f)
4922 f->output_data.w32->menubar_active = 1;
4923
4924 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4925 0, hwnd, NULL))
4926 {
4927 MSG amsg;
4928 /* Eat any mouse messages during popupmenu */
4929 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4930 PM_REMOVE));
4931 /* Get the menu selection, if any */
4932 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4933 {
4934 retval = LOWORD (amsg.wParam);
4935 }
4936 else
4937 {
4938 retval = 0;
4939 }
4940 }
4941 else
4942 {
4943 retval = -1;
4944 }
4945
4946 return retval;
4947 }
4948
4949 default:
4950 /* Check for messages registered at runtime. */
4951 if (msg == msh_mousewheel)
4952 {
4953 wmsg.dwModifiers = w32_get_modifiers ();
4954 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4955 return 0;
4956 }
4957
4958 dflt:
4959 return DefWindowProc (hwnd, msg, wParam, lParam);
4960 }
4961
4962
4963 /* The most common default return code for handled messages is 0. */
4964 return 0;
4965 }
4966
4967 void
4968 my_create_window (f)
4969 struct frame * f;
4970 {
4971 MSG msg;
4972
4973 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4974 abort ();
4975 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4976 }
4977
4978 /* Create and set up the w32 window for frame F. */
4979
4980 static void
4981 w32_window (f, window_prompting, minibuffer_only)
4982 struct frame *f;
4983 long window_prompting;
4984 int minibuffer_only;
4985 {
4986 BLOCK_INPUT;
4987
4988 /* Use the resource name as the top-level window name
4989 for looking up resources. Make a non-Lisp copy
4990 for the window manager, so GC relocation won't bother it.
4991
4992 Elsewhere we specify the window name for the window manager. */
4993
4994 {
4995 char *str = (char *) XSTRING (Vx_resource_name)->data;
4996 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4997 strcpy (f->namebuf, str);
4998 }
4999
5000 my_create_window (f);
5001
5002 validate_x_resource_name ();
5003
5004 /* x_set_name normally ignores requests to set the name if the
5005 requested name is the same as the current name. This is the one
5006 place where that assumption isn't correct; f->name is set, but
5007 the server hasn't been told. */
5008 {
5009 Lisp_Object name;
5010 int explicit = f->explicit_name;
5011
5012 f->explicit_name = 0;
5013 name = f->name;
5014 f->name = Qnil;
5015 x_set_name (f, name, explicit);
5016 }
5017
5018 UNBLOCK_INPUT;
5019
5020 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5021 initialize_frame_menubar (f);
5022
5023 if (FRAME_W32_WINDOW (f) == 0)
5024 error ("Unable to create window");
5025 }
5026
5027 /* Handle the icon stuff for this window. Perhaps later we might
5028 want an x_set_icon_position which can be called interactively as
5029 well. */
5030
5031 static void
5032 x_icon (f, parms)
5033 struct frame *f;
5034 Lisp_Object parms;
5035 {
5036 Lisp_Object icon_x, icon_y;
5037
5038 /* Set the position of the icon. Note that Windows 95 groups all
5039 icons in the tray. */
5040 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5041 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5042 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5043 {
5044 CHECK_NUMBER (icon_x, 0);
5045 CHECK_NUMBER (icon_y, 0);
5046 }
5047 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5048 error ("Both left and top icon corners of icon must be specified");
5049
5050 BLOCK_INPUT;
5051
5052 if (! EQ (icon_x, Qunbound))
5053 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5054
5055 #if 0 /* TODO */
5056 /* Start up iconic or window? */
5057 x_wm_set_window_state
5058 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5059 ? IconicState
5060 : NormalState));
5061
5062 x_text_icon (f, (char *) XSTRING ((!NILP (f->icon_name)
5063 ? f->icon_name
5064 : f->name))->data);
5065 #endif
5066
5067 UNBLOCK_INPUT;
5068 }
5069
5070
5071 static void
5072 x_make_gc (f)
5073 struct frame *f;
5074 {
5075 XGCValues gc_values;
5076
5077 BLOCK_INPUT;
5078
5079 /* Create the GC's of this frame.
5080 Note that many default values are used. */
5081
5082 /* Normal video */
5083 gc_values.font = f->output_data.w32->font;
5084
5085 /* Cursor has cursor-color background, background-color foreground. */
5086 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5087 gc_values.background = f->output_data.w32->cursor_pixel;
5088 f->output_data.w32->cursor_gc
5089 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5090 (GCFont | GCForeground | GCBackground),
5091 &gc_values);
5092
5093 /* Reliefs. */
5094 f->output_data.w32->white_relief.gc = 0;
5095 f->output_data.w32->black_relief.gc = 0;
5096
5097 UNBLOCK_INPUT;
5098 }
5099
5100
5101 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5102 1, 1, 0,
5103 "Make a new window, which is called a \"frame\" in Emacs terms.\n\
5104 Returns an Emacs frame object.\n\
5105 ALIST is an alist of frame parameters.\n\
5106 If the parameters specify that the frame should not have a minibuffer,\n\
5107 and do not specify a specific minibuffer window to use,\n\
5108 then `default-minibuffer-frame' must be a frame whose minibuffer can\n\
5109 be shared by the new frame.\n\
5110 \n\
5111 This function is an internal primitive--use `make-frame' instead.")
5112 (parms)
5113 Lisp_Object parms;
5114 {
5115 struct frame *f;
5116 Lisp_Object frame, tem;
5117 Lisp_Object name;
5118 int minibuffer_only = 0;
5119 long window_prompting = 0;
5120 int width, height;
5121 int count = specpdl_ptr - specpdl;
5122 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5123 Lisp_Object display;
5124 struct w32_display_info *dpyinfo = NULL;
5125 Lisp_Object parent;
5126 struct kboard *kb;
5127
5128 check_w32 ();
5129
5130 /* Use this general default value to start with
5131 until we know if this frame has a specified name. */
5132 Vx_resource_name = Vinvocation_name;
5133
5134 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5135 if (EQ (display, Qunbound))
5136 display = Qnil;
5137 dpyinfo = check_x_display_info (display);
5138 #ifdef MULTI_KBOARD
5139 kb = dpyinfo->kboard;
5140 #else
5141 kb = &the_only_kboard;
5142 #endif
5143
5144 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5145 if (!STRINGP (name)
5146 && ! EQ (name, Qunbound)
5147 && ! NILP (name))
5148 error ("Invalid frame name--not a string or nil");
5149
5150 if (STRINGP (name))
5151 Vx_resource_name = name;
5152
5153 /* See if parent window is specified. */
5154 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5155 if (EQ (parent, Qunbound))
5156 parent = Qnil;
5157 if (! NILP (parent))
5158 CHECK_NUMBER (parent, 0);
5159
5160 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5161 /* No need to protect DISPLAY because that's not used after passing
5162 it to make_frame_without_minibuffer. */
5163 frame = Qnil;
5164 GCPRO4 (parms, parent, name, frame);
5165 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5166 RES_TYPE_SYMBOL);
5167 if (EQ (tem, Qnone) || NILP (tem))
5168 f = make_frame_without_minibuffer (Qnil, kb, display);
5169 else if (EQ (tem, Qonly))
5170 {
5171 f = make_minibuffer_frame ();
5172 minibuffer_only = 1;
5173 }
5174 else if (WINDOWP (tem))
5175 f = make_frame_without_minibuffer (tem, kb, display);
5176 else
5177 f = make_frame (1);
5178
5179 XSETFRAME (frame, f);
5180
5181 /* Note that Windows does support scroll bars. */
5182 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5183 /* By default, make scrollbars the system standard width. */
5184 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5185
5186 f->output_method = output_w32;
5187 f->output_data.w32 =
5188 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5189 bzero (f->output_data.w32, sizeof (struct w32_output));
5190
5191 FRAME_FONTSET (f) = -1;
5192
5193 f->icon_name
5194 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5195 if (! STRINGP (f->icon_name))
5196 f->icon_name = Qnil;
5197
5198 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5199 #ifdef MULTI_KBOARD
5200 FRAME_KBOARD (f) = kb;
5201 #endif
5202
5203 /* Specify the parent under which to make this window. */
5204
5205 if (!NILP (parent))
5206 {
5207 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5208 f->output_data.w32->explicit_parent = 1;
5209 }
5210 else
5211 {
5212 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5213 f->output_data.w32->explicit_parent = 0;
5214 }
5215
5216 /* Set the name; the functions to which we pass f expect the name to
5217 be set. */
5218 if (EQ (name, Qunbound) || NILP (name))
5219 {
5220 f->name = build_string (dpyinfo->w32_id_name);
5221 f->explicit_name = 0;
5222 }
5223 else
5224 {
5225 f->name = name;
5226 f->explicit_name = 1;
5227 /* use the frame's title when getting resources for this frame. */
5228 specbind (Qx_resource_name, name);
5229 }
5230
5231 /* Extract the window parameters from the supplied values
5232 that are needed to determine window geometry. */
5233 {
5234 Lisp_Object font;
5235
5236 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5237
5238 BLOCK_INPUT;
5239 /* First, try whatever font the caller has specified. */
5240 if (STRINGP (font))
5241 {
5242 tem = Fquery_fontset (font, Qnil);
5243 if (STRINGP (tem))
5244 font = x_new_fontset (f, XSTRING (tem)->data);
5245 else
5246 font = x_new_font (f, XSTRING (font)->data);
5247 }
5248 /* Try out a font which we hope has bold and italic variations. */
5249 if (!STRINGP (font))
5250 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5251 if (! STRINGP (font))
5252 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5253 /* If those didn't work, look for something which will at least work. */
5254 if (! STRINGP (font))
5255 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5256 UNBLOCK_INPUT;
5257 if (! STRINGP (font))
5258 font = build_string ("Fixedsys");
5259
5260 x_default_parameter (f, parms, Qfont, font,
5261 "font", "Font", RES_TYPE_STRING);
5262 }
5263
5264 x_default_parameter (f, parms, Qborder_width, make_number (2),
5265 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5266 /* This defaults to 2 in order to match xterm. We recognize either
5267 internalBorderWidth or internalBorder (which is what xterm calls
5268 it). */
5269 if (NILP (Fassq (Qinternal_border_width, parms)))
5270 {
5271 Lisp_Object value;
5272
5273 value = w32_get_arg (parms, Qinternal_border_width,
5274 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5275 if (! EQ (value, Qunbound))
5276 parms = Fcons (Fcons (Qinternal_border_width, value),
5277 parms);
5278 }
5279 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5280 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5281 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5282 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5283 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5284
5285 /* Also do the stuff which must be set before the window exists. */
5286 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5287 "foreground", "Foreground", RES_TYPE_STRING);
5288 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5289 "background", "Background", RES_TYPE_STRING);
5290 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5291 "pointerColor", "Foreground", RES_TYPE_STRING);
5292 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5293 "cursorColor", "Foreground", RES_TYPE_STRING);
5294 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5295 "borderColor", "BorderColor", RES_TYPE_STRING);
5296 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5297 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5298 x_default_parameter (f, parms, Qline_spacing, Qnil,
5299 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5300
5301
5302 /* Init faces before x_default_parameter is called for scroll-bar
5303 parameters because that function calls x_set_scroll_bar_width,
5304 which calls change_frame_size, which calls Fset_window_buffer,
5305 which runs hooks, which call Fvertical_motion. At the end, we
5306 end up in init_iterator with a null face cache, which should not
5307 happen. */
5308 init_frame_faces (f);
5309
5310 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5311 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5312 x_default_parameter (f, parms, Qtool_bar_lines, make_number (0),
5313 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5314 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5315 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5316 x_default_parameter (f, parms, Qtitle, Qnil,
5317 "title", "Title", RES_TYPE_STRING);
5318
5319 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5320 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5321 window_prompting = x_figure_window_size (f, parms);
5322
5323 if (window_prompting & XNegative)
5324 {
5325 if (window_prompting & YNegative)
5326 f->output_data.w32->win_gravity = SouthEastGravity;
5327 else
5328 f->output_data.w32->win_gravity = NorthEastGravity;
5329 }
5330 else
5331 {
5332 if (window_prompting & YNegative)
5333 f->output_data.w32->win_gravity = SouthWestGravity;
5334 else
5335 f->output_data.w32->win_gravity = NorthWestGravity;
5336 }
5337
5338 f->output_data.w32->size_hint_flags = window_prompting;
5339
5340 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5341 f->no_split = minibuffer_only || EQ (tem, Qt);
5342
5343 /* Create the window. Add the tool-bar height to the initial frame
5344 height so that the user gets a text display area of the size he
5345 specified with -g or via the registry. Later changes of the
5346 tool-bar height don't change the frame size. This is done so that
5347 users can create tall Emacs frames without having to guess how
5348 tall the tool-bar will get. */
5349 f->height += FRAME_TOOL_BAR_LINES (f);
5350 w32_window (f, window_prompting, minibuffer_only);
5351 x_icon (f, parms);
5352
5353 x_make_gc (f);
5354
5355 /* Now consider the frame official. */
5356 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5357 Vframe_list = Fcons (frame, Vframe_list);
5358
5359 /* We need to do this after creating the window, so that the
5360 icon-creation functions can say whose icon they're describing. */
5361 x_default_parameter (f, parms, Qicon_type, Qnil,
5362 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5363
5364 x_default_parameter (f, parms, Qauto_raise, Qnil,
5365 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5366 x_default_parameter (f, parms, Qauto_lower, Qnil,
5367 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5368 x_default_parameter (f, parms, Qcursor_type, Qbox,
5369 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5370 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5371 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5372
5373 /* Dimensions, especially f->height, must be done via change_frame_size.
5374 Change will not be effected unless different from the current
5375 f->height. */
5376 width = f->width;
5377 height = f->height;
5378 f->height = 0;
5379 SET_FRAME_WIDTH (f, 0);
5380 change_frame_size (f, height, width, 1, 0, 0);
5381
5382 /* Tell the server what size and position, etc, we want, and how
5383 badly we want them. This should be done after we have the menu
5384 bar so that its size can be taken into account. */
5385 BLOCK_INPUT;
5386 x_wm_set_size_hint (f, window_prompting, 0);
5387 UNBLOCK_INPUT;
5388
5389 /* Make the window appear on the frame and enable display, unless
5390 the caller says not to. However, with explicit parent, Emacs
5391 cannot control visibility, so don't try. */
5392 if (! f->output_data.w32->explicit_parent)
5393 {
5394 Lisp_Object visibility;
5395
5396 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5397 if (EQ (visibility, Qunbound))
5398 visibility = Qt;
5399
5400 if (EQ (visibility, Qicon))
5401 x_iconify_frame (f);
5402 else if (! NILP (visibility))
5403 x_make_frame_visible (f);
5404 else
5405 /* Must have been Qnil. */
5406 ;
5407 }
5408 UNGCPRO;
5409 return unbind_to (count, frame);
5410 }
5411
5412 /* FRAME is used only to get a handle on the X display. We don't pass the
5413 display info directly because we're called from frame.c, which doesn't
5414 know about that structure. */
5415 Lisp_Object
5416 x_get_focus_frame (frame)
5417 struct frame *frame;
5418 {
5419 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5420 Lisp_Object xfocus;
5421 if (! dpyinfo->w32_focus_frame)
5422 return Qnil;
5423
5424 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5425 return xfocus;
5426 }
5427
5428 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5429 "Give FRAME input focus, raising to foreground if necessary.")
5430 (frame)
5431 Lisp_Object frame;
5432 {
5433 x_focus_on_frame (check_x_frame (frame));
5434 return Qnil;
5435 }
5436
5437 \f
5438 /* Return the charset portion of a font name. */
5439 char * xlfd_charset_of_font (char * fontname)
5440 {
5441 char *charset, *encoding;
5442
5443 encoding = strrchr(fontname, '-');
5444 if (!encoding)
5445 return NULL;
5446
5447 *encoding = 0;
5448 charset = strrchr(fontname, '-');
5449 *encoding = '-';
5450
5451 if (!charset || strcmp(charset, "-*-*") == 0)
5452 return NULL;
5453
5454 return charset + 1;
5455 }
5456
5457 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5458 int size, char* filename);
5459 BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len, char * charset);
5460
5461 struct font_info *
5462 w32_load_system_font (f,fontname,size)
5463 struct frame *f;
5464 char * fontname;
5465 int size;
5466 {
5467 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5468 Lisp_Object font_names;
5469
5470 /* Get a list of all the fonts that match this name. Once we
5471 have a list of matching fonts, we compare them against the fonts
5472 we already have loaded by comparing names. */
5473 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5474
5475 if (!NILP (font_names))
5476 {
5477 Lisp_Object tail;
5478 int i;
5479
5480 /* First check if any are already loaded, as that is cheaper
5481 than loading another one. */
5482 for (i = 0; i < dpyinfo->n_fonts; i++)
5483 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5484 if (dpyinfo->font_table[i].name
5485 && (!strcmp (dpyinfo->font_table[i].name,
5486 XSTRING (XCAR (tail))->data)
5487 || !strcmp (dpyinfo->font_table[i].full_name,
5488 XSTRING (XCAR (tail))->data)))
5489 return (dpyinfo->font_table + i);
5490
5491 fontname = (char *) XSTRING (XCAR (font_names))->data;
5492 }
5493 else if (w32_strict_fontnames)
5494 {
5495 /* If EnumFontFamiliesEx was available, we got a full list of
5496 fonts back so stop now to avoid the possibility of loading a
5497 random font. If we had to fall back to EnumFontFamilies, the
5498 list is incomplete, so continue whether the font we want was
5499 listed or not. */
5500 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5501 FARPROC enum_font_families_ex
5502 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5503 if (enum_font_families_ex)
5504 return NULL;
5505 }
5506
5507 /* Load the font and add it to the table. */
5508 {
5509 char *full_name, *encoding, *charset;
5510 XFontStruct *font;
5511 struct font_info *fontp;
5512 LOGFONT lf;
5513 BOOL ok;
5514 int i;
5515
5516 if (!fontname || !x_to_w32_font (fontname, &lf))
5517 return (NULL);
5518
5519 if (!*lf.lfFaceName)
5520 /* If no name was specified for the font, we get a random font
5521 from CreateFontIndirect - this is not particularly
5522 desirable, especially since CreateFontIndirect does not
5523 fill out the missing name in lf, so we never know what we
5524 ended up with. */
5525 return NULL;
5526
5527 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5528 bzero (font, sizeof (*font));
5529
5530 /* Set bdf to NULL to indicate that this is a Windows font. */
5531 font->bdf = NULL;
5532
5533 BLOCK_INPUT;
5534
5535 font->hfont = CreateFontIndirect (&lf);
5536
5537 if (font->hfont == NULL)
5538 {
5539 ok = FALSE;
5540 }
5541 else
5542 {
5543 HDC hdc;
5544 HANDLE oldobj;
5545 int codepage = w32_codepage_for_font (fontname);
5546
5547 hdc = GetDC (dpyinfo->root_window);
5548 oldobj = SelectObject (hdc, font->hfont);
5549
5550 ok = GetTextMetrics (hdc, &font->tm);
5551 if (codepage == CP_UNICODE)
5552 font->double_byte_p = 1;
5553 else
5554 font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS;
5555
5556 SelectObject (hdc, oldobj);
5557 ReleaseDC (dpyinfo->root_window, hdc);
5558 /* Fill out details in lf according to the font that was
5559 actually loaded. */
5560 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5561 lf.lfWidth = font->tm.tmAveCharWidth;
5562 lf.lfWeight = font->tm.tmWeight;
5563 lf.lfItalic = font->tm.tmItalic;
5564 lf.lfCharSet = font->tm.tmCharSet;
5565 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5566 ? VARIABLE_PITCH : FIXED_PITCH);
5567 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5568 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5569
5570 w32_cache_char_metrics (font);
5571 }
5572
5573 UNBLOCK_INPUT;
5574
5575 if (!ok)
5576 {
5577 w32_unload_font (dpyinfo, font);
5578 return (NULL);
5579 }
5580
5581 /* Find a free slot in the font table. */
5582 for (i = 0; i < dpyinfo->n_fonts; ++i)
5583 if (dpyinfo->font_table[i].name == NULL)
5584 break;
5585
5586 /* If no free slot found, maybe enlarge the font table. */
5587 if (i == dpyinfo->n_fonts
5588 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5589 {
5590 int sz;
5591 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5592 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5593 dpyinfo->font_table
5594 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5595 }
5596
5597 fontp = dpyinfo->font_table + i;
5598 if (i == dpyinfo->n_fonts)
5599 ++dpyinfo->n_fonts;
5600
5601 /* Now fill in the slots of *FONTP. */
5602 BLOCK_INPUT;
5603 fontp->font = font;
5604 fontp->font_idx = i;
5605 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5606 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5607
5608 charset = xlfd_charset_of_font (fontname);
5609
5610 /* Work out the font's full name. */
5611 full_name = (char *)xmalloc (100);
5612 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
5613 fontp->full_name = full_name;
5614 else
5615 {
5616 /* If all else fails - just use the name we used to load it. */
5617 xfree (full_name);
5618 fontp->full_name = fontp->name;
5619 }
5620
5621 fontp->size = FONT_WIDTH (font);
5622 fontp->height = FONT_HEIGHT (font);
5623
5624 /* The slot `encoding' specifies how to map a character
5625 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
5626 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
5627 (0:0x20..0x7F, 1:0xA0..0xFF,
5628 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
5629 2:0xA020..0xFF7F). For the moment, we don't know which charset
5630 uses this font. So, we set information in fontp->encoding[1]
5631 which is never used by any charset. If mapping can't be
5632 decided, set FONT_ENCODING_NOT_DECIDED. */
5633
5634 /* SJIS fonts need to be set to type 4, all others seem to work as
5635 type FONT_ENCODING_NOT_DECIDED. */
5636 encoding = strrchr (fontp->name, '-');
5637 if (encoding && stricmp (encoding+1, "sjis") == 0)
5638 fontp->encoding[1] = 4;
5639 else
5640 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
5641
5642 /* The following three values are set to 0 under W32, which is
5643 what they get set to if XGetFontProperty fails under X. */
5644 fontp->baseline_offset = 0;
5645 fontp->relative_compose = 0;
5646 fontp->default_ascent = 0;
5647
5648 /* Set global flag fonts_changed_p to non-zero if the font loaded
5649 has a character with a smaller width than any other character
5650 before, or if the font loaded has a smalle>r height than any
5651 other font loaded before. If this happens, it will make a
5652 glyph matrix reallocation necessary. */
5653 fonts_changed_p = x_compute_min_glyph_bounds (f);
5654 UNBLOCK_INPUT;
5655 return fontp;
5656 }
5657 }
5658
5659 /* Load font named FONTNAME of size SIZE for frame F, and return a
5660 pointer to the structure font_info while allocating it dynamically.
5661 If loading fails, return NULL. */
5662 struct font_info *
5663 w32_load_font (f,fontname,size)
5664 struct frame *f;
5665 char * fontname;
5666 int size;
5667 {
5668 Lisp_Object bdf_fonts;
5669 struct font_info *retval = NULL;
5670
5671 bdf_fonts = w32_list_bdf_fonts (build_string (fontname));
5672
5673 while (!retval && CONSP (bdf_fonts))
5674 {
5675 char *bdf_name, *bdf_file;
5676 Lisp_Object bdf_pair;
5677
5678 bdf_name = XSTRING (XCAR (bdf_fonts))->data;
5679 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
5680 bdf_file = XSTRING (XCDR (bdf_pair))->data;
5681
5682 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
5683
5684 bdf_fonts = XCDR (bdf_fonts);
5685 }
5686
5687 if (retval)
5688 return retval;
5689
5690 return w32_load_system_font(f, fontname, size);
5691 }
5692
5693
5694 void
5695 w32_unload_font (dpyinfo, font)
5696 struct w32_display_info *dpyinfo;
5697 XFontStruct * font;
5698 {
5699 if (font)
5700 {
5701 if (font->per_char) xfree (font->per_char);
5702 if (font->bdf) w32_free_bdf_font (font->bdf);
5703
5704 if (font->hfont) DeleteObject(font->hfont);
5705 xfree (font);
5706 }
5707 }
5708
5709 /* The font conversion stuff between x and w32 */
5710
5711 /* X font string is as follows (from faces.el)
5712 * (let ((- "[-?]")
5713 * (foundry "[^-]+")
5714 * (family "[^-]+")
5715 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
5716 * (weight\? "\\([^-]*\\)") ; 1
5717 * (slant "\\([ior]\\)") ; 2
5718 * (slant\? "\\([^-]?\\)") ; 2
5719 * (swidth "\\([^-]*\\)") ; 3
5720 * (adstyle "[^-]*") ; 4
5721 * (pixelsize "[0-9]+")
5722 * (pointsize "[0-9][0-9]+")
5723 * (resx "[0-9][0-9]+")
5724 * (resy "[0-9][0-9]+")
5725 * (spacing "[cmp?*]")
5726 * (avgwidth "[0-9]+")
5727 * (registry "[^-]+")
5728 * (encoding "[^-]+")
5729 * )
5730 */
5731
5732 LONG
5733 x_to_w32_weight (lpw)
5734 char * lpw;
5735 {
5736 if (!lpw) return (FW_DONTCARE);
5737
5738 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
5739 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
5740 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
5741 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
5742 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5743 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
5744 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
5745 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
5746 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
5747 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
5748 else
5749 return FW_DONTCARE;
5750 }
5751
5752
5753 char *
5754 w32_to_x_weight (fnweight)
5755 int fnweight;
5756 {
5757 if (fnweight >= FW_HEAVY) return "heavy";
5758 if (fnweight >= FW_EXTRABOLD) return "extrabold";
5759 if (fnweight >= FW_BOLD) return "bold";
5760 if (fnweight >= FW_SEMIBOLD) return "demibold";
5761 if (fnweight >= FW_MEDIUM) return "medium";
5762 if (fnweight >= FW_NORMAL) return "normal";
5763 if (fnweight >= FW_LIGHT) return "light";
5764 if (fnweight >= FW_EXTRALIGHT) return "extralight";
5765 if (fnweight >= FW_THIN) return "thin";
5766 else
5767 return "*";
5768 }
5769
5770 LONG
5771 x_to_w32_charset (lpcs)
5772 char * lpcs;
5773 {
5774 Lisp_Object this_entry, w32_charset;
5775
5776 /* Look through w32-charset-info-alist for the character set.
5777 Format of each entry is
5778 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5779 */
5780 this_entry = Fassoc (build_string(lpcs), Vw32_charset_info_alist);
5781
5782 if (NILP(this_entry))
5783 {
5784 /* At startup, we want iso8859-1 fonts to come up properly. */
5785 if (stricmp(lpcs, "iso8859-1") == 0)
5786 return ANSI_CHARSET;
5787 else
5788 return DEFAULT_CHARSET;
5789 }
5790
5791 w32_charset = Fcar (Fcdr (this_entry));
5792
5793 // Translate Lisp symbol to number.
5794 if (w32_charset == Qw32_charset_ansi)
5795 return ANSI_CHARSET;
5796 if (w32_charset == Qw32_charset_symbol)
5797 return SYMBOL_CHARSET;
5798 if (w32_charset == Qw32_charset_shiftjis)
5799 return SHIFTJIS_CHARSET;
5800 if (w32_charset == Qw32_charset_hangeul)
5801 return HANGEUL_CHARSET;
5802 if (w32_charset == Qw32_charset_chinesebig5)
5803 return CHINESEBIG5_CHARSET;
5804 if (w32_charset == Qw32_charset_gb2312)
5805 return GB2312_CHARSET;
5806 if (w32_charset == Qw32_charset_oem)
5807 return OEM_CHARSET;
5808 #ifdef JOHAB_CHARSET
5809 if (w32_charset == Qw32_charset_johab)
5810 return JOHAB_CHARSET;
5811 if (w32_charset == Qw32_charset_easteurope)
5812 return EASTEUROPE_CHARSET;
5813 if (w32_charset == Qw32_charset_turkish)
5814 return TURKISH_CHARSET;
5815 if (w32_charset == Qw32_charset_baltic)
5816 return BALTIC_CHARSET;
5817 if (w32_charset == Qw32_charset_russian)
5818 return RUSSIAN_CHARSET;
5819 if (w32_charset == Qw32_charset_arabic)
5820 return ARABIC_CHARSET;
5821 if (w32_charset == Qw32_charset_greek)
5822 return GREEK_CHARSET;
5823 if (w32_charset == Qw32_charset_hebrew)
5824 return HEBREW_CHARSET;
5825 if (w32_charset == Qw32_charset_vietnamese)
5826 return VIETNAMESE_CHARSET;
5827 if (w32_charset == Qw32_charset_thai)
5828 return THAI_CHARSET;
5829 if (w32_charset == Qw32_charset_mac)
5830 return MAC_CHARSET;
5831 #endif /* JOHAB_CHARSET */
5832 #ifdef UNICODE_CHARSET
5833 if (w32_charset == Qw32_charset_unicode)
5834 return UNICODE_CHARSET;
5835 #endif
5836
5837 return DEFAULT_CHARSET;
5838 }
5839
5840
5841 char *
5842 w32_to_x_charset (fncharset)
5843 int fncharset;
5844 {
5845 static char buf[16];
5846 Lisp_Object charset_type;
5847
5848 switch (fncharset)
5849 {
5850 case ANSI_CHARSET:
5851 /* Handle startup case of w32-charset-info-alist not
5852 being set up yet. */
5853 if (NILP(Vw32_charset_info_alist))
5854 return "iso8859-1";
5855 charset_type = Qw32_charset_ansi;
5856 break;
5857 case DEFAULT_CHARSET:
5858 charset_type = Qw32_charset_default;
5859 break;
5860 case SYMBOL_CHARSET:
5861 charset_type = Qw32_charset_symbol;
5862 break;
5863 case SHIFTJIS_CHARSET:
5864 charset_type = Qw32_charset_shiftjis;
5865 break;
5866 case HANGEUL_CHARSET:
5867 charset_type = Qw32_charset_hangeul;
5868 break;
5869 case GB2312_CHARSET:
5870 charset_type = Qw32_charset_gb2312;
5871 break;
5872 case CHINESEBIG5_CHARSET:
5873 charset_type = Qw32_charset_chinesebig5;
5874 break;
5875 case OEM_CHARSET:
5876 charset_type = Qw32_charset_oem;
5877 break;
5878
5879 /* More recent versions of Windows (95 and NT4.0) define more
5880 character sets. */
5881 #ifdef EASTEUROPE_CHARSET
5882 case EASTEUROPE_CHARSET:
5883 charset_type = Qw32_charset_easteurope;
5884 break;
5885 case TURKISH_CHARSET:
5886 charset_type = Qw32_charset_turkish;
5887 break;
5888 case BALTIC_CHARSET:
5889 charset_type = Qw32_charset_baltic;
5890 break;
5891 case RUSSIAN_CHARSET:
5892 charset_type = Qw32_charset_russian;
5893 break;
5894 case ARABIC_CHARSET:
5895 charset_type = Qw32_charset_arabic;
5896 break;
5897 case GREEK_CHARSET:
5898 charset_type = Qw32_charset_greek;
5899 break;
5900 case HEBREW_CHARSET:
5901 charset_type = Qw32_charset_hebrew;
5902 break;
5903 case VIETNAMESE_CHARSET:
5904 charset_type = Qw32_charset_vietnamese;
5905 break;
5906 case THAI_CHARSET:
5907 charset_type = Qw32_charset_thai;
5908 break;
5909 case MAC_CHARSET:
5910 charset_type = Qw32_charset_mac;
5911 break;
5912 case JOHAB_CHARSET:
5913 charset_type = Qw32_charset_johab;
5914 break;
5915 #endif
5916
5917 #ifdef UNICODE_CHARSET
5918 case UNICODE_CHARSET:
5919 charset_type = Qw32_charset_unicode;
5920 break;
5921 #endif
5922 default:
5923 /* Encode numerical value of unknown charset. */
5924 sprintf (buf, "*-#%u", fncharset);
5925 return buf;
5926 }
5927
5928 {
5929 Lisp_Object rest;
5930 char * best_match = NULL;
5931
5932 /* Look through w32-charset-info-alist for the character set.
5933 Prefer ISO codepages, and prefer lower numbers in the ISO
5934 range. Only return charsets for codepages which are installed.
5935
5936 Format of each entry is
5937 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5938 */
5939 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5940 {
5941 char * x_charset;
5942 Lisp_Object w32_charset;
5943 Lisp_Object codepage;
5944
5945 Lisp_Object this_entry = XCAR (rest);
5946
5947 /* Skip invalid entries in alist. */
5948 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5949 || !CONSP (XCDR (this_entry))
5950 || !SYMBOLP (XCAR (XCDR (this_entry))))
5951 continue;
5952
5953 x_charset = XSTRING (XCAR (this_entry))->data;
5954 w32_charset = XCAR (XCDR (this_entry));
5955 codepage = XCDR (XCDR (this_entry));
5956
5957 /* Look for Same charset and a valid codepage (or non-int
5958 which means ignore). */
5959 if (w32_charset == charset_type
5960 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5961 || IsValidCodePage (XINT (codepage))))
5962 {
5963 /* If we don't have a match already, then this is the
5964 best. */
5965 if (!best_match)
5966 best_match = x_charset;
5967 /* If this is an ISO codepage, and the best so far isn't,
5968 then this is better. */
5969 else if (stricmp (best_match, "iso") != 0
5970 && stricmp (x_charset, "iso") == 0)
5971 best_match = x_charset;
5972 /* If both are ISO8859 codepages, choose the one with the
5973 lowest number in the encoding field. */
5974 else if (stricmp (best_match, "iso8859-") == 0
5975 && stricmp (x_charset, "iso8859-") == 0)
5976 {
5977 int best_enc = atoi (best_match + 8);
5978 int this_enc = atoi (x_charset + 8);
5979 if (this_enc > 0 && this_enc < best_enc)
5980 best_match = x_charset;
5981 }
5982 }
5983 }
5984
5985 /* If no match, encode the numeric value. */
5986 if (!best_match)
5987 {
5988 sprintf (buf, "*-#%u", fncharset);
5989 return buf;
5990 }
5991
5992 strncpy(buf, best_match, 15);
5993 buf[15] = '\0';
5994 return buf;
5995 }
5996 }
5997
5998
5999 /* Get the Windows codepage corresponding to the specified font. The
6000 charset info in the font name is used to look up
6001 w32-charset-to-codepage-alist. */
6002 int
6003 w32_codepage_for_font (char *fontname)
6004 {
6005 Lisp_Object codepage, entry;
6006 char *charset_str, *charset, *end;
6007
6008 if (NILP (Vw32_charset_info_alist))
6009 return CP_DEFAULT;
6010
6011 /* Extract charset part of font string. */
6012 charset = xlfd_charset_of_font (fontname);
6013
6014 if (!charset)
6015 return CP_INVALID;
6016
6017 charset_str = (char *) alloca (strlen (charset));
6018 strcpy (charset_str, charset);
6019
6020 /* Remove leading "*-". */
6021 if (strncmp ("*-", charset_str, 2) == 0)
6022 charset = charset_str + 2;
6023 else
6024 charset = charset_str;
6025
6026 /* Stop match at wildcard (including preceding '-'). */
6027 if (end = strchr (charset, '*'))
6028 {
6029 if (end > charset && *(end-1) == '-')
6030 end--;
6031 *end = '\0';
6032 }
6033
6034 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6035 if (NILP (entry))
6036 return CP_INVALID;
6037
6038 codepage = Fcdr (Fcdr (entry));
6039
6040 if (NILP (codepage))
6041 return CP_8BIT;
6042 else if (XFASTINT (codepage) == XFASTINT (Qt))
6043 return CP_UNICODE;
6044 else if (INTEGERP (codepage))
6045 return XINT (codepage);
6046 else
6047 return CP_INVALID;
6048 }
6049
6050
6051 BOOL
6052 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6053 LOGFONT * lplogfont;
6054 char * lpxstr;
6055 int len;
6056 char * specific_charset;
6057 {
6058 char* fonttype;
6059 char *fontname;
6060 char height_pixels[8];
6061 char height_dpi[8];
6062 char width_pixels[8];
6063 char *fontname_dash;
6064 int display_resy = one_w32_display_info.resy;
6065 int display_resx = one_w32_display_info.resx;
6066 int bufsz;
6067 struct coding_system coding;
6068
6069 if (!lpxstr) abort ();
6070
6071 if (!lplogfont)
6072 return FALSE;
6073
6074 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6075 fonttype = "raster";
6076 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6077 fonttype = "outline";
6078 else
6079 fonttype = "unknown";
6080
6081 setup_coding_system (Fcheck_coding_system (Vw32_system_coding_system),
6082 &coding);
6083 coding.src_multibyte = 0;
6084 coding.dst_multibyte = 1;
6085 coding.mode |= CODING_MODE_LAST_BLOCK;
6086 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6087
6088 fontname = alloca(sizeof(*fontname) * bufsz);
6089 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6090 strlen(lplogfont->lfFaceName), bufsz - 1);
6091 *(fontname + coding.produced) = '\0';
6092
6093 /* Replace dashes with underscores so the dashes are not
6094 misinterpreted. */
6095 fontname_dash = fontname;
6096 while (fontname_dash = strchr (fontname_dash, '-'))
6097 *fontname_dash = '_';
6098
6099 if (lplogfont->lfHeight)
6100 {
6101 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6102 sprintf (height_dpi, "%u",
6103 abs (lplogfont->lfHeight) * 720 / display_resy);
6104 }
6105 else
6106 {
6107 strcpy (height_pixels, "*");
6108 strcpy (height_dpi, "*");
6109 }
6110 if (lplogfont->lfWidth)
6111 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6112 else
6113 strcpy (width_pixels, "*");
6114
6115 _snprintf (lpxstr, len - 1,
6116 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6117 fonttype, /* foundry */
6118 fontname, /* family */
6119 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6120 lplogfont->lfItalic?'i':'r', /* slant */
6121 /* setwidth name */
6122 /* add style name */
6123 height_pixels, /* pixel size */
6124 height_dpi, /* point size */
6125 display_resx, /* resx */
6126 display_resy, /* resy */
6127 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6128 ? 'p' : 'c', /* spacing */
6129 width_pixels, /* avg width */
6130 specific_charset ? specific_charset
6131 : w32_to_x_charset (lplogfont->lfCharSet)
6132 /* charset registry and encoding */
6133 );
6134
6135 lpxstr[len - 1] = 0; /* just to be sure */
6136 return (TRUE);
6137 }
6138
6139 BOOL
6140 x_to_w32_font (lpxstr, lplogfont)
6141 char * lpxstr;
6142 LOGFONT * lplogfont;
6143 {
6144 struct coding_system coding;
6145
6146 if (!lplogfont) return (FALSE);
6147
6148 memset (lplogfont, 0, sizeof (*lplogfont));
6149
6150 /* Set default value for each field. */
6151 #if 1
6152 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6153 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6154 lplogfont->lfQuality = DEFAULT_QUALITY;
6155 #else
6156 /* go for maximum quality */
6157 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6158 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6159 lplogfont->lfQuality = PROOF_QUALITY;
6160 #endif
6161
6162 lplogfont->lfCharSet = DEFAULT_CHARSET;
6163 lplogfont->lfWeight = FW_DONTCARE;
6164 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6165
6166 if (!lpxstr)
6167 return FALSE;
6168
6169 /* Provide a simple escape mechanism for specifying Windows font names
6170 * directly -- if font spec does not beginning with '-', assume this
6171 * format:
6172 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6173 */
6174
6175 if (*lpxstr == '-')
6176 {
6177 int fields, tem;
6178 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6179 width[10], resy[10], remainder[20];
6180 char * encoding;
6181 int dpi = one_w32_display_info.resy;
6182
6183 fields = sscanf (lpxstr,
6184 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%19s",
6185 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6186 if (fields == EOF) return (FALSE);
6187
6188 /* If wildcards cover more than one field, we don't know which
6189 field is which, so don't fill any in. */
6190
6191 if (fields < 9)
6192 fields = 0;
6193
6194 if (fields > 0 && name[0] != '*')
6195 {
6196 int bufsize;
6197 unsigned char *buf;
6198
6199 setup_coding_system
6200 (Fcheck_coding_system (Vw32_system_coding_system), &coding);
6201 coding.src_multibyte = 1;
6202 coding.dst_multibyte = 1;
6203 bufsize = encoding_buffer_size (&coding, strlen (name));
6204 buf = (unsigned char *) alloca (bufsize);
6205 coding.mode |= CODING_MODE_LAST_BLOCK;
6206 encode_coding (&coding, name, buf, strlen (name), bufsize);
6207 if (coding.produced >= LF_FACESIZE)
6208 coding.produced = LF_FACESIZE - 1;
6209 buf[coding.produced] = 0;
6210 strcpy (lplogfont->lfFaceName, buf);
6211 }
6212 else
6213 {
6214 lplogfont->lfFaceName[0] = '\0';
6215 }
6216
6217 fields--;
6218
6219 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6220
6221 fields--;
6222
6223 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6224
6225 fields--;
6226
6227 if (fields > 0 && pixels[0] != '*')
6228 lplogfont->lfHeight = atoi (pixels);
6229
6230 fields--;
6231 fields--;
6232 if (fields > 0 && resy[0] != '*')
6233 {
6234 tem = atoi (resy);
6235 if (tem > 0) dpi = tem;
6236 }
6237
6238 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6239 lplogfont->lfHeight = atoi (height) * dpi / 720;
6240
6241 if (fields > 0)
6242 lplogfont->lfPitchAndFamily =
6243 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6244
6245 fields--;
6246
6247 if (fields > 0 && width[0] != '*')
6248 lplogfont->lfWidth = atoi (width) / 10;
6249
6250 fields--;
6251
6252 /* Strip the trailing '-' if present. (it shouldn't be, as it
6253 fails the test against xlfd-tight-regexp in fontset.el). */
6254 {
6255 int len = strlen (remainder);
6256 if (len > 0 && remainder[len-1] == '-')
6257 remainder[len-1] = 0;
6258 }
6259 encoding = remainder;
6260 if (strncmp (encoding, "*-", 2) == 0)
6261 encoding += 2;
6262 lplogfont->lfCharSet = x_to_w32_charset (fields > 0 ? encoding : "");
6263 }
6264 else
6265 {
6266 int fields;
6267 char name[100], height[10], width[10], weight[20];
6268
6269 fields = sscanf (lpxstr,
6270 "%99[^:]:%9[^:]:%9[^:]:%19s",
6271 name, height, width, weight);
6272
6273 if (fields == EOF) return (FALSE);
6274
6275 if (fields > 0)
6276 {
6277 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6278 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6279 }
6280 else
6281 {
6282 lplogfont->lfFaceName[0] = 0;
6283 }
6284
6285 fields--;
6286
6287 if (fields > 0)
6288 lplogfont->lfHeight = atoi (height);
6289
6290 fields--;
6291
6292 if (fields > 0)
6293 lplogfont->lfWidth = atoi (width);
6294
6295 fields--;
6296
6297 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6298 }
6299
6300 /* This makes TrueType fonts work better. */
6301 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6302
6303 return (TRUE);
6304 }
6305
6306 /* Strip the pixel height and point height from the given xlfd, and
6307 return the pixel height. If no pixel height is specified, calculate
6308 one from the point height, or if that isn't defined either, return
6309 0 (which usually signifies a scalable font).
6310 */
6311 int xlfd_strip_height (char *fontname)
6312 {
6313 int pixel_height, point_height, dpi, field_number;
6314 char *read_from, *write_to;
6315
6316 xassert (fontname);
6317
6318 pixel_height = field_number = 0;
6319 write_to = NULL;
6320
6321 /* Look for height fields. */
6322 for (read_from = fontname; *read_from; read_from++)
6323 {
6324 if (*read_from == '-')
6325 {
6326 field_number++;
6327 if (field_number == 7) /* Pixel height. */
6328 {
6329 read_from++;
6330 write_to = read_from;
6331
6332 /* Find end of field. */
6333 for (;*read_from && *read_from != '-'; read_from++)
6334 ;
6335
6336 /* Split the fontname at end of field. */
6337 if (*read_from)
6338 {
6339 *read_from = '\0';
6340 read_from++;
6341 }
6342 pixel_height = atoi (write_to);
6343 /* Blank out field. */
6344 if (read_from > write_to)
6345 {
6346 *write_to = '-';
6347 write_to++;
6348 }
6349 /* If the pixel height field is at the end (partial xlfd),
6350 return now. */
6351 else
6352 return pixel_height;
6353
6354 /* If we got a pixel height, the point height can be
6355 ignored. Just blank it out and break now. */
6356 if (pixel_height)
6357 {
6358 /* Find end of point size field. */
6359 for (; *read_from && *read_from != '-'; read_from++)
6360 ;
6361
6362 if (*read_from)
6363 read_from++;
6364
6365 /* Blank out the point size field. */
6366 if (read_from > write_to)
6367 {
6368 *write_to = '-';
6369 write_to++;
6370 }
6371 else
6372 return pixel_height;
6373
6374 break;
6375 }
6376 /* If the point height is already blank, break now. */
6377 if (*read_from == '-')
6378 {
6379 read_from++;
6380 break;
6381 }
6382 }
6383 else if (field_number == 8)
6384 {
6385 /* If we didn't get a pixel height, try to get the point
6386 height and convert that. */
6387 int point_size;
6388 char *point_size_start = read_from++;
6389
6390 /* Find end of field. */
6391 for (; *read_from && *read_from != '-'; read_from++)
6392 ;
6393
6394 if (*read_from)
6395 {
6396 *read_from = '\0';
6397 read_from++;
6398 }
6399
6400 point_size = atoi (point_size_start);
6401
6402 /* Convert to pixel height. */
6403 pixel_height = point_size
6404 * one_w32_display_info.height_in / 720;
6405
6406 /* Blank out this field and break. */
6407 *write_to = '-';
6408 write_to++;
6409 break;
6410 }
6411 }
6412 }
6413
6414 /* Shift the rest of the font spec into place. */
6415 if (write_to && read_from > write_to)
6416 {
6417 for (; *read_from; read_from++, write_to++)
6418 *write_to = *read_from;
6419 *write_to = '\0';
6420 }
6421
6422 return pixel_height;
6423 }
6424
6425 /* Assume parameter 1 is fully qualified, no wildcards. */
6426 BOOL
6427 w32_font_match (fontname, pattern)
6428 char * fontname;
6429 char * pattern;
6430 {
6431 char *regex = alloca (strlen (pattern) * 2);
6432 char *font_name_copy = alloca (strlen (fontname) + 1);
6433 char *ptr;
6434
6435 /* Copy fontname so we can modify it during comparison. */
6436 strcpy (font_name_copy, fontname);
6437
6438 ptr = regex;
6439 *ptr++ = '^';
6440
6441 /* Turn pattern into a regexp and do a regexp match. */
6442 for (; *pattern; pattern++)
6443 {
6444 if (*pattern == '?')
6445 *ptr++ = '.';
6446 else if (*pattern == '*')
6447 {
6448 *ptr++ = '.';
6449 *ptr++ = '*';
6450 }
6451 else
6452 *ptr++ = *pattern;
6453 }
6454 *ptr = '$';
6455 *(ptr + 1) = '\0';
6456
6457 /* Strip out font heights and compare them seperately, since
6458 rounding error can cause mismatches. This also allows a
6459 comparison between a font that declares only a pixel height and a
6460 pattern that declares the point height.
6461 */
6462 {
6463 int font_height, pattern_height;
6464
6465 font_height = xlfd_strip_height (font_name_copy);
6466 pattern_height = xlfd_strip_height (regex);
6467
6468 /* Compare now, and don't bother doing expensive regexp matching
6469 if the heights differ. */
6470 if (font_height && pattern_height && (font_height != pattern_height))
6471 return FALSE;
6472 }
6473
6474 return (fast_c_string_match_ignore_case (build_string (regex),
6475 font_name_copy) >= 0);
6476 }
6477
6478 /* Callback functions, and a structure holding info they need, for
6479 listing system fonts on W32. We need one set of functions to do the
6480 job properly, but these don't work on NT 3.51 and earlier, so we
6481 have a second set which don't handle character sets properly to
6482 fall back on.
6483
6484 In both cases, there are two passes made. The first pass gets one
6485 font from each family, the second pass lists all the fonts from
6486 each family. */
6487
6488 typedef struct enumfont_t
6489 {
6490 HDC hdc;
6491 int numFonts;
6492 LOGFONT logfont;
6493 XFontStruct *size_ref;
6494 Lisp_Object *pattern;
6495 Lisp_Object *tail;
6496 } enumfont_t;
6497
6498 int CALLBACK
6499 enum_font_cb2 (lplf, lptm, FontType, lpef)
6500 ENUMLOGFONT * lplf;
6501 NEWTEXTMETRIC * lptm;
6502 int FontType;
6503 enumfont_t * lpef;
6504 {
6505 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
6506 return (1);
6507
6508 /* Check that the character set matches if it was specified */
6509 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
6510 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
6511 return (1);
6512
6513 {
6514 char buf[100];
6515 Lisp_Object width = Qnil;
6516 char *charset = NULL;
6517
6518 /* Truetype fonts do not report their true metrics until loaded */
6519 if (FontType != RASTER_FONTTYPE)
6520 {
6521 if (!NILP (*(lpef->pattern)))
6522 {
6523 /* Scalable fonts are as big as you want them to be. */
6524 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
6525 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
6526 width = make_number (lpef->logfont.lfWidth);
6527 }
6528 else
6529 {
6530 lplf->elfLogFont.lfHeight = 0;
6531 lplf->elfLogFont.lfWidth = 0;
6532 }
6533 }
6534
6535 /* Make sure the height used here is the same as everywhere
6536 else (ie character height, not cell height). */
6537 if (lplf->elfLogFont.lfHeight > 0)
6538 {
6539 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
6540 if (FontType == RASTER_FONTTYPE)
6541 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
6542 else
6543 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
6544 }
6545
6546 if (!NILP (*(lpef->pattern)))
6547 {
6548 charset = xlfd_charset_of_font (XSTRING(*(lpef->pattern))->data);
6549
6550 /* Ensure that charset is valid for this font. */
6551 if (charset
6552 && (x_to_w32_charset (charset) != lplf->elfLogFont.lfCharSet))
6553 charset = NULL;
6554 }
6555
6556 /* TODO: List all relevant charsets if charset not specified. */
6557 if (!w32_to_x_font (&(lplf->elfLogFont), buf, 100, charset))
6558 return (0);
6559
6560 if (NILP (*(lpef->pattern))
6561 || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
6562 {
6563 *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
6564 lpef->tail = &(XCDR (*lpef->tail));
6565 lpef->numFonts++;
6566 }
6567 }
6568
6569 return (1);
6570 }
6571
6572 int CALLBACK
6573 enum_font_cb1 (lplf, lptm, FontType, lpef)
6574 ENUMLOGFONT * lplf;
6575 NEWTEXTMETRIC * lptm;
6576 int FontType;
6577 enumfont_t * lpef;
6578 {
6579 return EnumFontFamilies (lpef->hdc,
6580 lplf->elfLogFont.lfFaceName,
6581 (FONTENUMPROC) enum_font_cb2,
6582 (LPARAM) lpef);
6583 }
6584
6585
6586 int CALLBACK
6587 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6588 ENUMLOGFONTEX * lplf;
6589 NEWTEXTMETRICEX * lptm;
6590 int font_type;
6591 enumfont_t * lpef;
6592 {
6593 /* We are not interested in the extra info we get back from the 'Ex
6594 version - only the fact that we get character set variations
6595 enumerated seperately. */
6596 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6597 font_type, lpef);
6598 }
6599
6600 int CALLBACK
6601 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6602 ENUMLOGFONTEX * lplf;
6603 NEWTEXTMETRICEX * lptm;
6604 int font_type;
6605 enumfont_t * lpef;
6606 {
6607 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6608 FARPROC enum_font_families_ex
6609 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6610 /* We don't really expect EnumFontFamiliesEx to disappear once we
6611 get here, so don't bother handling it gracefully. */
6612 if (enum_font_families_ex == NULL)
6613 error ("gdi32.dll has disappeared!");
6614 return enum_font_families_ex (lpef->hdc,
6615 &lplf->elfLogFont,
6616 (FONTENUMPROC) enum_fontex_cb2,
6617 (LPARAM) lpef, 0);
6618 }
6619
6620 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6621 and xterm.c in Emacs 20.3) */
6622
6623 Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6624 {
6625 char *fontname, *ptnstr;
6626 Lisp_Object list, tem, newlist = Qnil;
6627 int n_fonts = 0;
6628
6629 list = Vw32_bdf_filename_alist;
6630 ptnstr = XSTRING (pattern)->data;
6631
6632 for ( ; CONSP (list); list = XCDR (list))
6633 {
6634 tem = XCAR (list);
6635 if (CONSP (tem))
6636 fontname = XSTRING (XCAR (tem))->data;
6637 else if (STRINGP (tem))
6638 fontname = XSTRING (tem)->data;
6639 else
6640 continue;
6641
6642 if (w32_font_match (fontname, ptnstr))
6643 {
6644 newlist = Fcons (XCAR (tem), newlist);
6645 n_fonts++;
6646 if (n_fonts >= max_names)
6647 break;
6648 }
6649 }
6650
6651 return newlist;
6652 }
6653
6654 Lisp_Object w32_list_synthesized_fonts (FRAME_PTR f, Lisp_Object pattern,
6655 int size, int max_names);
6656
6657 /* Return a list of names of available fonts matching PATTERN on frame
6658 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6659 to be listed. Frame F NULL means we have not yet created any
6660 frame, which means we can't get proper size info, as we don't have
6661 a device context to use for GetTextMetrics.
6662 MAXNAMES sets a limit on how many fonts to match. */
6663
6664 Lisp_Object
6665 w32_list_fonts (FRAME_PTR f, Lisp_Object pattern, int size, int maxnames )
6666 {
6667 Lisp_Object patterns, key = Qnil, tem, tpat;
6668 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6669 struct w32_display_info *dpyinfo = &one_w32_display_info;
6670 int n_fonts = 0;
6671
6672 patterns = Fassoc (pattern, Valternate_fontname_alist);
6673 if (NILP (patterns))
6674 patterns = Fcons (pattern, Qnil);
6675
6676 for (; CONSP (patterns); patterns = XCDR (patterns))
6677 {
6678 enumfont_t ef;
6679 int codepage;
6680
6681 tpat = XCAR (patterns);
6682
6683 if (!STRINGP (tpat))
6684 continue;
6685
6686 /* Avoid expensive EnumFontFamilies functions if we are not
6687 going to be able to output one of these anyway. */
6688 codepage = w32_codepage_for_font (XSTRING (tpat)->data);
6689 if (codepage != CP_8BIT && codepage != CP_UNICODE
6690 && codepage != CP_DEFAULT && !IsValidCodePage(codepage))
6691 continue;
6692
6693 /* See if we cached the result for this particular query.
6694 The cache is an alist of the form:
6695 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6696 */
6697 if (tem = XCDR (dpyinfo->name_list_element),
6698 !NILP (list = Fassoc (tpat, tem)))
6699 {
6700 list = Fcdr_safe (list);
6701 /* We have a cached list. Don't have to get the list again. */
6702 goto label_cached;
6703 }
6704
6705 BLOCK_INPUT;
6706 /* At first, put PATTERN in the cache. */
6707 list = Qnil;
6708 ef.pattern = &tpat;
6709 ef.tail = &list;
6710 ef.numFonts = 0;
6711
6712 /* Use EnumFontFamiliesEx where it is available, as it knows
6713 about character sets. Fall back to EnumFontFamilies for
6714 older versions of NT that don't support the 'Ex function. */
6715 x_to_w32_font (XSTRING (tpat)->data, &ef.logfont);
6716 {
6717 LOGFONT font_match_pattern;
6718 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6719 FARPROC enum_font_families_ex
6720 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6721
6722 /* We do our own pattern matching so we can handle wildcards. */
6723 font_match_pattern.lfFaceName[0] = 0;
6724 font_match_pattern.lfPitchAndFamily = 0;
6725 /* We can use the charset, because if it is a wildcard it will
6726 be DEFAULT_CHARSET anyway. */
6727 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6728
6729 ef.hdc = GetDC (dpyinfo->root_window);
6730
6731 if (enum_font_families_ex)
6732 enum_font_families_ex (ef.hdc,
6733 &font_match_pattern,
6734 (FONTENUMPROC) enum_fontex_cb1,
6735 (LPARAM) &ef, 0);
6736 else
6737 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6738 (LPARAM)&ef);
6739
6740 ReleaseDC (dpyinfo->root_window, ef.hdc);
6741 }
6742
6743 UNBLOCK_INPUT;
6744
6745 /* Make a list of the fonts we got back.
6746 Store that in the font cache for the display. */
6747 XCDR (dpyinfo->name_list_element)
6748 = Fcons (Fcons (tpat, list),
6749 XCDR (dpyinfo->name_list_element));
6750
6751 label_cached:
6752 if (NILP (list)) continue; /* Try the remaining alternatives. */
6753
6754 newlist = second_best = Qnil;
6755
6756 /* Make a list of the fonts that have the right width. */
6757 for (; CONSP (list); list = XCDR (list))
6758 {
6759 int found_size;
6760 tem = XCAR (list);
6761
6762 if (!CONSP (tem))
6763 continue;
6764 if (NILP (XCAR (tem)))
6765 continue;
6766 if (!size)
6767 {
6768 newlist = Fcons (XCAR (tem), newlist);
6769 n_fonts++;
6770 if (n_fonts >= maxnames)
6771 break;
6772 else
6773 continue;
6774 }
6775 if (!INTEGERP (XCDR (tem)))
6776 {
6777 /* Since we don't yet know the size of the font, we must
6778 load it and try GetTextMetrics. */
6779 W32FontStruct thisinfo;
6780 LOGFONT lf;
6781 HDC hdc;
6782 HANDLE oldobj;
6783
6784 if (!x_to_w32_font (XSTRING (XCAR (tem))->data, &lf))
6785 continue;
6786
6787 BLOCK_INPUT;
6788 thisinfo.bdf = NULL;
6789 thisinfo.hfont = CreateFontIndirect (&lf);
6790 if (thisinfo.hfont == NULL)
6791 continue;
6792
6793 hdc = GetDC (dpyinfo->root_window);
6794 oldobj = SelectObject (hdc, thisinfo.hfont);
6795 if (GetTextMetrics (hdc, &thisinfo.tm))
6796 XCDR (tem) = make_number (FONT_WIDTH (&thisinfo));
6797 else
6798 XCDR (tem) = make_number (0);
6799 SelectObject (hdc, oldobj);
6800 ReleaseDC (dpyinfo->root_window, hdc);
6801 DeleteObject(thisinfo.hfont);
6802 UNBLOCK_INPUT;
6803 }
6804 found_size = XINT (XCDR (tem));
6805 if (found_size == size)
6806 {
6807 newlist = Fcons (XCAR (tem), newlist);
6808 n_fonts++;
6809 if (n_fonts >= maxnames)
6810 break;
6811 }
6812 /* keep track of the closest matching size in case
6813 no exact match is found. */
6814 else if (found_size > 0)
6815 {
6816 if (NILP (second_best))
6817 second_best = tem;
6818
6819 else if (found_size < size)
6820 {
6821 if (XINT (XCDR (second_best)) > size
6822 || XINT (XCDR (second_best)) < found_size)
6823 second_best = tem;
6824 }
6825 else
6826 {
6827 if (XINT (XCDR (second_best)) > size
6828 && XINT (XCDR (second_best)) >
6829 found_size)
6830 second_best = tem;
6831 }
6832 }
6833 }
6834
6835 if (!NILP (newlist))
6836 break;
6837 else if (!NILP (second_best))
6838 {
6839 newlist = Fcons (XCAR (second_best), Qnil);
6840 break;
6841 }
6842 }
6843
6844 /* Include any bdf fonts. */
6845 if (n_fonts < maxnames)
6846 {
6847 Lisp_Object combined[2];
6848 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6849 combined[1] = newlist;
6850 newlist = Fnconc(2, combined);
6851 }
6852
6853 /* If we can't find a font that matches, check if Windows would be
6854 able to synthesize it from a different style. */
6855 if (NILP (newlist) && !NILP (Vw32_enable_synthesized_fonts))
6856 newlist = w32_list_synthesized_fonts (f, pattern, size, maxnames);
6857
6858 return newlist;
6859 }
6860
6861 Lisp_Object
6862 w32_list_synthesized_fonts (f, pattern, size, max_names)
6863 FRAME_PTR f;
6864 Lisp_Object pattern;
6865 int size;
6866 int max_names;
6867 {
6868 int fields;
6869 char *full_pattn, *new_pattn, foundary[50], family[50], *pattn_part2;
6870 char style[20], slant;
6871 Lisp_Object matches, match, tem, synthed_matches = Qnil;
6872
6873 full_pattn = XSTRING (pattern)->data;
6874
6875 pattn_part2 = alloca (XSTRING (pattern)->size);
6876 /* Allow some space for wildcard expansion. */
6877 new_pattn = alloca (XSTRING (pattern)->size + 100);
6878
6879 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%19[^-]-%c-%s",
6880 foundary, family, style, &slant, pattn_part2);
6881 if (fields == EOF || fields < 5)
6882 return Qnil;
6883
6884 /* If the style and slant are wildcards already there is no point
6885 checking again (and we don't want to keep recursing). */
6886 if (*style == '*' && slant == '*')
6887 return Qnil;
6888
6889 sprintf (new_pattn, "-%s-%s-*-*-%s", foundary, family, pattn_part2);
6890
6891 matches = w32_list_fonts (f, build_string (new_pattn), size, max_names);
6892
6893 for ( ; CONSP (matches); matches = XCDR (matches))
6894 {
6895 tem = XCAR (matches);
6896 if (!STRINGP (tem))
6897 continue;
6898
6899 full_pattn = XSTRING (tem)->data;
6900 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%*[^-]-%*c-%s",
6901 foundary, family, pattn_part2);
6902 if (fields == EOF || fields < 3)
6903 continue;
6904
6905 sprintf (new_pattn, "-%s-%s-%s-%c-%s", foundary, family, style,
6906 slant, pattn_part2);
6907
6908 synthed_matches = Fcons (build_string (new_pattn),
6909 synthed_matches);
6910 }
6911
6912 return synthed_matches;
6913 }
6914
6915
6916 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6917 struct font_info *
6918 w32_get_font_info (f, font_idx)
6919 FRAME_PTR f;
6920 int font_idx;
6921 {
6922 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6923 }
6924
6925
6926 struct font_info*
6927 w32_query_font (struct frame *f, char *fontname)
6928 {
6929 int i;
6930 struct font_info *pfi;
6931
6932 pfi = FRAME_W32_FONT_TABLE (f);
6933
6934 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6935 {
6936 if (strcmp(pfi->name, fontname) == 0) return pfi;
6937 }
6938
6939 return NULL;
6940 }
6941
6942 /* Find a CCL program for a font specified by FONTP, and set the member
6943 `encoder' of the structure. */
6944
6945 void
6946 w32_find_ccl_program (fontp)
6947 struct font_info *fontp;
6948 {
6949 Lisp_Object list, elt;
6950
6951 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6952 {
6953 elt = XCAR (list);
6954 if (CONSP (elt)
6955 && STRINGP (XCAR (elt))
6956 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6957 >= 0))
6958 break;
6959 }
6960 if (! NILP (list))
6961 {
6962 struct ccl_program *ccl
6963 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6964
6965 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6966 xfree (ccl);
6967 else
6968 fontp->font_encoder = ccl;
6969 }
6970 }
6971
6972 \f
6973 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6974 1, 1, 0,
6975 "Return a list of BDF fonts in DIR, suitable for appending to\n\
6976 w32-bdf-filename-alist. Fonts which do not contain an xlfd description\n\
6977 will not be included in the list. DIR may be a list of directories.")
6978 (directory)
6979 Lisp_Object directory;
6980 {
6981 Lisp_Object list = Qnil;
6982 struct gcpro gcpro1, gcpro2;
6983
6984 if (!CONSP (directory))
6985 return w32_find_bdf_fonts_in_dir (directory);
6986
6987 for ( ; CONSP (directory); directory = XCDR (directory))
6988 {
6989 Lisp_Object pair[2];
6990 pair[0] = list;
6991 pair[1] = Qnil;
6992 GCPRO2 (directory, list);
6993 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
6994 list = Fnconc( 2, pair );
6995 UNGCPRO;
6996 }
6997 return list;
6998 }
6999
7000 /* Find BDF files in a specified directory. (use GCPRO when calling,
7001 as this calls lisp to get a directory listing). */
7002 Lisp_Object w32_find_bdf_fonts_in_dir( Lisp_Object directory )
7003 {
7004 Lisp_Object filelist, list = Qnil;
7005 char fontname[100];
7006
7007 if (!STRINGP(directory))
7008 return Qnil;
7009
7010 filelist = Fdirectory_files (directory, Qt,
7011 build_string (".*\\.[bB][dD][fF]"), Qt);
7012
7013 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7014 {
7015 Lisp_Object filename = XCAR (filelist);
7016 if (w32_BDF_to_x_font (XSTRING (filename)->data, fontname, 100))
7017 store_in_alist (&list, build_string (fontname), filename);
7018 }
7019 return list;
7020 }
7021
7022 \f
7023 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7024 "Internal function called by `color-defined-p', which see.")
7025 (color, frame)
7026 Lisp_Object color, frame;
7027 {
7028 XColor foo;
7029 FRAME_PTR f = check_x_frame (frame);
7030
7031 CHECK_STRING (color, 1);
7032
7033 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7034 return Qt;
7035 else
7036 return Qnil;
7037 }
7038
7039 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7040 "Internal function called by `color-values', which see.")
7041 (color, frame)
7042 Lisp_Object color, frame;
7043 {
7044 XColor foo;
7045 FRAME_PTR f = check_x_frame (frame);
7046
7047 CHECK_STRING (color, 1);
7048
7049 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7050 {
7051 Lisp_Object rgb[3];
7052
7053 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7054 | GetRValue (foo.pixel));
7055 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7056 | GetGValue (foo.pixel));
7057 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7058 | GetBValue (foo.pixel));
7059 return Flist (3, rgb);
7060 }
7061 else
7062 return Qnil;
7063 }
7064
7065 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7066 "Internal function called by `display-color-p', which see.")
7067 (display)
7068 Lisp_Object display;
7069 {
7070 struct w32_display_info *dpyinfo = check_x_display_info (display);
7071
7072 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7073 return Qnil;
7074
7075 return Qt;
7076 }
7077
7078 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
7079 0, 1, 0,
7080 "Return t if the X display supports shades of gray.\n\
7081 Note that color displays do support shades of gray.\n\
7082 The optional argument DISPLAY specifies which display to ask about.\n\
7083 DISPLAY should be either a frame or a display name (a string).\n\
7084 If omitted or nil, that stands for the selected frame's display.")
7085 (display)
7086 Lisp_Object display;
7087 {
7088 struct w32_display_info *dpyinfo = check_x_display_info (display);
7089
7090 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7091 return Qnil;
7092
7093 return Qt;
7094 }
7095
7096 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
7097 0, 1, 0,
7098 "Returns the width in pixels of the X display DISPLAY.\n\
7099 The optional argument DISPLAY specifies which display to ask about.\n\
7100 DISPLAY should be either a frame or a display name (a string).\n\
7101 If omitted or nil, that stands for the selected frame's display.")
7102 (display)
7103 Lisp_Object display;
7104 {
7105 struct w32_display_info *dpyinfo = check_x_display_info (display);
7106
7107 return make_number (dpyinfo->width);
7108 }
7109
7110 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7111 Sx_display_pixel_height, 0, 1, 0,
7112 "Returns the height in pixels of the X display DISPLAY.\n\
7113 The optional argument DISPLAY specifies which display to ask about.\n\
7114 DISPLAY should be either a frame or a display name (a string).\n\
7115 If omitted or nil, that stands for the selected frame's display.")
7116 (display)
7117 Lisp_Object display;
7118 {
7119 struct w32_display_info *dpyinfo = check_x_display_info (display);
7120
7121 return make_number (dpyinfo->height);
7122 }
7123
7124 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7125 0, 1, 0,
7126 "Returns the number of bitplanes of the display DISPLAY.\n\
7127 The optional argument DISPLAY specifies which display to ask about.\n\
7128 DISPLAY should be either a frame or a display name (a string).\n\
7129 If omitted or nil, that stands for the selected frame's display.")
7130 (display)
7131 Lisp_Object display;
7132 {
7133 struct w32_display_info *dpyinfo = check_x_display_info (display);
7134
7135 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7136 }
7137
7138 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7139 0, 1, 0,
7140 "Returns the number of color cells of the display DISPLAY.\n\
7141 The optional argument DISPLAY specifies which display to ask about.\n\
7142 DISPLAY should be either a frame or a display name (a string).\n\
7143 If omitted or nil, that stands for the selected frame's display.")
7144 (display)
7145 Lisp_Object display;
7146 {
7147 struct w32_display_info *dpyinfo = check_x_display_info (display);
7148 HDC hdc;
7149 int cap;
7150
7151 hdc = GetDC (dpyinfo->root_window);
7152 if (dpyinfo->has_palette)
7153 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7154 else
7155 cap = GetDeviceCaps (hdc,NUMCOLORS);
7156
7157 ReleaseDC (dpyinfo->root_window, hdc);
7158
7159 return make_number (cap);
7160 }
7161
7162 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7163 Sx_server_max_request_size,
7164 0, 1, 0,
7165 "Returns the maximum request size of the server of display DISPLAY.\n\
7166 The optional argument DISPLAY specifies which display to ask about.\n\
7167 DISPLAY should be either a frame or a display name (a string).\n\
7168 If omitted or nil, that stands for the selected frame's display.")
7169 (display)
7170 Lisp_Object display;
7171 {
7172 struct w32_display_info *dpyinfo = check_x_display_info (display);
7173
7174 return make_number (1);
7175 }
7176
7177 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7178 "Returns the vendor ID string of the W32 system (Microsoft).\n\
7179 The optional argument DISPLAY specifies which display to ask about.\n\
7180 DISPLAY should be either a frame or a display name (a string).\n\
7181 If omitted or nil, that stands for the selected frame's display.")
7182 (display)
7183 Lisp_Object display;
7184 {
7185 return build_string ("Microsoft Corp.");
7186 }
7187
7188 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7189 "Returns the version numbers of the server of display DISPLAY.\n\
7190 The value is a list of three integers: the major and minor\n\
7191 version numbers, and the vendor-specific release\n\
7192 number. See also the function `x-server-vendor'.\n\n\
7193 The optional argument DISPLAY specifies which display to ask about.\n\
7194 DISPLAY should be either a frame or a display name (a string).\n\
7195 If omitted or nil, that stands for the selected frame's display.")
7196 (display)
7197 Lisp_Object display;
7198 {
7199 return Fcons (make_number (w32_major_version),
7200 Fcons (make_number (w32_minor_version),
7201 Fcons (make_number (w32_build_number), Qnil)));
7202 }
7203
7204 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7205 "Returns the number of screens on the server of display DISPLAY.\n\
7206 The optional argument DISPLAY specifies which display to ask about.\n\
7207 DISPLAY should be either a frame or a display name (a string).\n\
7208 If omitted or nil, that stands for the selected frame's display.")
7209 (display)
7210 Lisp_Object display;
7211 {
7212 return make_number (1);
7213 }
7214
7215 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
7216 "Returns the height in millimeters of the X display DISPLAY.\n\
7217 The optional argument DISPLAY specifies which display to ask about.\n\
7218 DISPLAY should be either a frame or a display name (a string).\n\
7219 If omitted or nil, that stands for the selected frame's display.")
7220 (display)
7221 Lisp_Object display;
7222 {
7223 struct w32_display_info *dpyinfo = check_x_display_info (display);
7224 HDC hdc;
7225 int cap;
7226
7227 hdc = GetDC (dpyinfo->root_window);
7228
7229 cap = GetDeviceCaps (hdc, VERTSIZE);
7230
7231 ReleaseDC (dpyinfo->root_window, hdc);
7232
7233 return make_number (cap);
7234 }
7235
7236 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7237 "Returns the width in millimeters of the X display DISPLAY.\n\
7238 The optional argument DISPLAY specifies which display to ask about.\n\
7239 DISPLAY should be either a frame or a display name (a string).\n\
7240 If omitted or nil, that stands for the selected frame's display.")
7241 (display)
7242 Lisp_Object display;
7243 {
7244 struct w32_display_info *dpyinfo = check_x_display_info (display);
7245
7246 HDC hdc;
7247 int cap;
7248
7249 hdc = GetDC (dpyinfo->root_window);
7250
7251 cap = GetDeviceCaps (hdc, HORZSIZE);
7252
7253 ReleaseDC (dpyinfo->root_window, hdc);
7254
7255 return make_number (cap);
7256 }
7257
7258 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7259 Sx_display_backing_store, 0, 1, 0,
7260 "Returns an indication of whether display DISPLAY does backing store.\n\
7261 The value may be `always', `when-mapped', or `not-useful'.\n\
7262 The optional argument DISPLAY specifies which display to ask about.\n\
7263 DISPLAY should be either a frame or a display name (a string).\n\
7264 If omitted or nil, that stands for the selected frame's display.")
7265 (display)
7266 Lisp_Object display;
7267 {
7268 return intern ("not-useful");
7269 }
7270
7271 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7272 Sx_display_visual_class, 0, 1, 0,
7273 "Returns the visual class of the display DISPLAY.\n\
7274 The value is one of the symbols `static-gray', `gray-scale',\n\
7275 `static-color', `pseudo-color', `true-color', or `direct-color'.\n\n\
7276 The optional argument DISPLAY specifies which display to ask about.\n\
7277 DISPLAY should be either a frame or a display name (a string).\n\
7278 If omitted or nil, that stands for the selected frame's display.")
7279 (display)
7280 Lisp_Object display;
7281 {
7282 struct w32_display_info *dpyinfo = check_x_display_info (display);
7283
7284 #if 0
7285 switch (dpyinfo->visual->class)
7286 {
7287 case StaticGray: return (intern ("static-gray"));
7288 case GrayScale: return (intern ("gray-scale"));
7289 case StaticColor: return (intern ("static-color"));
7290 case PseudoColor: return (intern ("pseudo-color"));
7291 case TrueColor: return (intern ("true-color"));
7292 case DirectColor: return (intern ("direct-color"));
7293 default:
7294 error ("Display has an unknown visual class");
7295 }
7296 #endif
7297
7298 error ("Display has an unknown visual class");
7299 }
7300
7301 DEFUN ("x-display-save-under", Fx_display_save_under,
7302 Sx_display_save_under, 0, 1, 0,
7303 "Returns t if the display DISPLAY supports the save-under feature.\n\
7304 The optional argument DISPLAY specifies which display to ask about.\n\
7305 DISPLAY should be either a frame or a display name (a string).\n\
7306 If omitted or nil, that stands for the selected frame's display.")
7307 (display)
7308 Lisp_Object display;
7309 {
7310 return Qnil;
7311 }
7312 \f
7313 int
7314 x_pixel_width (f)
7315 register struct frame *f;
7316 {
7317 return PIXEL_WIDTH (f);
7318 }
7319
7320 int
7321 x_pixel_height (f)
7322 register struct frame *f;
7323 {
7324 return PIXEL_HEIGHT (f);
7325 }
7326
7327 int
7328 x_char_width (f)
7329 register struct frame *f;
7330 {
7331 return FONT_WIDTH (f->output_data.w32->font);
7332 }
7333
7334 int
7335 x_char_height (f)
7336 register struct frame *f;
7337 {
7338 return f->output_data.w32->line_height;
7339 }
7340
7341 int
7342 x_screen_planes (f)
7343 register struct frame *f;
7344 {
7345 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7346 }
7347 \f
7348 /* Return the display structure for the display named NAME.
7349 Open a new connection if necessary. */
7350
7351 struct w32_display_info *
7352 x_display_info_for_name (name)
7353 Lisp_Object name;
7354 {
7355 Lisp_Object names;
7356 struct w32_display_info *dpyinfo;
7357
7358 CHECK_STRING (name, 0);
7359
7360 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7361 dpyinfo;
7362 dpyinfo = dpyinfo->next, names = XCDR (names))
7363 {
7364 Lisp_Object tem;
7365 tem = Fstring_equal (XCAR (XCAR (names)), name);
7366 if (!NILP (tem))
7367 return dpyinfo;
7368 }
7369
7370 /* Use this general default value to start with. */
7371 Vx_resource_name = Vinvocation_name;
7372
7373 validate_x_resource_name ();
7374
7375 dpyinfo = w32_term_init (name, (unsigned char *)0,
7376 (char *) XSTRING (Vx_resource_name)->data);
7377
7378 if (dpyinfo == 0)
7379 error ("Cannot connect to server %s", XSTRING (name)->data);
7380
7381 w32_in_use = 1;
7382 XSETFASTINT (Vwindow_system_version, 3);
7383
7384 return dpyinfo;
7385 }
7386
7387 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7388 1, 3, 0, "Open a connection to a server.\n\
7389 DISPLAY is the name of the display to connect to.\n\
7390 Optional second arg XRM-STRING is a string of resources in xrdb format.\n\
7391 If the optional third arg MUST-SUCCEED is non-nil,\n\
7392 terminate Emacs if we can't open the connection.")
7393 (display, xrm_string, must_succeed)
7394 Lisp_Object display, xrm_string, must_succeed;
7395 {
7396 unsigned char *xrm_option;
7397 struct w32_display_info *dpyinfo;
7398
7399 CHECK_STRING (display, 0);
7400 if (! NILP (xrm_string))
7401 CHECK_STRING (xrm_string, 1);
7402
7403 if (! EQ (Vwindow_system, intern ("w32")))
7404 error ("Not using Microsoft Windows");
7405
7406 /* Allow color mapping to be defined externally; first look in user's
7407 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
7408 {
7409 Lisp_Object color_file;
7410 struct gcpro gcpro1;
7411
7412 color_file = build_string("~/rgb.txt");
7413
7414 GCPRO1 (color_file);
7415
7416 if (NILP (Ffile_readable_p (color_file)))
7417 color_file =
7418 Fexpand_file_name (build_string ("rgb.txt"),
7419 Fsymbol_value (intern ("data-directory")));
7420
7421 Vw32_color_map = Fw32_load_color_file (color_file);
7422
7423 UNGCPRO;
7424 }
7425 if (NILP (Vw32_color_map))
7426 Vw32_color_map = Fw32_default_color_map ();
7427
7428 if (! NILP (xrm_string))
7429 xrm_option = (unsigned char *) XSTRING (xrm_string)->data;
7430 else
7431 xrm_option = (unsigned char *) 0;
7432
7433 /* Use this general default value to start with. */
7434 /* First remove .exe suffix from invocation-name - it looks ugly. */
7435 {
7436 char basename[ MAX_PATH ], *str;
7437
7438 strcpy (basename, XSTRING (Vinvocation_name)->data);
7439 str = strrchr (basename, '.');
7440 if (str) *str = 0;
7441 Vinvocation_name = build_string (basename);
7442 }
7443 Vx_resource_name = Vinvocation_name;
7444
7445 validate_x_resource_name ();
7446
7447 /* This is what opens the connection and sets x_current_display.
7448 This also initializes many symbols, such as those used for input. */
7449 dpyinfo = w32_term_init (display, xrm_option,
7450 (char *) XSTRING (Vx_resource_name)->data);
7451
7452 if (dpyinfo == 0)
7453 {
7454 if (!NILP (must_succeed))
7455 fatal ("Cannot connect to server %s.\n",
7456 XSTRING (display)->data);
7457 else
7458 error ("Cannot connect to server %s", XSTRING (display)->data);
7459 }
7460
7461 w32_in_use = 1;
7462
7463 XSETFASTINT (Vwindow_system_version, 3);
7464 return Qnil;
7465 }
7466
7467 DEFUN ("x-close-connection", Fx_close_connection,
7468 Sx_close_connection, 1, 1, 0,
7469 "Close the connection to DISPLAY's server.\n\
7470 For DISPLAY, specify either a frame or a display name (a string).\n\
7471 If DISPLAY is nil, that stands for the selected frame's display.")
7472 (display)
7473 Lisp_Object display;
7474 {
7475 struct w32_display_info *dpyinfo = check_x_display_info (display);
7476 int i;
7477
7478 if (dpyinfo->reference_count > 0)
7479 error ("Display still has frames on it");
7480
7481 BLOCK_INPUT;
7482 /* Free the fonts in the font table. */
7483 for (i = 0; i < dpyinfo->n_fonts; i++)
7484 if (dpyinfo->font_table[i].name)
7485 {
7486 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
7487 xfree (dpyinfo->font_table[i].full_name);
7488 xfree (dpyinfo->font_table[i].name);
7489 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
7490 }
7491 x_destroy_all_bitmaps (dpyinfo);
7492
7493 x_delete_display (dpyinfo);
7494 UNBLOCK_INPUT;
7495
7496 return Qnil;
7497 }
7498
7499 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
7500 "Return the list of display names that Emacs has connections to.")
7501 ()
7502 {
7503 Lisp_Object tail, result;
7504
7505 result = Qnil;
7506 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
7507 result = Fcons (XCAR (XCAR (tail)), result);
7508
7509 return result;
7510 }
7511
7512 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7513 "If ON is non-nil, report errors as soon as the erring request is made.\n\
7514 If ON is nil, allow buffering of requests.\n\
7515 This is a noop on W32 systems.\n\
7516 The optional second argument DISPLAY specifies which display to act on.\n\
7517 DISPLAY should be either a frame or a display name (a string).\n\
7518 If DISPLAY is omitted or nil, that stands for the selected frame's display.")
7519 (on, display)
7520 Lisp_Object display, on;
7521 {
7522 return Qnil;
7523 }
7524
7525 \f
7526 \f
7527 /***********************************************************************
7528 Image types
7529 ***********************************************************************/
7530
7531 /* Value is the number of elements of vector VECTOR. */
7532
7533 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
7534
7535 /* List of supported image types. Use define_image_type to add new
7536 types. Use lookup_image_type to find a type for a given symbol. */
7537
7538 static struct image_type *image_types;
7539
7540 /* The symbol `image' which is the car of the lists used to represent
7541 images in Lisp. */
7542
7543 extern Lisp_Object Qimage;
7544
7545 /* The symbol `xbm' which is used as the type symbol for XBM images. */
7546
7547 Lisp_Object Qxbm;
7548
7549 /* Keywords. */
7550
7551 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
7552 extern Lisp_Object QCdata;
7553 Lisp_Object QCtype, QCascent, QCmargin, QCrelief;
7554 Lisp_Object QCalgorithm, QCcolor_symbols, QCheuristic_mask;
7555 Lisp_Object QCindex;
7556
7557 /* Other symbols. */
7558
7559 Lisp_Object Qlaplace;
7560
7561 /* Time in seconds after which images should be removed from the cache
7562 if not displayed. */
7563
7564 Lisp_Object Vimage_cache_eviction_delay;
7565
7566 /* Function prototypes. */
7567
7568 static void define_image_type P_ ((struct image_type *type));
7569 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
7570 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
7571 static void x_laplace P_ ((struct frame *, struct image *));
7572 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
7573 Lisp_Object));
7574
7575
7576 /* Define a new image type from TYPE. This adds a copy of TYPE to
7577 image_types and adds the symbol *TYPE->type to Vimage_types. */
7578
7579 static void
7580 define_image_type (type)
7581 struct image_type *type;
7582 {
7583 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
7584 The initialized data segment is read-only. */
7585 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
7586 bcopy (type, p, sizeof *p);
7587 p->next = image_types;
7588 image_types = p;
7589 Vimage_types = Fcons (*p->type, Vimage_types);
7590 }
7591
7592
7593 /* Look up image type SYMBOL, and return a pointer to its image_type
7594 structure. Value is null if SYMBOL is not a known image type. */
7595
7596 static INLINE struct image_type *
7597 lookup_image_type (symbol)
7598 Lisp_Object symbol;
7599 {
7600 struct image_type *type;
7601
7602 for (type = image_types; type; type = type->next)
7603 if (EQ (symbol, *type->type))
7604 break;
7605
7606 return type;
7607 }
7608
7609
7610 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
7611 valid image specification is a list whose car is the symbol
7612 `image', and whose rest is a property list. The property list must
7613 contain a value for key `:type'. That value must be the name of a
7614 supported image type. The rest of the property list depends on the
7615 image type. */
7616
7617 int
7618 valid_image_p (object)
7619 Lisp_Object object;
7620 {
7621 int valid_p = 0;
7622
7623 if (CONSP (object) && EQ (XCAR (object), Qimage))
7624 {
7625 Lisp_Object symbol = Fplist_get (XCDR (object), QCtype);
7626 struct image_type *type = lookup_image_type (symbol);
7627
7628 if (type)
7629 valid_p = type->valid_p (object);
7630 }
7631
7632 return valid_p;
7633 }
7634
7635
7636 /* Log error message with format string FORMAT and argument ARG.
7637 Signaling an error, e.g. when an image cannot be loaded, is not a
7638 good idea because this would interrupt redisplay, and the error
7639 message display would lead to another redisplay. This function
7640 therefore simply displays a message. */
7641
7642 static void
7643 image_error (format, arg1, arg2)
7644 char *format;
7645 Lisp_Object arg1, arg2;
7646 {
7647 add_to_log (format, arg1, arg2);
7648 }
7649
7650
7651 \f
7652 /***********************************************************************
7653 Image specifications
7654 ***********************************************************************/
7655
7656 enum image_value_type
7657 {
7658 IMAGE_DONT_CHECK_VALUE_TYPE,
7659 IMAGE_STRING_VALUE,
7660 IMAGE_SYMBOL_VALUE,
7661 IMAGE_POSITIVE_INTEGER_VALUE,
7662 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
7663 IMAGE_ASCENT_VALUE,
7664 IMAGE_INTEGER_VALUE,
7665 IMAGE_FUNCTION_VALUE,
7666 IMAGE_NUMBER_VALUE,
7667 IMAGE_BOOL_VALUE
7668 };
7669
7670 /* Structure used when parsing image specifications. */
7671
7672 struct image_keyword
7673 {
7674 /* Name of keyword. */
7675 char *name;
7676
7677 /* The type of value allowed. */
7678 enum image_value_type type;
7679
7680 /* Non-zero means key must be present. */
7681 int mandatory_p;
7682
7683 /* Used to recognize duplicate keywords in a property list. */
7684 int count;
7685
7686 /* The value that was found. */
7687 Lisp_Object value;
7688 };
7689
7690
7691 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7692 int, Lisp_Object));
7693 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7694
7695
7696 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
7697 has the format (image KEYWORD VALUE ...). One of the keyword/
7698 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7699 image_keywords structures of size NKEYWORDS describing other
7700 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7701
7702 static int
7703 parse_image_spec (spec, keywords, nkeywords, type)
7704 Lisp_Object spec;
7705 struct image_keyword *keywords;
7706 int nkeywords;
7707 Lisp_Object type;
7708 {
7709 int i;
7710 Lisp_Object plist;
7711
7712 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7713 return 0;
7714
7715 plist = XCDR (spec);
7716 while (CONSP (plist))
7717 {
7718 Lisp_Object key, value;
7719
7720 /* First element of a pair must be a symbol. */
7721 key = XCAR (plist);
7722 plist = XCDR (plist);
7723 if (!SYMBOLP (key))
7724 return 0;
7725
7726 /* There must follow a value. */
7727 if (!CONSP (plist))
7728 return 0;
7729 value = XCAR (plist);
7730 plist = XCDR (plist);
7731
7732 /* Find key in KEYWORDS. Error if not found. */
7733 for (i = 0; i < nkeywords; ++i)
7734 if (strcmp (keywords[i].name, XSYMBOL (key)->name->data) == 0)
7735 break;
7736
7737 if (i == nkeywords)
7738 continue;
7739
7740 /* Record that we recognized the keyword. If a keywords
7741 was found more than once, it's an error. */
7742 keywords[i].value = value;
7743 ++keywords[i].count;
7744
7745 if (keywords[i].count > 1)
7746 return 0;
7747
7748 /* Check type of value against allowed type. */
7749 switch (keywords[i].type)
7750 {
7751 case IMAGE_STRING_VALUE:
7752 if (!STRINGP (value))
7753 return 0;
7754 break;
7755
7756 case IMAGE_SYMBOL_VALUE:
7757 if (!SYMBOLP (value))
7758 return 0;
7759 break;
7760
7761 case IMAGE_POSITIVE_INTEGER_VALUE:
7762 if (!INTEGERP (value) || XINT (value) <= 0)
7763 return 0;
7764 break;
7765
7766 case IMAGE_ASCENT_VALUE:
7767 if (SYMBOLP (value) && EQ (value, Qcenter))
7768 break;
7769 else if (INTEGERP (value)
7770 && XINT (value) >= 0
7771 && XINT (value) <= 100)
7772 break;
7773 return 0;
7774
7775 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7776 if (!INTEGERP (value) || XINT (value) < 0)
7777 return 0;
7778 break;
7779
7780 case IMAGE_DONT_CHECK_VALUE_TYPE:
7781 break;
7782
7783 case IMAGE_FUNCTION_VALUE:
7784 value = indirect_function (value);
7785 if (SUBRP (value)
7786 || COMPILEDP (value)
7787 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7788 break;
7789 return 0;
7790
7791 case IMAGE_NUMBER_VALUE:
7792 if (!INTEGERP (value) && !FLOATP (value))
7793 return 0;
7794 break;
7795
7796 case IMAGE_INTEGER_VALUE:
7797 if (!INTEGERP (value))
7798 return 0;
7799 break;
7800
7801 case IMAGE_BOOL_VALUE:
7802 if (!NILP (value) && !EQ (value, Qt))
7803 return 0;
7804 break;
7805
7806 default:
7807 abort ();
7808 break;
7809 }
7810
7811 if (EQ (key, QCtype) && !EQ (type, value))
7812 return 0;
7813 }
7814
7815 /* Check that all mandatory fields are present. */
7816 for (i = 0; i < nkeywords; ++i)
7817 if (keywords[i].mandatory_p && keywords[i].count == 0)
7818 return 0;
7819
7820 return NILP (plist);
7821 }
7822
7823
7824 /* Return the value of KEY in image specification SPEC. Value is nil
7825 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7826 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7827
7828 static Lisp_Object
7829 image_spec_value (spec, key, found)
7830 Lisp_Object spec, key;
7831 int *found;
7832 {
7833 Lisp_Object tail;
7834
7835 xassert (valid_image_p (spec));
7836
7837 for (tail = XCDR (spec);
7838 CONSP (tail) && CONSP (XCDR (tail));
7839 tail = XCDR (XCDR (tail)))
7840 {
7841 if (EQ (XCAR (tail), key))
7842 {
7843 if (found)
7844 *found = 1;
7845 return XCAR (XCDR (tail));
7846 }
7847 }
7848
7849 if (found)
7850 *found = 0;
7851 return Qnil;
7852 }
7853
7854
7855
7856 \f
7857 /***********************************************************************
7858 Image type independent image structures
7859 ***********************************************************************/
7860
7861 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7862 static void free_image P_ ((struct frame *f, struct image *img));
7863
7864
7865 /* Allocate and return a new image structure for image specification
7866 SPEC. SPEC has a hash value of HASH. */
7867
7868 static struct image *
7869 make_image (spec, hash)
7870 Lisp_Object spec;
7871 unsigned hash;
7872 {
7873 struct image *img = (struct image *) xmalloc (sizeof *img);
7874
7875 xassert (valid_image_p (spec));
7876 bzero (img, sizeof *img);
7877 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7878 xassert (img->type != NULL);
7879 img->spec = spec;
7880 img->data.lisp_val = Qnil;
7881 img->ascent = DEFAULT_IMAGE_ASCENT;
7882 img->hash = hash;
7883 return img;
7884 }
7885
7886
7887 /* Free image IMG which was used on frame F, including its resources. */
7888
7889 static void
7890 free_image (f, img)
7891 struct frame *f;
7892 struct image *img;
7893 {
7894 if (img)
7895 {
7896 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7897
7898 /* Remove IMG from the hash table of its cache. */
7899 if (img->prev)
7900 img->prev->next = img->next;
7901 else
7902 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7903
7904 if (img->next)
7905 img->next->prev = img->prev;
7906
7907 c->images[img->id] = NULL;
7908
7909 /* Free resources, then free IMG. */
7910 img->type->free (f, img);
7911 xfree (img);
7912 }
7913 }
7914
7915
7916 /* Prepare image IMG for display on frame F. Must be called before
7917 drawing an image. */
7918
7919 void
7920 prepare_image_for_display (f, img)
7921 struct frame *f;
7922 struct image *img;
7923 {
7924 EMACS_TIME t;
7925
7926 /* We're about to display IMG, so set its timestamp to `now'. */
7927 EMACS_GET_TIME (t);
7928 img->timestamp = EMACS_SECS (t);
7929
7930 /* If IMG doesn't have a pixmap yet, load it now, using the image
7931 type dependent loader function. */
7932 if (img->pixmap == 0 && !img->load_failed_p)
7933 img->load_failed_p = img->type->load (f, img) == 0;
7934 }
7935
7936
7937 /* Value is the number of pixels for the ascent of image IMG when
7938 drawn in face FACE. */
7939
7940 int
7941 image_ascent (img, face)
7942 struct image *img;
7943 struct face *face;
7944 {
7945 int height = img->height + img->margin;
7946 int ascent;
7947
7948 if (img->ascent == CENTERED_IMAGE_ASCENT)
7949 {
7950 if (face->font)
7951 ascent = height / 2 - (FONT_DESCENT(face->font)
7952 - FONT_BASE(face->font)) / 2;
7953 else
7954 ascent = height / 2;
7955 }
7956 else
7957 ascent = height * img->ascent / 100.0;
7958
7959 return ascent;
7960 }
7961
7962
7963 \f
7964 /***********************************************************************
7965 Helper functions for X image types
7966 ***********************************************************************/
7967
7968 static void x_clear_image P_ ((struct frame *f, struct image *img));
7969 static unsigned long x_alloc_image_color P_ ((struct frame *f,
7970 struct image *img,
7971 Lisp_Object color_name,
7972 unsigned long dflt));
7973
7974 /* Free X resources of image IMG which is used on frame F. */
7975
7976 static void
7977 x_clear_image (f, img)
7978 struct frame *f;
7979 struct image *img;
7980 {
7981 #if 0 /* TODO: W32 image support */
7982
7983 if (img->pixmap)
7984 {
7985 BLOCK_INPUT;
7986 XFreePixmap (NULL, img->pixmap);
7987 img->pixmap = 0;
7988 UNBLOCK_INPUT;
7989 }
7990
7991 if (img->ncolors)
7992 {
7993 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
7994
7995 /* If display has an immutable color map, freeing colors is not
7996 necessary and some servers don't allow it. So don't do it. */
7997 if (class != StaticColor
7998 && class != StaticGray
7999 && class != TrueColor)
8000 {
8001 Colormap cmap;
8002 BLOCK_INPUT;
8003 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8004 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8005 img->ncolors, 0);
8006 UNBLOCK_INPUT;
8007 }
8008
8009 xfree (img->colors);
8010 img->colors = NULL;
8011 img->ncolors = 0;
8012 }
8013 #endif
8014 }
8015
8016
8017 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8018 cannot be allocated, use DFLT. Add a newly allocated color to
8019 IMG->colors, so that it can be freed again. Value is the pixel
8020 color. */
8021
8022 static unsigned long
8023 x_alloc_image_color (f, img, color_name, dflt)
8024 struct frame *f;
8025 struct image *img;
8026 Lisp_Object color_name;
8027 unsigned long dflt;
8028 {
8029 #if 0 /* TODO: allocing colors. */
8030 XColor color;
8031 unsigned long result;
8032
8033 xassert (STRINGP (color_name));
8034
8035 if (w32_defined_color (f, XSTRING (color_name)->data, &color, 1))
8036 {
8037 /* This isn't called frequently so we get away with simply
8038 reallocating the color vector to the needed size, here. */
8039 ++img->ncolors;
8040 img->colors =
8041 (unsigned long *) xrealloc (img->colors,
8042 img->ncolors * sizeof *img->colors);
8043 img->colors[img->ncolors - 1] = color.pixel;
8044 result = color.pixel;
8045 }
8046 else
8047 result = dflt;
8048 return result;
8049 #endif
8050 return 0;
8051 }
8052
8053
8054 \f
8055 /***********************************************************************
8056 Image Cache
8057 ***********************************************************************/
8058
8059 static void cache_image P_ ((struct frame *f, struct image *img));
8060
8061
8062 /* Return a new, initialized image cache that is allocated from the
8063 heap. Call free_image_cache to free an image cache. */
8064
8065 struct image_cache *
8066 make_image_cache ()
8067 {
8068 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8069 int size;
8070
8071 bzero (c, sizeof *c);
8072 c->size = 50;
8073 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8074 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8075 c->buckets = (struct image **) xmalloc (size);
8076 bzero (c->buckets, size);
8077 return c;
8078 }
8079
8080
8081 /* Free image cache of frame F. Be aware that X frames share images
8082 caches. */
8083
8084 void
8085 free_image_cache (f)
8086 struct frame *f;
8087 {
8088 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8089 if (c)
8090 {
8091 int i;
8092
8093 /* Cache should not be referenced by any frame when freed. */
8094 xassert (c->refcount == 0);
8095
8096 for (i = 0; i < c->used; ++i)
8097 free_image (f, c->images[i]);
8098 xfree (c->images);
8099 xfree (c);
8100 xfree (c->buckets);
8101 FRAME_X_IMAGE_CACHE (f) = NULL;
8102 }
8103 }
8104
8105
8106 /* Clear image cache of frame F. FORCE_P non-zero means free all
8107 images. FORCE_P zero means clear only images that haven't been
8108 displayed for some time. Should be called from time to time to
8109 reduce the number of loaded images. If image-eviction-seconds is
8110 non-nil, this frees images in the cache which weren't displayed for
8111 at least that many seconds. */
8112
8113 void
8114 clear_image_cache (f, force_p)
8115 struct frame *f;
8116 int force_p;
8117 {
8118 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8119
8120 if (c && INTEGERP (Vimage_cache_eviction_delay))
8121 {
8122 EMACS_TIME t;
8123 unsigned long old;
8124 int i, any_freed_p = 0;
8125
8126 EMACS_GET_TIME (t);
8127 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8128
8129 for (i = 0; i < c->used; ++i)
8130 {
8131 struct image *img = c->images[i];
8132 if (img != NULL
8133 && (force_p
8134 || (img->timestamp > old)))
8135 {
8136 free_image (f, img);
8137 any_freed_p = 1;
8138 }
8139 }
8140
8141 /* We may be clearing the image cache because, for example,
8142 Emacs was iconified for a longer period of time. In that
8143 case, current matrices may still contain references to
8144 images freed above. So, clear these matrices. */
8145 if (any_freed_p)
8146 {
8147 clear_current_matrices (f);
8148 ++windows_or_buffers_changed;
8149 }
8150 }
8151 }
8152
8153
8154 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
8155 0, 1, 0,
8156 "Clear the image cache of FRAME.\n\
8157 FRAME nil or omitted means use the selected frame.\n\
8158 FRAME t means clear the image caches of all frames.")
8159 (frame)
8160 Lisp_Object frame;
8161 {
8162 if (EQ (frame, Qt))
8163 {
8164 Lisp_Object tail;
8165
8166 FOR_EACH_FRAME (tail, frame)
8167 if (FRAME_W32_P (XFRAME (frame)))
8168 clear_image_cache (XFRAME (frame), 1);
8169 }
8170 else
8171 clear_image_cache (check_x_frame (frame), 1);
8172
8173 return Qnil;
8174 }
8175
8176
8177 /* Return the id of image with Lisp specification SPEC on frame F.
8178 SPEC must be a valid Lisp image specification (see valid_image_p). */
8179
8180 int
8181 lookup_image (f, spec)
8182 struct frame *f;
8183 Lisp_Object spec;
8184 {
8185 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8186 struct image *img;
8187 int i;
8188 unsigned hash;
8189 struct gcpro gcpro1;
8190 EMACS_TIME now;
8191
8192 /* F must be a window-system frame, and SPEC must be a valid image
8193 specification. */
8194 xassert (FRAME_WINDOW_P (f));
8195 xassert (valid_image_p (spec));
8196
8197 GCPRO1 (spec);
8198
8199 /* Look up SPEC in the hash table of the image cache. */
8200 hash = sxhash (spec, 0);
8201 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
8202
8203 for (img = c->buckets[i]; img; img = img->next)
8204 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
8205 break;
8206
8207 /* If not found, create a new image and cache it. */
8208 if (img == NULL)
8209 {
8210 img = make_image (spec, hash);
8211 cache_image (f, img);
8212 img->load_failed_p = img->type->load (f, img) == 0;
8213 xassert (!interrupt_input_blocked);
8214
8215 /* If we can't load the image, and we don't have a width and
8216 height, use some arbitrary width and height so that we can
8217 draw a rectangle for it. */
8218 if (img->load_failed_p)
8219 {
8220 Lisp_Object value;
8221
8222 value = image_spec_value (spec, QCwidth, NULL);
8223 img->width = (INTEGERP (value)
8224 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
8225 value = image_spec_value (spec, QCheight, NULL);
8226 img->height = (INTEGERP (value)
8227 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
8228 }
8229 else
8230 {
8231 /* Handle image type independent image attributes
8232 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF'. */
8233 Lisp_Object ascent, margin, relief, algorithm, heuristic_mask;
8234 Lisp_Object file;
8235
8236 ascent = image_spec_value (spec, QCascent, NULL);
8237 if (INTEGERP (ascent))
8238 img->ascent = XFASTINT (ascent);
8239 else if (EQ (ascent, Qcenter))
8240 img->ascent = CENTERED_IMAGE_ASCENT;
8241
8242 margin = image_spec_value (spec, QCmargin, NULL);
8243 if (INTEGERP (margin) && XINT (margin) >= 0)
8244 img->margin = XFASTINT (margin);
8245
8246 relief = image_spec_value (spec, QCrelief, NULL);
8247 if (INTEGERP (relief))
8248 {
8249 img->relief = XINT (relief);
8250 img->margin += abs (img->relief);
8251 }
8252
8253 /* Should we apply a Laplace edge-detection algorithm? */
8254 algorithm = image_spec_value (spec, QCalgorithm, NULL);
8255 if (img->pixmap && EQ (algorithm, Qlaplace))
8256 x_laplace (f, img);
8257
8258 /* Should we built a mask heuristically? */
8259 heuristic_mask = image_spec_value (spec, QCheuristic_mask, NULL);
8260 if (img->pixmap && !img->mask && !NILP (heuristic_mask))
8261 x_build_heuristic_mask (f, img, heuristic_mask);
8262 }
8263 }
8264
8265 /* We're using IMG, so set its timestamp to `now'. */
8266 EMACS_GET_TIME (now);
8267 img->timestamp = EMACS_SECS (now);
8268
8269 UNGCPRO;
8270
8271 /* Value is the image id. */
8272 return img->id;
8273 }
8274
8275
8276 /* Cache image IMG in the image cache of frame F. */
8277
8278 static void
8279 cache_image (f, img)
8280 struct frame *f;
8281 struct image *img;
8282 {
8283 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8284 int i;
8285
8286 /* Find a free slot in c->images. */
8287 for (i = 0; i < c->used; ++i)
8288 if (c->images[i] == NULL)
8289 break;
8290
8291 /* If no free slot found, maybe enlarge c->images. */
8292 if (i == c->used && c->used == c->size)
8293 {
8294 c->size *= 2;
8295 c->images = (struct image **) xrealloc (c->images,
8296 c->size * sizeof *c->images);
8297 }
8298
8299 /* Add IMG to c->images, and assign IMG an id. */
8300 c->images[i] = img;
8301 img->id = i;
8302 if (i == c->used)
8303 ++c->used;
8304
8305 /* Add IMG to the cache's hash table. */
8306 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8307 img->next = c->buckets[i];
8308 if (img->next)
8309 img->next->prev = img;
8310 img->prev = NULL;
8311 c->buckets[i] = img;
8312 }
8313
8314
8315 /* Call FN on every image in the image cache of frame F. Used to mark
8316 Lisp Objects in the image cache. */
8317
8318 void
8319 forall_images_in_image_cache (f, fn)
8320 struct frame *f;
8321 void (*fn) P_ ((struct image *img));
8322 {
8323 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8324 {
8325 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8326 if (c)
8327 {
8328 int i;
8329 for (i = 0; i < c->used; ++i)
8330 if (c->images[i])
8331 fn (c->images[i]);
8332 }
8333 }
8334 }
8335
8336
8337 \f
8338 /***********************************************************************
8339 W32 support code
8340 ***********************************************************************/
8341
8342 #if 0 /* TODO: W32 specific image code. */
8343
8344 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8345 XImage **, Pixmap *));
8346 static void x_destroy_x_image P_ ((XImage *));
8347 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8348
8349
8350 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8351 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8352 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
8353 via xmalloc. Print error messages via image_error if an error
8354 occurs. Value is non-zero if successful. */
8355
8356 static int
8357 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8358 struct frame *f;
8359 int width, height, depth;
8360 XImage **ximg;
8361 Pixmap *pixmap;
8362 {
8363 #if 0 /* TODO: Image support for W32 */
8364 Display *display = FRAME_W32_DISPLAY (f);
8365 Screen *screen = FRAME_X_SCREEN (f);
8366 Window window = FRAME_W32_WINDOW (f);
8367
8368 xassert (interrupt_input_blocked);
8369
8370 if (depth <= 0)
8371 depth = DefaultDepthOfScreen (screen);
8372 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
8373 depth, ZPixmap, 0, NULL, width, height,
8374 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
8375 if (*ximg == NULL)
8376 {
8377 image_error ("Unable to allocate X image", Qnil, Qnil);
8378 return 0;
8379 }
8380
8381 /* Allocate image raster. */
8382 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
8383
8384 /* Allocate a pixmap of the same size. */
8385 *pixmap = XCreatePixmap (display, window, width, height, depth);
8386 if (*pixmap == 0)
8387 {
8388 x_destroy_x_image (*ximg);
8389 *ximg = NULL;
8390 image_error ("Unable to create X pixmap", Qnil, Qnil);
8391 return 0;
8392 }
8393 #endif
8394 return 1;
8395 }
8396
8397
8398 /* Destroy XImage XIMG. Free XIMG->data. */
8399
8400 static void
8401 x_destroy_x_image (ximg)
8402 XImage *ximg;
8403 {
8404 xassert (interrupt_input_blocked);
8405 if (ximg)
8406 {
8407 xfree (ximg->data);
8408 ximg->data = NULL;
8409 XDestroyImage (ximg);
8410 }
8411 }
8412
8413
8414 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8415 are width and height of both the image and pixmap. */
8416
8417 static void
8418 x_put_x_image (f, ximg, pixmap, width, height)
8419 struct frame *f;
8420 XImage *ximg;
8421 Pixmap pixmap;
8422 {
8423 GC gc;
8424
8425 xassert (interrupt_input_blocked);
8426 gc = XCreateGC (NULL, pixmap, 0, NULL);
8427 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
8428 XFreeGC (NULL, gc);
8429 }
8430
8431 #endif
8432
8433 \f
8434 /***********************************************************************
8435 Searching files
8436 ***********************************************************************/
8437
8438 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
8439
8440 /* Find image file FILE. Look in data-directory, then
8441 x-bitmap-file-path. Value is the full name of the file found, or
8442 nil if not found. */
8443
8444 static Lisp_Object
8445 x_find_image_file (file)
8446 Lisp_Object file;
8447 {
8448 Lisp_Object file_found, search_path;
8449 struct gcpro gcpro1, gcpro2;
8450 int fd;
8451
8452 file_found = Qnil;
8453 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8454 GCPRO2 (file_found, search_path);
8455
8456 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
8457 fd = openp (search_path, file, "", &file_found, 0);
8458
8459 if (fd == -1)
8460 file_found = Qnil;
8461 else
8462 close (fd);
8463
8464 UNGCPRO;
8465 return file_found;
8466 }
8467
8468
8469 \f
8470 /***********************************************************************
8471 XBM images
8472 ***********************************************************************/
8473
8474 static int xbm_load P_ ((struct frame *f, struct image *img));
8475 static int xbm_load_image_from_file P_ ((struct frame *f, struct image *img,
8476 Lisp_Object file));
8477 static int xbm_image_p P_ ((Lisp_Object object));
8478 static int xbm_read_bitmap_file_data P_ ((char *, int *, int *,
8479 unsigned char **));
8480
8481
8482 /* Indices of image specification fields in xbm_format, below. */
8483
8484 enum xbm_keyword_index
8485 {
8486 XBM_TYPE,
8487 XBM_FILE,
8488 XBM_WIDTH,
8489 XBM_HEIGHT,
8490 XBM_DATA,
8491 XBM_FOREGROUND,
8492 XBM_BACKGROUND,
8493 XBM_ASCENT,
8494 XBM_MARGIN,
8495 XBM_RELIEF,
8496 XBM_ALGORITHM,
8497 XBM_HEURISTIC_MASK,
8498 XBM_LAST
8499 };
8500
8501 /* Vector of image_keyword structures describing the format
8502 of valid XBM image specifications. */
8503
8504 static struct image_keyword xbm_format[XBM_LAST] =
8505 {
8506 {":type", IMAGE_SYMBOL_VALUE, 1},
8507 {":file", IMAGE_STRING_VALUE, 0},
8508 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8509 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8510 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8511 {":foreground", IMAGE_STRING_VALUE, 0},
8512 {":background", IMAGE_STRING_VALUE, 0},
8513 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8514 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8515 {":relief", IMAGE_INTEGER_VALUE, 0},
8516 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8517 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8518 };
8519
8520 /* Structure describing the image type XBM. */
8521
8522 static struct image_type xbm_type =
8523 {
8524 &Qxbm,
8525 xbm_image_p,
8526 xbm_load,
8527 x_clear_image,
8528 NULL
8529 };
8530
8531 /* Tokens returned from xbm_scan. */
8532
8533 enum xbm_token
8534 {
8535 XBM_TK_IDENT = 256,
8536 XBM_TK_NUMBER
8537 };
8538
8539
8540 /* Return non-zero if OBJECT is a valid XBM-type image specification.
8541 A valid specification is a list starting with the symbol `image'
8542 The rest of the list is a property list which must contain an
8543 entry `:type xbm..
8544
8545 If the specification specifies a file to load, it must contain
8546 an entry `:file FILENAME' where FILENAME is a string.
8547
8548 If the specification is for a bitmap loaded from memory it must
8549 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8550 WIDTH and HEIGHT are integers > 0. DATA may be:
8551
8552 1. a string large enough to hold the bitmap data, i.e. it must
8553 have a size >= (WIDTH + 7) / 8 * HEIGHT
8554
8555 2. a bool-vector of size >= WIDTH * HEIGHT
8556
8557 3. a vector of strings or bool-vectors, one for each line of the
8558 bitmap.
8559
8560 Both the file and data forms may contain the additional entries
8561 `:background COLOR' and `:foreground COLOR'. If not present,
8562 foreground and background of the frame on which the image is
8563 displayed, is used. */
8564
8565 static int
8566 xbm_image_p (object)
8567 Lisp_Object object;
8568 {
8569 struct image_keyword kw[XBM_LAST];
8570
8571 bcopy (xbm_format, kw, sizeof kw);
8572 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8573 return 0;
8574
8575 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8576
8577 if (kw[XBM_FILE].count)
8578 {
8579 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8580 return 0;
8581 }
8582 else
8583 {
8584 Lisp_Object data;
8585 int width, height;
8586
8587 /* Entries for `:width', `:height' and `:data' must be present. */
8588 if (!kw[XBM_WIDTH].count
8589 || !kw[XBM_HEIGHT].count
8590 || !kw[XBM_DATA].count)
8591 return 0;
8592
8593 data = kw[XBM_DATA].value;
8594 width = XFASTINT (kw[XBM_WIDTH].value);
8595 height = XFASTINT (kw[XBM_HEIGHT].value);
8596
8597 /* Check type of data, and width and height against contents of
8598 data. */
8599 if (VECTORP (data))
8600 {
8601 int i;
8602
8603 /* Number of elements of the vector must be >= height. */
8604 if (XVECTOR (data)->size < height)
8605 return 0;
8606
8607 /* Each string or bool-vector in data must be large enough
8608 for one line of the image. */
8609 for (i = 0; i < height; ++i)
8610 {
8611 Lisp_Object elt = XVECTOR (data)->contents[i];
8612
8613 if (STRINGP (elt))
8614 {
8615 if (XSTRING (elt)->size
8616 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8617 return 0;
8618 }
8619 else if (BOOL_VECTOR_P (elt))
8620 {
8621 if (XBOOL_VECTOR (elt)->size < width)
8622 return 0;
8623 }
8624 else
8625 return 0;
8626 }
8627 }
8628 else if (STRINGP (data))
8629 {
8630 if (XSTRING (data)->size
8631 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8632 return 0;
8633 }
8634 else if (BOOL_VECTOR_P (data))
8635 {
8636 if (XBOOL_VECTOR (data)->size < width * height)
8637 return 0;
8638 }
8639 else
8640 return 0;
8641 }
8642
8643 /* Baseline must be a value between 0 and 100 (a percentage). */
8644 if (kw[XBM_ASCENT].count
8645 && XFASTINT (kw[XBM_ASCENT].value) > 100)
8646 return 0;
8647
8648 return 1;
8649 }
8650
8651
8652 /* Scan a bitmap file. FP is the stream to read from. Value is
8653 either an enumerator from enum xbm_token, or a character for a
8654 single-character token, or 0 at end of file. If scanning an
8655 identifier, store the lexeme of the identifier in SVAL. If
8656 scanning a number, store its value in *IVAL. */
8657
8658 static int
8659 xbm_scan (fp, sval, ival)
8660 FILE *fp;
8661 char *sval;
8662 int *ival;
8663 {
8664 int c;
8665
8666 /* Skip white space. */
8667 while ((c = fgetc (fp)) != EOF && isspace (c))
8668 ;
8669
8670 if (c == EOF)
8671 c = 0;
8672 else if (isdigit (c))
8673 {
8674 int value = 0, digit;
8675
8676 if (c == '0')
8677 {
8678 c = fgetc (fp);
8679 if (c == 'x' || c == 'X')
8680 {
8681 while ((c = fgetc (fp)) != EOF)
8682 {
8683 if (isdigit (c))
8684 digit = c - '0';
8685 else if (c >= 'a' && c <= 'f')
8686 digit = c - 'a' + 10;
8687 else if (c >= 'A' && c <= 'F')
8688 digit = c - 'A' + 10;
8689 else
8690 break;
8691 value = 16 * value + digit;
8692 }
8693 }
8694 else if (isdigit (c))
8695 {
8696 value = c - '0';
8697 while ((c = fgetc (fp)) != EOF
8698 && isdigit (c))
8699 value = 8 * value + c - '0';
8700 }
8701 }
8702 else
8703 {
8704 value = c - '0';
8705 while ((c = fgetc (fp)) != EOF
8706 && isdigit (c))
8707 value = 10 * value + c - '0';
8708 }
8709
8710 if (c != EOF)
8711 ungetc (c, fp);
8712 *ival = value;
8713 c = XBM_TK_NUMBER;
8714 }
8715 else if (isalpha (c) || c == '_')
8716 {
8717 *sval++ = c;
8718 while ((c = fgetc (fp)) != EOF
8719 && (isalnum (c) || c == '_'))
8720 *sval++ = c;
8721 *sval = 0;
8722 if (c != EOF)
8723 ungetc (c, fp);
8724 c = XBM_TK_IDENT;
8725 }
8726
8727 return c;
8728 }
8729
8730
8731 /* Replacement for XReadBitmapFileData which isn't available under old
8732 X versions. FILE is the name of the bitmap file to read. Set
8733 *WIDTH and *HEIGHT to the width and height of the image. Return in
8734 *DATA the bitmap data allocated with xmalloc. Value is non-zero if
8735 successful. */
8736
8737 static int
8738 xbm_read_bitmap_file_data (file, width, height, data)
8739 char *file;
8740 int *width, *height;
8741 unsigned char **data;
8742 {
8743 FILE *fp;
8744 char buffer[BUFSIZ];
8745 int padding_p = 0;
8746 int v10 = 0;
8747 int bytes_per_line, i, nbytes;
8748 unsigned char *p;
8749 int value;
8750 int LA1;
8751
8752 #define match() \
8753 LA1 = xbm_scan (fp, buffer, &value)
8754
8755 #define expect(TOKEN) \
8756 if (LA1 != (TOKEN)) \
8757 goto failure; \
8758 else \
8759 match ()
8760
8761 #define expect_ident(IDENT) \
8762 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8763 match (); \
8764 else \
8765 goto failure
8766
8767 fp = fopen (file, "r");
8768 if (fp == NULL)
8769 return 0;
8770
8771 *width = *height = -1;
8772 *data = NULL;
8773 LA1 = xbm_scan (fp, buffer, &value);
8774
8775 /* Parse defines for width, height and hot-spots. */
8776 while (LA1 == '#')
8777 {
8778 match ();
8779 expect_ident ("define");
8780 expect (XBM_TK_IDENT);
8781
8782 if (LA1 == XBM_TK_NUMBER);
8783 {
8784 char *p = strrchr (buffer, '_');
8785 p = p ? p + 1 : buffer;
8786 if (strcmp (p, "width") == 0)
8787 *width = value;
8788 else if (strcmp (p, "height") == 0)
8789 *height = value;
8790 }
8791 expect (XBM_TK_NUMBER);
8792 }
8793
8794 if (*width < 0 || *height < 0)
8795 goto failure;
8796
8797 /* Parse bits. Must start with `static'. */
8798 expect_ident ("static");
8799 if (LA1 == XBM_TK_IDENT)
8800 {
8801 if (strcmp (buffer, "unsigned") == 0)
8802 {
8803 match ();
8804 expect_ident ("char");
8805 }
8806 else if (strcmp (buffer, "short") == 0)
8807 {
8808 match ();
8809 v10 = 1;
8810 if (*width % 16 && *width % 16 < 9)
8811 padding_p = 1;
8812 }
8813 else if (strcmp (buffer, "char") == 0)
8814 match ();
8815 else
8816 goto failure;
8817 }
8818 else
8819 goto failure;
8820
8821 expect (XBM_TK_IDENT);
8822 expect ('[');
8823 expect (']');
8824 expect ('=');
8825 expect ('{');
8826
8827 bytes_per_line = (*width + 7) / 8 + padding_p;
8828 nbytes = bytes_per_line * *height;
8829 p = *data = (char *) xmalloc (nbytes);
8830
8831 if (v10)
8832 {
8833
8834 for (i = 0; i < nbytes; i += 2)
8835 {
8836 int val = value;
8837 expect (XBM_TK_NUMBER);
8838
8839 *p++ = val;
8840 if (!padding_p || ((i + 2) % bytes_per_line))
8841 *p++ = value >> 8;
8842
8843 if (LA1 == ',' || LA1 == '}')
8844 match ();
8845 else
8846 goto failure;
8847 }
8848 }
8849 else
8850 {
8851 for (i = 0; i < nbytes; ++i)
8852 {
8853 int val = value;
8854 expect (XBM_TK_NUMBER);
8855
8856 *p++ = val;
8857
8858 if (LA1 == ',' || LA1 == '}')
8859 match ();
8860 else
8861 goto failure;
8862 }
8863 }
8864
8865 fclose (fp);
8866 return 1;
8867
8868 failure:
8869
8870 fclose (fp);
8871 if (*data)
8872 {
8873 xfree (*data);
8874 *data = NULL;
8875 }
8876 return 0;
8877
8878 #undef match
8879 #undef expect
8880 #undef expect_ident
8881 }
8882
8883
8884 /* Load XBM image IMG which will be displayed on frame F from file
8885 SPECIFIED_FILE. Value is non-zero if successful. */
8886
8887 static int
8888 xbm_load_image_from_file (f, img, specified_file)
8889 struct frame *f;
8890 struct image *img;
8891 Lisp_Object specified_file;
8892 {
8893 int rc;
8894 unsigned char *data;
8895 int success_p = 0;
8896 Lisp_Object file;
8897 struct gcpro gcpro1;
8898
8899 xassert (STRINGP (specified_file));
8900 file = Qnil;
8901 GCPRO1 (file);
8902
8903 file = x_find_image_file (specified_file);
8904 if (!STRINGP (file))
8905 {
8906 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8907 UNGCPRO;
8908 return 0;
8909 }
8910
8911 rc = xbm_read_bitmap_file_data (XSTRING (file)->data, &img->width,
8912 &img->height, &data);
8913 if (rc)
8914 {
8915 int depth = one_w32_display_info.n_cbits;
8916 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8917 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8918 Lisp_Object value;
8919
8920 xassert (img->width > 0 && img->height > 0);
8921
8922 /* Get foreground and background colors, maybe allocate colors. */
8923 value = image_spec_value (img->spec, QCforeground, NULL);
8924 if (!NILP (value))
8925 foreground = x_alloc_image_color (f, img, value, foreground);
8926
8927 value = image_spec_value (img->spec, QCbackground, NULL);
8928 if (!NILP (value))
8929 background = x_alloc_image_color (f, img, value, background);
8930
8931 #if 0 /* TODO : Port image display to W32 */
8932 BLOCK_INPUT;
8933 img->pixmap
8934 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
8935 FRAME_W32_WINDOW (f),
8936 data,
8937 img->width, img->height,
8938 foreground, background,
8939 depth);
8940 xfree (data);
8941
8942 if (img->pixmap == 0)
8943 {
8944 x_clear_image (f, img);
8945 image_error ("Unable to create X pixmap for `%s'", file, Qnil);
8946 }
8947 else
8948 success_p = 1;
8949
8950 UNBLOCK_INPUT;
8951 #endif
8952 }
8953 else
8954 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8955
8956 UNGCPRO;
8957 return success_p;
8958 }
8959
8960
8961 /* Fill image IMG which is used on frame F with pixmap data. Value is
8962 non-zero if successful. */
8963
8964 static int
8965 xbm_load (f, img)
8966 struct frame *f;
8967 struct image *img;
8968 {
8969 int success_p = 0;
8970 Lisp_Object file_name;
8971
8972 xassert (xbm_image_p (img->spec));
8973
8974 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8975 file_name = image_spec_value (img->spec, QCfile, NULL);
8976 if (STRINGP (file_name))
8977 success_p = xbm_load_image_from_file (f, img, file_name);
8978 else
8979 {
8980 struct image_keyword fmt[XBM_LAST];
8981 Lisp_Object data;
8982 int depth;
8983 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8984 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8985 char *bits;
8986 int parsed_p;
8987
8988 /* Parse the list specification. */
8989 bcopy (xbm_format, fmt, sizeof fmt);
8990 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
8991 xassert (parsed_p);
8992
8993 /* Get specified width, and height. */
8994 img->width = XFASTINT (fmt[XBM_WIDTH].value);
8995 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
8996 xassert (img->width > 0 && img->height > 0);
8997
8998 BLOCK_INPUT;
8999
9000 if (fmt[XBM_ASCENT].count)
9001 img->ascent = XFASTINT (fmt[XBM_ASCENT].value);
9002
9003 /* Get foreground and background colors, maybe allocate colors. */
9004 if (fmt[XBM_FOREGROUND].count)
9005 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
9006 foreground);
9007 if (fmt[XBM_BACKGROUND].count)
9008 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
9009 background);
9010
9011 /* Set bits to the bitmap image data. */
9012 data = fmt[XBM_DATA].value;
9013 if (VECTORP (data))
9014 {
9015 int i;
9016 char *p;
9017 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
9018
9019 p = bits = (char *) alloca (nbytes * img->height);
9020 for (i = 0; i < img->height; ++i, p += nbytes)
9021 {
9022 Lisp_Object line = XVECTOR (data)->contents[i];
9023 if (STRINGP (line))
9024 bcopy (XSTRING (line)->data, p, nbytes);
9025 else
9026 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
9027 }
9028 }
9029 else if (STRINGP (data))
9030 bits = XSTRING (data)->data;
9031 else
9032 bits = XBOOL_VECTOR (data)->data;
9033
9034 #if 0 /* TODO : W32 XPM code */
9035 /* Create the pixmap. */
9036 depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
9037 img->pixmap
9038 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
9039 FRAME_W32_WINDOW (f),
9040 bits,
9041 img->width, img->height,
9042 foreground, background,
9043 depth);
9044 #endif /* TODO */
9045
9046 if (img->pixmap)
9047 success_p = 1;
9048 else
9049 {
9050 image_error ("Unable to create pixmap for XBM image `%s'",
9051 img->spec, Qnil);
9052 x_clear_image (f, img);
9053 }
9054
9055 UNBLOCK_INPUT;
9056 }
9057
9058 return success_p;
9059 }
9060
9061
9062 \f
9063 /***********************************************************************
9064 XPM images
9065 ***********************************************************************/
9066
9067 #if HAVE_XPM
9068
9069 static int xpm_image_p P_ ((Lisp_Object object));
9070 static int xpm_load P_ ((struct frame *f, struct image *img));
9071 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
9072
9073 #include "X11/xpm.h"
9074
9075 /* The symbol `xpm' identifying XPM-format images. */
9076
9077 Lisp_Object Qxpm;
9078
9079 /* Indices of image specification fields in xpm_format, below. */
9080
9081 enum xpm_keyword_index
9082 {
9083 XPM_TYPE,
9084 XPM_FILE,
9085 XPM_DATA,
9086 XPM_ASCENT,
9087 XPM_MARGIN,
9088 XPM_RELIEF,
9089 XPM_ALGORITHM,
9090 XPM_HEURISTIC_MASK,
9091 XPM_COLOR_SYMBOLS,
9092 XPM_LAST
9093 };
9094
9095 /* Vector of image_keyword structures describing the format
9096 of valid XPM image specifications. */
9097
9098 static struct image_keyword xpm_format[XPM_LAST] =
9099 {
9100 {":type", IMAGE_SYMBOL_VALUE, 1},
9101 {":file", IMAGE_STRING_VALUE, 0},
9102 {":data", IMAGE_STRING_VALUE, 0},
9103 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9104 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9105 {":relief", IMAGE_INTEGER_VALUE, 0},
9106 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9107 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9108 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9109 };
9110
9111 /* Structure describing the image type XBM. */
9112
9113 static struct image_type xpm_type =
9114 {
9115 &Qxpm,
9116 xpm_image_p,
9117 xpm_load,
9118 x_clear_image,
9119 NULL
9120 };
9121
9122
9123 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9124 for XPM images. Such a list must consist of conses whose car and
9125 cdr are strings. */
9126
9127 static int
9128 xpm_valid_color_symbols_p (color_symbols)
9129 Lisp_Object color_symbols;
9130 {
9131 while (CONSP (color_symbols))
9132 {
9133 Lisp_Object sym = XCAR (color_symbols);
9134 if (!CONSP (sym)
9135 || !STRINGP (XCAR (sym))
9136 || !STRINGP (XCDR (sym)))
9137 break;
9138 color_symbols = XCDR (color_symbols);
9139 }
9140
9141 return NILP (color_symbols);
9142 }
9143
9144
9145 /* Value is non-zero if OBJECT is a valid XPM image specification. */
9146
9147 static int
9148 xpm_image_p (object)
9149 Lisp_Object object;
9150 {
9151 struct image_keyword fmt[XPM_LAST];
9152 bcopy (xpm_format, fmt, sizeof fmt);
9153 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9154 /* Either `:file' or `:data' must be present. */
9155 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9156 /* Either no `:color-symbols' or it's a list of conses
9157 whose car and cdr are strings. */
9158 && (fmt[XPM_COLOR_SYMBOLS].count == 0
9159 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
9160 && (fmt[XPM_ASCENT].count == 0
9161 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
9162 }
9163
9164
9165 /* Load image IMG which will be displayed on frame F. Value is
9166 non-zero if successful. */
9167
9168 static int
9169 xpm_load (f, img)
9170 struct frame *f;
9171 struct image *img;
9172 {
9173 int rc, i;
9174 XpmAttributes attrs;
9175 Lisp_Object specified_file, color_symbols;
9176
9177 /* Configure the XPM lib. Use the visual of frame F. Allocate
9178 close colors. Return colors allocated. */
9179 bzero (&attrs, sizeof attrs);
9180 attrs.visual = FRAME_X_VISUAL (f);
9181 attrs.colormap = FRAME_X_COLORMAP (f);
9182 attrs.valuemask |= XpmVisual;
9183 attrs.valuemask |= XpmColormap;
9184 attrs.valuemask |= XpmReturnAllocPixels;
9185 #ifdef XpmAllocCloseColors
9186 attrs.alloc_close_colors = 1;
9187 attrs.valuemask |= XpmAllocCloseColors;
9188 #else
9189 attrs.closeness = 600;
9190 attrs.valuemask |= XpmCloseness;
9191 #endif
9192
9193 /* If image specification contains symbolic color definitions, add
9194 these to `attrs'. */
9195 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
9196 if (CONSP (color_symbols))
9197 {
9198 Lisp_Object tail;
9199 XpmColorSymbol *xpm_syms;
9200 int i, size;
9201
9202 attrs.valuemask |= XpmColorSymbols;
9203
9204 /* Count number of symbols. */
9205 attrs.numsymbols = 0;
9206 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
9207 ++attrs.numsymbols;
9208
9209 /* Allocate an XpmColorSymbol array. */
9210 size = attrs.numsymbols * sizeof *xpm_syms;
9211 xpm_syms = (XpmColorSymbol *) alloca (size);
9212 bzero (xpm_syms, size);
9213 attrs.colorsymbols = xpm_syms;
9214
9215 /* Fill the color symbol array. */
9216 for (tail = color_symbols, i = 0;
9217 CONSP (tail);
9218 ++i, tail = XCDR (tail))
9219 {
9220 Lisp_Object name = XCAR (XCAR (tail));
9221 Lisp_Object color = XCDR (XCAR (tail));
9222 xpm_syms[i].name = (char *) alloca (XSTRING (name)->size + 1);
9223 strcpy (xpm_syms[i].name, XSTRING (name)->data);
9224 xpm_syms[i].value = (char *) alloca (XSTRING (color)->size + 1);
9225 strcpy (xpm_syms[i].value, XSTRING (color)->data);
9226 }
9227 }
9228
9229 /* Create a pixmap for the image, either from a file, or from a
9230 string buffer containing data in the same format as an XPM file. */
9231 BLOCK_INPUT;
9232 specified_file = image_spec_value (img->spec, QCfile, NULL);
9233 if (STRINGP (specified_file))
9234 {
9235 Lisp_Object file = x_find_image_file (specified_file);
9236 if (!STRINGP (file))
9237 {
9238 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9239 UNBLOCK_INPUT;
9240 return 0;
9241 }
9242
9243 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
9244 XSTRING (file)->data, &img->pixmap, &img->mask,
9245 &attrs);
9246 }
9247 else
9248 {
9249 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
9250 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
9251 XSTRING (buffer)->data,
9252 &img->pixmap, &img->mask,
9253 &attrs);
9254 }
9255 UNBLOCK_INPUT;
9256
9257 if (rc == XpmSuccess)
9258 {
9259 /* Remember allocated colors. */
9260 img->ncolors = attrs.nalloc_pixels;
9261 img->colors = (unsigned long *) xmalloc (img->ncolors
9262 * sizeof *img->colors);
9263 for (i = 0; i < attrs.nalloc_pixels; ++i)
9264 img->colors[i] = attrs.alloc_pixels[i];
9265
9266 img->width = attrs.width;
9267 img->height = attrs.height;
9268 xassert (img->width > 0 && img->height > 0);
9269
9270 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
9271 BLOCK_INPUT;
9272 XpmFreeAttributes (&attrs);
9273 UNBLOCK_INPUT;
9274 }
9275 else
9276 {
9277 switch (rc)
9278 {
9279 case XpmOpenFailed:
9280 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9281 break;
9282
9283 case XpmFileInvalid:
9284 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9285 break;
9286
9287 case XpmNoMemory:
9288 image_error ("Out of memory (%s)", img->spec, Qnil);
9289 break;
9290
9291 case XpmColorFailed:
9292 image_error ("Color allocation error (%s)", img->spec, Qnil);
9293 break;
9294
9295 default:
9296 image_error ("Unknown error (%s)", img->spec, Qnil);
9297 break;
9298 }
9299 }
9300
9301 return rc == XpmSuccess;
9302 }
9303
9304 #endif /* HAVE_XPM != 0 */
9305
9306 \f
9307 #if 0 /* TODO : Color tables on W32. */
9308 /***********************************************************************
9309 Color table
9310 ***********************************************************************/
9311
9312 /* An entry in the color table mapping an RGB color to a pixel color. */
9313
9314 struct ct_color
9315 {
9316 int r, g, b;
9317 unsigned long pixel;
9318
9319 /* Next in color table collision list. */
9320 struct ct_color *next;
9321 };
9322
9323 /* The bucket vector size to use. Must be prime. */
9324
9325 #define CT_SIZE 101
9326
9327 /* Value is a hash of the RGB color given by R, G, and B. */
9328
9329 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9330
9331 /* The color hash table. */
9332
9333 struct ct_color **ct_table;
9334
9335 /* Number of entries in the color table. */
9336
9337 int ct_colors_allocated;
9338
9339 /* Function prototypes. */
9340
9341 static void init_color_table P_ ((void));
9342 static void free_color_table P_ ((void));
9343 static unsigned long *colors_in_color_table P_ ((int *n));
9344 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9345 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9346
9347
9348 /* Initialize the color table. */
9349
9350 static void
9351 init_color_table ()
9352 {
9353 int size = CT_SIZE * sizeof (*ct_table);
9354 ct_table = (struct ct_color **) xmalloc (size);
9355 bzero (ct_table, size);
9356 ct_colors_allocated = 0;
9357 }
9358
9359
9360 /* Free memory associated with the color table. */
9361
9362 static void
9363 free_color_table ()
9364 {
9365 int i;
9366 struct ct_color *p, *next;
9367
9368 for (i = 0; i < CT_SIZE; ++i)
9369 for (p = ct_table[i]; p; p = next)
9370 {
9371 next = p->next;
9372 xfree (p);
9373 }
9374
9375 xfree (ct_table);
9376 ct_table = NULL;
9377 }
9378
9379
9380 /* Value is a pixel color for RGB color R, G, B on frame F. If an
9381 entry for that color already is in the color table, return the
9382 pixel color of that entry. Otherwise, allocate a new color for R,
9383 G, B, and make an entry in the color table. */
9384
9385 static unsigned long
9386 lookup_rgb_color (f, r, g, b)
9387 struct frame *f;
9388 int r, g, b;
9389 {
9390 unsigned hash = CT_HASH_RGB (r, g, b);
9391 int i = hash % CT_SIZE;
9392 struct ct_color *p;
9393
9394 for (p = ct_table[i]; p; p = p->next)
9395 if (p->r == r && p->g == g && p->b == b)
9396 break;
9397
9398 if (p == NULL)
9399 {
9400 COLORREF color;
9401 Colormap cmap;
9402 int rc;
9403
9404 color = PALETTERGB (r, g, b);
9405
9406 ++ct_colors_allocated;
9407
9408 p = (struct ct_color *) xmalloc (sizeof *p);
9409 p->r = r;
9410 p->g = g;
9411 p->b = b;
9412 p->pixel = color;
9413 p->next = ct_table[i];
9414 ct_table[i] = p;
9415 }
9416
9417 return p->pixel;
9418 }
9419
9420
9421 /* Look up pixel color PIXEL which is used on frame F in the color
9422 table. If not already present, allocate it. Value is PIXEL. */
9423
9424 static unsigned long
9425 lookup_pixel_color (f, pixel)
9426 struct frame *f;
9427 unsigned long pixel;
9428 {
9429 int i = pixel % CT_SIZE;
9430 struct ct_color *p;
9431
9432 for (p = ct_table[i]; p; p = p->next)
9433 if (p->pixel == pixel)
9434 break;
9435
9436 if (p == NULL)
9437 {
9438 XColor color;
9439 Colormap cmap;
9440 int rc;
9441
9442 BLOCK_INPUT;
9443
9444 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9445 color.pixel = pixel;
9446 XQueryColor (NULL, cmap, &color);
9447 rc = x_alloc_nearest_color (f, cmap, &color);
9448 UNBLOCK_INPUT;
9449
9450 if (rc)
9451 {
9452 ++ct_colors_allocated;
9453
9454 p = (struct ct_color *) xmalloc (sizeof *p);
9455 p->r = color.red;
9456 p->g = color.green;
9457 p->b = color.blue;
9458 p->pixel = pixel;
9459 p->next = ct_table[i];
9460 ct_table[i] = p;
9461 }
9462 else
9463 return FRAME_FOREGROUND_PIXEL (f);
9464 }
9465 return p->pixel;
9466 }
9467
9468
9469 /* Value is a vector of all pixel colors contained in the color table,
9470 allocated via xmalloc. Set *N to the number of colors. */
9471
9472 static unsigned long *
9473 colors_in_color_table (n)
9474 int *n;
9475 {
9476 int i, j;
9477 struct ct_color *p;
9478 unsigned long *colors;
9479
9480 if (ct_colors_allocated == 0)
9481 {
9482 *n = 0;
9483 colors = NULL;
9484 }
9485 else
9486 {
9487 colors = (unsigned long *) xmalloc (ct_colors_allocated
9488 * sizeof *colors);
9489 *n = ct_colors_allocated;
9490
9491 for (i = j = 0; i < CT_SIZE; ++i)
9492 for (p = ct_table[i]; p; p = p->next)
9493 colors[j++] = p->pixel;
9494 }
9495
9496 return colors;
9497 }
9498
9499 #endif /* TODO */
9500
9501 \f
9502 /***********************************************************************
9503 Algorithms
9504 ***********************************************************************/
9505
9506 #if 0 /* TODO : W32 versions of low level algorithms */
9507 static void x_laplace_write_row P_ ((struct frame *, long *,
9508 int, XImage *, int));
9509 static void x_laplace_read_row P_ ((struct frame *, Colormap,
9510 XColor *, int, XImage *, int));
9511
9512
9513 /* Fill COLORS with RGB colors from row Y of image XIMG. F is the
9514 frame we operate on, CMAP is the color-map in effect, and WIDTH is
9515 the width of one row in the image. */
9516
9517 static void
9518 x_laplace_read_row (f, cmap, colors, width, ximg, y)
9519 struct frame *f;
9520 Colormap cmap;
9521 XColor *colors;
9522 int width;
9523 XImage *ximg;
9524 int y;
9525 {
9526 int x;
9527
9528 for (x = 0; x < width; ++x)
9529 colors[x].pixel = XGetPixel (ximg, x, y);
9530
9531 XQueryColors (NULL, cmap, colors, width);
9532 }
9533
9534
9535 /* Write row Y of image XIMG. PIXELS is an array of WIDTH longs
9536 containing the pixel colors to write. F is the frame we are
9537 working on. */
9538
9539 static void
9540 x_laplace_write_row (f, pixels, width, ximg, y)
9541 struct frame *f;
9542 long *pixels;
9543 int width;
9544 XImage *ximg;
9545 int y;
9546 {
9547 int x;
9548
9549 for (x = 0; x < width; ++x)
9550 XPutPixel (ximg, x, y, pixels[x]);
9551 }
9552 #endif
9553
9554 /* Transform image IMG which is used on frame F with a Laplace
9555 edge-detection algorithm. The result is an image that can be used
9556 to draw disabled buttons, for example. */
9557
9558 static void
9559 x_laplace (f, img)
9560 struct frame *f;
9561 struct image *img;
9562 {
9563 #if 0 /* TODO : W32 version */
9564 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9565 XImage *ximg, *oimg;
9566 XColor *in[3];
9567 long *out;
9568 Pixmap pixmap;
9569 int x, y, i;
9570 long pixel;
9571 int in_y, out_y, rc;
9572 int mv2 = 45000;
9573
9574 BLOCK_INPUT;
9575
9576 /* Get the X image IMG->pixmap. */
9577 ximg = XGetImage (NULL, img->pixmap,
9578 0, 0, img->width, img->height, ~0, ZPixmap);
9579
9580 /* Allocate 3 input rows, and one output row of colors. */
9581 for (i = 0; i < 3; ++i)
9582 in[i] = (XColor *) alloca (img->width * sizeof (XColor));
9583 out = (long *) alloca (img->width * sizeof (long));
9584
9585 /* Create an X image for output. */
9586 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9587 &oimg, &pixmap);
9588
9589 /* Fill first two rows. */
9590 x_laplace_read_row (f, cmap, in[0], img->width, ximg, 0);
9591 x_laplace_read_row (f, cmap, in[1], img->width, ximg, 1);
9592 in_y = 2;
9593
9594 /* Write first row, all zeros. */
9595 init_color_table ();
9596 pixel = lookup_rgb_color (f, 0, 0, 0);
9597 for (x = 0; x < img->width; ++x)
9598 out[x] = pixel;
9599 x_laplace_write_row (f, out, img->width, oimg, 0);
9600 out_y = 1;
9601
9602 for (y = 2; y < img->height; ++y)
9603 {
9604 int rowa = y % 3;
9605 int rowb = (y + 2) % 3;
9606
9607 x_laplace_read_row (f, cmap, in[rowa], img->width, ximg, in_y++);
9608
9609 for (x = 0; x < img->width - 2; ++x)
9610 {
9611 int r = in[rowa][x].red + mv2 - in[rowb][x + 2].red;
9612 int g = in[rowa][x].green + mv2 - in[rowb][x + 2].green;
9613 int b = in[rowa][x].blue + mv2 - in[rowb][x + 2].blue;
9614
9615 out[x + 1] = lookup_rgb_color (f, r & 0xffff, g & 0xffff,
9616 b & 0xffff);
9617 }
9618
9619 x_laplace_write_row (f, out, img->width, oimg, out_y++);
9620 }
9621
9622 /* Write last line, all zeros. */
9623 for (x = 0; x < img->width; ++x)
9624 out[x] = pixel;
9625 x_laplace_write_row (f, out, img->width, oimg, out_y);
9626
9627 /* Free the input image, and free resources of IMG. */
9628 XDestroyImage (ximg);
9629 x_clear_image (f, img);
9630
9631 /* Put the output image into pixmap, and destroy it. */
9632 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9633 x_destroy_x_image (oimg);
9634
9635 /* Remember new pixmap and colors in IMG. */
9636 img->pixmap = pixmap;
9637 img->colors = colors_in_color_table (&img->ncolors);
9638 free_color_table ();
9639
9640 UNBLOCK_INPUT;
9641 #endif /* TODO */
9642 }
9643
9644
9645 /* Build a mask for image IMG which is used on frame F. FILE is the
9646 name of an image file, for error messages. HOW determines how to
9647 determine the background color of IMG. If it is a list '(R G B)',
9648 with R, G, and B being integers >= 0, take that as the color of the
9649 background. Otherwise, determine the background color of IMG
9650 heuristically. Value is non-zero if successful. */
9651
9652 static int
9653 x_build_heuristic_mask (f, img, how)
9654 struct frame *f;
9655 struct image *img;
9656 Lisp_Object how;
9657 {
9658 #if 0 /* TODO : W32 version */
9659 Display *dpy = FRAME_W32_DISPLAY (f);
9660 XImage *ximg, *mask_img;
9661 int x, y, rc, look_at_corners_p;
9662 unsigned long bg;
9663
9664 BLOCK_INPUT;
9665
9666 /* Create an image and pixmap serving as mask. */
9667 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
9668 &mask_img, &img->mask);
9669 if (!rc)
9670 {
9671 UNBLOCK_INPUT;
9672 return 0;
9673 }
9674
9675 /* Get the X image of IMG->pixmap. */
9676 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
9677 ~0, ZPixmap);
9678
9679 /* Determine the background color of ximg. If HOW is `(R G B)'
9680 take that as color. Otherwise, try to determine the color
9681 heuristically. */
9682 look_at_corners_p = 1;
9683
9684 if (CONSP (how))
9685 {
9686 int rgb[3], i = 0;
9687
9688 while (i < 3
9689 && CONSP (how)
9690 && NATNUMP (XCAR (how)))
9691 {
9692 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9693 how = XCDR (how);
9694 }
9695
9696 if (i == 3 && NILP (how))
9697 {
9698 char color_name[30];
9699 XColor exact, color;
9700 Colormap cmap;
9701
9702 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
9703
9704 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9705 if (XLookupColor (dpy, cmap, color_name, &exact, &color))
9706 {
9707 bg = color.pixel;
9708 look_at_corners_p = 0;
9709 }
9710 }
9711 }
9712
9713 if (look_at_corners_p)
9714 {
9715 unsigned long corners[4];
9716 int i, best_count;
9717
9718 /* Get the colors at the corners of ximg. */
9719 corners[0] = XGetPixel (ximg, 0, 0);
9720 corners[1] = XGetPixel (ximg, img->width - 1, 0);
9721 corners[2] = XGetPixel (ximg, img->width - 1, img->height - 1);
9722 corners[3] = XGetPixel (ximg, 0, img->height - 1);
9723
9724 /* Choose the most frequently found color as background. */
9725 for (i = best_count = 0; i < 4; ++i)
9726 {
9727 int j, n;
9728
9729 for (j = n = 0; j < 4; ++j)
9730 if (corners[i] == corners[j])
9731 ++n;
9732
9733 if (n > best_count)
9734 bg = corners[i], best_count = n;
9735 }
9736 }
9737
9738 /* Set all bits in mask_img to 1 whose color in ximg is different
9739 from the background color bg. */
9740 for (y = 0; y < img->height; ++y)
9741 for (x = 0; x < img->width; ++x)
9742 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
9743
9744 /* Put mask_img into img->mask. */
9745 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
9746 x_destroy_x_image (mask_img);
9747 XDestroyImage (ximg);
9748
9749 UNBLOCK_INPUT;
9750 #endif /* TODO */
9751
9752 return 1;
9753 }
9754
9755
9756 \f
9757 /***********************************************************************
9758 PBM (mono, gray, color)
9759 ***********************************************************************/
9760 #ifdef HAVE_PBM
9761
9762 static int pbm_image_p P_ ((Lisp_Object object));
9763 static int pbm_load P_ ((struct frame *f, struct image *img));
9764 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
9765
9766 /* The symbol `pbm' identifying images of this type. */
9767
9768 Lisp_Object Qpbm;
9769
9770 /* Indices of image specification fields in gs_format, below. */
9771
9772 enum pbm_keyword_index
9773 {
9774 PBM_TYPE,
9775 PBM_FILE,
9776 PBM_DATA,
9777 PBM_ASCENT,
9778 PBM_MARGIN,
9779 PBM_RELIEF,
9780 PBM_ALGORITHM,
9781 PBM_HEURISTIC_MASK,
9782 PBM_LAST
9783 };
9784
9785 /* Vector of image_keyword structures describing the format
9786 of valid user-defined image specifications. */
9787
9788 static struct image_keyword pbm_format[PBM_LAST] =
9789 {
9790 {":type", IMAGE_SYMBOL_VALUE, 1},
9791 {":file", IMAGE_STRING_VALUE, 0},
9792 {":data", IMAGE_STRING_VALUE, 0},
9793 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9794 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9795 {":relief", IMAGE_INTEGER_VALUE, 0},
9796 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9797 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9798 };
9799
9800 /* Structure describing the image type `pbm'. */
9801
9802 static struct image_type pbm_type =
9803 {
9804 &Qpbm,
9805 pbm_image_p,
9806 pbm_load,
9807 x_clear_image,
9808 NULL
9809 };
9810
9811
9812 /* Return non-zero if OBJECT is a valid PBM image specification. */
9813
9814 static int
9815 pbm_image_p (object)
9816 Lisp_Object object;
9817 {
9818 struct image_keyword fmt[PBM_LAST];
9819
9820 bcopy (pbm_format, fmt, sizeof fmt);
9821
9822 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
9823 || (fmt[PBM_ASCENT].count
9824 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
9825 return 0;
9826
9827 /* Must specify either :data or :file. */
9828 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
9829 }
9830
9831
9832 /* Scan a decimal number from *S and return it. Advance *S while
9833 reading the number. END is the end of the string. Value is -1 at
9834 end of input. */
9835
9836 static int
9837 pbm_scan_number (s, end)
9838 unsigned char **s, *end;
9839 {
9840 int c, val = -1;
9841
9842 while (*s < end)
9843 {
9844 /* Skip white-space. */
9845 while (*s < end && (c = *(*s)++, isspace (c)))
9846 ;
9847
9848 if (c == '#')
9849 {
9850 /* Skip comment to end of line. */
9851 while (*s < end && (c = *(*s)++, c != '\n'))
9852 ;
9853 }
9854 else if (isdigit (c))
9855 {
9856 /* Read decimal number. */
9857 val = c - '0';
9858 while (*s < end && (c = *(*s)++, isdigit (c)))
9859 val = 10 * val + c - '0';
9860 break;
9861 }
9862 else
9863 break;
9864 }
9865
9866 return val;
9867 }
9868
9869
9870 /* Read FILE into memory. Value is a pointer to a buffer allocated
9871 with xmalloc holding FILE's contents. Value is null if an error
9872 occured. *SIZE is set to the size of the file. */
9873
9874 static char *
9875 pbm_read_file (file, size)
9876 Lisp_Object file;
9877 int *size;
9878 {
9879 FILE *fp = NULL;
9880 char *buf = NULL;
9881 struct stat st;
9882
9883 if (stat (XSTRING (file)->data, &st) == 0
9884 && (fp = fopen (XSTRING (file)->data, "r")) != NULL
9885 && (buf = (char *) xmalloc (st.st_size),
9886 fread (buf, 1, st.st_size, fp) == st.st_size))
9887 {
9888 *size = st.st_size;
9889 fclose (fp);
9890 }
9891 else
9892 {
9893 if (fp)
9894 fclose (fp);
9895 if (buf)
9896 {
9897 xfree (buf);
9898 buf = NULL;
9899 }
9900 }
9901
9902 return buf;
9903 }
9904
9905
9906 /* Load PBM image IMG for use on frame F. */
9907
9908 static int
9909 pbm_load (f, img)
9910 struct frame *f;
9911 struct image *img;
9912 {
9913 int raw_p, x, y;
9914 int width, height, max_color_idx = 0;
9915 XImage *ximg;
9916 Lisp_Object file, specified_file;
9917 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
9918 struct gcpro gcpro1;
9919 unsigned char *contents = NULL;
9920 unsigned char *end, *p;
9921 int size;
9922
9923 specified_file = image_spec_value (img->spec, QCfile, NULL);
9924 file = Qnil;
9925 GCPRO1 (file);
9926
9927 if (STRINGP (specified_file))
9928 {
9929 file = x_find_image_file (specified_file);
9930 if (!STRINGP (file))
9931 {
9932 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9933 UNGCPRO;
9934 return 0;
9935 }
9936
9937 contents = pbm_read_file (file, &size);
9938 if (contents == NULL)
9939 {
9940 image_error ("Error reading `%s'", file, Qnil);
9941 UNGCPRO;
9942 return 0;
9943 }
9944
9945 p = contents;
9946 end = contents + size;
9947 }
9948 else
9949 {
9950 Lisp_Object data;
9951 data = image_spec_value (img->spec, QCdata, NULL);
9952 p = XSTRING (data)->data;
9953 end = p + STRING_BYTES (XSTRING (data));
9954 }
9955
9956 /* Check magic number. */
9957 if (end - p < 2 || *p++ != 'P')
9958 {
9959 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
9960 error:
9961 xfree (contents);
9962 UNGCPRO;
9963 return 0;
9964 }
9965
9966 switch (*p++)
9967 {
9968 case '1':
9969 raw_p = 0, type = PBM_MONO;
9970 break;
9971
9972 case '2':
9973 raw_p = 0, type = PBM_GRAY;
9974 break;
9975
9976 case '3':
9977 raw_p = 0, type = PBM_COLOR;
9978 break;
9979
9980 case '4':
9981 raw_p = 1, type = PBM_MONO;
9982 break;
9983
9984 case '5':
9985 raw_p = 1, type = PBM_GRAY;
9986 break;
9987
9988 case '6':
9989 raw_p = 1, type = PBM_COLOR;
9990 break;
9991
9992 default:
9993 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
9994 goto error;
9995 }
9996
9997 /* Read width, height, maximum color-component. Characters
9998 starting with `#' up to the end of a line are ignored. */
9999 width = pbm_scan_number (&p, end);
10000 height = pbm_scan_number (&p, end);
10001
10002 if (type != PBM_MONO)
10003 {
10004 max_color_idx = pbm_scan_number (&p, end);
10005 if (raw_p && max_color_idx > 255)
10006 max_color_idx = 255;
10007 }
10008
10009 if (width < 0
10010 || height < 0
10011 || (type != PBM_MONO && max_color_idx < 0))
10012 goto error;
10013
10014 BLOCK_INPUT;
10015 if (!x_create_x_image_and_pixmap (f, width, height, 0,
10016 &ximg, &img->pixmap))
10017 {
10018 UNBLOCK_INPUT;
10019 goto error;
10020 }
10021
10022 /* Initialize the color hash table. */
10023 init_color_table ();
10024
10025 if (type == PBM_MONO)
10026 {
10027 int c = 0, g;
10028
10029 for (y = 0; y < height; ++y)
10030 for (x = 0; x < width; ++x)
10031 {
10032 if (raw_p)
10033 {
10034 if ((x & 7) == 0)
10035 c = *p++;
10036 g = c & 0x80;
10037 c <<= 1;
10038 }
10039 else
10040 g = pbm_scan_number (&p, end);
10041
10042 XPutPixel (ximg, x, y, (g
10043 ? FRAME_FOREGROUND_PIXEL (f)
10044 : FRAME_BACKGROUND_PIXEL (f)));
10045 }
10046 }
10047 else
10048 {
10049 for (y = 0; y < height; ++y)
10050 for (x = 0; x < width; ++x)
10051 {
10052 int r, g, b;
10053
10054 if (type == PBM_GRAY)
10055 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
10056 else if (raw_p)
10057 {
10058 r = *p++;
10059 g = *p++;
10060 b = *p++;
10061 }
10062 else
10063 {
10064 r = pbm_scan_number (&p, end);
10065 g = pbm_scan_number (&p, end);
10066 b = pbm_scan_number (&p, end);
10067 }
10068
10069 if (r < 0 || g < 0 || b < 0)
10070 {
10071 xfree (ximg->data);
10072 ximg->data = NULL;
10073 XDestroyImage (ximg);
10074 UNBLOCK_INPUT;
10075 image_error ("Invalid pixel value in image `%s'",
10076 img->spec, Qnil);
10077 goto error;
10078 }
10079
10080 /* RGB values are now in the range 0..max_color_idx.
10081 Scale this to the range 0..0xffff supported by X. */
10082 r = (double) r * 65535 / max_color_idx;
10083 g = (double) g * 65535 / max_color_idx;
10084 b = (double) b * 65535 / max_color_idx;
10085 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10086 }
10087 }
10088
10089 /* Store in IMG->colors the colors allocated for the image, and
10090 free the color table. */
10091 img->colors = colors_in_color_table (&img->ncolors);
10092 free_color_table ();
10093
10094 /* Put the image into a pixmap. */
10095 x_put_x_image (f, ximg, img->pixmap, width, height);
10096 x_destroy_x_image (ximg);
10097 UNBLOCK_INPUT;
10098
10099 img->width = width;
10100 img->height = height;
10101
10102 UNGCPRO;
10103 xfree (contents);
10104 return 1;
10105 }
10106 #endif /* HAVE_PBM */
10107
10108 \f
10109 /***********************************************************************
10110 PNG
10111 ***********************************************************************/
10112
10113 #if HAVE_PNG
10114
10115 #include <png.h>
10116
10117 /* Function prototypes. */
10118
10119 static int png_image_p P_ ((Lisp_Object object));
10120 static int png_load P_ ((struct frame *f, struct image *img));
10121
10122 /* The symbol `png' identifying images of this type. */
10123
10124 Lisp_Object Qpng;
10125
10126 /* Indices of image specification fields in png_format, below. */
10127
10128 enum png_keyword_index
10129 {
10130 PNG_TYPE,
10131 PNG_DATA,
10132 PNG_FILE,
10133 PNG_ASCENT,
10134 PNG_MARGIN,
10135 PNG_RELIEF,
10136 PNG_ALGORITHM,
10137 PNG_HEURISTIC_MASK,
10138 PNG_LAST
10139 };
10140
10141 /* Vector of image_keyword structures describing the format
10142 of valid user-defined image specifications. */
10143
10144 static struct image_keyword png_format[PNG_LAST] =
10145 {
10146 {":type", IMAGE_SYMBOL_VALUE, 1},
10147 {":data", IMAGE_STRING_VALUE, 0},
10148 {":file", IMAGE_STRING_VALUE, 0},
10149 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10150 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10151 {":relief", IMAGE_INTEGER_VALUE, 0},
10152 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10153 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10154 };
10155
10156 /* Structure describing the image type `png'. */
10157
10158 static struct image_type png_type =
10159 {
10160 &Qpng,
10161 png_image_p,
10162 png_load,
10163 x_clear_image,
10164 NULL
10165 };
10166
10167
10168 /* Return non-zero if OBJECT is a valid PNG image specification. */
10169
10170 static int
10171 png_image_p (object)
10172 Lisp_Object object;
10173 {
10174 struct image_keyword fmt[PNG_LAST];
10175 bcopy (png_format, fmt, sizeof fmt);
10176
10177 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
10178 || (fmt[PNG_ASCENT].count
10179 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
10180 return 0;
10181
10182 /* Must specify either the :data or :file keyword. */
10183 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
10184 }
10185
10186
10187 /* Error and warning handlers installed when the PNG library
10188 is initialized. */
10189
10190 static void
10191 my_png_error (png_ptr, msg)
10192 png_struct *png_ptr;
10193 char *msg;
10194 {
10195 xassert (png_ptr != NULL);
10196 image_error ("PNG error: %s", build_string (msg), Qnil);
10197 longjmp (png_ptr->jmpbuf, 1);
10198 }
10199
10200
10201 static void
10202 my_png_warning (png_ptr, msg)
10203 png_struct *png_ptr;
10204 char *msg;
10205 {
10206 xassert (png_ptr != NULL);
10207 image_error ("PNG warning: %s", build_string (msg), Qnil);
10208 }
10209
10210 /* Memory source for PNG decoding. */
10211
10212 struct png_memory_storage
10213 {
10214 unsigned char *bytes; /* The data */
10215 size_t len; /* How big is it? */
10216 int index; /* Where are we? */
10217 };
10218
10219
10220 /* Function set as reader function when reading PNG image from memory.
10221 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
10222 bytes from the input to DATA. */
10223
10224 static void
10225 png_read_from_memory (png_ptr, data, length)
10226 png_structp png_ptr;
10227 png_bytep data;
10228 png_size_t length;
10229 {
10230 struct png_memory_storage *tbr
10231 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
10232
10233 if (length > tbr->len - tbr->index)
10234 png_error (png_ptr, "Read error");
10235
10236 bcopy (tbr->bytes + tbr->index, data, length);
10237 tbr->index = tbr->index + length;
10238 }
10239
10240 /* Load PNG image IMG for use on frame F. Value is non-zero if
10241 successful. */
10242
10243 static int
10244 png_load (f, img)
10245 struct frame *f;
10246 struct image *img;
10247 {
10248 Lisp_Object file, specified_file;
10249 Lisp_Object specified_data;
10250 int x, y, i;
10251 XImage *ximg, *mask_img = NULL;
10252 struct gcpro gcpro1;
10253 png_struct *png_ptr = NULL;
10254 png_info *info_ptr = NULL, *end_info = NULL;
10255 FILE *fp = NULL;
10256 png_byte sig[8];
10257 png_byte *pixels = NULL;
10258 png_byte **rows = NULL;
10259 png_uint_32 width, height;
10260 int bit_depth, color_type, interlace_type;
10261 png_byte channels;
10262 png_uint_32 row_bytes;
10263 int transparent_p;
10264 char *gamma_str;
10265 double screen_gamma, image_gamma;
10266 int intent;
10267 struct png_memory_storage tbr; /* Data to be read */
10268
10269 /* Find out what file to load. */
10270 specified_file = image_spec_value (img->spec, QCfile, NULL);
10271 specified_data = image_spec_value (img->spec, QCdata, NULL);
10272 file = Qnil;
10273 GCPRO1 (file);
10274
10275 if (NILP (specified_data))
10276 {
10277 file = x_find_image_file (specified_file);
10278 if (!STRINGP (file))
10279 {
10280 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10281 UNGCPRO;
10282 return 0;
10283 }
10284
10285 /* Open the image file. */
10286 fp = fopen (XSTRING (file)->data, "rb");
10287 if (!fp)
10288 {
10289 image_error ("Cannot open image file `%s'", file, Qnil);
10290 UNGCPRO;
10291 fclose (fp);
10292 return 0;
10293 }
10294
10295 /* Check PNG signature. */
10296 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
10297 || !png_check_sig (sig, sizeof sig))
10298 {
10299 image_error ("Not a PNG file:` %s'", file, Qnil);
10300 UNGCPRO;
10301 fclose (fp);
10302 return 0;
10303 }
10304 }
10305 else
10306 {
10307 /* Read from memory. */
10308 tbr.bytes = XSTRING (specified_data)->data;
10309 tbr.len = STRING_BYTES (XSTRING (specified_data));
10310 tbr.index = 0;
10311
10312 /* Check PNG signature. */
10313 if (tbr.len < sizeof sig
10314 || !png_check_sig (tbr.bytes, sizeof sig))
10315 {
10316 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10317 UNGCPRO;
10318 return 0;
10319 }
10320
10321 /* Need to skip past the signature. */
10322 tbr.bytes += sizeof (sig);
10323 }
10324
10325 /* Initialize read and info structs for PNG lib. */
10326 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10327 my_png_error, my_png_warning);
10328 if (!png_ptr)
10329 {
10330 if (fp) fclose (fp);
10331 UNGCPRO;
10332 return 0;
10333 }
10334
10335 info_ptr = png_create_info_struct (png_ptr);
10336 if (!info_ptr)
10337 {
10338 png_destroy_read_struct (&png_ptr, NULL, NULL);
10339 if (fp) fclose (fp);
10340 UNGCPRO;
10341 return 0;
10342 }
10343
10344 end_info = png_create_info_struct (png_ptr);
10345 if (!end_info)
10346 {
10347 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
10348 if (fp) fclose (fp);
10349 UNGCPRO;
10350 return 0;
10351 }
10352
10353 /* Set error jump-back. We come back here when the PNG library
10354 detects an error. */
10355 if (setjmp (png_ptr->jmpbuf))
10356 {
10357 error:
10358 if (png_ptr)
10359 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10360 xfree (pixels);
10361 xfree (rows);
10362 if (fp) fclose (fp);
10363 UNGCPRO;
10364 return 0;
10365 }
10366
10367 /* Read image info. */
10368 if (!NILP (specified_data))
10369 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
10370 else
10371 png_init_io (png_ptr, fp);
10372
10373 png_set_sig_bytes (png_ptr, sizeof sig);
10374 png_read_info (png_ptr, info_ptr);
10375 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10376 &interlace_type, NULL, NULL);
10377
10378 /* If image contains simply transparency data, we prefer to
10379 construct a clipping mask. */
10380 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
10381 transparent_p = 1;
10382 else
10383 transparent_p = 0;
10384
10385 /* This function is easier to write if we only have to handle
10386 one data format: RGB or RGBA with 8 bits per channel. Let's
10387 transform other formats into that format. */
10388
10389 /* Strip more than 8 bits per channel. */
10390 if (bit_depth == 16)
10391 png_set_strip_16 (png_ptr);
10392
10393 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10394 if available. */
10395 png_set_expand (png_ptr);
10396
10397 /* Convert grayscale images to RGB. */
10398 if (color_type == PNG_COLOR_TYPE_GRAY
10399 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
10400 png_set_gray_to_rgb (png_ptr);
10401
10402 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
10403 gamma_str = getenv ("SCREEN_GAMMA");
10404 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
10405
10406 /* Tell the PNG lib to handle gamma correction for us. */
10407
10408 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10409 if (png_get_sRGB (png_ptr, info_ptr, &intent))
10410 /* There is a special chunk in the image specifying the gamma. */
10411 png_set_sRGB (png_ptr, info_ptr, intent);
10412 else
10413 #endif
10414 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10415 /* Image contains gamma information. */
10416 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10417 else
10418 /* Use a default of 0.5 for the image gamma. */
10419 png_set_gamma (png_ptr, screen_gamma, 0.5);
10420
10421 /* Handle alpha channel by combining the image with a background
10422 color. Do this only if a real alpha channel is supplied. For
10423 simple transparency, we prefer a clipping mask. */
10424 if (!transparent_p)
10425 {
10426 png_color_16 *image_background;
10427
10428 if (png_get_bKGD (png_ptr, info_ptr, &image_background))
10429 /* Image contains a background color with which to
10430 combine the image. */
10431 png_set_background (png_ptr, image_background,
10432 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
10433 else
10434 {
10435 /* Image does not contain a background color with which
10436 to combine the image data via an alpha channel. Use
10437 the frame's background instead. */
10438 XColor color;
10439 Colormap cmap;
10440 png_color_16 frame_background;
10441
10442 BLOCK_INPUT;
10443 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10444 color.pixel = FRAME_BACKGROUND_PIXEL (f);
10445 XQueryColor (FRAME_W32_DISPLAY (f), cmap, &color);
10446 UNBLOCK_INPUT;
10447
10448 bzero (&frame_background, sizeof frame_background);
10449 frame_background.red = color.red;
10450 frame_background.green = color.green;
10451 frame_background.blue = color.blue;
10452
10453 png_set_background (png_ptr, &frame_background,
10454 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10455 }
10456 }
10457
10458 /* Update info structure. */
10459 png_read_update_info (png_ptr, info_ptr);
10460
10461 /* Get number of channels. Valid values are 1 for grayscale images
10462 and images with a palette, 2 for grayscale images with transparency
10463 information (alpha channel), 3 for RGB images, and 4 for RGB
10464 images with alpha channel, i.e. RGBA. If conversions above were
10465 sufficient we should only have 3 or 4 channels here. */
10466 channels = png_get_channels (png_ptr, info_ptr);
10467 xassert (channels == 3 || channels == 4);
10468
10469 /* Number of bytes needed for one row of the image. */
10470 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
10471
10472 /* Allocate memory for the image. */
10473 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10474 rows = (png_byte **) xmalloc (height * sizeof *rows);
10475 for (i = 0; i < height; ++i)
10476 rows[i] = pixels + i * row_bytes;
10477
10478 /* Read the entire image. */
10479 png_read_image (png_ptr, rows);
10480 png_read_end (png_ptr, info_ptr);
10481 if (fp)
10482 {
10483 fclose (fp);
10484 fp = NULL;
10485 }
10486
10487 BLOCK_INPUT;
10488
10489 /* Create the X image and pixmap. */
10490 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10491 &img->pixmap))
10492 {
10493 UNBLOCK_INPUT;
10494 goto error;
10495 }
10496
10497 /* Create an image and pixmap serving as mask if the PNG image
10498 contains an alpha channel. */
10499 if (channels == 4
10500 && !transparent_p
10501 && !x_create_x_image_and_pixmap (f, width, height, 1,
10502 &mask_img, &img->mask))
10503 {
10504 x_destroy_x_image (ximg);
10505 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
10506 img->pixmap = 0;
10507 UNBLOCK_INPUT;
10508 goto error;
10509 }
10510
10511 /* Fill the X image and mask from PNG data. */
10512 init_color_table ();
10513
10514 for (y = 0; y < height; ++y)
10515 {
10516 png_byte *p = rows[y];
10517
10518 for (x = 0; x < width; ++x)
10519 {
10520 unsigned r, g, b;
10521
10522 r = *p++ << 8;
10523 g = *p++ << 8;
10524 b = *p++ << 8;
10525 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10526
10527 /* An alpha channel, aka mask channel, associates variable
10528 transparency with an image. Where other image formats
10529 support binary transparency---fully transparent or fully
10530 opaque---PNG allows up to 254 levels of partial transparency.
10531 The PNG library implements partial transparency by combining
10532 the image with a specified background color.
10533
10534 I'm not sure how to handle this here nicely: because the
10535 background on which the image is displayed may change, for
10536 real alpha channel support, it would be necessary to create
10537 a new image for each possible background.
10538
10539 What I'm doing now is that a mask is created if we have
10540 boolean transparency information. Otherwise I'm using
10541 the frame's background color to combine the image with. */
10542
10543 if (channels == 4)
10544 {
10545 if (mask_img)
10546 XPutPixel (mask_img, x, y, *p > 0);
10547 ++p;
10548 }
10549 }
10550 }
10551
10552 /* Remember colors allocated for this image. */
10553 img->colors = colors_in_color_table (&img->ncolors);
10554 free_color_table ();
10555
10556 /* Clean up. */
10557 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10558 xfree (rows);
10559 xfree (pixels);
10560
10561 img->width = width;
10562 img->height = height;
10563
10564 /* Put the image into the pixmap, then free the X image and its buffer. */
10565 x_put_x_image (f, ximg, img->pixmap, width, height);
10566 x_destroy_x_image (ximg);
10567
10568 /* Same for the mask. */
10569 if (mask_img)
10570 {
10571 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10572 x_destroy_x_image (mask_img);
10573 }
10574
10575 UNBLOCK_INPUT;
10576 UNGCPRO;
10577 return 1;
10578 }
10579
10580 #endif /* HAVE_PNG != 0 */
10581
10582
10583 \f
10584 /***********************************************************************
10585 JPEG
10586 ***********************************************************************/
10587
10588 #if HAVE_JPEG
10589
10590 /* Work around a warning about HAVE_STDLIB_H being redefined in
10591 jconfig.h. */
10592 #ifdef HAVE_STDLIB_H
10593 #define HAVE_STDLIB_H_1
10594 #undef HAVE_STDLIB_H
10595 #endif /* HAVE_STLIB_H */
10596
10597 #include <jpeglib.h>
10598 #include <jerror.h>
10599 #include <setjmp.h>
10600
10601 #ifdef HAVE_STLIB_H_1
10602 #define HAVE_STDLIB_H 1
10603 #endif
10604
10605 static int jpeg_image_p P_ ((Lisp_Object object));
10606 static int jpeg_load P_ ((struct frame *f, struct image *img));
10607
10608 /* The symbol `jpeg' identifying images of this type. */
10609
10610 Lisp_Object Qjpeg;
10611
10612 /* Indices of image specification fields in gs_format, below. */
10613
10614 enum jpeg_keyword_index
10615 {
10616 JPEG_TYPE,
10617 JPEG_DATA,
10618 JPEG_FILE,
10619 JPEG_ASCENT,
10620 JPEG_MARGIN,
10621 JPEG_RELIEF,
10622 JPEG_ALGORITHM,
10623 JPEG_HEURISTIC_MASK,
10624 JPEG_LAST
10625 };
10626
10627 /* Vector of image_keyword structures describing the format
10628 of valid user-defined image specifications. */
10629
10630 static struct image_keyword jpeg_format[JPEG_LAST] =
10631 {
10632 {":type", IMAGE_SYMBOL_VALUE, 1},
10633 {":data", IMAGE_STRING_VALUE, 0},
10634 {":file", IMAGE_STRING_VALUE, 0},
10635 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10636 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10637 {":relief", IMAGE_INTEGER_VALUE, 0},
10638 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10639 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10640 };
10641
10642 /* Structure describing the image type `jpeg'. */
10643
10644 static struct image_type jpeg_type =
10645 {
10646 &Qjpeg,
10647 jpeg_image_p,
10648 jpeg_load,
10649 x_clear_image,
10650 NULL
10651 };
10652
10653
10654 /* Return non-zero if OBJECT is a valid JPEG image specification. */
10655
10656 static int
10657 jpeg_image_p (object)
10658 Lisp_Object object;
10659 {
10660 struct image_keyword fmt[JPEG_LAST];
10661
10662 bcopy (jpeg_format, fmt, sizeof fmt);
10663
10664 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
10665 || (fmt[JPEG_ASCENT].count
10666 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
10667 return 0;
10668
10669 /* Must specify either the :data or :file keyword. */
10670 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
10671 }
10672
10673
10674 struct my_jpeg_error_mgr
10675 {
10676 struct jpeg_error_mgr pub;
10677 jmp_buf setjmp_buffer;
10678 };
10679
10680 static void
10681 my_error_exit (cinfo)
10682 j_common_ptr cinfo;
10683 {
10684 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
10685 longjmp (mgr->setjmp_buffer, 1);
10686 }
10687
10688 /* Init source method for JPEG data source manager. Called by
10689 jpeg_read_header() before any data is actually read. See
10690 libjpeg.doc from the JPEG lib distribution. */
10691
10692 static void
10693 our_init_source (cinfo)
10694 j_decompress_ptr cinfo;
10695 {
10696 }
10697
10698
10699 /* Fill input buffer method for JPEG data source manager. Called
10700 whenever more data is needed. We read the whole image in one step,
10701 so this only adds a fake end of input marker at the end. */
10702
10703 static boolean
10704 our_fill_input_buffer (cinfo)
10705 j_decompress_ptr cinfo;
10706 {
10707 /* Insert a fake EOI marker. */
10708 struct jpeg_source_mgr *src = cinfo->src;
10709 static JOCTET buffer[2];
10710
10711 buffer[0] = (JOCTET) 0xFF;
10712 buffer[1] = (JOCTET) JPEG_EOI;
10713
10714 src->next_input_byte = buffer;
10715 src->bytes_in_buffer = 2;
10716 return TRUE;
10717 }
10718
10719
10720 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
10721 is the JPEG data source manager. */
10722
10723 static void
10724 our_skip_input_data (cinfo, num_bytes)
10725 j_decompress_ptr cinfo;
10726 long num_bytes;
10727 {
10728 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
10729
10730 if (src)
10731 {
10732 if (num_bytes > src->bytes_in_buffer)
10733 ERREXIT (cinfo, JERR_INPUT_EOF);
10734
10735 src->bytes_in_buffer -= num_bytes;
10736 src->next_input_byte += num_bytes;
10737 }
10738 }
10739
10740
10741 /* Method to terminate data source. Called by
10742 jpeg_finish_decompress() after all data has been processed. */
10743
10744 static void
10745 our_term_source (cinfo)
10746 j_decompress_ptr cinfo;
10747 {
10748 }
10749
10750
10751 /* Set up the JPEG lib for reading an image from DATA which contains
10752 LEN bytes. CINFO is the decompression info structure created for
10753 reading the image. */
10754
10755 static void
10756 jpeg_memory_src (cinfo, data, len)
10757 j_decompress_ptr cinfo;
10758 JOCTET *data;
10759 unsigned int len;
10760 {
10761 struct jpeg_source_mgr *src;
10762
10763 if (cinfo->src == NULL)
10764 {
10765 /* First time for this JPEG object? */
10766 cinfo->src = (struct jpeg_source_mgr *)
10767 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
10768 sizeof (struct jpeg_source_mgr));
10769 src = (struct jpeg_source_mgr *) cinfo->src;
10770 src->next_input_byte = data;
10771 }
10772
10773 src = (struct jpeg_source_mgr *) cinfo->src;
10774 src->init_source = our_init_source;
10775 src->fill_input_buffer = our_fill_input_buffer;
10776 src->skip_input_data = our_skip_input_data;
10777 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
10778 src->term_source = our_term_source;
10779 src->bytes_in_buffer = len;
10780 src->next_input_byte = data;
10781 }
10782
10783
10784 /* Load image IMG for use on frame F. Patterned after example.c
10785 from the JPEG lib. */
10786
10787 static int
10788 jpeg_load (f, img)
10789 struct frame *f;
10790 struct image *img;
10791 {
10792 struct jpeg_decompress_struct cinfo;
10793 struct my_jpeg_error_mgr mgr;
10794 Lisp_Object file, specified_file;
10795 Lisp_Object specified_data;
10796 FILE *fp = NULL;
10797 JSAMPARRAY buffer;
10798 int row_stride, x, y;
10799 XImage *ximg = NULL;
10800 int rc;
10801 unsigned long *colors;
10802 int width, height;
10803 struct gcpro gcpro1;
10804
10805 /* Open the JPEG file. */
10806 specified_file = image_spec_value (img->spec, QCfile, NULL);
10807 specified_data = image_spec_value (img->spec, QCdata, NULL);
10808 file = Qnil;
10809 GCPRO1 (file);
10810
10811 if (NILP (specified_data))
10812 {
10813 file = x_find_image_file (specified_file);
10814 if (!STRINGP (file))
10815 {
10816 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10817 UNGCPRO;
10818 return 0;
10819 }
10820
10821 fp = fopen (XSTRING (file)->data, "r");
10822 if (fp == NULL)
10823 {
10824 image_error ("Cannot open `%s'", file, Qnil);
10825 UNGCPRO;
10826 return 0;
10827 }
10828 }
10829
10830 /* Customize libjpeg's error handling to call my_error_exit when an
10831 error is detected. This function will perform a longjmp. */
10832 mgr.pub.error_exit = my_error_exit;
10833 cinfo.err = jpeg_std_error (&mgr.pub);
10834
10835 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
10836 {
10837 if (rc == 1)
10838 {
10839 /* Called from my_error_exit. Display a JPEG error. */
10840 char buffer[JMSG_LENGTH_MAX];
10841 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
10842 image_error ("Error reading JPEG image `%s': %s", img->spec,
10843 build_string (buffer));
10844 }
10845
10846 /* Close the input file and destroy the JPEG object. */
10847 if (fp)
10848 fclose (fp);
10849 jpeg_destroy_decompress (&cinfo);
10850
10851 BLOCK_INPUT;
10852
10853 /* If we already have an XImage, free that. */
10854 x_destroy_x_image (ximg);
10855
10856 /* Free pixmap and colors. */
10857 x_clear_image (f, img);
10858
10859 UNBLOCK_INPUT;
10860 UNGCPRO;
10861 return 0;
10862 }
10863
10864 /* Create the JPEG decompression object. Let it read from fp.
10865 Read the JPEG image header. */
10866 jpeg_create_decompress (&cinfo);
10867
10868 if (NILP (specified_data))
10869 jpeg_stdio_src (&cinfo, fp);
10870 else
10871 jpeg_memory_src (&cinfo, XSTRING (specified_data)->data,
10872 STRING_BYTES (XSTRING (specified_data)));
10873
10874 jpeg_read_header (&cinfo, TRUE);
10875
10876 /* Customize decompression so that color quantization will be used.
10877 Start decompression. */
10878 cinfo.quantize_colors = TRUE;
10879 jpeg_start_decompress (&cinfo);
10880 width = img->width = cinfo.output_width;
10881 height = img->height = cinfo.output_height;
10882
10883 BLOCK_INPUT;
10884
10885 /* Create X image and pixmap. */
10886 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10887 &img->pixmap))
10888 {
10889 UNBLOCK_INPUT;
10890 longjmp (mgr.setjmp_buffer, 2);
10891 }
10892
10893 /* Allocate colors. When color quantization is used,
10894 cinfo.actual_number_of_colors has been set with the number of
10895 colors generated, and cinfo.colormap is a two-dimensional array
10896 of color indices in the range 0..cinfo.actual_number_of_colors.
10897 No more than 255 colors will be generated. */
10898 {
10899 int i, ir, ig, ib;
10900
10901 if (cinfo.out_color_components > 2)
10902 ir = 0, ig = 1, ib = 2;
10903 else if (cinfo.out_color_components > 1)
10904 ir = 0, ig = 1, ib = 0;
10905 else
10906 ir = 0, ig = 0, ib = 0;
10907
10908 /* Use the color table mechanism because it handles colors that
10909 cannot be allocated nicely. Such colors will be replaced with
10910 a default color, and we don't have to care about which colors
10911 can be freed safely, and which can't. */
10912 init_color_table ();
10913 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
10914 * sizeof *colors);
10915
10916 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
10917 {
10918 /* Multiply RGB values with 255 because X expects RGB values
10919 in the range 0..0xffff. */
10920 int r = cinfo.colormap[ir][i] << 8;
10921 int g = cinfo.colormap[ig][i] << 8;
10922 int b = cinfo.colormap[ib][i] << 8;
10923 colors[i] = lookup_rgb_color (f, r, g, b);
10924 }
10925
10926 /* Remember those colors actually allocated. */
10927 img->colors = colors_in_color_table (&img->ncolors);
10928 free_color_table ();
10929 }
10930
10931 /* Read pixels. */
10932 row_stride = width * cinfo.output_components;
10933 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
10934 row_stride, 1);
10935 for (y = 0; y < height; ++y)
10936 {
10937 jpeg_read_scanlines (&cinfo, buffer, 1);
10938 for (x = 0; x < cinfo.output_width; ++x)
10939 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
10940 }
10941
10942 /* Clean up. */
10943 jpeg_finish_decompress (&cinfo);
10944 jpeg_destroy_decompress (&cinfo);
10945 if (fp)
10946 fclose (fp);
10947
10948 /* Put the image into the pixmap. */
10949 x_put_x_image (f, ximg, img->pixmap, width, height);
10950 x_destroy_x_image (ximg);
10951 UNBLOCK_INPUT;
10952 UNGCPRO;
10953 return 1;
10954 }
10955
10956 #endif /* HAVE_JPEG */
10957
10958
10959 \f
10960 /***********************************************************************
10961 TIFF
10962 ***********************************************************************/
10963
10964 #if HAVE_TIFF
10965
10966 #include <tiffio.h>
10967
10968 static int tiff_image_p P_ ((Lisp_Object object));
10969 static int tiff_load P_ ((struct frame *f, struct image *img));
10970
10971 /* The symbol `tiff' identifying images of this type. */
10972
10973 Lisp_Object Qtiff;
10974
10975 /* Indices of image specification fields in tiff_format, below. */
10976
10977 enum tiff_keyword_index
10978 {
10979 TIFF_TYPE,
10980 TIFF_DATA,
10981 TIFF_FILE,
10982 TIFF_ASCENT,
10983 TIFF_MARGIN,
10984 TIFF_RELIEF,
10985 TIFF_ALGORITHM,
10986 TIFF_HEURISTIC_MASK,
10987 TIFF_LAST
10988 };
10989
10990 /* Vector of image_keyword structures describing the format
10991 of valid user-defined image specifications. */
10992
10993 static struct image_keyword tiff_format[TIFF_LAST] =
10994 {
10995 {":type", IMAGE_SYMBOL_VALUE, 1},
10996 {":data", IMAGE_STRING_VALUE, 0},
10997 {":file", IMAGE_STRING_VALUE, 0},
10998 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10999 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11000 {":relief", IMAGE_INTEGER_VALUE, 0},
11001 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11002 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11003 };
11004
11005 /* Structure describing the image type `tiff'. */
11006
11007 static struct image_type tiff_type =
11008 {
11009 &Qtiff,
11010 tiff_image_p,
11011 tiff_load,
11012 x_clear_image,
11013 NULL
11014 };
11015
11016
11017 /* Return non-zero if OBJECT is a valid TIFF image specification. */
11018
11019 static int
11020 tiff_image_p (object)
11021 Lisp_Object object;
11022 {
11023 struct image_keyword fmt[TIFF_LAST];
11024 bcopy (tiff_format, fmt, sizeof fmt);
11025
11026 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
11027 || (fmt[TIFF_ASCENT].count
11028 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
11029 return 0;
11030
11031 /* Must specify either the :data or :file keyword. */
11032 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
11033 }
11034
11035
11036 /* Reading from a memory buffer for TIFF images Based on the PNG
11037 memory source, but we have to provide a lot of extra functions.
11038 Blah.
11039
11040 We really only need to implement read and seek, but I am not
11041 convinced that the TIFF library is smart enough not to destroy
11042 itself if we only hand it the function pointers we need to
11043 override. */
11044
11045 typedef struct
11046 {
11047 unsigned char *bytes;
11048 size_t len;
11049 int index;
11050 }
11051 tiff_memory_source;
11052
11053 static size_t
11054 tiff_read_from_memory (data, buf, size)
11055 thandle_t data;
11056 tdata_t buf;
11057 tsize_t size;
11058 {
11059 tiff_memory_source *src = (tiff_memory_source *) data;
11060
11061 if (size > src->len - src->index)
11062 return (size_t) -1;
11063 bcopy (src->bytes + src->index, buf, size);
11064 src->index += size;
11065 return size;
11066 }
11067
11068 static size_t
11069 tiff_write_from_memory (data, buf, size)
11070 thandle_t data;
11071 tdata_t buf;
11072 tsize_t size;
11073 {
11074 return (size_t) -1;
11075 }
11076
11077 static toff_t
11078 tiff_seek_in_memory (data, off, whence)
11079 thandle_t data;
11080 toff_t off;
11081 int whence;
11082 {
11083 tiff_memory_source *src = (tiff_memory_source *) data;
11084 int idx;
11085
11086 switch (whence)
11087 {
11088 case SEEK_SET: /* Go from beginning of source. */
11089 idx = off;
11090 break;
11091
11092 case SEEK_END: /* Go from end of source. */
11093 idx = src->len + off;
11094 break;
11095
11096 case SEEK_CUR: /* Go from current position. */
11097 idx = src->index + off;
11098 break;
11099
11100 default: /* Invalid `whence'. */
11101 return -1;
11102 }
11103
11104 if (idx > src->len || idx < 0)
11105 return -1;
11106
11107 src->index = idx;
11108 return src->index;
11109 }
11110
11111 static int
11112 tiff_close_memory (data)
11113 thandle_t data;
11114 {
11115 /* NOOP */
11116 return 0;
11117 }
11118
11119 static int
11120 tiff_mmap_memory (data, pbase, psize)
11121 thandle_t data;
11122 tdata_t *pbase;
11123 toff_t *psize;
11124 {
11125 /* It is already _IN_ memory. */
11126 return 0;
11127 }
11128
11129 static void
11130 tiff_unmap_memory (data, base, size)
11131 thandle_t data;
11132 tdata_t base;
11133 toff_t size;
11134 {
11135 /* We don't need to do this. */
11136 }
11137
11138 static toff_t
11139 tiff_size_of_memory (data)
11140 thandle_t data;
11141 {
11142 return ((tiff_memory_source *) data)->len;
11143 }
11144
11145 /* Load TIFF image IMG for use on frame F. Value is non-zero if
11146 successful. */
11147
11148 static int
11149 tiff_load (f, img)
11150 struct frame *f;
11151 struct image *img;
11152 {
11153 Lisp_Object file, specified_file;
11154 Lisp_Object specified_data;
11155 TIFF *tiff;
11156 int width, height, x, y;
11157 uint32 *buf;
11158 int rc;
11159 XImage *ximg;
11160 struct gcpro gcpro1;
11161 tiff_memory_source memsrc;
11162
11163 specified_file = image_spec_value (img->spec, QCfile, NULL);
11164 specified_data = image_spec_value (img->spec, QCdata, NULL);
11165 file = Qnil;
11166 GCPRO1 (file);
11167
11168 if (NILP (specified_data))
11169 {
11170 /* Read from a file */
11171 file = x_find_image_file (specified_file);
11172 if (!STRINGP (file))
11173 {
11174 image_error ("Cannot find image file `%s'", file, Qnil);
11175 UNGCPRO;
11176 return 0;
11177 }
11178
11179 /* Try to open the image file. */
11180 tiff = TIFFOpen (XSTRING (file)->data, "r");
11181 if (tiff == NULL)
11182 {
11183 image_error ("Cannot open `%s'", file, Qnil);
11184 UNGCPRO;
11185 return 0;
11186 }
11187 }
11188 else
11189 {
11190 /* Memory source! */
11191 memsrc.bytes = XSTRING (specified_data)->data;
11192 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11193 memsrc.index = 0;
11194
11195 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
11196 (TIFFReadWriteProc) tiff_read_from_memory,
11197 (TIFFReadWriteProc) tiff_write_from_memory,
11198 tiff_seek_in_memory,
11199 tiff_close_memory,
11200 tiff_size_of_memory,
11201 tiff_mmap_memory,
11202 tiff_unmap_memory);
11203
11204 if (!tiff)
11205 {
11206 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
11207 UNGCPRO;
11208 return 0;
11209 }
11210 }
11211
11212 /* Get width and height of the image, and allocate a raster buffer
11213 of width x height 32-bit values. */
11214 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
11215 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
11216 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
11217
11218 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
11219 TIFFClose (tiff);
11220 if (!rc)
11221 {
11222 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
11223 xfree (buf);
11224 UNGCPRO;
11225 return 0;
11226 }
11227
11228 BLOCK_INPUT;
11229
11230 /* Create the X image and pixmap. */
11231 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11232 {
11233 UNBLOCK_INPUT;
11234 xfree (buf);
11235 UNGCPRO;
11236 return 0;
11237 }
11238
11239 /* Initialize the color table. */
11240 init_color_table ();
11241
11242 /* Process the pixel raster. Origin is in the lower-left corner. */
11243 for (y = 0; y < height; ++y)
11244 {
11245 uint32 *row = buf + y * width;
11246
11247 for (x = 0; x < width; ++x)
11248 {
11249 uint32 abgr = row[x];
11250 int r = TIFFGetR (abgr) << 8;
11251 int g = TIFFGetG (abgr) << 8;
11252 int b = TIFFGetB (abgr) << 8;
11253 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
11254 }
11255 }
11256
11257 /* Remember the colors allocated for the image. Free the color table. */
11258 img->colors = colors_in_color_table (&img->ncolors);
11259 free_color_table ();
11260
11261 /* Put the image into the pixmap, then free the X image and its buffer. */
11262 x_put_x_image (f, ximg, img->pixmap, width, height);
11263 x_destroy_x_image (ximg);
11264 xfree (buf);
11265 UNBLOCK_INPUT;
11266
11267 img->width = width;
11268 img->height = height;
11269
11270 UNGCPRO;
11271 return 1;
11272 }
11273
11274 #endif /* HAVE_TIFF != 0 */
11275
11276
11277 \f
11278 /***********************************************************************
11279 GIF
11280 ***********************************************************************/
11281
11282 #if HAVE_GIF
11283
11284 #include <gif_lib.h>
11285
11286 static int gif_image_p P_ ((Lisp_Object object));
11287 static int gif_load P_ ((struct frame *f, struct image *img));
11288
11289 /* The symbol `gif' identifying images of this type. */
11290
11291 Lisp_Object Qgif;
11292
11293 /* Indices of image specification fields in gif_format, below. */
11294
11295 enum gif_keyword_index
11296 {
11297 GIF_TYPE,
11298 GIF_DATA,
11299 GIF_FILE,
11300 GIF_ASCENT,
11301 GIF_MARGIN,
11302 GIF_RELIEF,
11303 GIF_ALGORITHM,
11304 GIF_HEURISTIC_MASK,
11305 GIF_IMAGE,
11306 GIF_LAST
11307 };
11308
11309 /* Vector of image_keyword structures describing the format
11310 of valid user-defined image specifications. */
11311
11312 static struct image_keyword gif_format[GIF_LAST] =
11313 {
11314 {":type", IMAGE_SYMBOL_VALUE, 1},
11315 {":data", IMAGE_STRING_VALUE, 0},
11316 {":file", IMAGE_STRING_VALUE, 0},
11317 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11318 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11319 {":relief", IMAGE_INTEGER_VALUE, 0},
11320 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11321 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11322 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
11323 };
11324
11325 /* Structure describing the image type `gif'. */
11326
11327 static struct image_type gif_type =
11328 {
11329 &Qgif,
11330 gif_image_p,
11331 gif_load,
11332 x_clear_image,
11333 NULL
11334 };
11335
11336 /* Return non-zero if OBJECT is a valid GIF image specification. */
11337
11338 static int
11339 gif_image_p (object)
11340 Lisp_Object object;
11341 {
11342 struct image_keyword fmt[GIF_LAST];
11343 bcopy (gif_format, fmt, sizeof fmt);
11344
11345 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
11346 || (fmt[GIF_ASCENT].count
11347 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
11348 return 0;
11349
11350 /* Must specify either the :data or :file keyword. */
11351 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11352 }
11353
11354 /* Reading a GIF image from memory
11355 Based on the PNG memory stuff to a certain extent. */
11356
11357 typedef struct
11358 {
11359 unsigned char *bytes;
11360 size_t len;
11361 int index;
11362 }
11363 gif_memory_source;
11364
11365 /* Make the current memory source available to gif_read_from_memory.
11366 It's done this way because not all versions of libungif support
11367 a UserData field in the GifFileType structure. */
11368 static gif_memory_source *current_gif_memory_src;
11369
11370 static int
11371 gif_read_from_memory (file, buf, len)
11372 GifFileType *file;
11373 GifByteType *buf;
11374 int len;
11375 {
11376 gif_memory_source *src = current_gif_memory_src;
11377
11378 if (len > src->len - src->index)
11379 return -1;
11380
11381 bcopy (src->bytes + src->index, buf, len);
11382 src->index += len;
11383 return len;
11384 }
11385
11386
11387 /* Load GIF image IMG for use on frame F. Value is non-zero if
11388 successful. */
11389
11390 static int
11391 gif_load (f, img)
11392 struct frame *f;
11393 struct image *img;
11394 {
11395 Lisp_Object file, specified_file;
11396 Lisp_Object specified_data;
11397 int rc, width, height, x, y, i;
11398 XImage *ximg;
11399 ColorMapObject *gif_color_map;
11400 unsigned long pixel_colors[256];
11401 GifFileType *gif;
11402 struct gcpro gcpro1;
11403 Lisp_Object image;
11404 int ino, image_left, image_top, image_width, image_height;
11405 gif_memory_source memsrc;
11406 unsigned char *raster;
11407
11408 specified_file = image_spec_value (img->spec, QCfile, NULL);
11409 specified_data = image_spec_value (img->spec, QCdata, NULL);
11410 file = Qnil;
11411 GCPRO1 (file);
11412
11413 if (NILP (specified_data))
11414 {
11415 file = x_find_image_file (specified_file);
11416 if (!STRINGP (file))
11417 {
11418 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11419 UNGCPRO;
11420 return 0;
11421 }
11422
11423 /* Open the GIF file. */
11424 gif = DGifOpenFileName (XSTRING (file)->data);
11425 if (gif == NULL)
11426 {
11427 image_error ("Cannot open `%s'", file, Qnil);
11428 UNGCPRO;
11429 return 0;
11430 }
11431 }
11432 else
11433 {
11434 /* Read from memory! */
11435 current_gif_memory_src = &memsrc;
11436 memsrc.bytes = XSTRING (specified_data)->data;
11437 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11438 memsrc.index = 0;
11439
11440 gif = DGifOpen(&memsrc, gif_read_from_memory);
11441 if (!gif)
11442 {
11443 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11444 UNGCPRO;
11445 return 0;
11446 }
11447 }
11448
11449 /* Read entire contents. */
11450 rc = DGifSlurp (gif);
11451 if (rc == GIF_ERROR)
11452 {
11453 image_error ("Error reading `%s'", img->spec, Qnil);
11454 DGifCloseFile (gif);
11455 UNGCPRO;
11456 return 0;
11457 }
11458
11459 image = image_spec_value (img->spec, QCindex, NULL);
11460 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11461 if (ino >= gif->ImageCount)
11462 {
11463 image_error ("Invalid image number `%s' in image `%s'",
11464 image, img->spec);
11465 DGifCloseFile (gif);
11466 UNGCPRO;
11467 return 0;
11468 }
11469
11470 width = img->width = gif->SWidth;
11471 height = img->height = gif->SHeight;
11472
11473 BLOCK_INPUT;
11474
11475 /* Create the X image and pixmap. */
11476 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11477 {
11478 UNBLOCK_INPUT;
11479 DGifCloseFile (gif);
11480 UNGCPRO;
11481 return 0;
11482 }
11483
11484 /* Allocate colors. */
11485 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11486 if (!gif_color_map)
11487 gif_color_map = gif->SColorMap;
11488 init_color_table ();
11489 bzero (pixel_colors, sizeof pixel_colors);
11490
11491 for (i = 0; i < gif_color_map->ColorCount; ++i)
11492 {
11493 int r = gif_color_map->Colors[i].Red << 8;
11494 int g = gif_color_map->Colors[i].Green << 8;
11495 int b = gif_color_map->Colors[i].Blue << 8;
11496 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
11497 }
11498
11499 img->colors = colors_in_color_table (&img->ncolors);
11500 free_color_table ();
11501
11502 /* Clear the part of the screen image that are not covered by
11503 the image from the GIF file. Full animated GIF support
11504 requires more than can be done here (see the gif89 spec,
11505 disposal methods). Let's simply assume that the part
11506 not covered by a sub-image is in the frame's background color. */
11507 image_top = gif->SavedImages[ino].ImageDesc.Top;
11508 image_left = gif->SavedImages[ino].ImageDesc.Left;
11509 image_width = gif->SavedImages[ino].ImageDesc.Width;
11510 image_height = gif->SavedImages[ino].ImageDesc.Height;
11511
11512 for (y = 0; y < image_top; ++y)
11513 for (x = 0; x < width; ++x)
11514 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11515
11516 for (y = image_top + image_height; y < height; ++y)
11517 for (x = 0; x < width; ++x)
11518 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11519
11520 for (y = image_top; y < image_top + image_height; ++y)
11521 {
11522 for (x = 0; x < image_left; ++x)
11523 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11524 for (x = image_left + image_width; x < width; ++x)
11525 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11526 }
11527
11528 /* Read the GIF image into the X image. We use a local variable
11529 `raster' here because RasterBits below is a char *, and invites
11530 problems with bytes >= 0x80. */
11531 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
11532
11533 if (gif->SavedImages[ino].ImageDesc.Interlace)
11534 {
11535 static int interlace_start[] = {0, 4, 2, 1};
11536 static int interlace_increment[] = {8, 8, 4, 2};
11537 int pass, inc;
11538 int row = interlace_start[0];
11539
11540 pass = 0;
11541
11542 for (y = 0; y < image_height; y++)
11543 {
11544 if (row >= image_height)
11545 {
11546 row = interlace_start[++pass];
11547 while (row >= image_height)
11548 row = interlace_start[++pass];
11549 }
11550
11551 for (x = 0; x < image_width; x++)
11552 {
11553 int i = raster[(y * image_width) + x];
11554 XPutPixel (ximg, x + image_left, row + image_top,
11555 pixel_colors[i]);
11556 }
11557
11558 row += interlace_increment[pass];
11559 }
11560 }
11561 else
11562 {
11563 for (y = 0; y < image_height; ++y)
11564 for (x = 0; x < image_width; ++x)
11565 {
11566 int i = raster[y* image_width + x];
11567 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
11568 }
11569 }
11570
11571 DGifCloseFile (gif);
11572
11573 /* Put the image into the pixmap, then free the X image and its buffer. */
11574 x_put_x_image (f, ximg, img->pixmap, width, height);
11575 x_destroy_x_image (ximg);
11576 UNBLOCK_INPUT;
11577
11578 UNGCPRO;
11579 return 1;
11580 }
11581
11582 #endif /* HAVE_GIF != 0 */
11583
11584
11585 \f
11586 /***********************************************************************
11587 Ghostscript
11588 ***********************************************************************/
11589
11590 #ifdef HAVE_GHOSTSCRIPT
11591 static int gs_image_p P_ ((Lisp_Object object));
11592 static int gs_load P_ ((struct frame *f, struct image *img));
11593 static void gs_clear_image P_ ((struct frame *f, struct image *img));
11594
11595 /* The symbol `postscript' identifying images of this type. */
11596
11597 Lisp_Object Qpostscript;
11598
11599 /* Keyword symbols. */
11600
11601 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
11602
11603 /* Indices of image specification fields in gs_format, below. */
11604
11605 enum gs_keyword_index
11606 {
11607 GS_TYPE,
11608 GS_PT_WIDTH,
11609 GS_PT_HEIGHT,
11610 GS_FILE,
11611 GS_LOADER,
11612 GS_BOUNDING_BOX,
11613 GS_ASCENT,
11614 GS_MARGIN,
11615 GS_RELIEF,
11616 GS_ALGORITHM,
11617 GS_HEURISTIC_MASK,
11618 GS_LAST
11619 };
11620
11621 /* Vector of image_keyword structures describing the format
11622 of valid user-defined image specifications. */
11623
11624 static struct image_keyword gs_format[GS_LAST] =
11625 {
11626 {":type", IMAGE_SYMBOL_VALUE, 1},
11627 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11628 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11629 {":file", IMAGE_STRING_VALUE, 1},
11630 {":loader", IMAGE_FUNCTION_VALUE, 0},
11631 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
11632 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11633 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11634 {":relief", IMAGE_INTEGER_VALUE, 0},
11635 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11636 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11637 };
11638
11639 /* Structure describing the image type `ghostscript'. */
11640
11641 static struct image_type gs_type =
11642 {
11643 &Qpostscript,
11644 gs_image_p,
11645 gs_load,
11646 gs_clear_image,
11647 NULL
11648 };
11649
11650
11651 /* Free X resources of Ghostscript image IMG which is used on frame F. */
11652
11653 static void
11654 gs_clear_image (f, img)
11655 struct frame *f;
11656 struct image *img;
11657 {
11658 /* IMG->data.ptr_val may contain a recorded colormap. */
11659 xfree (img->data.ptr_val);
11660 x_clear_image (f, img);
11661 }
11662
11663
11664 /* Return non-zero if OBJECT is a valid Ghostscript image
11665 specification. */
11666
11667 static int
11668 gs_image_p (object)
11669 Lisp_Object object;
11670 {
11671 struct image_keyword fmt[GS_LAST];
11672 Lisp_Object tem;
11673 int i;
11674
11675 bcopy (gs_format, fmt, sizeof fmt);
11676
11677 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
11678 || (fmt[GS_ASCENT].count
11679 && XFASTINT (fmt[GS_ASCENT].value) > 100))
11680 return 0;
11681
11682 /* Bounding box must be a list or vector containing 4 integers. */
11683 tem = fmt[GS_BOUNDING_BOX].value;
11684 if (CONSP (tem))
11685 {
11686 for (i = 0; i < 4; ++i, tem = XCDR (tem))
11687 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
11688 return 0;
11689 if (!NILP (tem))
11690 return 0;
11691 }
11692 else if (VECTORP (tem))
11693 {
11694 if (XVECTOR (tem)->size != 4)
11695 return 0;
11696 for (i = 0; i < 4; ++i)
11697 if (!INTEGERP (XVECTOR (tem)->contents[i]))
11698 return 0;
11699 }
11700 else
11701 return 0;
11702
11703 return 1;
11704 }
11705
11706
11707 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
11708 if successful. */
11709
11710 static int
11711 gs_load (f, img)
11712 struct frame *f;
11713 struct image *img;
11714 {
11715 char buffer[100];
11716 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
11717 struct gcpro gcpro1, gcpro2;
11718 Lisp_Object frame;
11719 double in_width, in_height;
11720 Lisp_Object pixel_colors = Qnil;
11721
11722 /* Compute pixel size of pixmap needed from the given size in the
11723 image specification. Sizes in the specification are in pt. 1 pt
11724 = 1/72 in, xdpi and ydpi are stored in the frame's X display
11725 info. */
11726 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
11727 in_width = XFASTINT (pt_width) / 72.0;
11728 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
11729 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
11730 in_height = XFASTINT (pt_height) / 72.0;
11731 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
11732
11733 /* Create the pixmap. */
11734 BLOCK_INPUT;
11735 xassert (img->pixmap == 0);
11736 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11737 img->width, img->height,
11738 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
11739 UNBLOCK_INPUT;
11740
11741 if (!img->pixmap)
11742 {
11743 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
11744 return 0;
11745 }
11746
11747 /* Call the loader to fill the pixmap. It returns a process object
11748 if successful. We do not record_unwind_protect here because
11749 other places in redisplay like calling window scroll functions
11750 don't either. Let the Lisp loader use `unwind-protect' instead. */
11751 GCPRO2 (window_and_pixmap_id, pixel_colors);
11752
11753 sprintf (buffer, "%lu %lu",
11754 (unsigned long) FRAME_W32_WINDOW (f),
11755 (unsigned long) img->pixmap);
11756 window_and_pixmap_id = build_string (buffer);
11757
11758 sprintf (buffer, "%lu %lu",
11759 FRAME_FOREGROUND_PIXEL (f),
11760 FRAME_BACKGROUND_PIXEL (f));
11761 pixel_colors = build_string (buffer);
11762
11763 XSETFRAME (frame, f);
11764 loader = image_spec_value (img->spec, QCloader, NULL);
11765 if (NILP (loader))
11766 loader = intern ("gs-load-image");
11767
11768 img->data.lisp_val = call6 (loader, frame, img->spec,
11769 make_number (img->width),
11770 make_number (img->height),
11771 window_and_pixmap_id,
11772 pixel_colors);
11773 UNGCPRO;
11774 return PROCESSP (img->data.lisp_val);
11775 }
11776
11777
11778 /* Kill the Ghostscript process that was started to fill PIXMAP on
11779 frame F. Called from XTread_socket when receiving an event
11780 telling Emacs that Ghostscript has finished drawing. */
11781
11782 void
11783 x_kill_gs_process (pixmap, f)
11784 Pixmap pixmap;
11785 struct frame *f;
11786 {
11787 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
11788 int class, i;
11789 struct image *img;
11790
11791 /* Find the image containing PIXMAP. */
11792 for (i = 0; i < c->used; ++i)
11793 if (c->images[i]->pixmap == pixmap)
11794 break;
11795
11796 /* Kill the GS process. We should have found PIXMAP in the image
11797 cache and its image should contain a process object. */
11798 xassert (i < c->used);
11799 img = c->images[i];
11800 xassert (PROCESSP (img->data.lisp_val));
11801 Fkill_process (img->data.lisp_val, Qnil);
11802 img->data.lisp_val = Qnil;
11803
11804 /* On displays with a mutable colormap, figure out the colors
11805 allocated for the image by looking at the pixels of an XImage for
11806 img->pixmap. */
11807 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
11808 if (class != StaticColor && class != StaticGray && class != TrueColor)
11809 {
11810 XImage *ximg;
11811
11812 BLOCK_INPUT;
11813
11814 /* Try to get an XImage for img->pixmep. */
11815 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
11816 0, 0, img->width, img->height, ~0, ZPixmap);
11817 if (ximg)
11818 {
11819 int x, y;
11820
11821 /* Initialize the color table. */
11822 init_color_table ();
11823
11824 /* For each pixel of the image, look its color up in the
11825 color table. After having done so, the color table will
11826 contain an entry for each color used by the image. */
11827 for (y = 0; y < img->height; ++y)
11828 for (x = 0; x < img->width; ++x)
11829 {
11830 unsigned long pixel = XGetPixel (ximg, x, y);
11831 lookup_pixel_color (f, pixel);
11832 }
11833
11834 /* Record colors in the image. Free color table and XImage. */
11835 img->colors = colors_in_color_table (&img->ncolors);
11836 free_color_table ();
11837 XDestroyImage (ximg);
11838
11839 #if 0 /* This doesn't seem to be the case. If we free the colors
11840 here, we get a BadAccess later in x_clear_image when
11841 freeing the colors. */
11842 /* We have allocated colors once, but Ghostscript has also
11843 allocated colors on behalf of us. So, to get the
11844 reference counts right, free them once. */
11845 if (img->ncolors)
11846 {
11847 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
11848 XFreeColors (FRAME_W32_DISPLAY (f), cmap,
11849 img->colors, img->ncolors, 0);
11850 }
11851 #endif
11852 }
11853 else
11854 image_error ("Cannot get X image of `%s'; colors will not be freed",
11855 img->spec, Qnil);
11856
11857 UNBLOCK_INPUT;
11858 }
11859 }
11860
11861 #endif /* HAVE_GHOSTSCRIPT */
11862
11863 \f
11864 /***********************************************************************
11865 Window properties
11866 ***********************************************************************/
11867
11868 DEFUN ("x-change-window-property", Fx_change_window_property,
11869 Sx_change_window_property, 2, 3, 0,
11870 "Change window property PROP to VALUE on the X window of FRAME.\n\
11871 PROP and VALUE must be strings. FRAME nil or omitted means use the\n\
11872 selected frame. Value is VALUE.")
11873 (prop, value, frame)
11874 Lisp_Object frame, prop, value;
11875 {
11876 #if 0 /* TODO : port window properties to W32 */
11877 struct frame *f = check_x_frame (frame);
11878 Atom prop_atom;
11879
11880 CHECK_STRING (prop, 1);
11881 CHECK_STRING (value, 2);
11882
11883 BLOCK_INPUT;
11884 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11885 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11886 prop_atom, XA_STRING, 8, PropModeReplace,
11887 XSTRING (value)->data, XSTRING (value)->size);
11888
11889 /* Make sure the property is set when we return. */
11890 XFlush (FRAME_W32_DISPLAY (f));
11891 UNBLOCK_INPUT;
11892
11893 #endif /* TODO */
11894
11895 return value;
11896 }
11897
11898
11899 DEFUN ("x-delete-window-property", Fx_delete_window_property,
11900 Sx_delete_window_property, 1, 2, 0,
11901 "Remove window property PROP from X window of FRAME.\n\
11902 FRAME nil or omitted means use the selected frame. Value is PROP.")
11903 (prop, frame)
11904 Lisp_Object prop, frame;
11905 {
11906 #if 0 /* TODO : port window properties to W32 */
11907
11908 struct frame *f = check_x_frame (frame);
11909 Atom prop_atom;
11910
11911 CHECK_STRING (prop, 1);
11912 BLOCK_INPUT;
11913 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11914 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
11915
11916 /* Make sure the property is removed when we return. */
11917 XFlush (FRAME_W32_DISPLAY (f));
11918 UNBLOCK_INPUT;
11919 #endif /* TODO */
11920
11921 return prop;
11922 }
11923
11924
11925 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
11926 1, 2, 0,
11927 "Value is the value of window property PROP on FRAME.\n\
11928 If FRAME is nil or omitted, use the selected frame. Value is nil\n\
11929 if FRAME hasn't a property with name PROP or if PROP has no string\n\
11930 value.")
11931 (prop, frame)
11932 Lisp_Object prop, frame;
11933 {
11934 #if 0 /* TODO : port window properties to W32 */
11935
11936 struct frame *f = check_x_frame (frame);
11937 Atom prop_atom;
11938 int rc;
11939 Lisp_Object prop_value = Qnil;
11940 char *tmp_data = NULL;
11941 Atom actual_type;
11942 int actual_format;
11943 unsigned long actual_size, bytes_remaining;
11944
11945 CHECK_STRING (prop, 1);
11946 BLOCK_INPUT;
11947 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11948 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11949 prop_atom, 0, 0, False, XA_STRING,
11950 &actual_type, &actual_format, &actual_size,
11951 &bytes_remaining, (unsigned char **) &tmp_data);
11952 if (rc == Success)
11953 {
11954 int size = bytes_remaining;
11955
11956 XFree (tmp_data);
11957 tmp_data = NULL;
11958
11959 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11960 prop_atom, 0, bytes_remaining,
11961 False, XA_STRING,
11962 &actual_type, &actual_format,
11963 &actual_size, &bytes_remaining,
11964 (unsigned char **) &tmp_data);
11965 if (rc == Success)
11966 prop_value = make_string (tmp_data, size);
11967
11968 XFree (tmp_data);
11969 }
11970
11971 UNBLOCK_INPUT;
11972
11973 return prop_value;
11974
11975 #endif /* TODO */
11976 return Qnil;
11977 }
11978
11979
11980 \f
11981 /***********************************************************************
11982 Busy cursor
11983 ***********************************************************************/
11984
11985 /* If non-null, an asynchronous timer that, when it expires, displays
11986 a busy cursor on all frames. */
11987
11988 static struct atimer *busy_cursor_atimer;
11989
11990 /* Non-zero means a busy cursor is currently shown. */
11991
11992 static int busy_cursor_shown_p;
11993
11994 /* Number of seconds to wait before displaying a busy cursor. */
11995
11996 static Lisp_Object Vbusy_cursor_delay;
11997
11998 /* Default number of seconds to wait before displaying a busy
11999 cursor. */
12000
12001 #define DEFAULT_BUSY_CURSOR_DELAY 1
12002
12003 /* Function prototypes. */
12004
12005 static void show_busy_cursor P_ ((struct atimer *));
12006 static void hide_busy_cursor P_ ((void));
12007
12008
12009 /* Cancel a currently active busy-cursor timer, and start a new one. */
12010
12011 void
12012 start_busy_cursor ()
12013 {
12014 #if 0 /* TODO: cursor shape changes. */
12015 EMACS_TIME delay;
12016 int secs, usecs = 0;
12017
12018 cancel_busy_cursor ();
12019
12020 if (INTEGERP (Vbusy_cursor_delay)
12021 && XINT (Vbusy_cursor_delay) > 0)
12022 secs = XFASTINT (Vbusy_cursor_delay);
12023 else if (FLOATP (Vbusy_cursor_delay)
12024 && XFLOAT_DATA (Vbusy_cursor_delay) > 0)
12025 {
12026 Lisp_Object tem;
12027 tem = Ftruncate (Vbusy_cursor_delay, Qnil);
12028 secs = XFASTINT (tem);
12029 usecs = (XFLOAT_DATA (Vbusy_cursor_delay) - secs) * 1000000;
12030 }
12031 else
12032 secs = DEFAULT_BUSY_CURSOR_DELAY;
12033
12034 EMACS_SET_SECS_USECS (delay, secs, usecs);
12035 busy_cursor_atimer = start_atimer (ATIMER_RELATIVE, delay,
12036 show_busy_cursor, NULL);
12037 #endif
12038 }
12039
12040
12041 /* Cancel the busy cursor timer if active, hide a busy cursor if
12042 shown. */
12043
12044 void
12045 cancel_busy_cursor ()
12046 {
12047 if (busy_cursor_atimer)
12048 {
12049 cancel_atimer (busy_cursor_atimer);
12050 busy_cursor_atimer = NULL;
12051 }
12052
12053 if (busy_cursor_shown_p)
12054 hide_busy_cursor ();
12055 }
12056
12057
12058 /* Timer function of busy_cursor_atimer. TIMER is equal to
12059 busy_cursor_atimer.
12060
12061 Display a busy cursor on all frames by mapping the frames'
12062 busy_window. Set the busy_p flag in the frames' output_data.x
12063 structure to indicate that a busy cursor is shown on the
12064 frames. */
12065
12066 static void
12067 show_busy_cursor (timer)
12068 struct atimer *timer;
12069 {
12070 #if 0 /* TODO: cursor shape changes. */
12071 /* The timer implementation will cancel this timer automatically
12072 after this function has run. Set busy_cursor_atimer to null
12073 so that we know the timer doesn't have to be canceled. */
12074 busy_cursor_atimer = NULL;
12075
12076 if (!busy_cursor_shown_p)
12077 {
12078 Lisp_Object rest, frame;
12079
12080 BLOCK_INPUT;
12081
12082 FOR_EACH_FRAME (rest, frame)
12083 if (FRAME_X_P (XFRAME (frame)))
12084 {
12085 struct frame *f = XFRAME (frame);
12086
12087 f->output_data.w32->busy_p = 1;
12088
12089 if (!f->output_data.w32->busy_window)
12090 {
12091 unsigned long mask = CWCursor;
12092 XSetWindowAttributes attrs;
12093
12094 attrs.cursor = f->output_data.w32->busy_cursor;
12095
12096 f->output_data.w32->busy_window
12097 = XCreateWindow (FRAME_X_DISPLAY (f),
12098 FRAME_OUTER_WINDOW (f),
12099 0, 0, 32000, 32000, 0, 0,
12100 InputOnly,
12101 CopyFromParent,
12102 mask, &attrs);
12103 }
12104
12105 XMapRaised (FRAME_X_DISPLAY (f), f->output_data.w32->busy_window);
12106 XFlush (FRAME_X_DISPLAY (f));
12107 }
12108
12109 busy_cursor_shown_p = 1;
12110 UNBLOCK_INPUT;
12111 }
12112 #endif
12113 }
12114
12115
12116 /* Hide the busy cursor on all frames, if it is currently shown. */
12117
12118 static void
12119 hide_busy_cursor ()
12120 {
12121 #if 0 /* TODO: cursor shape changes. */
12122 if (busy_cursor_shown_p)
12123 {
12124 Lisp_Object rest, frame;
12125
12126 BLOCK_INPUT;
12127 FOR_EACH_FRAME (rest, frame)
12128 {
12129 struct frame *f = XFRAME (frame);
12130
12131 if (FRAME_X_P (f)
12132 /* Watch out for newly created frames. */
12133 && f->output_data.x->busy_window)
12134 {
12135 XUnmapWindow (FRAME_X_DISPLAY (f), f->output_data.x->busy_window);
12136 /* Sync here because XTread_socket looks at the busy_p flag
12137 that is reset to zero below. */
12138 XSync (FRAME_X_DISPLAY (f), False);
12139 f->output_data.x->busy_p = 0;
12140 }
12141 }
12142
12143 busy_cursor_shown_p = 0;
12144 UNBLOCK_INPUT;
12145 }
12146 #endif
12147 }
12148
12149
12150 \f
12151 /***********************************************************************
12152 Tool tips
12153 ***********************************************************************/
12154
12155 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
12156 Lisp_Object));
12157
12158 /* The frame of a currently visible tooltip, or null. */
12159
12160 struct frame *tip_frame;
12161
12162 /* If non-nil, a timer started that hides the last tooltip when it
12163 fires. */
12164
12165 Lisp_Object tip_timer;
12166 Window tip_window;
12167
12168 /* Create a frame for a tooltip on the display described by DPYINFO.
12169 PARMS is a list of frame parameters. Value is the frame. */
12170
12171 static Lisp_Object
12172 x_create_tip_frame (dpyinfo, parms)
12173 struct w32_display_info *dpyinfo;
12174 Lisp_Object parms;
12175 {
12176 #if 0 /* TODO : w32 version */
12177 struct frame *f;
12178 Lisp_Object frame, tem;
12179 Lisp_Object name;
12180 long window_prompting = 0;
12181 int width, height;
12182 int count = specpdl_ptr - specpdl;
12183 struct gcpro gcpro1, gcpro2, gcpro3;
12184 struct kboard *kb;
12185
12186 check_x ();
12187
12188 /* Use this general default value to start with until we know if
12189 this frame has a specified name. */
12190 Vx_resource_name = Vinvocation_name;
12191
12192 #ifdef MULTI_KBOARD
12193 kb = dpyinfo->kboard;
12194 #else
12195 kb = &the_only_kboard;
12196 #endif
12197
12198 /* Get the name of the frame to use for resource lookup. */
12199 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
12200 if (!STRINGP (name)
12201 && !EQ (name, Qunbound)
12202 && !NILP (name))
12203 error ("Invalid frame name--not a string or nil");
12204 Vx_resource_name = name;
12205
12206 frame = Qnil;
12207 GCPRO3 (parms, name, frame);
12208 tip_frame = f = make_frame (1);
12209 XSETFRAME (frame, f);
12210 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
12211
12212 f->output_method = output_w32;
12213 f->output_data.w32 =
12214 (struct w32_output *) xmalloc (sizeof (struct w32_output));
12215 bzero (f->output_data.w32, sizeof (struct w32_output));
12216 #if 0
12217 f->output_data.w32->icon_bitmap = -1;
12218 #endif
12219 f->output_data.w32->fontset = -1;
12220 f->icon_name = Qnil;
12221
12222 #ifdef MULTI_KBOARD
12223 FRAME_KBOARD (f) = kb;
12224 #endif
12225 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12226 f->output_data.w32->explicit_parent = 0;
12227
12228 /* Set the name; the functions to which we pass f expect the name to
12229 be set. */
12230 if (EQ (name, Qunbound) || NILP (name))
12231 {
12232 f->name = build_string (dpyinfo->x_id_name);
12233 f->explicit_name = 0;
12234 }
12235 else
12236 {
12237 f->name = name;
12238 f->explicit_name = 1;
12239 /* use the frame's title when getting resources for this frame. */
12240 specbind (Qx_resource_name, name);
12241 }
12242
12243 /* Extract the window parameters from the supplied values
12244 that are needed to determine window geometry. */
12245 {
12246 Lisp_Object font;
12247
12248 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12249
12250 BLOCK_INPUT;
12251 /* First, try whatever font the caller has specified. */
12252 if (STRINGP (font))
12253 {
12254 tem = Fquery_fontset (font, Qnil);
12255 if (STRINGP (tem))
12256 font = x_new_fontset (f, XSTRING (tem)->data);
12257 else
12258 font = x_new_font (f, XSTRING (font)->data);
12259 }
12260
12261 /* Try out a font which we hope has bold and italic variations. */
12262 if (!STRINGP (font))
12263 font = x_new_font (f, "-*-courier new-normal-r-*-*-*-100-*-*-*-*-iso8859-1");
12264 if (!STRINGP (font))
12265 font = x_new_font (f, "-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12266 if (! STRINGP (font))
12267 font = x_new_font (f, "-*-*-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12268 if (! STRINGP (font))
12269 /* This was formerly the first thing tried, but it finds too many fonts
12270 and takes too long. */
12271 font = x_new_font (f, "-*-*-medium-r-*-*-*-*-*-*-c-*-iso8859-1");
12272 /* If those didn't work, look for something which will at least work. */
12273 if (! STRINGP (font))
12274 font = x_new_font (f, "-*-fixed-*-*-*-*-*-140-*-*-c-*-iso8859-1");
12275 UNBLOCK_INPUT;
12276 if (! STRINGP (font))
12277 font = build_string ("fixed");
12278
12279 x_default_parameter (f, parms, Qfont, font,
12280 "font", "Font", RES_TYPE_STRING);
12281 }
12282
12283 x_default_parameter (f, parms, Qborder_width, make_number (2),
12284 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
12285
12286 /* This defaults to 2 in order to match xterm. We recognize either
12287 internalBorderWidth or internalBorder (which is what xterm calls
12288 it). */
12289 if (NILP (Fassq (Qinternal_border_width, parms)))
12290 {
12291 Lisp_Object value;
12292
12293 value = w32_get_arg (parms, Qinternal_border_width,
12294 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12295 if (! EQ (value, Qunbound))
12296 parms = Fcons (Fcons (Qinternal_border_width, value),
12297 parms);
12298 }
12299
12300 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
12301 "internalBorderWidth", "internalBorderWidth",
12302 RES_TYPE_NUMBER);
12303
12304 /* Also do the stuff which must be set before the window exists. */
12305 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12306 "foreground", "Foreground", RES_TYPE_STRING);
12307 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12308 "background", "Background", RES_TYPE_STRING);
12309 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12310 "pointerColor", "Foreground", RES_TYPE_STRING);
12311 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12312 "cursorColor", "Foreground", RES_TYPE_STRING);
12313 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12314 "borderColor", "BorderColor", RES_TYPE_STRING);
12315
12316 /* Init faces before x_default_parameter is called for scroll-bar
12317 parameters because that function calls x_set_scroll_bar_width,
12318 which calls change_frame_size, which calls Fset_window_buffer,
12319 which runs hooks, which call Fvertical_motion. At the end, we
12320 end up in init_iterator with a null face cache, which should not
12321 happen. */
12322 init_frame_faces (f);
12323
12324 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12325 window_prompting = x_figure_window_size (f, parms);
12326
12327 if (window_prompting & XNegative)
12328 {
12329 if (window_prompting & YNegative)
12330 f->output_data.w32->win_gravity = SouthEastGravity;
12331 else
12332 f->output_data.w32->win_gravity = NorthEastGravity;
12333 }
12334 else
12335 {
12336 if (window_prompting & YNegative)
12337 f->output_data.w32->win_gravity = SouthWestGravity;
12338 else
12339 f->output_data.w32->win_gravity = NorthWestGravity;
12340 }
12341
12342 f->output_data.w32->size_hint_flags = window_prompting;
12343 {
12344 XSetWindowAttributes attrs;
12345 unsigned long mask;
12346
12347 BLOCK_INPUT;
12348 mask = CWBackPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask;
12349 /* Window managers looks at the override-redirect flag to
12350 determine whether or net to give windows a decoration (Xlib
12351 3.2.8). */
12352 attrs.override_redirect = True;
12353 attrs.save_under = True;
12354 attrs.background_pixel = FRAME_BACKGROUND_PIXEL (f);
12355 /* Arrange for getting MapNotify and UnmapNotify events. */
12356 attrs.event_mask = StructureNotifyMask;
12357 tip_window
12358 = FRAME_W32_WINDOW (f)
12359 = XCreateWindow (FRAME_W32_DISPLAY (f),
12360 FRAME_W32_DISPLAY_INFO (f)->root_window,
12361 /* x, y, width, height */
12362 0, 0, 1, 1,
12363 /* Border. */
12364 1,
12365 CopyFromParent, InputOutput, CopyFromParent,
12366 mask, &attrs);
12367 UNBLOCK_INPUT;
12368 }
12369
12370 x_make_gc (f);
12371
12372 x_default_parameter (f, parms, Qauto_raise, Qnil,
12373 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12374 x_default_parameter (f, parms, Qauto_lower, Qnil,
12375 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12376 x_default_parameter (f, parms, Qcursor_type, Qbox,
12377 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12378
12379 /* Dimensions, especially f->height, must be done via change_frame_size.
12380 Change will not be effected unless different from the current
12381 f->height. */
12382 width = f->width;
12383 height = f->height;
12384 f->height = 0;
12385 SET_FRAME_WIDTH (f, 0);
12386 change_frame_size (f, height, width, 1, 0, 0);
12387
12388 f->no_split = 1;
12389
12390 UNGCPRO;
12391
12392 /* It is now ok to make the frame official even if we get an error
12393 below. And the frame needs to be on Vframe_list or making it
12394 visible won't work. */
12395 Vframe_list = Fcons (frame, Vframe_list);
12396
12397 /* Now that the frame is official, it counts as a reference to
12398 its display. */
12399 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
12400
12401 return unbind_to (count, frame);
12402 #endif /* TODO */
12403 return Qnil;
12404 }
12405
12406 #ifdef TODO /* Tooltip support not complete. */
12407 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
12408 "Show STRING in a \"tooltip\" window on frame FRAME.\n\
12409 A tooltip window is a small X window displaying a string.\n\
12410 \n\
12411 FRAME nil or omitted means use the selected frame.\n\
12412 \n\
12413 PARMS is an optional list of frame parameters which can be\n\
12414 used to change the tooltip's appearance.\n\
12415 \n\
12416 Automatically hide the tooltip after TIMEOUT seconds.\n\
12417 TIMEOUT nil means use the default timeout of 5 seconds.\n\
12418 \n\
12419 If the list of frame parameters PARAMS contains a `left' parameters,\n\
12420 the tooltip is displayed at that x-position. Otherwise it is\n\
12421 displayed at the mouse position, with offset DX added (default is 5 if\n\
12422 DX isn't specified). Likewise for the y-position; if a `top' frame\n\
12423 parameter is specified, it determines the y-position of the tooltip\n\
12424 window, otherwise it is displayed at the mouse position, with offset\n\
12425 DY added (default is -5).")
12426 (string, frame, parms, timeout, dx, dy)
12427 Lisp_Object string, frame, parms, timeout, dx, dy;
12428 {
12429 struct frame *f;
12430 struct window *w;
12431 Window root, child;
12432 Lisp_Object buffer, top, left;
12433 struct buffer *old_buffer;
12434 struct text_pos pos;
12435 int i, width, height;
12436 int root_x, root_y, win_x, win_y;
12437 unsigned pmask;
12438 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
12439 int old_windows_or_buffers_changed = windows_or_buffers_changed;
12440 int count = specpdl_ptr - specpdl;
12441
12442 specbind (Qinhibit_redisplay, Qt);
12443
12444 GCPRO4 (string, parms, frame, timeout);
12445
12446 CHECK_STRING (string, 0);
12447 f = check_x_frame (frame);
12448 if (NILP (timeout))
12449 timeout = make_number (5);
12450 else
12451 CHECK_NATNUM (timeout, 2);
12452
12453 if (NILP (dx))
12454 dx = make_number (5);
12455 else
12456 CHECK_NUMBER (dx, 5);
12457
12458 if (NILP (dy))
12459 dy = make_number (-5);
12460 else
12461 CHECK_NUMBER (dy, 6);
12462
12463 /* Hide a previous tip, if any. */
12464 Fx_hide_tip ();
12465
12466 /* Add default values to frame parameters. */
12467 if (NILP (Fassq (Qname, parms)))
12468 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
12469 if (NILP (Fassq (Qinternal_border_width, parms)))
12470 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
12471 if (NILP (Fassq (Qborder_width, parms)))
12472 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
12473 if (NILP (Fassq (Qborder_color, parms)))
12474 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
12475 if (NILP (Fassq (Qbackground_color, parms)))
12476 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
12477 parms);
12478
12479 /* Create a frame for the tooltip, and record it in the global
12480 variable tip_frame. */
12481 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms);
12482 tip_frame = f = XFRAME (frame);
12483
12484 /* Set up the frame's root window. Currently we use a size of 80
12485 columns x 40 lines. If someone wants to show a larger tip, he
12486 will loose. I don't think this is a realistic case. */
12487 w = XWINDOW (FRAME_ROOT_WINDOW (f));
12488 w->left = w->top = make_number (0);
12489 w->width = 80;
12490 w->height = 40;
12491 adjust_glyphs (f);
12492 w->pseudo_window_p = 1;
12493
12494 /* Display the tooltip text in a temporary buffer. */
12495 buffer = Fget_buffer_create (build_string (" *tip*"));
12496 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
12497 old_buffer = current_buffer;
12498 set_buffer_internal_1 (XBUFFER (buffer));
12499 Ferase_buffer ();
12500 Finsert (make_number (1), &string);
12501 clear_glyph_matrix (w->desired_matrix);
12502 clear_glyph_matrix (w->current_matrix);
12503 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
12504 try_window (FRAME_ROOT_WINDOW (f), pos);
12505
12506 /* Compute width and height of the tooltip. */
12507 width = height = 0;
12508 for (i = 0; i < w->desired_matrix->nrows; ++i)
12509 {
12510 struct glyph_row *row = &w->desired_matrix->rows[i];
12511 struct glyph *last;
12512 int row_width;
12513
12514 /* Stop at the first empty row at the end. */
12515 if (!row->enabled_p || !row->displays_text_p)
12516 break;
12517
12518 /* Let the row go over the full width of the frame. */
12519 row->full_width_p = 1;
12520
12521 /* There's a glyph at the end of rows that is use to place
12522 the cursor there. Don't include the width of this glyph. */
12523 if (row->used[TEXT_AREA])
12524 {
12525 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
12526 row_width = row->pixel_width - last->pixel_width;
12527 }
12528 else
12529 row_width = row->pixel_width;
12530
12531 height += row->height;
12532 width = max (width, row_width);
12533 }
12534
12535 /* Add the frame's internal border to the width and height the X
12536 window should have. */
12537 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12538 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12539
12540 /* User-specified position? */
12541 left = Fcdr (Fassq (Qleft, parms));
12542 top = Fcdr (Fassq (Qtop, parms));
12543
12544 /* Move the tooltip window where the mouse pointer is. Resize and
12545 show it. */
12546 #if 0 /* TODO : W32 specifics */
12547 BLOCK_INPUT;
12548 XQueryPointer (FRAME_X_DISPLAY (f), FRAME_X_DISPLAY_INFO (f)->root_window,
12549 &root, &child, &root_x, &root_y, &win_x, &win_y, &pmask);
12550 UNBLOCK_INPUT;
12551
12552 root_x += XINT (dx);
12553 root_y += XINT (dy);
12554
12555 if (INTEGERP (left))
12556 root_x = XINT (left);
12557 if (INTEGERP (top))
12558 root_y = XINT (top);
12559
12560 BLOCK_INPUT;
12561 XMoveResizeWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12562 root_x, root_y - height, width, height);
12563 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12564 UNBLOCK_INPUT;
12565 #endif /* TODO */
12566
12567 /* Draw into the window. */
12568 w->must_be_updated_p = 1;
12569 update_single_window (w, 1);
12570
12571 /* Restore original current buffer. */
12572 set_buffer_internal_1 (old_buffer);
12573 windows_or_buffers_changed = old_windows_or_buffers_changed;
12574
12575 /* Let the tip disappear after timeout seconds. */
12576 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
12577 intern ("x-hide-tip"));
12578
12579 UNGCPRO;
12580 return unbind_to (count, Qnil);
12581 }
12582
12583
12584 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
12585 "Hide the current tooltip window, if there is any.\n\
12586 Value is t is tooltip was open, nil otherwise.")
12587 ()
12588 {
12589 int count = specpdl_ptr - specpdl;
12590 int deleted_p = 0;
12591
12592 specbind (Qinhibit_redisplay, Qt);
12593
12594 if (!NILP (tip_timer))
12595 {
12596 call1 (intern ("cancel-timer"), tip_timer);
12597 tip_timer = Qnil;
12598 }
12599
12600 if (tip_frame)
12601 {
12602 Lisp_Object frame;
12603
12604 XSETFRAME (frame, tip_frame);
12605 Fdelete_frame (frame, Qt);
12606 tip_frame = NULL;
12607 deleted_p = 1;
12608 }
12609
12610 return unbind_to (count, deleted_p ? Qt : Qnil);
12611 }
12612 #endif
12613
12614
12615 \f
12616 /***********************************************************************
12617 File selection dialog
12618 ***********************************************************************/
12619
12620 extern Lisp_Object Qfile_name_history;
12621
12622 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
12623 "Read file name, prompting with PROMPT in directory DIR.\n\
12624 Use a file selection dialog.\n\
12625 Select DEFAULT-FILENAME in the dialog's file selection box, if\n\
12626 specified. Don't let the user enter a file name in the file\n\
12627 selection dialog's entry field, if MUSTMATCH is non-nil.")
12628 (prompt, dir, default_filename, mustmatch)
12629 Lisp_Object prompt, dir, default_filename, mustmatch;
12630 {
12631 struct frame *f = SELECTED_FRAME ();
12632 Lisp_Object file = Qnil;
12633 int count = specpdl_ptr - specpdl;
12634 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
12635 char filename[MAX_PATH + 1];
12636 char init_dir[MAX_PATH + 1];
12637 int use_dialog_p = 1;
12638
12639 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
12640 CHECK_STRING (prompt, 0);
12641 CHECK_STRING (dir, 1);
12642
12643 /* Create the dialog with PROMPT as title, using DIR as initial
12644 directory and using "*" as pattern. */
12645 dir = Fexpand_file_name (dir, Qnil);
12646 strncpy (init_dir, XSTRING (dir)->data, MAX_PATH);
12647 init_dir[MAX_PATH] = '\0';
12648 unixtodos_filename (init_dir);
12649
12650 if (STRINGP (default_filename))
12651 {
12652 char *file_name_only;
12653 char *full_path_name = XSTRING (default_filename)->data;
12654
12655 unixtodos_filename (full_path_name);
12656
12657 file_name_only = strrchr (full_path_name, '\\');
12658 if (!file_name_only)
12659 file_name_only = full_path_name;
12660 else
12661 {
12662 file_name_only++;
12663
12664 /* If default_file_name is a directory, don't use the open
12665 file dialog, as it does not support selecting
12666 directories. */
12667 if (!(*file_name_only))
12668 use_dialog_p = 0;
12669 }
12670
12671 strncpy (filename, file_name_only, MAX_PATH);
12672 filename[MAX_PATH] = '\0';
12673 }
12674 else
12675 filename[0] = '\0';
12676
12677 if (use_dialog_p)
12678 {
12679 OPENFILENAME file_details;
12680 char *filename_file;
12681
12682 /* Prevent redisplay. */
12683 specbind (Qinhibit_redisplay, Qt);
12684 BLOCK_INPUT;
12685
12686 bzero (&file_details, sizeof (file_details));
12687 file_details.lStructSize = sizeof (file_details);
12688 file_details.hwndOwner = FRAME_W32_WINDOW (f);
12689 file_details.lpstrFile = filename;
12690 file_details.nMaxFile = sizeof (filename);
12691 file_details.lpstrInitialDir = init_dir;
12692 file_details.lpstrTitle = XSTRING (prompt)->data;
12693 file_details.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
12694
12695 if (!NILP (mustmatch))
12696 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
12697
12698 if (GetOpenFileName (&file_details))
12699 {
12700 dostounix_filename (filename);
12701 file = build_string (filename);
12702 }
12703 else
12704 file = Qnil;
12705
12706 UNBLOCK_INPUT;
12707 file = unbind_to (count, file);
12708 }
12709 /* Open File dialog will not allow folders to be selected, so resort
12710 to minibuffer completing reads for directories. */
12711 else
12712 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
12713 dir, mustmatch, dir, Qfile_name_history,
12714 default_filename, Qnil);
12715
12716 UNGCPRO;
12717
12718 /* Make "Cancel" equivalent to C-g. */
12719 if (NILP (file))
12720 Fsignal (Qquit, Qnil);
12721
12722 return unbind_to (count, file);
12723 }
12724
12725
12726 \f
12727 /***********************************************************************
12728 Tests
12729 ***********************************************************************/
12730
12731 #if GLYPH_DEBUG
12732
12733 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
12734 "Value is non-nil if SPEC is a valid image specification.")
12735 (spec)
12736 Lisp_Object spec;
12737 {
12738 return valid_image_p (spec) ? Qt : Qnil;
12739 }
12740
12741
12742 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
12743 (spec)
12744 Lisp_Object spec;
12745 {
12746 int id = -1;
12747
12748 if (valid_image_p (spec))
12749 id = lookup_image (SELECTED_FRAME (), spec);
12750
12751 debug_print (spec);
12752 return make_number (id);
12753 }
12754
12755 #endif /* GLYPH_DEBUG != 0 */
12756
12757
12758 \f
12759 /***********************************************************************
12760 w32 specialized functions
12761 ***********************************************************************/
12762
12763 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 1, 0,
12764 "This will display the W32 font dialog and return an X font string corresponding to the selection.")
12765 (frame)
12766 Lisp_Object frame;
12767 {
12768 FRAME_PTR f = check_x_frame (frame);
12769 CHOOSEFONT cf;
12770 LOGFONT lf;
12771 TEXTMETRIC tm;
12772 HDC hdc;
12773 HANDLE oldobj;
12774 char buf[100];
12775
12776 bzero (&cf, sizeof (cf));
12777 bzero (&lf, sizeof (lf));
12778
12779 cf.lStructSize = sizeof (cf);
12780 cf.hwndOwner = FRAME_W32_WINDOW (f);
12781 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS;
12782 cf.lpLogFont = &lf;
12783
12784 /* Initialize as much of the font details as we can from the current
12785 default font. */
12786 hdc = GetDC (FRAME_W32_WINDOW (f));
12787 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
12788 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
12789 if (GetTextMetrics (hdc, &tm))
12790 {
12791 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
12792 lf.lfWeight = tm.tmWeight;
12793 lf.lfItalic = tm.tmItalic;
12794 lf.lfUnderline = tm.tmUnderlined;
12795 lf.lfStrikeOut = tm.tmStruckOut;
12796 lf.lfCharSet = tm.tmCharSet;
12797 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
12798 }
12799 SelectObject (hdc, oldobj);
12800 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
12801
12802 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
12803 return Qnil;
12804
12805 return build_string (buf);
12806 }
12807
12808 DEFUN ("w32-send-sys-command", Fw32_send_sys_command, Sw32_send_sys_command, 1, 2, 0,
12809 "Send frame a Windows WM_SYSCOMMAND message of type COMMAND.\n\
12810 Some useful values for command are 0xf030 to maximise frame (0xf020\n\
12811 to minimize), 0xf120 to restore frame to original size, and 0xf100\n\
12812 to activate the menubar for keyboard access. 0xf140 activates the\n\
12813 screen saver if defined.\n\
12814 \n\
12815 If optional parameter FRAME is not specified, use selected frame.")
12816 (command, frame)
12817 Lisp_Object command, frame;
12818 {
12819 WPARAM code;
12820 FRAME_PTR f = check_x_frame (frame);
12821
12822 CHECK_NUMBER (command, 0);
12823
12824 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
12825
12826 return Qnil;
12827 }
12828
12829 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
12830 "Get Windows to perform OPERATION on DOCUMENT.\n\
12831 This is a wrapper around the ShellExecute system function, which\n\
12832 invokes the application registered to handle OPERATION for DOCUMENT.\n\
12833 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be\n\
12834 nil for the default action), and DOCUMENT is typically the name of a\n\
12835 document file or URL, but can also be a program executable to run or\n\
12836 a directory to open in the Windows Explorer.\n\
12837 \n\
12838 If DOCUMENT is a program executable, PARAMETERS can be a string\n\
12839 containing command line parameters, but otherwise should be nil.\n\
12840 \n\
12841 SHOW-FLAG can be used to control whether the invoked application is hidden\n\
12842 or minimized. If SHOW-FLAG is nil, the application is displayed normally,\n\
12843 otherwise it is an integer representing a ShowWindow flag:\n\
12844 \n\
12845 0 - start hidden\n\
12846 1 - start normally\n\
12847 3 - start maximized\n\
12848 6 - start minimized")
12849 (operation, document, parameters, show_flag)
12850 Lisp_Object operation, document, parameters, show_flag;
12851 {
12852 Lisp_Object current_dir;
12853
12854 CHECK_STRING (document, 0);
12855
12856 /* Encode filename and current directory. */
12857 current_dir = ENCODE_FILE (current_buffer->directory);
12858 document = ENCODE_FILE (document);
12859 if ((int) ShellExecute (NULL,
12860 (STRINGP (operation) ?
12861 XSTRING (operation)->data : NULL),
12862 XSTRING (document)->data,
12863 (STRINGP (parameters) ?
12864 XSTRING (parameters)->data : NULL),
12865 XSTRING (current_dir)->data,
12866 (INTEGERP (show_flag) ?
12867 XINT (show_flag) : SW_SHOWDEFAULT))
12868 > 32)
12869 return Qt;
12870 error ("ShellExecute failed");
12871 }
12872
12873 /* Lookup virtual keycode from string representing the name of a
12874 non-ascii keystroke into the corresponding virtual key, using
12875 lispy_function_keys. */
12876 static int
12877 lookup_vk_code (char *key)
12878 {
12879 int i;
12880
12881 for (i = 0; i < 256; i++)
12882 if (lispy_function_keys[i] != 0
12883 && strcmp (lispy_function_keys[i], key) == 0)
12884 return i;
12885
12886 return -1;
12887 }
12888
12889 /* Convert a one-element vector style key sequence to a hot key
12890 definition. */
12891 static int
12892 w32_parse_hot_key (key)
12893 Lisp_Object key;
12894 {
12895 /* Copied from Fdefine_key and store_in_keymap. */
12896 register Lisp_Object c;
12897 int vk_code;
12898 int lisp_modifiers;
12899 int w32_modifiers;
12900 struct gcpro gcpro1;
12901
12902 CHECK_VECTOR (key, 0);
12903
12904 if (XFASTINT (Flength (key)) != 1)
12905 return Qnil;
12906
12907 GCPRO1 (key);
12908
12909 c = Faref (key, make_number (0));
12910
12911 if (CONSP (c) && lucid_event_type_list_p (c))
12912 c = Fevent_convert_list (c);
12913
12914 UNGCPRO;
12915
12916 if (! INTEGERP (c) && ! SYMBOLP (c))
12917 error ("Key definition is invalid");
12918
12919 /* Work out the base key and the modifiers. */
12920 if (SYMBOLP (c))
12921 {
12922 c = parse_modifiers (c);
12923 lisp_modifiers = Fcar (Fcdr (c));
12924 c = Fcar (c);
12925 if (!SYMBOLP (c))
12926 abort ();
12927 vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
12928 }
12929 else if (INTEGERP (c))
12930 {
12931 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
12932 /* Many ascii characters are their own virtual key code. */
12933 vk_code = XINT (c) & CHARACTERBITS;
12934 }
12935
12936 if (vk_code < 0 || vk_code > 255)
12937 return Qnil;
12938
12939 if ((lisp_modifiers & meta_modifier) != 0
12940 && !NILP (Vw32_alt_is_meta))
12941 lisp_modifiers |= alt_modifier;
12942
12943 /* Supply defs missing from mingw32. */
12944 #ifndef MOD_ALT
12945 #define MOD_ALT 0x0001
12946 #define MOD_CONTROL 0x0002
12947 #define MOD_SHIFT 0x0004
12948 #define MOD_WIN 0x0008
12949 #endif
12950
12951 /* Convert lisp modifiers to Windows hot-key form. */
12952 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
12953 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
12954 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
12955 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
12956
12957 return HOTKEY (vk_code, w32_modifiers);
12958 }
12959
12960 DEFUN ("w32-register-hot-key", Fw32_register_hot_key, Sw32_register_hot_key, 1, 1, 0,
12961 "Register KEY as a hot-key combination.\n\
12962 Certain key combinations like Alt-Tab are reserved for system use on\n\
12963 Windows, and therefore are normally intercepted by the system. However,\n\
12964 most of these key combinations can be received by registering them as\n\
12965 hot-keys, overriding their special meaning.\n\
12966 \n\
12967 KEY must be a one element key definition in vector form that would be\n\
12968 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta\n\
12969 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper\n\
12970 is always interpreted as the Windows modifier keys.\n\
12971 \n\
12972 The return value is the hotkey-id if registered, otherwise nil.")
12973 (key)
12974 Lisp_Object key;
12975 {
12976 key = w32_parse_hot_key (key);
12977
12978 if (NILP (Fmemq (key, w32_grabbed_keys)))
12979 {
12980 /* Reuse an empty slot if possible. */
12981 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
12982
12983 /* Safe to add new key to list, even if we have focus. */
12984 if (NILP (item))
12985 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
12986 else
12987 XCAR (item) = key;
12988
12989 /* Notify input thread about new hot-key definition, so that it
12990 takes effect without needing to switch focus. */
12991 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
12992 (WPARAM) key, 0);
12993 }
12994
12995 return key;
12996 }
12997
12998 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key, Sw32_unregister_hot_key, 1, 1, 0,
12999 "Unregister HOTKEY as a hot-key combination.")
13000 (key)
13001 Lisp_Object key;
13002 {
13003 Lisp_Object item;
13004
13005 if (!INTEGERP (key))
13006 key = w32_parse_hot_key (key);
13007
13008 item = Fmemq (key, w32_grabbed_keys);
13009
13010 if (!NILP (item))
13011 {
13012 /* Notify input thread about hot-key definition being removed, so
13013 that it takes effect without needing focus switch. */
13014 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
13015 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
13016 {
13017 MSG msg;
13018 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13019 }
13020 return Qt;
13021 }
13022 return Qnil;
13023 }
13024
13025 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys, Sw32_registered_hot_keys, 0, 0, 0,
13026 "Return list of registered hot-key IDs.")
13027 ()
13028 {
13029 return Fcopy_sequence (w32_grabbed_keys);
13030 }
13031
13032 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key, Sw32_reconstruct_hot_key, 1, 1, 0,
13033 "Convert hot-key ID to a lisp key combination.")
13034 (hotkeyid)
13035 Lisp_Object hotkeyid;
13036 {
13037 int vk_code, w32_modifiers;
13038 Lisp_Object key;
13039
13040 CHECK_NUMBER (hotkeyid, 0);
13041
13042 vk_code = HOTKEY_VK_CODE (hotkeyid);
13043 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
13044
13045 if (lispy_function_keys[vk_code])
13046 key = intern (lispy_function_keys[vk_code]);
13047 else
13048 key = make_number (vk_code);
13049
13050 key = Fcons (key, Qnil);
13051 if (w32_modifiers & MOD_SHIFT)
13052 key = Fcons (Qshift, key);
13053 if (w32_modifiers & MOD_CONTROL)
13054 key = Fcons (Qctrl, key);
13055 if (w32_modifiers & MOD_ALT)
13056 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
13057 if (w32_modifiers & MOD_WIN)
13058 key = Fcons (Qhyper, key);
13059
13060 return key;
13061 }
13062
13063 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key, Sw32_toggle_lock_key, 1, 2, 0,
13064 "Toggle the state of the lock key KEY.\n\
13065 KEY can be `capslock', `kp-numlock', or `scroll'.\n\
13066 If the optional parameter NEW-STATE is a number, then the state of KEY\n\
13067 is set to off if the low bit of NEW-STATE is zero, otherwise on.")
13068 (key, new_state)
13069 Lisp_Object key, new_state;
13070 {
13071 int vk_code;
13072 int cur_state;
13073
13074 if (EQ (key, intern ("capslock")))
13075 vk_code = VK_CAPITAL;
13076 else if (EQ (key, intern ("kp-numlock")))
13077 vk_code = VK_NUMLOCK;
13078 else if (EQ (key, intern ("scroll")))
13079 vk_code = VK_SCROLL;
13080 else
13081 return Qnil;
13082
13083 if (!dwWindowsThreadId)
13084 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
13085
13086 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
13087 (WPARAM) vk_code, (LPARAM) new_state))
13088 {
13089 MSG msg;
13090 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13091 return make_number (msg.wParam);
13092 }
13093 return Qnil;
13094 }
13095 \f
13096 syms_of_w32fns ()
13097 {
13098 /* This is zero if not using MS-Windows. */
13099 w32_in_use = 0;
13100
13101 /* The section below is built by the lisp expression at the top of the file,
13102 just above where these variables are declared. */
13103 /*&&& init symbols here &&&*/
13104 Qauto_raise = intern ("auto-raise");
13105 staticpro (&Qauto_raise);
13106 Qauto_lower = intern ("auto-lower");
13107 staticpro (&Qauto_lower);
13108 Qbar = intern ("bar");
13109 staticpro (&Qbar);
13110 Qborder_color = intern ("border-color");
13111 staticpro (&Qborder_color);
13112 Qborder_width = intern ("border-width");
13113 staticpro (&Qborder_width);
13114 Qbox = intern ("box");
13115 staticpro (&Qbox);
13116 Qcursor_color = intern ("cursor-color");
13117 staticpro (&Qcursor_color);
13118 Qcursor_type = intern ("cursor-type");
13119 staticpro (&Qcursor_type);
13120 Qgeometry = intern ("geometry");
13121 staticpro (&Qgeometry);
13122 Qicon_left = intern ("icon-left");
13123 staticpro (&Qicon_left);
13124 Qicon_top = intern ("icon-top");
13125 staticpro (&Qicon_top);
13126 Qicon_type = intern ("icon-type");
13127 staticpro (&Qicon_type);
13128 Qicon_name = intern ("icon-name");
13129 staticpro (&Qicon_name);
13130 Qinternal_border_width = intern ("internal-border-width");
13131 staticpro (&Qinternal_border_width);
13132 Qleft = intern ("left");
13133 staticpro (&Qleft);
13134 Qright = intern ("right");
13135 staticpro (&Qright);
13136 Qmouse_color = intern ("mouse-color");
13137 staticpro (&Qmouse_color);
13138 Qnone = intern ("none");
13139 staticpro (&Qnone);
13140 Qparent_id = intern ("parent-id");
13141 staticpro (&Qparent_id);
13142 Qscroll_bar_width = intern ("scroll-bar-width");
13143 staticpro (&Qscroll_bar_width);
13144 Qsuppress_icon = intern ("suppress-icon");
13145 staticpro (&Qsuppress_icon);
13146 Qundefined_color = intern ("undefined-color");
13147 staticpro (&Qundefined_color);
13148 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
13149 staticpro (&Qvertical_scroll_bars);
13150 Qvisibility = intern ("visibility");
13151 staticpro (&Qvisibility);
13152 Qwindow_id = intern ("window-id");
13153 staticpro (&Qwindow_id);
13154 Qx_frame_parameter = intern ("x-frame-parameter");
13155 staticpro (&Qx_frame_parameter);
13156 Qx_resource_name = intern ("x-resource-name");
13157 staticpro (&Qx_resource_name);
13158 Quser_position = intern ("user-position");
13159 staticpro (&Quser_position);
13160 Quser_size = intern ("user-size");
13161 staticpro (&Quser_size);
13162 Qscreen_gamma = intern ("screen-gamma");
13163 staticpro (&Qscreen_gamma);
13164 Qline_spacing = intern ("line-spacing");
13165 staticpro (&Qline_spacing);
13166 Qcenter = intern ("center");
13167 staticpro (&Qcenter);
13168 /* This is the end of symbol initialization. */
13169
13170 Qhyper = intern ("hyper");
13171 staticpro (&Qhyper);
13172 Qsuper = intern ("super");
13173 staticpro (&Qsuper);
13174 Qmeta = intern ("meta");
13175 staticpro (&Qmeta);
13176 Qalt = intern ("alt");
13177 staticpro (&Qalt);
13178 Qctrl = intern ("ctrl");
13179 staticpro (&Qctrl);
13180 Qcontrol = intern ("control");
13181 staticpro (&Qcontrol);
13182 Qshift = intern ("shift");
13183 staticpro (&Qshift);
13184
13185 /* Text property `display' should be nonsticky by default. */
13186 Vtext_property_default_nonsticky
13187 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
13188
13189
13190 Qlaplace = intern ("laplace");
13191 staticpro (&Qlaplace);
13192
13193 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
13194 staticpro (&Qface_set_after_frame_default);
13195
13196 Fput (Qundefined_color, Qerror_conditions,
13197 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
13198 Fput (Qundefined_color, Qerror_message,
13199 build_string ("Undefined color"));
13200
13201 staticpro (&w32_grabbed_keys);
13202 w32_grabbed_keys = Qnil;
13203
13204 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
13205 "An array of color name mappings for windows.");
13206 Vw32_color_map = Qnil;
13207
13208 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
13209 "Non-nil if alt key presses are passed on to Windows.\n\
13210 When non-nil, for example, alt pressed and released and then space will\n\
13211 open the System menu. When nil, Emacs silently swallows alt key events.");
13212 Vw32_pass_alt_to_system = Qnil;
13213
13214 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
13215 "Non-nil if the alt key is to be considered the same as the meta key.\n\
13216 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta.");
13217 Vw32_alt_is_meta = Qt;
13218
13219 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
13220 "If non-zero, the virtual key code for an alternative quit key.");
13221 XSETINT (Vw32_quit_key, 0);
13222
13223 DEFVAR_LISP ("w32-pass-lwindow-to-system",
13224 &Vw32_pass_lwindow_to_system,
13225 "Non-nil if the left \"Windows\" key is passed on to Windows.\n\
13226 When non-nil, the Start menu is opened by tapping the key.");
13227 Vw32_pass_lwindow_to_system = Qt;
13228
13229 DEFVAR_LISP ("w32-pass-rwindow-to-system",
13230 &Vw32_pass_rwindow_to_system,
13231 "Non-nil if the right \"Windows\" key is passed on to Windows.\n\
13232 When non-nil, the Start menu is opened by tapping the key.");
13233 Vw32_pass_rwindow_to_system = Qt;
13234
13235 DEFVAR_INT ("w32-phantom-key-code",
13236 &Vw32_phantom_key_code,
13237 "Virtual key code used to generate \"phantom\" key presses.\n\
13238 Value is a number between 0 and 255.\n\
13239 \n\
13240 Phantom key presses are generated in order to stop the system from\n\
13241 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or\n\
13242 `w32-pass-rwindow-to-system' is nil.");
13243 /* Although 255 is technically not a valid key code, it works and
13244 means that this hack won't interfere with any real key code. */
13245 Vw32_phantom_key_code = 255;
13246
13247 DEFVAR_LISP ("w32-enable-num-lock",
13248 &Vw32_enable_num_lock,
13249 "Non-nil if Num Lock should act normally.\n\
13250 Set to nil to see Num Lock as the key `kp-numlock'.");
13251 Vw32_enable_num_lock = Qt;
13252
13253 DEFVAR_LISP ("w32-enable-caps-lock",
13254 &Vw32_enable_caps_lock,
13255 "Non-nil if Caps Lock should act normally.\n\
13256 Set to nil to see Caps Lock as the key `capslock'.");
13257 Vw32_enable_caps_lock = Qt;
13258
13259 DEFVAR_LISP ("w32-scroll-lock-modifier",
13260 &Vw32_scroll_lock_modifier,
13261 "Modifier to use for the Scroll Lock on state.\n\
13262 The value can be hyper, super, meta, alt, control or shift for the\n\
13263 respective modifier, or nil to see Scroll Lock as the key `scroll'.\n\
13264 Any other value will cause the key to be ignored.");
13265 Vw32_scroll_lock_modifier = Qt;
13266
13267 DEFVAR_LISP ("w32-lwindow-modifier",
13268 &Vw32_lwindow_modifier,
13269 "Modifier to use for the left \"Windows\" key.\n\
13270 The value can be hyper, super, meta, alt, control or shift for the\n\
13271 respective modifier, or nil to appear as the key `lwindow'.\n\
13272 Any other value will cause the key to be ignored.");
13273 Vw32_lwindow_modifier = Qnil;
13274
13275 DEFVAR_LISP ("w32-rwindow-modifier",
13276 &Vw32_rwindow_modifier,
13277 "Modifier to use for the right \"Windows\" key.\n\
13278 The value can be hyper, super, meta, alt, control or shift for the\n\
13279 respective modifier, or nil to appear as the key `rwindow'.\n\
13280 Any other value will cause the key to be ignored.");
13281 Vw32_rwindow_modifier = Qnil;
13282
13283 DEFVAR_LISP ("w32-apps-modifier",
13284 &Vw32_apps_modifier,
13285 "Modifier to use for the \"Apps\" key.\n\
13286 The value can be hyper, super, meta, alt, control or shift for the\n\
13287 respective modifier, or nil to appear as the key `apps'.\n\
13288 Any other value will cause the key to be ignored.");
13289 Vw32_apps_modifier = Qnil;
13290
13291 DEFVAR_LISP ("w32-enable-synthesized-fonts", &Vw32_enable_synthesized_fonts,
13292 "Non-nil enables selection of artificially italicized and bold fonts.");
13293 Vw32_enable_synthesized_fonts = Qnil;
13294
13295 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
13296 "Non-nil enables Windows palette management to map colors exactly.");
13297 Vw32_enable_palette = Qt;
13298
13299 DEFVAR_INT ("w32-mouse-button-tolerance",
13300 &Vw32_mouse_button_tolerance,
13301 "Analogue of double click interval for faking middle mouse events.\n\
13302 The value is the minimum time in milliseconds that must elapse between\n\
13303 left/right button down events before they are considered distinct events.\n\
13304 If both mouse buttons are depressed within this interval, a middle mouse\n\
13305 button down event is generated instead.");
13306 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
13307
13308 DEFVAR_INT ("w32-mouse-move-interval",
13309 &Vw32_mouse_move_interval,
13310 "Minimum interval between mouse move events.\n\
13311 The value is the minimum time in milliseconds that must elapse between\n\
13312 successive mouse move (or scroll bar drag) events before they are\n\
13313 reported as lisp events.");
13314 XSETINT (Vw32_mouse_move_interval, 0);
13315
13316 init_x_parm_symbols ();
13317
13318 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
13319 "List of directories to search for bitmap files for w32.");
13320 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
13321
13322 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
13323 "The shape of the pointer when over text.\n\
13324 Changing the value does not affect existing frames\n\
13325 unless you set the mouse color.");
13326 Vx_pointer_shape = Qnil;
13327
13328 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
13329 "The name Emacs uses to look up resources; for internal use only.\n\
13330 `x-get-resource' uses this as the first component of the instance name\n\
13331 when requesting resource values.\n\
13332 Emacs initially sets `x-resource-name' to the name under which Emacs\n\
13333 was invoked, or to the value specified with the `-name' or `-rn'\n\
13334 switches, if present.");
13335 Vx_resource_name = Qnil;
13336
13337 Vx_nontext_pointer_shape = Qnil;
13338
13339 Vx_mode_pointer_shape = Qnil;
13340
13341 DEFVAR_LISP ("x-busy-pointer-shape", &Vx_busy_pointer_shape,
13342 "The shape of the pointer when Emacs is busy.\n\
13343 This variable takes effect when you create a new frame\n\
13344 or when you set the mouse color.");
13345 Vx_busy_pointer_shape = Qnil;
13346
13347 DEFVAR_BOOL ("display-busy-cursor", &display_busy_cursor_p,
13348 "Non-zero means Emacs displays a busy cursor on window systems.");
13349 display_busy_cursor_p = 1;
13350
13351 DEFVAR_LISP ("busy-cursor-delay", &Vbusy_cursor_delay,
13352 "*Seconds to wait before displaying a busy-cursor.\n\
13353 Value must be an integer or float.");
13354 Vbusy_cursor_delay = make_number (DEFAULT_BUSY_CURSOR_DELAY);
13355
13356 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
13357 &Vx_sensitive_text_pointer_shape,
13358 "The shape of the pointer when over mouse-sensitive text.\n\
13359 This variable takes effect when you create a new frame\n\
13360 or when you set the mouse color.");
13361 Vx_sensitive_text_pointer_shape = Qnil;
13362
13363 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
13364 "A string indicating the foreground color of the cursor box.");
13365 Vx_cursor_fore_pixel = Qnil;
13366
13367 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
13368 "Non-nil if no window manager is in use.\n\
13369 Emacs doesn't try to figure this out; this is always nil\n\
13370 unless you set it to something else.");
13371 /* We don't have any way to find this out, so set it to nil
13372 and maybe the user would like to set it to t. */
13373 Vx_no_window_manager = Qnil;
13374
13375 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
13376 &Vx_pixel_size_width_font_regexp,
13377 "Regexp matching a font name whose width is the same as `PIXEL_SIZE'.\n\
13378 \n\
13379 Since Emacs gets width of a font matching with this regexp from\n\
13380 PIXEL_SIZE field of the name, font finding mechanism gets faster for\n\
13381 such a font. This is especially effective for such large fonts as\n\
13382 Chinese, Japanese, and Korean.");
13383 Vx_pixel_size_width_font_regexp = Qnil;
13384
13385 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
13386 "Time after which cached images are removed from the cache.\n\
13387 When an image has not been displayed this many seconds, remove it\n\
13388 from the image cache. Value must be an integer or nil with nil\n\
13389 meaning don't clear the cache.");
13390 Vimage_cache_eviction_delay = make_number (30 * 60);
13391
13392 DEFVAR_LISP ("w32-bdf-filename-alist",
13393 &Vw32_bdf_filename_alist,
13394 "List of bdf fonts and their corresponding filenames.");
13395 Vw32_bdf_filename_alist = Qnil;
13396
13397 DEFVAR_BOOL ("w32-strict-fontnames",
13398 &w32_strict_fontnames,
13399 "Non-nil means only use fonts that are exact matches for those requested.\n\
13400 Default is nil, which allows old fontnames that are not XLFD compliant,\n\
13401 and allows third-party CJK display to work by specifying false charset\n\
13402 fields to trick Emacs into translating to Big5, SJIS etc.\n\
13403 Setting this to t will prevent wrong fonts being selected when\n\
13404 fontsets are automatically created.");
13405 w32_strict_fontnames = 0;
13406
13407 DEFVAR_BOOL ("w32-strict-painting",
13408 &w32_strict_painting,
13409 "Non-nil means use strict rules for repainting frames.\n\
13410 Set this to nil to get the old behaviour for repainting; this should\n\
13411 only be necessary if the default setting causes problems.");
13412 w32_strict_painting = 1;
13413
13414 DEFVAR_LISP ("w32-system-coding-system",
13415 &Vw32_system_coding_system,
13416 "Coding system used by Windows system functions, such as for font names.");
13417 Vw32_system_coding_system = Qnil;
13418
13419 DEFVAR_LISP ("w32-charset-info-alist",
13420 &Vw32_charset_info_alist,
13421 "Alist linking Emacs character sets to Windows fonts\n\
13422 and codepages. Each entry should be of the form:\n\
13423 \n\
13424 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))\n\
13425 \n\
13426 where CHARSET_NAME is a string used in font names to identify the charset,\n\
13427 WINDOWS_CHARSET is a symbol that can be one of:\n\
13428 w32-charset-ansi, w32-charset-default, w32-charset-symbol,\n\
13429 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,\n\
13430 w32-charset-chinesebig5, "
13431 #ifdef JOHAB_CHARSET
13432 "w32-charset-johab, w32-charset-hebrew,\n\
13433 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,\n\
13434 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,\n\
13435 w32-charset-russian, w32-charset-mac, w32-charset-baltic,\n"
13436 #endif
13437 #ifdef UNICODE_CHARSET
13438 "w32-charset-unicode, "
13439 #endif
13440 "or w32-charset-oem.\n\
13441 CODEPAGE should be an integer specifying the codepage that should be used\n\
13442 to display the character set, t to do no translation and output as Unicode,\n\
13443 or nil to do no translation and output as 8 bit (or multibyte on far-east\n\
13444 versions of Windows) characters.");
13445 Vw32_charset_info_alist = Qnil;
13446
13447 staticpro (&Qw32_charset_ansi);
13448 Qw32_charset_ansi = intern ("w32-charset-ansi");
13449 staticpro (&Qw32_charset_symbol);
13450 Qw32_charset_symbol = intern ("w32-charset-symbol");
13451 staticpro (&Qw32_charset_shiftjis);
13452 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
13453 staticpro (&Qw32_charset_hangeul);
13454 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
13455 staticpro (&Qw32_charset_chinesebig5);
13456 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
13457 staticpro (&Qw32_charset_gb2312);
13458 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
13459 staticpro (&Qw32_charset_oem);
13460 Qw32_charset_oem = intern ("w32-charset-oem");
13461
13462 #ifdef JOHAB_CHARSET
13463 {
13464 static int w32_extra_charsets_defined = 1;
13465 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined, "");
13466
13467 staticpro (&Qw32_charset_johab);
13468 Qw32_charset_johab = intern ("w32-charset-johab");
13469 staticpro (&Qw32_charset_easteurope);
13470 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
13471 staticpro (&Qw32_charset_turkish);
13472 Qw32_charset_turkish = intern ("w32-charset-turkish");
13473 staticpro (&Qw32_charset_baltic);
13474 Qw32_charset_baltic = intern ("w32-charset-baltic");
13475 staticpro (&Qw32_charset_russian);
13476 Qw32_charset_russian = intern ("w32-charset-russian");
13477 staticpro (&Qw32_charset_arabic);
13478 Qw32_charset_arabic = intern ("w32-charset-arabic");
13479 staticpro (&Qw32_charset_greek);
13480 Qw32_charset_greek = intern ("w32-charset-greek");
13481 staticpro (&Qw32_charset_hebrew);
13482 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
13483 staticpro (&Qw32_charset_vietnamese);
13484 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
13485 staticpro (&Qw32_charset_thai);
13486 Qw32_charset_thai = intern ("w32-charset-thai");
13487 staticpro (&Qw32_charset_mac);
13488 Qw32_charset_mac = intern ("w32-charset-mac");
13489 }
13490 #endif
13491
13492 #ifdef UNICODE_CHARSET
13493 {
13494 static int w32_unicode_charset_defined = 1;
13495 DEFVAR_BOOL ("w32-unicode-charset-defined",
13496 &w32_unicode_charset_defined, "");
13497
13498 staticpro (&Qw32_charset_unicode);
13499 Qw32_charset_unicode = intern ("w32-charset-unicode");
13500 #endif
13501
13502 defsubr (&Sx_get_resource);
13503 #if 0 /* TODO: Port to W32 */
13504 defsubr (&Sx_change_window_property);
13505 defsubr (&Sx_delete_window_property);
13506 defsubr (&Sx_window_property);
13507 #endif
13508 defsubr (&Sxw_display_color_p);
13509 defsubr (&Sx_display_grayscale_p);
13510 defsubr (&Sxw_color_defined_p);
13511 defsubr (&Sxw_color_values);
13512 defsubr (&Sx_server_max_request_size);
13513 defsubr (&Sx_server_vendor);
13514 defsubr (&Sx_server_version);
13515 defsubr (&Sx_display_pixel_width);
13516 defsubr (&Sx_display_pixel_height);
13517 defsubr (&Sx_display_mm_width);
13518 defsubr (&Sx_display_mm_height);
13519 defsubr (&Sx_display_screens);
13520 defsubr (&Sx_display_planes);
13521 defsubr (&Sx_display_color_cells);
13522 defsubr (&Sx_display_visual_class);
13523 defsubr (&Sx_display_backing_store);
13524 defsubr (&Sx_display_save_under);
13525 defsubr (&Sx_parse_geometry);
13526 defsubr (&Sx_create_frame);
13527 defsubr (&Sx_open_connection);
13528 defsubr (&Sx_close_connection);
13529 defsubr (&Sx_display_list);
13530 defsubr (&Sx_synchronize);
13531
13532 /* W32 specific functions */
13533
13534 defsubr (&Sw32_focus_frame);
13535 defsubr (&Sw32_select_font);
13536 defsubr (&Sw32_define_rgb_color);
13537 defsubr (&Sw32_default_color_map);
13538 defsubr (&Sw32_load_color_file);
13539 defsubr (&Sw32_send_sys_command);
13540 defsubr (&Sw32_shell_execute);
13541 defsubr (&Sw32_register_hot_key);
13542 defsubr (&Sw32_unregister_hot_key);
13543 defsubr (&Sw32_registered_hot_keys);
13544 defsubr (&Sw32_reconstruct_hot_key);
13545 defsubr (&Sw32_toggle_lock_key);
13546 defsubr (&Sw32_find_bdf_fonts);
13547
13548 /* Setting callback functions for fontset handler. */
13549 get_font_info_func = w32_get_font_info;
13550
13551 #if 0 /* This function pointer doesn't seem to be used anywhere.
13552 And the pointer assigned has the wrong type, anyway. */
13553 list_fonts_func = w32_list_fonts;
13554 #endif
13555
13556 load_font_func = w32_load_font;
13557 find_ccl_program_func = w32_find_ccl_program;
13558 query_font_func = w32_query_font;
13559 set_frame_fontset_func = x_set_font;
13560 check_window_system_func = check_w32;
13561
13562 #if 0 /* TODO Image support for W32 */
13563 /* Images. */
13564 Qxbm = intern ("xbm");
13565 staticpro (&Qxbm);
13566 QCtype = intern (":type");
13567 staticpro (&QCtype);
13568 QCalgorithm = intern (":algorithm");
13569 staticpro (&QCalgorithm);
13570 QCheuristic_mask = intern (":heuristic-mask");
13571 staticpro (&QCheuristic_mask);
13572 QCcolor_symbols = intern (":color-symbols");
13573 staticpro (&QCcolor_symbols);
13574 QCascent = intern (":ascent");
13575 staticpro (&QCascent);
13576 QCmargin = intern (":margin");
13577 staticpro (&QCmargin);
13578 QCrelief = intern (":relief");
13579 staticpro (&QCrelief);
13580 Qpostscript = intern ("postscript");
13581 staticpro (&Qpostscript);
13582 QCloader = intern (":loader");
13583 staticpro (&QCloader);
13584 QCbounding_box = intern (":bounding-box");
13585 staticpro (&QCbounding_box);
13586 QCpt_width = intern (":pt-width");
13587 staticpro (&QCpt_width);
13588 QCpt_height = intern (":pt-height");
13589 staticpro (&QCpt_height);
13590 QCindex = intern (":index");
13591 staticpro (&QCindex);
13592 Qpbm = intern ("pbm");
13593 staticpro (&Qpbm);
13594
13595 #if HAVE_XPM
13596 Qxpm = intern ("xpm");
13597 staticpro (&Qxpm);
13598 #endif
13599
13600 #if HAVE_JPEG
13601 Qjpeg = intern ("jpeg");
13602 staticpro (&Qjpeg);
13603 #endif
13604
13605 #if HAVE_TIFF
13606 Qtiff = intern ("tiff");
13607 staticpro (&Qtiff);
13608 #endif
13609
13610 #if HAVE_GIF
13611 Qgif = intern ("gif");
13612 staticpro (&Qgif);
13613 #endif
13614
13615 #if HAVE_PNG
13616 Qpng = intern ("png");
13617 staticpro (&Qpng);
13618 #endif
13619
13620 defsubr (&Sclear_image_cache);
13621
13622 #if GLYPH_DEBUG
13623 defsubr (&Simagep);
13624 defsubr (&Slookup_image);
13625 #endif
13626 #endif /* TODO */
13627
13628 busy_cursor_atimer = NULL;
13629 busy_cursor_shown_p = 0;
13630 #ifdef TODO /* Tooltip support not complete. */
13631 defsubr (&Sx_show_tip);
13632 defsubr (&Sx_hide_tip);
13633 #endif
13634 staticpro (&tip_timer);
13635 tip_timer = Qnil;
13636
13637 defsubr (&Sx_file_dialog);
13638 }
13639
13640
13641 void
13642 init_xfns ()
13643 {
13644 image_types = NULL;
13645 Vimage_types = Qnil;
13646
13647 #if 0 /* TODO : Image support for W32 */
13648 define_image_type (&xbm_type);
13649 define_image_type (&gs_type);
13650 define_image_type (&pbm_type);
13651
13652 #if HAVE_XPM
13653 define_image_type (&xpm_type);
13654 #endif
13655
13656 #if HAVE_JPEG
13657 define_image_type (&jpeg_type);
13658 #endif
13659
13660 #if HAVE_TIFF
13661 define_image_type (&tiff_type);
13662 #endif
13663
13664 #if HAVE_GIF
13665 define_image_type (&gif_type);
13666 #endif
13667
13668 #if HAVE_PNG
13669 define_image_type (&png_type);
13670 #endif
13671 #endif /* TODO */
13672 }
13673
13674 #undef abort
13675
13676 void
13677 w32_abort()
13678 {
13679 int button;
13680 button = MessageBox (NULL,
13681 "A fatal error has occurred!\n\n"
13682 "Select Abort to exit, Retry to debug, Ignore to continue",
13683 "Emacs Abort Dialog",
13684 MB_ICONEXCLAMATION | MB_TASKMODAL
13685 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
13686 switch (button)
13687 {
13688 case IDRETRY:
13689 DebugBreak ();
13690 break;
13691 case IDIGNORE:
13692 break;
13693 case IDABORT:
13694 default:
13695 abort ();
13696 break;
13697 }
13698 }
13699
13700 /* For convenience when debugging. */
13701 int
13702 w32_last_error()
13703 {
13704 return GetLastError ();
13705 }