]> code.delx.au - gnu-emacs/blob - src/w32fns.c
9fe4a451b398376501fd027995bb731241bfe9be
[gnu-emacs] / src / w32fns.c
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 92, 93, 94, 95, 1996, 1997, 1998, 1999
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, Vx_window_horizontal_drag_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 if (!NILP (Vx_window_horizontal_drag_shape))
2093 {
2094 CHECK_NUMBER (Vx_window_horizontal_drag_shape, 0);
2095 horizontal_drag_cursor
2096 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2097 XINT (Vx_window_horizontal_drag_shape));
2098 }
2099 else
2100 horizontal_drag_cursor
2101 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2102
2103 /* Check and report errors with the above calls. */
2104 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2105 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2106
2107 {
2108 XColor fore_color, back_color;
2109
2110 fore_color.pixel = f->output_data.w32->mouse_pixel;
2111 back_color.pixel = mask_color;
2112 XQueryColor (FRAME_W32_DISPLAY (f),
2113 DefaultColormap (FRAME_W32_DISPLAY (f),
2114 DefaultScreen (FRAME_W32_DISPLAY (f))),
2115 &fore_color);
2116 XQueryColor (FRAME_W32_DISPLAY (f),
2117 DefaultColormap (FRAME_W32_DISPLAY (f),
2118 DefaultScreen (FRAME_W32_DISPLAY (f))),
2119 &back_color);
2120 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2121 &fore_color, &back_color);
2122 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2123 &fore_color, &back_color);
2124 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2125 &fore_color, &back_color);
2126 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2127 &fore_color, &back_color);
2128 XRecolorCursor (FRAME_W32_DISPLAY (f), busy_cursor,
2129 &fore_color, &back_color);
2130 }
2131
2132 if (FRAME_W32_WINDOW (f) != 0)
2133 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2134
2135 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2136 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2137 f->output_data.w32->text_cursor = cursor;
2138
2139 if (nontext_cursor != f->output_data.w32->nontext_cursor
2140 && f->output_data.w32->nontext_cursor != 0)
2141 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2142 f->output_data.w32->nontext_cursor = nontext_cursor;
2143
2144 if (busy_cursor != f->output_data.w32->busy_cursor
2145 && f->output_data.w32->busy_cursor != 0)
2146 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->busy_cursor);
2147 f->output_data.w32->busy_cursor = busy_cursor;
2148
2149 if (mode_cursor != f->output_data.w32->modeline_cursor
2150 && f->output_data.w32->modeline_cursor != 0)
2151 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2152 f->output_data.w32->modeline_cursor = mode_cursor;
2153
2154 if (cross_cursor != f->output_data.w32->cross_cursor
2155 && f->output_data.w32->cross_cursor != 0)
2156 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2157 f->output_data.w32->cross_cursor = cross_cursor;
2158
2159 XFlush (FRAME_W32_DISPLAY (f));
2160 UNBLOCK_INPUT;
2161
2162 update_face_from_frame_parameter (f, Qmouse_color, arg);
2163 #endif /* TODO */
2164 }
2165
2166 /* Defined in w32term.c. */
2167 void x_update_cursor (struct frame *f, int on_p);
2168
2169 void
2170 x_set_cursor_color (f, arg, oldval)
2171 struct frame *f;
2172 Lisp_Object arg, oldval;
2173 {
2174 unsigned long fore_pixel, pixel;
2175
2176 if (!NILP (Vx_cursor_fore_pixel))
2177 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2178 WHITE_PIX_DEFAULT (f));
2179 else
2180 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2181
2182 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2183
2184 /* Make sure that the cursor color differs from the background color. */
2185 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2186 {
2187 pixel = f->output_data.w32->mouse_pixel;
2188 if (pixel == fore_pixel)
2189 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2190 }
2191
2192 FRAME_FOREGROUND_PIXEL (f) = fore_pixel;
2193 f->output_data.w32->cursor_pixel = pixel;
2194
2195 if (FRAME_W32_WINDOW (f) != 0)
2196 {
2197 if (FRAME_VISIBLE_P (f))
2198 {
2199 x_update_cursor (f, 0);
2200 x_update_cursor (f, 1);
2201 }
2202 }
2203
2204 update_face_from_frame_parameter (f, Qcursor_color, arg);
2205 }
2206
2207 /* Set the border-color of frame F to pixel value PIX.
2208 Note that this does not fully take effect if done before
2209 F has an window. */
2210 void
2211 x_set_border_pixel (f, pix)
2212 struct frame *f;
2213 int pix;
2214 {
2215 f->output_data.w32->border_pixel = pix;
2216
2217 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2218 {
2219 if (FRAME_VISIBLE_P (f))
2220 redraw_frame (f);
2221 }
2222 }
2223
2224 /* Set the border-color of frame F to value described by ARG.
2225 ARG can be a string naming a color.
2226 The border-color is used for the border that is drawn by the server.
2227 Note that this does not fully take effect if done before
2228 F has a window; it must be redone when the window is created. */
2229
2230 void
2231 x_set_border_color (f, arg, oldval)
2232 struct frame *f;
2233 Lisp_Object arg, oldval;
2234 {
2235 int pix;
2236
2237 CHECK_STRING (arg, 0);
2238 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2239 x_set_border_pixel (f, pix);
2240 update_face_from_frame_parameter (f, Qborder_color, arg);
2241 }
2242
2243 /* Value is the internal representation of the specified cursor type
2244 ARG. If type is BAR_CURSOR, return in *WIDTH the specified width
2245 of the bar cursor. */
2246
2247 enum text_cursor_kinds
2248 x_specified_cursor_type (arg, width)
2249 Lisp_Object arg;
2250 int *width;
2251 {
2252 enum text_cursor_kinds type;
2253
2254 if (EQ (arg, Qbar))
2255 {
2256 type = BAR_CURSOR;
2257 *width = 2;
2258 }
2259 else if (CONSP (arg)
2260 && EQ (XCAR (arg), Qbar)
2261 && INTEGERP (XCDR (arg))
2262 && XINT (XCDR (arg)) >= 0)
2263 {
2264 type = BAR_CURSOR;
2265 *width = XINT (XCDR (arg));
2266 }
2267 else if (NILP (arg))
2268 type = NO_CURSOR;
2269 else
2270 /* Treat anything unknown as "box cursor".
2271 It was bad to signal an error; people have trouble fixing
2272 .Xdefaults with Emacs, when it has something bad in it. */
2273 type = FILLED_BOX_CURSOR;
2274
2275 return type;
2276 }
2277
2278 void
2279 x_set_cursor_type (f, arg, oldval)
2280 FRAME_PTR f;
2281 Lisp_Object arg, oldval;
2282 {
2283 int width;
2284
2285 FRAME_DESIRED_CURSOR (f) = x_specified_cursor_type (arg, &width);
2286 f->output_data.w32->cursor_width = width;
2287
2288 /* Make sure the cursor gets redrawn. This is overkill, but how
2289 often do people change cursor types? */
2290 update_mode_lines++;
2291 }
2292 \f
2293 void
2294 x_set_icon_type (f, arg, oldval)
2295 struct frame *f;
2296 Lisp_Object arg, oldval;
2297 {
2298 int result;
2299
2300 if (NILP (arg) && NILP (oldval))
2301 return;
2302
2303 if (STRINGP (arg) && STRINGP (oldval)
2304 && EQ (Fstring_equal (oldval, arg), Qt))
2305 return;
2306
2307 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2308 return;
2309
2310 BLOCK_INPUT;
2311
2312 result = x_bitmap_icon (f, arg);
2313 if (result)
2314 {
2315 UNBLOCK_INPUT;
2316 error ("No icon window available");
2317 }
2318
2319 UNBLOCK_INPUT;
2320 }
2321
2322 /* Return non-nil if frame F wants a bitmap icon. */
2323
2324 Lisp_Object
2325 x_icon_type (f)
2326 FRAME_PTR f;
2327 {
2328 Lisp_Object tem;
2329
2330 tem = assq_no_quit (Qicon_type, f->param_alist);
2331 if (CONSP (tem))
2332 return XCDR (tem);
2333 else
2334 return Qnil;
2335 }
2336
2337 void
2338 x_set_icon_name (f, arg, oldval)
2339 struct frame *f;
2340 Lisp_Object arg, oldval;
2341 {
2342 int result;
2343
2344 if (STRINGP (arg))
2345 {
2346 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2347 return;
2348 }
2349 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2350 return;
2351
2352 f->icon_name = arg;
2353
2354 #if 0
2355 if (f->output_data.w32->icon_bitmap != 0)
2356 return;
2357
2358 BLOCK_INPUT;
2359
2360 result = x_text_icon (f,
2361 (char *) XSTRING ((!NILP (f->icon_name)
2362 ? f->icon_name
2363 : !NILP (f->title)
2364 ? f->title
2365 : f->name))->data);
2366
2367 if (result)
2368 {
2369 UNBLOCK_INPUT;
2370 error ("No icon window available");
2371 }
2372
2373 /* If the window was unmapped (and its icon was mapped),
2374 the new icon is not mapped, so map the window in its stead. */
2375 if (FRAME_VISIBLE_P (f))
2376 {
2377 #ifdef USE_X_TOOLKIT
2378 XtPopup (f->output_data.w32->widget, XtGrabNone);
2379 #endif
2380 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2381 }
2382
2383 XFlush (FRAME_W32_DISPLAY (f));
2384 UNBLOCK_INPUT;
2385 #endif
2386 }
2387
2388 extern Lisp_Object x_new_font ();
2389 extern Lisp_Object x_new_fontset();
2390
2391 void
2392 x_set_font (f, arg, oldval)
2393 struct frame *f;
2394 Lisp_Object arg, oldval;
2395 {
2396 Lisp_Object result;
2397 Lisp_Object fontset_name;
2398 Lisp_Object frame;
2399
2400 CHECK_STRING (arg, 1);
2401
2402 fontset_name = Fquery_fontset (arg, Qnil);
2403
2404 BLOCK_INPUT;
2405 result = (STRINGP (fontset_name)
2406 ? x_new_fontset (f, XSTRING (fontset_name)->data)
2407 : x_new_font (f, XSTRING (arg)->data));
2408 UNBLOCK_INPUT;
2409
2410 if (EQ (result, Qnil))
2411 error ("Font `%s' is not defined", XSTRING (arg)->data);
2412 else if (EQ (result, Qt))
2413 error ("The characters of the given font have varying widths");
2414 else if (STRINGP (result))
2415 {
2416 store_frame_param (f, Qfont, result);
2417 recompute_basic_faces (f);
2418 }
2419 else
2420 abort ();
2421
2422 do_pending_window_change (0);
2423
2424 /* Don't call `face-set-after-frame-default' when faces haven't been
2425 initialized yet. This is the case when called from
2426 Fx_create_frame. In that case, the X widget or window doesn't
2427 exist either, and we can end up in x_report_frame_params with a
2428 null widget which gives a segfault. */
2429 if (FRAME_FACE_CACHE (f))
2430 {
2431 XSETFRAME (frame, f);
2432 call1 (Qface_set_after_frame_default, frame);
2433 }
2434 }
2435
2436 void
2437 x_set_border_width (f, arg, oldval)
2438 struct frame *f;
2439 Lisp_Object arg, oldval;
2440 {
2441 CHECK_NUMBER (arg, 0);
2442
2443 if (XINT (arg) == f->output_data.w32->border_width)
2444 return;
2445
2446 if (FRAME_W32_WINDOW (f) != 0)
2447 error ("Cannot change the border width of a window");
2448
2449 f->output_data.w32->border_width = XINT (arg);
2450 }
2451
2452 void
2453 x_set_internal_border_width (f, arg, oldval)
2454 struct frame *f;
2455 Lisp_Object arg, oldval;
2456 {
2457 int old = f->output_data.w32->internal_border_width;
2458
2459 CHECK_NUMBER (arg, 0);
2460 f->output_data.w32->internal_border_width = XINT (arg);
2461 if (f->output_data.w32->internal_border_width < 0)
2462 f->output_data.w32->internal_border_width = 0;
2463
2464 if (f->output_data.w32->internal_border_width == old)
2465 return;
2466
2467 if (FRAME_W32_WINDOW (f) != 0)
2468 {
2469 x_set_window_size (f, 0, f->width, f->height);
2470 SET_FRAME_GARBAGED (f);
2471 do_pending_window_change (0);
2472 }
2473 }
2474
2475 void
2476 x_set_visibility (f, value, oldval)
2477 struct frame *f;
2478 Lisp_Object value, oldval;
2479 {
2480 Lisp_Object frame;
2481 XSETFRAME (frame, f);
2482
2483 if (NILP (value))
2484 Fmake_frame_invisible (frame, Qt);
2485 else if (EQ (value, Qicon))
2486 Ficonify_frame (frame);
2487 else
2488 Fmake_frame_visible (frame);
2489 }
2490
2491 \f
2492 /* Change window heights in windows rooted in WINDOW by N lines. */
2493
2494 static void
2495 x_change_window_heights (window, n)
2496 Lisp_Object window;
2497 int n;
2498 {
2499 struct window *w = XWINDOW (window);
2500
2501 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2502 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2503
2504 if (INTEGERP (w->orig_top))
2505 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2506 if (INTEGERP (w->orig_height))
2507 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2508
2509 /* Handle just the top child in a vertical split. */
2510 if (!NILP (w->vchild))
2511 x_change_window_heights (w->vchild, n);
2512
2513 /* Adjust all children in a horizontal split. */
2514 for (window = w->hchild; !NILP (window); window = w->next)
2515 {
2516 w = XWINDOW (window);
2517 x_change_window_heights (window, n);
2518 }
2519 }
2520
2521 void
2522 x_set_menu_bar_lines (f, value, oldval)
2523 struct frame *f;
2524 Lisp_Object value, oldval;
2525 {
2526 int nlines;
2527 int olines = FRAME_MENU_BAR_LINES (f);
2528
2529 /* Right now, menu bars don't work properly in minibuf-only frames;
2530 most of the commands try to apply themselves to the minibuffer
2531 frame itself, and get an error because you can't switch buffers
2532 in or split the minibuffer window. */
2533 if (FRAME_MINIBUF_ONLY_P (f))
2534 return;
2535
2536 if (INTEGERP (value))
2537 nlines = XINT (value);
2538 else
2539 nlines = 0;
2540
2541 FRAME_MENU_BAR_LINES (f) = 0;
2542 if (nlines)
2543 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2544 else
2545 {
2546 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2547 free_frame_menubar (f);
2548 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2549
2550 /* Adjust the frame size so that the client (text) dimensions
2551 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2552 set correctly. */
2553 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2554 do_pending_window_change (0);
2555 }
2556 adjust_glyphs (f);
2557 }
2558
2559
2560 /* Set the number of lines used for the tool bar of frame F to VALUE.
2561 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2562 is the old number of tool bar lines. This function changes the
2563 height of all windows on frame F to match the new tool bar height.
2564 The frame's height doesn't change. */
2565
2566 void
2567 x_set_tool_bar_lines (f, value, oldval)
2568 struct frame *f;
2569 Lisp_Object value, oldval;
2570 {
2571 int delta, nlines, root_height;
2572 Lisp_Object root_window;
2573
2574 /* Use VALUE only if an integer >= 0. */
2575 if (INTEGERP (value) && XINT (value) >= 0)
2576 nlines = XFASTINT (value);
2577 else
2578 nlines = 0;
2579
2580 /* Make sure we redisplay all windows in this frame. */
2581 ++windows_or_buffers_changed;
2582
2583 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2584
2585 /* Don't resize the tool-bar to more than we have room for. */
2586 root_window = FRAME_ROOT_WINDOW (f);
2587 root_height = XINT (XWINDOW (root_window)->height);
2588 if (root_height - delta < 1)
2589 {
2590 delta = root_height - 1;
2591 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2592 }
2593
2594 FRAME_TOOL_BAR_LINES (f) = nlines;
2595 x_change_window_heights (root_window, delta);
2596 adjust_glyphs (f);
2597
2598 /* We also have to make sure that the internal border at the top of
2599 the frame, below the menu bar or tool bar, is redrawn when the
2600 tool bar disappears. This is so because the internal border is
2601 below the tool bar if one is displayed, but is below the menu bar
2602 if there isn't a tool bar. The tool bar draws into the area
2603 below the menu bar. */
2604 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2605 {
2606 updating_frame = f;
2607 clear_frame ();
2608 clear_current_matrices (f);
2609 updating_frame = NULL;
2610 }
2611
2612 /* If the tool bar gets smaller, the internal border below it
2613 has to be cleared. It was formerly part of the display
2614 of the larger tool bar, and updating windows won't clear it. */
2615 if (delta < 0)
2616 {
2617 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2618 int width = PIXEL_WIDTH (f);
2619 int y = nlines * CANON_Y_UNIT (f);
2620
2621 BLOCK_INPUT;
2622 {
2623 HDC hdc = get_frame_dc (f);
2624 w32_clear_area (f, hdc, 0, y, width, height);
2625 release_frame_dc (f, hdc);
2626 }
2627 UNBLOCK_INPUT;
2628 }
2629 }
2630
2631
2632 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2633 w32_id_name.
2634
2635 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2636 name; if NAME is a string, set F's name to NAME and set
2637 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2638
2639 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2640 suggesting a new name, which lisp code should override; if
2641 F->explicit_name is set, ignore the new name; otherwise, set it. */
2642
2643 void
2644 x_set_name (f, name, explicit)
2645 struct frame *f;
2646 Lisp_Object name;
2647 int explicit;
2648 {
2649 /* Make sure that requests from lisp code override requests from
2650 Emacs redisplay code. */
2651 if (explicit)
2652 {
2653 /* If we're switching from explicit to implicit, we had better
2654 update the mode lines and thereby update the title. */
2655 if (f->explicit_name && NILP (name))
2656 update_mode_lines = 1;
2657
2658 f->explicit_name = ! NILP (name);
2659 }
2660 else if (f->explicit_name)
2661 return;
2662
2663 /* If NAME is nil, set the name to the w32_id_name. */
2664 if (NILP (name))
2665 {
2666 /* Check for no change needed in this very common case
2667 before we do any consing. */
2668 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2669 XSTRING (f->name)->data))
2670 return;
2671 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2672 }
2673 else
2674 CHECK_STRING (name, 0);
2675
2676 /* Don't change the name if it's already NAME. */
2677 if (! NILP (Fstring_equal (name, f->name)))
2678 return;
2679
2680 f->name = name;
2681
2682 /* For setting the frame title, the title parameter should override
2683 the name parameter. */
2684 if (! NILP (f->title))
2685 name = f->title;
2686
2687 if (FRAME_W32_WINDOW (f))
2688 {
2689 if (STRING_MULTIBYTE (name))
2690 name = ENCODE_SYSTEM (name);
2691
2692 BLOCK_INPUT;
2693 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2694 UNBLOCK_INPUT;
2695 }
2696 }
2697
2698 /* This function should be called when the user's lisp code has
2699 specified a name for the frame; the name will override any set by the
2700 redisplay code. */
2701 void
2702 x_explicitly_set_name (f, arg, oldval)
2703 FRAME_PTR f;
2704 Lisp_Object arg, oldval;
2705 {
2706 x_set_name (f, arg, 1);
2707 }
2708
2709 /* This function should be called by Emacs redisplay code to set the
2710 name; names set this way will never override names set by the user's
2711 lisp code. */
2712 void
2713 x_implicitly_set_name (f, arg, oldval)
2714 FRAME_PTR f;
2715 Lisp_Object arg, oldval;
2716 {
2717 x_set_name (f, arg, 0);
2718 }
2719 \f
2720 /* Change the title of frame F to NAME.
2721 If NAME is nil, use the frame name as the title.
2722
2723 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2724 name; if NAME is a string, set F's name to NAME and set
2725 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2726
2727 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2728 suggesting a new name, which lisp code should override; if
2729 F->explicit_name is set, ignore the new name; otherwise, set it. */
2730
2731 void
2732 x_set_title (f, name, old_name)
2733 struct frame *f;
2734 Lisp_Object name, old_name;
2735 {
2736 /* Don't change the title if it's already NAME. */
2737 if (EQ (name, f->title))
2738 return;
2739
2740 update_mode_lines = 1;
2741
2742 f->title = name;
2743
2744 if (NILP (name))
2745 name = f->name;
2746
2747 if (FRAME_W32_WINDOW (f))
2748 {
2749 if (STRING_MULTIBYTE (name))
2750 name = ENCODE_SYSTEM (name);
2751
2752 BLOCK_INPUT;
2753 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2754 UNBLOCK_INPUT;
2755 }
2756 }
2757 \f
2758 void
2759 x_set_autoraise (f, arg, oldval)
2760 struct frame *f;
2761 Lisp_Object arg, oldval;
2762 {
2763 f->auto_raise = !EQ (Qnil, arg);
2764 }
2765
2766 void
2767 x_set_autolower (f, arg, oldval)
2768 struct frame *f;
2769 Lisp_Object arg, oldval;
2770 {
2771 f->auto_lower = !EQ (Qnil, arg);
2772 }
2773
2774 void
2775 x_set_unsplittable (f, arg, oldval)
2776 struct frame *f;
2777 Lisp_Object arg, oldval;
2778 {
2779 f->no_split = !NILP (arg);
2780 }
2781
2782 void
2783 x_set_vertical_scroll_bars (f, arg, oldval)
2784 struct frame *f;
2785 Lisp_Object arg, oldval;
2786 {
2787 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2788 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2789 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2790 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2791 {
2792 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2793 vertical_scroll_bar_none :
2794 /* Put scroll bars on the right by default, as is conventional
2795 on MS-Windows. */
2796 EQ (Qleft, arg)
2797 ? vertical_scroll_bar_left
2798 : vertical_scroll_bar_right;
2799
2800 /* We set this parameter before creating the window for the
2801 frame, so we can get the geometry right from the start.
2802 However, if the window hasn't been created yet, we shouldn't
2803 call x_set_window_size. */
2804 if (FRAME_W32_WINDOW (f))
2805 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2806 do_pending_window_change (0);
2807 }
2808 }
2809
2810 void
2811 x_set_scroll_bar_width (f, arg, oldval)
2812 struct frame *f;
2813 Lisp_Object arg, oldval;
2814 {
2815 int wid = FONT_WIDTH (f->output_data.w32->font);
2816
2817 if (NILP (arg))
2818 {
2819 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2820 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2821 wid - 1) / wid;
2822 if (FRAME_W32_WINDOW (f))
2823 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2824 do_pending_window_change (0);
2825 }
2826 else if (INTEGERP (arg) && XINT (arg) > 0
2827 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2828 {
2829 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2830 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2831 + wid-1) / wid;
2832 if (FRAME_W32_WINDOW (f))
2833 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2834 do_pending_window_change (0);
2835 }
2836 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2837 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2838 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2839 }
2840 \f
2841 /* Subroutines of creating an frame. */
2842
2843 /* Make sure that Vx_resource_name is set to a reasonable value.
2844 Fix it up, or set it to `emacs' if it is too hopeless. */
2845
2846 static void
2847 validate_x_resource_name ()
2848 {
2849 int len = 0;
2850 /* Number of valid characters in the resource name. */
2851 int good_count = 0;
2852 /* Number of invalid characters in the resource name. */
2853 int bad_count = 0;
2854 Lisp_Object new;
2855 int i;
2856
2857 if (STRINGP (Vx_resource_name))
2858 {
2859 unsigned char *p = XSTRING (Vx_resource_name)->data;
2860 int i;
2861
2862 len = STRING_BYTES (XSTRING (Vx_resource_name));
2863
2864 /* Only letters, digits, - and _ are valid in resource names.
2865 Count the valid characters and count the invalid ones. */
2866 for (i = 0; i < len; i++)
2867 {
2868 int c = p[i];
2869 if (! ((c >= 'a' && c <= 'z')
2870 || (c >= 'A' && c <= 'Z')
2871 || (c >= '0' && c <= '9')
2872 || c == '-' || c == '_'))
2873 bad_count++;
2874 else
2875 good_count++;
2876 }
2877 }
2878 else
2879 /* Not a string => completely invalid. */
2880 bad_count = 5, good_count = 0;
2881
2882 /* If name is valid already, return. */
2883 if (bad_count == 0)
2884 return;
2885
2886 /* If name is entirely invalid, or nearly so, use `emacs'. */
2887 if (good_count == 0
2888 || (good_count == 1 && bad_count > 0))
2889 {
2890 Vx_resource_name = build_string ("emacs");
2891 return;
2892 }
2893
2894 /* Name is partly valid. Copy it and replace the invalid characters
2895 with underscores. */
2896
2897 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2898
2899 for (i = 0; i < len; i++)
2900 {
2901 int c = XSTRING (new)->data[i];
2902 if (! ((c >= 'a' && c <= 'z')
2903 || (c >= 'A' && c <= 'Z')
2904 || (c >= '0' && c <= '9')
2905 || c == '-' || c == '_'))
2906 XSTRING (new)->data[i] = '_';
2907 }
2908 }
2909
2910
2911 extern char *x_get_string_resource ();
2912
2913 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2914 "Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.\n\
2915 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the\n\
2916 class, where INSTANCE is the name under which Emacs was invoked, or\n\
2917 the name specified by the `-name' or `-rn' command-line arguments.\n\
2918 \n\
2919 The optional arguments COMPONENT and SUBCLASS add to the key and the\n\
2920 class, respectively. You must specify both of them or neither.\n\
2921 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'\n\
2922 and the class is `Emacs.CLASS.SUBCLASS'.")
2923 (attribute, class, component, subclass)
2924 Lisp_Object attribute, class, component, subclass;
2925 {
2926 register char *value;
2927 char *name_key;
2928 char *class_key;
2929
2930 CHECK_STRING (attribute, 0);
2931 CHECK_STRING (class, 0);
2932
2933 if (!NILP (component))
2934 CHECK_STRING (component, 1);
2935 if (!NILP (subclass))
2936 CHECK_STRING (subclass, 2);
2937 if (NILP (component) != NILP (subclass))
2938 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
2939
2940 validate_x_resource_name ();
2941
2942 /* Allocate space for the components, the dots which separate them,
2943 and the final '\0'. Make them big enough for the worst case. */
2944 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vx_resource_name))
2945 + (STRINGP (component)
2946 ? STRING_BYTES (XSTRING (component)) : 0)
2947 + STRING_BYTES (XSTRING (attribute))
2948 + 3);
2949
2950 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2951 + STRING_BYTES (XSTRING (class))
2952 + (STRINGP (subclass)
2953 ? STRING_BYTES (XSTRING (subclass)) : 0)
2954 + 3);
2955
2956 /* Start with emacs.FRAMENAME for the name (the specific one)
2957 and with `Emacs' for the class key (the general one). */
2958 strcpy (name_key, XSTRING (Vx_resource_name)->data);
2959 strcpy (class_key, EMACS_CLASS);
2960
2961 strcat (class_key, ".");
2962 strcat (class_key, XSTRING (class)->data);
2963
2964 if (!NILP (component))
2965 {
2966 strcat (class_key, ".");
2967 strcat (class_key, XSTRING (subclass)->data);
2968
2969 strcat (name_key, ".");
2970 strcat (name_key, XSTRING (component)->data);
2971 }
2972
2973 strcat (name_key, ".");
2974 strcat (name_key, XSTRING (attribute)->data);
2975
2976 value = x_get_string_resource (Qnil,
2977 name_key, class_key);
2978
2979 if (value != (char *) 0)
2980 return build_string (value);
2981 else
2982 return Qnil;
2983 }
2984
2985 /* Used when C code wants a resource value. */
2986
2987 char *
2988 x_get_resource_string (attribute, class)
2989 char *attribute, *class;
2990 {
2991 char *name_key;
2992 char *class_key;
2993 struct frame *sf = SELECTED_FRAME ();
2994
2995 /* Allocate space for the components, the dots which separate them,
2996 and the final '\0'. */
2997 name_key = (char *) alloca (STRING_BYTES (XSTRING (Vinvocation_name))
2998 + strlen (attribute) + 2);
2999 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3000 + strlen (class) + 2);
3001
3002 sprintf (name_key, "%s.%s",
3003 XSTRING (Vinvocation_name)->data,
3004 attribute);
3005 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
3006
3007 return x_get_string_resource (sf, name_key, class_key);
3008 }
3009
3010 /* Types we might convert a resource string into. */
3011 enum resource_types
3012 {
3013 RES_TYPE_NUMBER,
3014 RES_TYPE_FLOAT,
3015 RES_TYPE_BOOLEAN,
3016 RES_TYPE_STRING,
3017 RES_TYPE_SYMBOL
3018 };
3019
3020 /* Return the value of parameter PARAM.
3021
3022 First search ALIST, then Vdefault_frame_alist, then the X defaults
3023 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3024
3025 Convert the resource to the type specified by desired_type.
3026
3027 If no default is specified, return Qunbound. If you call
3028 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3029 and don't let it get stored in any Lisp-visible variables! */
3030
3031 static Lisp_Object
3032 w32_get_arg (alist, param, attribute, class, type)
3033 Lisp_Object alist, param;
3034 char *attribute;
3035 char *class;
3036 enum resource_types type;
3037 {
3038 register Lisp_Object tem;
3039
3040 tem = Fassq (param, alist);
3041 if (EQ (tem, Qnil))
3042 tem = Fassq (param, Vdefault_frame_alist);
3043 if (EQ (tem, Qnil))
3044 {
3045
3046 if (attribute)
3047 {
3048 tem = Fx_get_resource (build_string (attribute),
3049 build_string (class),
3050 Qnil, Qnil);
3051
3052 if (NILP (tem))
3053 return Qunbound;
3054
3055 switch (type)
3056 {
3057 case RES_TYPE_NUMBER:
3058 return make_number (atoi (XSTRING (tem)->data));
3059
3060 case RES_TYPE_FLOAT:
3061 return make_float (atof (XSTRING (tem)->data));
3062
3063 case RES_TYPE_BOOLEAN:
3064 tem = Fdowncase (tem);
3065 if (!strcmp (XSTRING (tem)->data, "on")
3066 || !strcmp (XSTRING (tem)->data, "true"))
3067 return Qt;
3068 else
3069 return Qnil;
3070
3071 case RES_TYPE_STRING:
3072 return tem;
3073
3074 case RES_TYPE_SYMBOL:
3075 /* As a special case, we map the values `true' and `on'
3076 to Qt, and `false' and `off' to Qnil. */
3077 {
3078 Lisp_Object lower;
3079 lower = Fdowncase (tem);
3080 if (!strcmp (XSTRING (lower)->data, "on")
3081 || !strcmp (XSTRING (lower)->data, "true"))
3082 return Qt;
3083 else if (!strcmp (XSTRING (lower)->data, "off")
3084 || !strcmp (XSTRING (lower)->data, "false"))
3085 return Qnil;
3086 else
3087 return Fintern (tem, Qnil);
3088 }
3089
3090 default:
3091 abort ();
3092 }
3093 }
3094 else
3095 return Qunbound;
3096 }
3097 return Fcdr (tem);
3098 }
3099
3100 /* Record in frame F the specified or default value according to ALIST
3101 of the parameter named PROP (a Lisp symbol).
3102 If no value is specified for PROP, look for an X default for XPROP
3103 on the frame named NAME.
3104 If that is not found either, use the value DEFLT. */
3105
3106 static Lisp_Object
3107 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3108 struct frame *f;
3109 Lisp_Object alist;
3110 Lisp_Object prop;
3111 Lisp_Object deflt;
3112 char *xprop;
3113 char *xclass;
3114 enum resource_types type;
3115 {
3116 Lisp_Object tem;
3117
3118 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3119 if (EQ (tem, Qunbound))
3120 tem = deflt;
3121 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3122 return tem;
3123 }
3124 \f
3125 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3126 "Parse an X-style geometry string STRING.\n\
3127 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).\n\
3128 The properties returned may include `top', `left', `height', and `width'.\n\
3129 The value of `left' or `top' may be an integer,\n\
3130 or a list (+ N) meaning N pixels relative to top/left corner,\n\
3131 or a list (- N) meaning -N pixels relative to bottom/right corner.")
3132 (string)
3133 Lisp_Object string;
3134 {
3135 int geometry, x, y;
3136 unsigned int width, height;
3137 Lisp_Object result;
3138
3139 CHECK_STRING (string, 0);
3140
3141 geometry = XParseGeometry ((char *) XSTRING (string)->data,
3142 &x, &y, &width, &height);
3143
3144 result = Qnil;
3145 if (geometry & XValue)
3146 {
3147 Lisp_Object element;
3148
3149 if (x >= 0 && (geometry & XNegative))
3150 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3151 else if (x < 0 && ! (geometry & XNegative))
3152 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3153 else
3154 element = Fcons (Qleft, make_number (x));
3155 result = Fcons (element, result);
3156 }
3157
3158 if (geometry & YValue)
3159 {
3160 Lisp_Object element;
3161
3162 if (y >= 0 && (geometry & YNegative))
3163 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3164 else if (y < 0 && ! (geometry & YNegative))
3165 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3166 else
3167 element = Fcons (Qtop, make_number (y));
3168 result = Fcons (element, result);
3169 }
3170
3171 if (geometry & WidthValue)
3172 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3173 if (geometry & HeightValue)
3174 result = Fcons (Fcons (Qheight, make_number (height)), result);
3175
3176 return result;
3177 }
3178
3179 /* Calculate the desired size and position of this window,
3180 and return the flags saying which aspects were specified.
3181
3182 This function does not make the coordinates positive. */
3183
3184 #define DEFAULT_ROWS 40
3185 #define DEFAULT_COLS 80
3186
3187 static int
3188 x_figure_window_size (f, parms)
3189 struct frame *f;
3190 Lisp_Object parms;
3191 {
3192 register Lisp_Object tem0, tem1, tem2;
3193 long window_prompting = 0;
3194
3195 /* Default values if we fall through.
3196 Actually, if that happens we should get
3197 window manager prompting. */
3198 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3199 f->height = DEFAULT_ROWS;
3200 /* Window managers expect that if program-specified
3201 positions are not (0,0), they're intentional, not defaults. */
3202 f->output_data.w32->top_pos = 0;
3203 f->output_data.w32->left_pos = 0;
3204
3205 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3206 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3207 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3208 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3209 {
3210 if (!EQ (tem0, Qunbound))
3211 {
3212 CHECK_NUMBER (tem0, 0);
3213 f->height = XINT (tem0);
3214 }
3215 if (!EQ (tem1, Qunbound))
3216 {
3217 CHECK_NUMBER (tem1, 0);
3218 SET_FRAME_WIDTH (f, XINT (tem1));
3219 }
3220 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3221 window_prompting |= USSize;
3222 else
3223 window_prompting |= PSize;
3224 }
3225
3226 f->output_data.w32->vertical_scroll_bar_extra
3227 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3228 ? 0
3229 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3230 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3231 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3232 f->output_data.w32->flags_areas_extra
3233 = FRAME_FLAGS_AREA_WIDTH (f);
3234 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3235 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3236
3237 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3238 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3239 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3240 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3241 {
3242 if (EQ (tem0, Qminus))
3243 {
3244 f->output_data.w32->top_pos = 0;
3245 window_prompting |= YNegative;
3246 }
3247 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3248 && CONSP (XCDR (tem0))
3249 && INTEGERP (XCAR (XCDR (tem0))))
3250 {
3251 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3252 window_prompting |= YNegative;
3253 }
3254 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3255 && CONSP (XCDR (tem0))
3256 && INTEGERP (XCAR (XCDR (tem0))))
3257 {
3258 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3259 }
3260 else if (EQ (tem0, Qunbound))
3261 f->output_data.w32->top_pos = 0;
3262 else
3263 {
3264 CHECK_NUMBER (tem0, 0);
3265 f->output_data.w32->top_pos = XINT (tem0);
3266 if (f->output_data.w32->top_pos < 0)
3267 window_prompting |= YNegative;
3268 }
3269
3270 if (EQ (tem1, Qminus))
3271 {
3272 f->output_data.w32->left_pos = 0;
3273 window_prompting |= XNegative;
3274 }
3275 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3276 && CONSP (XCDR (tem1))
3277 && INTEGERP (XCAR (XCDR (tem1))))
3278 {
3279 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3280 window_prompting |= XNegative;
3281 }
3282 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3283 && CONSP (XCDR (tem1))
3284 && INTEGERP (XCAR (XCDR (tem1))))
3285 {
3286 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3287 }
3288 else if (EQ (tem1, Qunbound))
3289 f->output_data.w32->left_pos = 0;
3290 else
3291 {
3292 CHECK_NUMBER (tem1, 0);
3293 f->output_data.w32->left_pos = XINT (tem1);
3294 if (f->output_data.w32->left_pos < 0)
3295 window_prompting |= XNegative;
3296 }
3297
3298 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3299 window_prompting |= USPosition;
3300 else
3301 window_prompting |= PPosition;
3302 }
3303
3304 return window_prompting;
3305 }
3306
3307 \f
3308
3309 extern LRESULT CALLBACK w32_wnd_proc ();
3310
3311 BOOL
3312 w32_init_class (hinst)
3313 HINSTANCE hinst;
3314 {
3315 WNDCLASS wc;
3316
3317 wc.style = CS_HREDRAW | CS_VREDRAW;
3318 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3319 wc.cbClsExtra = 0;
3320 wc.cbWndExtra = WND_EXTRA_BYTES;
3321 wc.hInstance = hinst;
3322 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3323 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3324 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3325 wc.lpszMenuName = NULL;
3326 wc.lpszClassName = EMACS_CLASS;
3327
3328 return (RegisterClass (&wc));
3329 }
3330
3331 HWND
3332 w32_createscrollbar (f, bar)
3333 struct frame *f;
3334 struct scroll_bar * bar;
3335 {
3336 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3337 /* Position and size of scroll bar. */
3338 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3339 XINT(bar->top),
3340 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3341 XINT(bar->height),
3342 FRAME_W32_WINDOW (f),
3343 NULL,
3344 hinst,
3345 NULL));
3346 }
3347
3348 void
3349 w32_createwindow (f)
3350 struct frame *f;
3351 {
3352 HWND hwnd;
3353 RECT rect;
3354
3355 rect.left = rect.top = 0;
3356 rect.right = PIXEL_WIDTH (f);
3357 rect.bottom = PIXEL_HEIGHT (f);
3358
3359 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3360 FRAME_EXTERNAL_MENU_BAR (f));
3361
3362 /* Do first time app init */
3363
3364 if (!hprevinst)
3365 {
3366 w32_init_class (hinst);
3367 }
3368
3369 FRAME_W32_WINDOW (f) = hwnd
3370 = CreateWindow (EMACS_CLASS,
3371 f->namebuf,
3372 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3373 f->output_data.w32->left_pos,
3374 f->output_data.w32->top_pos,
3375 rect.right - rect.left,
3376 rect.bottom - rect.top,
3377 NULL,
3378 NULL,
3379 hinst,
3380 NULL);
3381
3382 if (hwnd)
3383 {
3384 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3385 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3386 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3387 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3388 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3389
3390 /* Enable drag-n-drop. */
3391 DragAcceptFiles (hwnd, TRUE);
3392
3393 /* Do this to discard the default setting specified by our parent. */
3394 ShowWindow (hwnd, SW_HIDE);
3395 }
3396 }
3397
3398 void
3399 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3400 W32Msg * wmsg;
3401 HWND hwnd;
3402 UINT msg;
3403 WPARAM wParam;
3404 LPARAM lParam;
3405 {
3406 wmsg->msg.hwnd = hwnd;
3407 wmsg->msg.message = msg;
3408 wmsg->msg.wParam = wParam;
3409 wmsg->msg.lParam = lParam;
3410 wmsg->msg.time = GetMessageTime ();
3411
3412 post_msg (wmsg);
3413 }
3414
3415 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3416 between left and right keys as advertised. We test for this
3417 support dynamically, and set a flag when the support is absent. If
3418 absent, we keep track of the left and right control and alt keys
3419 ourselves. This is particularly necessary on keyboards that rely
3420 upon the AltGr key, which is represented as having the left control
3421 and right alt keys pressed. For these keyboards, we need to know
3422 when the left alt key has been pressed in addition to the AltGr key
3423 so that we can properly support M-AltGr-key sequences (such as M-@
3424 on Swedish keyboards). */
3425
3426 #define EMACS_LCONTROL 0
3427 #define EMACS_RCONTROL 1
3428 #define EMACS_LMENU 2
3429 #define EMACS_RMENU 3
3430
3431 static int modifiers[4];
3432 static int modifiers_recorded;
3433 static int modifier_key_support_tested;
3434
3435 static void
3436 test_modifier_support (unsigned int wparam)
3437 {
3438 unsigned int l, r;
3439
3440 if (wparam != VK_CONTROL && wparam != VK_MENU)
3441 return;
3442 if (wparam == VK_CONTROL)
3443 {
3444 l = VK_LCONTROL;
3445 r = VK_RCONTROL;
3446 }
3447 else
3448 {
3449 l = VK_LMENU;
3450 r = VK_RMENU;
3451 }
3452 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3453 modifiers_recorded = 1;
3454 else
3455 modifiers_recorded = 0;
3456 modifier_key_support_tested = 1;
3457 }
3458
3459 static void
3460 record_keydown (unsigned int wparam, unsigned int lparam)
3461 {
3462 int i;
3463
3464 if (!modifier_key_support_tested)
3465 test_modifier_support (wparam);
3466
3467 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3468 return;
3469
3470 if (wparam == VK_CONTROL)
3471 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3472 else
3473 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3474
3475 modifiers[i] = 1;
3476 }
3477
3478 static void
3479 record_keyup (unsigned int wparam, unsigned int lparam)
3480 {
3481 int i;
3482
3483 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3484 return;
3485
3486 if (wparam == VK_CONTROL)
3487 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3488 else
3489 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3490
3491 modifiers[i] = 0;
3492 }
3493
3494 /* Emacs can lose focus while a modifier key has been pressed. When
3495 it regains focus, be conservative and clear all modifiers since
3496 we cannot reconstruct the left and right modifier state. */
3497 static void
3498 reset_modifiers ()
3499 {
3500 SHORT ctrl, alt;
3501
3502 if (GetFocus () == NULL)
3503 /* Emacs doesn't have keyboard focus. Do nothing. */
3504 return;
3505
3506 ctrl = GetAsyncKeyState (VK_CONTROL);
3507 alt = GetAsyncKeyState (VK_MENU);
3508
3509 if (!(ctrl & 0x08000))
3510 /* Clear any recorded control modifier state. */
3511 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3512
3513 if (!(alt & 0x08000))
3514 /* Clear any recorded alt modifier state. */
3515 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3516
3517 /* Update the state of all modifier keys, because modifiers used in
3518 hot-key combinations can get stuck on if Emacs loses focus as a
3519 result of a hot-key being pressed. */
3520 {
3521 BYTE keystate[256];
3522
3523 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3524
3525 GetKeyboardState (keystate);
3526 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3527 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3528 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3529 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3530 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3531 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3532 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3533 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3534 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3535 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3536 SetKeyboardState (keystate);
3537 }
3538 }
3539
3540 /* Synchronize modifier state with what is reported with the current
3541 keystroke. Even if we cannot distinguish between left and right
3542 modifier keys, we know that, if no modifiers are set, then neither
3543 the left or right modifier should be set. */
3544 static void
3545 sync_modifiers ()
3546 {
3547 if (!modifiers_recorded)
3548 return;
3549
3550 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3551 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3552
3553 if (!(GetKeyState (VK_MENU) & 0x8000))
3554 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3555 }
3556
3557 static int
3558 modifier_set (int vkey)
3559 {
3560 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3561 return (GetKeyState (vkey) & 0x1);
3562 if (!modifiers_recorded)
3563 return (GetKeyState (vkey) & 0x8000);
3564
3565 switch (vkey)
3566 {
3567 case VK_LCONTROL:
3568 return modifiers[EMACS_LCONTROL];
3569 case VK_RCONTROL:
3570 return modifiers[EMACS_RCONTROL];
3571 case VK_LMENU:
3572 return modifiers[EMACS_LMENU];
3573 case VK_RMENU:
3574 return modifiers[EMACS_RMENU];
3575 }
3576 return (GetKeyState (vkey) & 0x8000);
3577 }
3578
3579 /* Convert between the modifier bits W32 uses and the modifier bits
3580 Emacs uses. */
3581
3582 unsigned int
3583 w32_key_to_modifier (int key)
3584 {
3585 Lisp_Object key_mapping;
3586
3587 switch (key)
3588 {
3589 case VK_LWIN:
3590 key_mapping = Vw32_lwindow_modifier;
3591 break;
3592 case VK_RWIN:
3593 key_mapping = Vw32_rwindow_modifier;
3594 break;
3595 case VK_APPS:
3596 key_mapping = Vw32_apps_modifier;
3597 break;
3598 case VK_SCROLL:
3599 key_mapping = Vw32_scroll_lock_modifier;
3600 break;
3601 default:
3602 key_mapping = Qnil;
3603 }
3604
3605 /* NB. This code runs in the input thread, asychronously to the lisp
3606 thread, so we must be careful to ensure access to lisp data is
3607 thread-safe. The following code is safe because the modifier
3608 variable values are updated atomically from lisp and symbols are
3609 not relocated by GC. Also, we don't have to worry about seeing GC
3610 markbits here. */
3611 if (EQ (key_mapping, Qhyper))
3612 return hyper_modifier;
3613 if (EQ (key_mapping, Qsuper))
3614 return super_modifier;
3615 if (EQ (key_mapping, Qmeta))
3616 return meta_modifier;
3617 if (EQ (key_mapping, Qalt))
3618 return alt_modifier;
3619 if (EQ (key_mapping, Qctrl))
3620 return ctrl_modifier;
3621 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3622 return ctrl_modifier;
3623 if (EQ (key_mapping, Qshift))
3624 return shift_modifier;
3625
3626 /* Don't generate any modifier if not explicitly requested. */
3627 return 0;
3628 }
3629
3630 unsigned int
3631 w32_get_modifiers ()
3632 {
3633 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3634 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3635 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3636 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3637 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3638 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3639 (modifier_set (VK_MENU) ?
3640 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3641 }
3642
3643 /* We map the VK_* modifiers into console modifier constants
3644 so that we can use the same routines to handle both console
3645 and window input. */
3646
3647 static int
3648 construct_console_modifiers ()
3649 {
3650 int mods;
3651
3652 mods = 0;
3653 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3654 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3655 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3656 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3657 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3658 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3659 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3660 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3661 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3662 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3663 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3664
3665 return mods;
3666 }
3667
3668 static int
3669 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3670 {
3671 int mods;
3672
3673 /* Convert to emacs modifiers. */
3674 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3675
3676 return mods;
3677 }
3678
3679 unsigned int
3680 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3681 {
3682 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3683 return virt_key;
3684
3685 if (virt_key == VK_RETURN)
3686 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3687
3688 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3689 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3690
3691 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3692 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3693
3694 if (virt_key == VK_CLEAR)
3695 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3696
3697 return virt_key;
3698 }
3699
3700 /* List of special key combinations which w32 would normally capture,
3701 but emacs should grab instead. Not directly visible to lisp, to
3702 simplify synchronization. Each item is an integer encoding a virtual
3703 key code and modifier combination to capture. */
3704 Lisp_Object w32_grabbed_keys;
3705
3706 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3707 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3708 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3709 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3710
3711 /* Register hot-keys for reserved key combinations when Emacs has
3712 keyboard focus, since this is the only way Emacs can receive key
3713 combinations like Alt-Tab which are used by the system. */
3714
3715 static void
3716 register_hot_keys (hwnd)
3717 HWND hwnd;
3718 {
3719 Lisp_Object keylist;
3720
3721 /* Use GC_CONSP, since we are called asynchronously. */
3722 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3723 {
3724 Lisp_Object key = XCAR (keylist);
3725
3726 /* Deleted entries get set to nil. */
3727 if (!INTEGERP (key))
3728 continue;
3729
3730 RegisterHotKey (hwnd, HOTKEY_ID (key),
3731 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3732 }
3733 }
3734
3735 static void
3736 unregister_hot_keys (hwnd)
3737 HWND hwnd;
3738 {
3739 Lisp_Object keylist;
3740
3741 /* Use GC_CONSP, since we are called asynchronously. */
3742 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3743 {
3744 Lisp_Object key = XCAR (keylist);
3745
3746 if (!INTEGERP (key))
3747 continue;
3748
3749 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3750 }
3751 }
3752
3753 /* Main message dispatch loop. */
3754
3755 static void
3756 w32_msg_pump (deferred_msg * msg_buf)
3757 {
3758 MSG msg;
3759 int result;
3760 HWND focus_window;
3761
3762 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3763
3764 while (GetMessage (&msg, NULL, 0, 0))
3765 {
3766 if (msg.hwnd == NULL)
3767 {
3768 switch (msg.message)
3769 {
3770 case WM_NULL:
3771 /* Produced by complete_deferred_msg; just ignore. */
3772 break;
3773 case WM_EMACS_CREATEWINDOW:
3774 w32_createwindow ((struct frame *) msg.wParam);
3775 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3776 abort ();
3777 break;
3778 case WM_EMACS_SETLOCALE:
3779 SetThreadLocale (msg.wParam);
3780 /* Reply is not expected. */
3781 break;
3782 case WM_EMACS_SETKEYBOARDLAYOUT:
3783 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3784 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3785 result, 0))
3786 abort ();
3787 break;
3788 case WM_EMACS_REGISTER_HOT_KEY:
3789 focus_window = GetFocus ();
3790 if (focus_window != NULL)
3791 RegisterHotKey (focus_window,
3792 HOTKEY_ID (msg.wParam),
3793 HOTKEY_MODIFIERS (msg.wParam),
3794 HOTKEY_VK_CODE (msg.wParam));
3795 /* Reply is not expected. */
3796 break;
3797 case WM_EMACS_UNREGISTER_HOT_KEY:
3798 focus_window = GetFocus ();
3799 if (focus_window != NULL)
3800 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3801 /* Mark item as erased. NB: this code must be
3802 thread-safe. The next line is okay because the cons
3803 cell is never made into garbage and is not relocated by
3804 GC. */
3805 XCAR ((Lisp_Object) msg.lParam) = Qnil;
3806 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3807 abort ();
3808 break;
3809 case WM_EMACS_TOGGLE_LOCK_KEY:
3810 {
3811 int vk_code = (int) msg.wParam;
3812 int cur_state = (GetKeyState (vk_code) & 1);
3813 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3814
3815 /* NB: This code must be thread-safe. It is safe to
3816 call NILP because symbols are not relocated by GC,
3817 and pointer here is not touched by GC (so the markbit
3818 can't be set). Numbers are safe because they are
3819 immediate values. */
3820 if (NILP (new_state)
3821 || (NUMBERP (new_state)
3822 && (XUINT (new_state)) & 1 != cur_state))
3823 {
3824 one_w32_display_info.faked_key = vk_code;
3825
3826 keybd_event ((BYTE) vk_code,
3827 (BYTE) MapVirtualKey (vk_code, 0),
3828 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3829 keybd_event ((BYTE) vk_code,
3830 (BYTE) MapVirtualKey (vk_code, 0),
3831 KEYEVENTF_EXTENDEDKEY | 0, 0);
3832 keybd_event ((BYTE) vk_code,
3833 (BYTE) MapVirtualKey (vk_code, 0),
3834 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3835 cur_state = !cur_state;
3836 }
3837 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3838 cur_state, 0))
3839 abort ();
3840 }
3841 break;
3842 default:
3843 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3844 }
3845 }
3846 else
3847 {
3848 DispatchMessage (&msg);
3849 }
3850
3851 /* Exit nested loop when our deferred message has completed. */
3852 if (msg_buf->completed)
3853 break;
3854 }
3855 }
3856
3857 deferred_msg * deferred_msg_head;
3858
3859 static deferred_msg *
3860 find_deferred_msg (HWND hwnd, UINT msg)
3861 {
3862 deferred_msg * item;
3863
3864 /* Don't actually need synchronization for read access, since
3865 modification of single pointer is always atomic. */
3866 /* enter_crit (); */
3867
3868 for (item = deferred_msg_head; item != NULL; item = item->next)
3869 if (item->w32msg.msg.hwnd == hwnd
3870 && item->w32msg.msg.message == msg)
3871 break;
3872
3873 /* leave_crit (); */
3874
3875 return item;
3876 }
3877
3878 static LRESULT
3879 send_deferred_msg (deferred_msg * msg_buf,
3880 HWND hwnd,
3881 UINT msg,
3882 WPARAM wParam,
3883 LPARAM lParam)
3884 {
3885 /* Only input thread can send deferred messages. */
3886 if (GetCurrentThreadId () != dwWindowsThreadId)
3887 abort ();
3888
3889 /* It is an error to send a message that is already deferred. */
3890 if (find_deferred_msg (hwnd, msg) != NULL)
3891 abort ();
3892
3893 /* Enforced synchronization is not needed because this is the only
3894 function that alters deferred_msg_head, and the following critical
3895 section is guaranteed to only be serially reentered (since only the
3896 input thread can call us). */
3897
3898 /* enter_crit (); */
3899
3900 msg_buf->completed = 0;
3901 msg_buf->next = deferred_msg_head;
3902 deferred_msg_head = msg_buf;
3903 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3904
3905 /* leave_crit (); */
3906
3907 /* Start a new nested message loop to process other messages until
3908 this one is completed. */
3909 w32_msg_pump (msg_buf);
3910
3911 deferred_msg_head = msg_buf->next;
3912
3913 return msg_buf->result;
3914 }
3915
3916 void
3917 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3918 {
3919 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3920
3921 if (msg_buf == NULL)
3922 /* Message may have been cancelled, so don't abort(). */
3923 return;
3924
3925 msg_buf->result = result;
3926 msg_buf->completed = 1;
3927
3928 /* Ensure input thread is woken so it notices the completion. */
3929 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3930 }
3931
3932 void
3933 cancel_all_deferred_msgs ()
3934 {
3935 deferred_msg * item;
3936
3937 /* Don't actually need synchronization for read access, since
3938 modification of single pointer is always atomic. */
3939 /* enter_crit (); */
3940
3941 for (item = deferred_msg_head; item != NULL; item = item->next)
3942 {
3943 item->result = 0;
3944 item->completed = 1;
3945 }
3946
3947 /* leave_crit (); */
3948
3949 /* Ensure input thread is woken so it notices the completion. */
3950 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3951 }
3952
3953 DWORD
3954 w32_msg_worker (dw)
3955 DWORD dw;
3956 {
3957 MSG msg;
3958 deferred_msg dummy_buf;
3959
3960 /* Ensure our message queue is created */
3961
3962 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3963
3964 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3965 abort ();
3966
3967 memset (&dummy_buf, 0, sizeof (dummy_buf));
3968 dummy_buf.w32msg.msg.hwnd = NULL;
3969 dummy_buf.w32msg.msg.message = WM_NULL;
3970
3971 /* This is the inital message loop which should only exit when the
3972 application quits. */
3973 w32_msg_pump (&dummy_buf);
3974
3975 return 0;
3976 }
3977
3978 static void
3979 post_character_message (hwnd, msg, wParam, lParam, modifiers)
3980 HWND hwnd;
3981 UINT msg;
3982 WPARAM wParam;
3983 LPARAM lParam;
3984 DWORD modifiers;
3985
3986 {
3987 W32Msg wmsg;
3988
3989 wmsg.dwModifiers = modifiers;
3990
3991 /* Detect quit_char and set quit-flag directly. Note that we
3992 still need to post a message to ensure the main thread will be
3993 woken up if blocked in sys_select(), but we do NOT want to post
3994 the quit_char message itself (because it will usually be as if
3995 the user had typed quit_char twice). Instead, we post a dummy
3996 message that has no particular effect. */
3997 {
3998 int c = wParam;
3999 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
4000 c = make_ctrl_char (c) & 0377;
4001 if (c == quit_char
4002 || (wmsg.dwModifiers == 0 &&
4003 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
4004 {
4005 Vquit_flag = Qt;
4006
4007 /* The choice of message is somewhat arbitrary, as long as
4008 the main thread handler just ignores it. */
4009 msg = WM_NULL;
4010
4011 /* Interrupt any blocking system calls. */
4012 signal_quit ();
4013
4014 /* As a safety precaution, forcibly complete any deferred
4015 messages. This is a kludge, but I don't see any particularly
4016 clean way to handle the situation where a deferred message is
4017 "dropped" in the lisp thread, and will thus never be
4018 completed, eg. by the user trying to activate the menubar
4019 when the lisp thread is busy, and then typing C-g when the
4020 menubar doesn't open promptly (with the result that the
4021 menubar never responds at all because the deferred
4022 WM_INITMENU message is never completed). Another problem
4023 situation is when the lisp thread calls SendMessage (to send
4024 a window manager command) when a message has been deferred;
4025 the lisp thread gets blocked indefinitely waiting for the
4026 deferred message to be completed, which itself is waiting for
4027 the lisp thread to respond.
4028
4029 Note that we don't want to block the input thread waiting for
4030 a reponse from the lisp thread (although that would at least
4031 solve the deadlock problem above), because we want to be able
4032 to receive C-g to interrupt the lisp thread. */
4033 cancel_all_deferred_msgs ();
4034 }
4035 }
4036
4037 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4038 }
4039
4040 /* Main window procedure */
4041
4042 LRESULT CALLBACK
4043 w32_wnd_proc (hwnd, msg, wParam, lParam)
4044 HWND hwnd;
4045 UINT msg;
4046 WPARAM wParam;
4047 LPARAM lParam;
4048 {
4049 struct frame *f;
4050 struct w32_display_info *dpyinfo = &one_w32_display_info;
4051 W32Msg wmsg;
4052 int windows_translate;
4053 int key;
4054
4055 /* Note that it is okay to call x_window_to_frame, even though we are
4056 not running in the main lisp thread, because frame deletion
4057 requires the lisp thread to synchronize with this thread. Thus, if
4058 a frame struct is returned, it can be used without concern that the
4059 lisp thread might make it disappear while we are using it.
4060
4061 NB. Walking the frame list in this thread is safe (as long as
4062 writes of Lisp_Object slots are atomic, which they are on Windows).
4063 Although delete-frame can destructively modify the frame list while
4064 we are walking it, a garbage collection cannot occur until after
4065 delete-frame has synchronized with this thread.
4066
4067 It is also safe to use functions that make GDI calls, such as
4068 w32_clear_rect, because these functions must obtain a DC handle
4069 from the frame struct using get_frame_dc which is thread-aware. */
4070
4071 switch (msg)
4072 {
4073 case WM_ERASEBKGND:
4074 f = x_window_to_frame (dpyinfo, hwnd);
4075 if (f)
4076 {
4077 HDC hdc = get_frame_dc (f);
4078 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4079 w32_clear_rect (f, hdc, &wmsg.rect);
4080 release_frame_dc (f, hdc);
4081
4082 #if defined (W32_DEBUG_DISPLAY)
4083 DebPrint (("WM_ERASEBKGND: erasing %d,%d-%d,%d\n",
4084 wmsg.rect.left, wmsg.rect.top, wmsg.rect.right,
4085 wmsg.rect.bottom));
4086 #endif /* W32_DEBUG_DISPLAY */
4087 }
4088 return 1;
4089 case WM_PALETTECHANGED:
4090 /* ignore our own changes */
4091 if ((HWND)wParam != hwnd)
4092 {
4093 f = x_window_to_frame (dpyinfo, hwnd);
4094 if (f)
4095 /* get_frame_dc will realize our palette and force all
4096 frames to be redrawn if needed. */
4097 release_frame_dc (f, get_frame_dc (f));
4098 }
4099 return 0;
4100 case WM_PAINT:
4101 {
4102 PAINTSTRUCT paintStruct;
4103 RECT update_rect;
4104
4105 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4106 fails. Apparently this can happen under some
4107 circumstances. */
4108 if (!w32_strict_painting || GetUpdateRect (hwnd, &update_rect, FALSE))
4109 {
4110 enter_crit ();
4111 BeginPaint (hwnd, &paintStruct);
4112
4113 if (w32_strict_painting)
4114 /* The rectangles returned by GetUpdateRect and BeginPaint
4115 do not always match. GetUpdateRect seems to be the
4116 more reliable of the two. */
4117 wmsg.rect = update_rect;
4118 else
4119 wmsg.rect = paintStruct.rcPaint;
4120
4121 #if defined (W32_DEBUG_DISPLAY)
4122 DebPrint (("WM_PAINT: painting %d,%d-%d,%d\n", wmsg.rect.left,
4123 wmsg.rect.top, wmsg.rect.right, wmsg.rect.bottom));
4124 DebPrint (("WM_PAINT: update region is %d,%d-%d,%d\n",
4125 update_rect.left, update_rect.top,
4126 update_rect.right, update_rect.bottom));
4127 #endif
4128 EndPaint (hwnd, &paintStruct);
4129 leave_crit ();
4130
4131 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4132
4133 return 0;
4134 }
4135
4136 /* If GetUpdateRect returns 0 (meaning there is no update
4137 region), assume the whole window needs to be repainted. */
4138 GetClientRect(hwnd, &wmsg.rect);
4139 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4140 return 0;
4141 }
4142
4143 case WM_INPUTLANGCHANGE:
4144 /* Inform lisp thread of keyboard layout changes. */
4145 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4146
4147 /* Clear dead keys in the keyboard state; for simplicity only
4148 preserve modifier key states. */
4149 {
4150 int i;
4151 BYTE keystate[256];
4152
4153 GetKeyboardState (keystate);
4154 for (i = 0; i < 256; i++)
4155 if (1
4156 && i != VK_SHIFT
4157 && i != VK_LSHIFT
4158 && i != VK_RSHIFT
4159 && i != VK_CAPITAL
4160 && i != VK_NUMLOCK
4161 && i != VK_SCROLL
4162 && i != VK_CONTROL
4163 && i != VK_LCONTROL
4164 && i != VK_RCONTROL
4165 && i != VK_MENU
4166 && i != VK_LMENU
4167 && i != VK_RMENU
4168 && i != VK_LWIN
4169 && i != VK_RWIN)
4170 keystate[i] = 0;
4171 SetKeyboardState (keystate);
4172 }
4173 goto dflt;
4174
4175 case WM_HOTKEY:
4176 /* Synchronize hot keys with normal input. */
4177 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4178 return (0);
4179
4180 case WM_KEYUP:
4181 case WM_SYSKEYUP:
4182 record_keyup (wParam, lParam);
4183 goto dflt;
4184
4185 case WM_KEYDOWN:
4186 case WM_SYSKEYDOWN:
4187 /* Ignore keystrokes we fake ourself; see below. */
4188 if (dpyinfo->faked_key == wParam)
4189 {
4190 dpyinfo->faked_key = 0;
4191 /* Make sure TranslateMessage sees them though (as long as
4192 they don't produce WM_CHAR messages). This ensures that
4193 indicator lights are toggled promptly on Windows 9x, for
4194 example. */
4195 if (lispy_function_keys[wParam] != 0)
4196 {
4197 windows_translate = 1;
4198 goto translate;
4199 }
4200 return 0;
4201 }
4202
4203 /* Synchronize modifiers with current keystroke. */
4204 sync_modifiers ();
4205 record_keydown (wParam, lParam);
4206 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4207
4208 windows_translate = 0;
4209
4210 switch (wParam)
4211 {
4212 case VK_LWIN:
4213 if (NILP (Vw32_pass_lwindow_to_system))
4214 {
4215 /* Prevent system from acting on keyup (which opens the
4216 Start menu if no other key was pressed) by simulating a
4217 press of Space which we will ignore. */
4218 if (GetAsyncKeyState (wParam) & 1)
4219 {
4220 if (NUMBERP (Vw32_phantom_key_code))
4221 key = XUINT (Vw32_phantom_key_code) & 255;
4222 else
4223 key = VK_SPACE;
4224 dpyinfo->faked_key = key;
4225 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4226 }
4227 }
4228 if (!NILP (Vw32_lwindow_modifier))
4229 return 0;
4230 break;
4231 case VK_RWIN:
4232 if (NILP (Vw32_pass_rwindow_to_system))
4233 {
4234 if (GetAsyncKeyState (wParam) & 1)
4235 {
4236 if (NUMBERP (Vw32_phantom_key_code))
4237 key = XUINT (Vw32_phantom_key_code) & 255;
4238 else
4239 key = VK_SPACE;
4240 dpyinfo->faked_key = key;
4241 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4242 }
4243 }
4244 if (!NILP (Vw32_rwindow_modifier))
4245 return 0;
4246 break;
4247 case VK_APPS:
4248 if (!NILP (Vw32_apps_modifier))
4249 return 0;
4250 break;
4251 case VK_MENU:
4252 if (NILP (Vw32_pass_alt_to_system))
4253 /* Prevent DefWindowProc from activating the menu bar if an
4254 Alt key is pressed and released by itself. */
4255 return 0;
4256 windows_translate = 1;
4257 break;
4258 case VK_CAPITAL:
4259 /* Decide whether to treat as modifier or function key. */
4260 if (NILP (Vw32_enable_caps_lock))
4261 goto disable_lock_key;
4262 windows_translate = 1;
4263 break;
4264 case VK_NUMLOCK:
4265 /* Decide whether to treat as modifier or function key. */
4266 if (NILP (Vw32_enable_num_lock))
4267 goto disable_lock_key;
4268 windows_translate = 1;
4269 break;
4270 case VK_SCROLL:
4271 /* Decide whether to treat as modifier or function key. */
4272 if (NILP (Vw32_scroll_lock_modifier))
4273 goto disable_lock_key;
4274 windows_translate = 1;
4275 break;
4276 disable_lock_key:
4277 /* Ensure the appropriate lock key state (and indicator light)
4278 remains in the same state. We do this by faking another
4279 press of the relevant key. Apparently, this really is the
4280 only way to toggle the state of the indicator lights. */
4281 dpyinfo->faked_key = wParam;
4282 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4283 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4284 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4285 KEYEVENTF_EXTENDEDKEY | 0, 0);
4286 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4287 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4288 /* Ensure indicator lights are updated promptly on Windows 9x
4289 (TranslateMessage apparently does this), after forwarding
4290 input event. */
4291 post_character_message (hwnd, msg, wParam, lParam,
4292 w32_get_key_modifiers (wParam, lParam));
4293 windows_translate = 1;
4294 break;
4295 case VK_CONTROL:
4296 case VK_SHIFT:
4297 case VK_PROCESSKEY: /* Generated by IME. */
4298 windows_translate = 1;
4299 break;
4300 case VK_CANCEL:
4301 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4302 which is confusing for purposes of key binding; convert
4303 VK_CANCEL events into VK_PAUSE events. */
4304 wParam = VK_PAUSE;
4305 break;
4306 case VK_PAUSE:
4307 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4308 for purposes of key binding; convert these back into
4309 VK_NUMLOCK events, at least when we want to see NumLock key
4310 presses. (Note that there is never any possibility that
4311 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4312 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4313 wParam = VK_NUMLOCK;
4314 break;
4315 default:
4316 /* If not defined as a function key, change it to a WM_CHAR message. */
4317 if (lispy_function_keys[wParam] == 0)
4318 {
4319 DWORD modifiers = construct_console_modifiers ();
4320
4321 if (!NILP (Vw32_recognize_altgr)
4322 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4323 {
4324 /* Always let TranslateMessage handle AltGr key chords;
4325 for some reason, ToAscii doesn't always process AltGr
4326 chords correctly. */
4327 windows_translate = 1;
4328 }
4329 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4330 {
4331 /* Handle key chords including any modifiers other
4332 than shift directly, in order to preserve as much
4333 modifier information as possible. */
4334 if ('A' <= wParam && wParam <= 'Z')
4335 {
4336 /* Don't translate modified alphabetic keystrokes,
4337 so the user doesn't need to constantly switch
4338 layout to type control or meta keystrokes when
4339 the normal layout translates alphabetic
4340 characters to non-ascii characters. */
4341 if (!modifier_set (VK_SHIFT))
4342 wParam += ('a' - 'A');
4343 msg = WM_CHAR;
4344 }
4345 else
4346 {
4347 /* Try to handle other keystrokes by determining the
4348 base character (ie. translating the base key plus
4349 shift modifier). */
4350 int add;
4351 int isdead = 0;
4352 KEY_EVENT_RECORD key;
4353
4354 key.bKeyDown = TRUE;
4355 key.wRepeatCount = 1;
4356 key.wVirtualKeyCode = wParam;
4357 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4358 key.uChar.AsciiChar = 0;
4359 key.dwControlKeyState = modifiers;
4360
4361 add = w32_kbd_patch_key (&key);
4362 /* 0 means an unrecognised keycode, negative means
4363 dead key. Ignore both. */
4364 while (--add >= 0)
4365 {
4366 /* Forward asciified character sequence. */
4367 post_character_message
4368 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4369 w32_get_key_modifiers (wParam, lParam));
4370 w32_kbd_patch_key (&key);
4371 }
4372 return 0;
4373 }
4374 }
4375 else
4376 {
4377 /* Let TranslateMessage handle everything else. */
4378 windows_translate = 1;
4379 }
4380 }
4381 }
4382
4383 translate:
4384 if (windows_translate)
4385 {
4386 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4387
4388 windows_msg.time = GetMessageTime ();
4389 TranslateMessage (&windows_msg);
4390 goto dflt;
4391 }
4392
4393 /* Fall through */
4394
4395 case WM_SYSCHAR:
4396 case WM_CHAR:
4397 post_character_message (hwnd, msg, wParam, lParam,
4398 w32_get_key_modifiers (wParam, lParam));
4399 break;
4400
4401 /* Simulate middle mouse button events when left and right buttons
4402 are used together, but only if user has two button mouse. */
4403 case WM_LBUTTONDOWN:
4404 case WM_RBUTTONDOWN:
4405 if (XINT (Vw32_num_mouse_buttons) > 2)
4406 goto handle_plain_button;
4407
4408 {
4409 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4410 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4411
4412 if (button_state & this)
4413 return 0;
4414
4415 if (button_state == 0)
4416 SetCapture (hwnd);
4417
4418 button_state |= this;
4419
4420 if (button_state & other)
4421 {
4422 if (mouse_button_timer)
4423 {
4424 KillTimer (hwnd, mouse_button_timer);
4425 mouse_button_timer = 0;
4426
4427 /* Generate middle mouse event instead. */
4428 msg = WM_MBUTTONDOWN;
4429 button_state |= MMOUSE;
4430 }
4431 else if (button_state & MMOUSE)
4432 {
4433 /* Ignore button event if we've already generated a
4434 middle mouse down event. This happens if the
4435 user releases and press one of the two buttons
4436 after we've faked a middle mouse event. */
4437 return 0;
4438 }
4439 else
4440 {
4441 /* Flush out saved message. */
4442 post_msg (&saved_mouse_button_msg);
4443 }
4444 wmsg.dwModifiers = w32_get_modifiers ();
4445 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4446
4447 /* Clear message buffer. */
4448 saved_mouse_button_msg.msg.hwnd = 0;
4449 }
4450 else
4451 {
4452 /* Hold onto message for now. */
4453 mouse_button_timer =
4454 SetTimer (hwnd, MOUSE_BUTTON_ID,
4455 XINT (Vw32_mouse_button_tolerance), NULL);
4456 saved_mouse_button_msg.msg.hwnd = hwnd;
4457 saved_mouse_button_msg.msg.message = msg;
4458 saved_mouse_button_msg.msg.wParam = wParam;
4459 saved_mouse_button_msg.msg.lParam = lParam;
4460 saved_mouse_button_msg.msg.time = GetMessageTime ();
4461 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4462 }
4463 }
4464 return 0;
4465
4466 case WM_LBUTTONUP:
4467 case WM_RBUTTONUP:
4468 if (XINT (Vw32_num_mouse_buttons) > 2)
4469 goto handle_plain_button;
4470
4471 {
4472 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4473 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4474
4475 if ((button_state & this) == 0)
4476 return 0;
4477
4478 button_state &= ~this;
4479
4480 if (button_state & MMOUSE)
4481 {
4482 /* Only generate event when second button is released. */
4483 if ((button_state & other) == 0)
4484 {
4485 msg = WM_MBUTTONUP;
4486 button_state &= ~MMOUSE;
4487
4488 if (button_state) abort ();
4489 }
4490 else
4491 return 0;
4492 }
4493 else
4494 {
4495 /* Flush out saved message if necessary. */
4496 if (saved_mouse_button_msg.msg.hwnd)
4497 {
4498 post_msg (&saved_mouse_button_msg);
4499 }
4500 }
4501 wmsg.dwModifiers = w32_get_modifiers ();
4502 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4503
4504 /* Always clear message buffer and cancel timer. */
4505 saved_mouse_button_msg.msg.hwnd = 0;
4506 KillTimer (hwnd, mouse_button_timer);
4507 mouse_button_timer = 0;
4508
4509 if (button_state == 0)
4510 ReleaseCapture ();
4511 }
4512 return 0;
4513
4514 case WM_MBUTTONDOWN:
4515 case WM_MBUTTONUP:
4516 handle_plain_button:
4517 {
4518 BOOL up;
4519 int button;
4520
4521 if (parse_button (msg, &button, &up))
4522 {
4523 if (up) ReleaseCapture ();
4524 else SetCapture (hwnd);
4525 button = (button == 0) ? LMOUSE :
4526 ((button == 1) ? MMOUSE : RMOUSE);
4527 if (up)
4528 button_state &= ~button;
4529 else
4530 button_state |= button;
4531 }
4532 }
4533
4534 wmsg.dwModifiers = w32_get_modifiers ();
4535 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4536 return 0;
4537
4538 case WM_VSCROLL:
4539 case WM_MOUSEMOVE:
4540 if (XINT (Vw32_mouse_move_interval) <= 0
4541 || (msg == WM_MOUSEMOVE && button_state == 0))
4542 {
4543 wmsg.dwModifiers = w32_get_modifiers ();
4544 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4545 return 0;
4546 }
4547
4548 /* Hang onto mouse move and scroll messages for a bit, to avoid
4549 sending such events to Emacs faster than it can process them.
4550 If we get more events before the timer from the first message
4551 expires, we just replace the first message. */
4552
4553 if (saved_mouse_move_msg.msg.hwnd == 0)
4554 mouse_move_timer =
4555 SetTimer (hwnd, MOUSE_MOVE_ID,
4556 XINT (Vw32_mouse_move_interval), NULL);
4557
4558 /* Hold onto message for now. */
4559 saved_mouse_move_msg.msg.hwnd = hwnd;
4560 saved_mouse_move_msg.msg.message = msg;
4561 saved_mouse_move_msg.msg.wParam = wParam;
4562 saved_mouse_move_msg.msg.lParam = lParam;
4563 saved_mouse_move_msg.msg.time = GetMessageTime ();
4564 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4565
4566 return 0;
4567
4568 case WM_MOUSEWHEEL:
4569 wmsg.dwModifiers = w32_get_modifiers ();
4570 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4571 return 0;
4572
4573 case WM_DROPFILES:
4574 wmsg.dwModifiers = w32_get_modifiers ();
4575 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4576 return 0;
4577
4578 case WM_TIMER:
4579 /* Flush out saved messages if necessary. */
4580 if (wParam == mouse_button_timer)
4581 {
4582 if (saved_mouse_button_msg.msg.hwnd)
4583 {
4584 post_msg (&saved_mouse_button_msg);
4585 saved_mouse_button_msg.msg.hwnd = 0;
4586 }
4587 KillTimer (hwnd, mouse_button_timer);
4588 mouse_button_timer = 0;
4589 }
4590 else if (wParam == mouse_move_timer)
4591 {
4592 if (saved_mouse_move_msg.msg.hwnd)
4593 {
4594 post_msg (&saved_mouse_move_msg);
4595 saved_mouse_move_msg.msg.hwnd = 0;
4596 }
4597 KillTimer (hwnd, mouse_move_timer);
4598 mouse_move_timer = 0;
4599 }
4600 return 0;
4601
4602 case WM_NCACTIVATE:
4603 /* Windows doesn't send us focus messages when putting up and
4604 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4605 The only indication we get that something happened is receiving
4606 this message afterwards. So this is a good time to reset our
4607 keyboard modifiers' state. */
4608 reset_modifiers ();
4609 goto dflt;
4610
4611 case WM_INITMENU:
4612 button_state = 0;
4613 ReleaseCapture ();
4614 /* We must ensure menu bar is fully constructed and up to date
4615 before allowing user interaction with it. To achieve this
4616 we send this message to the lisp thread and wait for a
4617 reply (whose value is not actually needed) to indicate that
4618 the menu bar is now ready for use, so we can now return.
4619
4620 To remain responsive in the meantime, we enter a nested message
4621 loop that can process all other messages.
4622
4623 However, we skip all this if the message results from calling
4624 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4625 thread a message because it is blocked on us at this point. We
4626 set menubar_active before calling TrackPopupMenu to indicate
4627 this (there is no possibility of confusion with real menubar
4628 being active). */
4629
4630 f = x_window_to_frame (dpyinfo, hwnd);
4631 if (f
4632 && (f->output_data.w32->menubar_active
4633 /* We can receive this message even in the absence of a
4634 menubar (ie. when the system menu is activated) - in this
4635 case we do NOT want to forward the message, otherwise it
4636 will cause the menubar to suddenly appear when the user
4637 had requested it to be turned off! */
4638 || f->output_data.w32->menubar_widget == NULL))
4639 return 0;
4640
4641 {
4642 deferred_msg msg_buf;
4643
4644 /* Detect if message has already been deferred; in this case
4645 we cannot return any sensible value to ignore this. */
4646 if (find_deferred_msg (hwnd, msg) != NULL)
4647 abort ();
4648
4649 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4650 }
4651
4652 case WM_EXITMENULOOP:
4653 f = x_window_to_frame (dpyinfo, hwnd);
4654
4655 /* Indicate that menubar can be modified again. */
4656 if (f)
4657 f->output_data.w32->menubar_active = 0;
4658 goto dflt;
4659
4660 case WM_MENUSELECT:
4661 wmsg.dwModifiers = w32_get_modifiers ();
4662 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4663 return 0;
4664
4665 case WM_MEASUREITEM:
4666 f = x_window_to_frame (dpyinfo, hwnd);
4667 if (f)
4668 {
4669 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4670
4671 if (pMis->CtlType == ODT_MENU)
4672 {
4673 /* Work out dimensions for popup menu titles. */
4674 char * title = (char *) pMis->itemData;
4675 HDC hdc = GetDC (hwnd);
4676 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4677 LOGFONT menu_logfont;
4678 HFONT old_font;
4679 SIZE size;
4680
4681 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4682 menu_logfont.lfWeight = FW_BOLD;
4683 menu_font = CreateFontIndirect (&menu_logfont);
4684 old_font = SelectObject (hdc, menu_font);
4685
4686 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4687 if (title)
4688 {
4689 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4690 pMis->itemWidth = size.cx;
4691 if (pMis->itemHeight < size.cy)
4692 pMis->itemHeight = size.cy;
4693 }
4694 else
4695 pMis->itemWidth = 0;
4696
4697 SelectObject (hdc, old_font);
4698 DeleteObject (menu_font);
4699 ReleaseDC (hwnd, hdc);
4700 return TRUE;
4701 }
4702 }
4703 return 0;
4704
4705 case WM_DRAWITEM:
4706 f = x_window_to_frame (dpyinfo, hwnd);
4707 if (f)
4708 {
4709 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4710
4711 if (pDis->CtlType == ODT_MENU)
4712 {
4713 /* Draw popup menu title. */
4714 char * title = (char *) pDis->itemData;
4715 if (title)
4716 {
4717 HDC hdc = pDis->hDC;
4718 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4719 LOGFONT menu_logfont;
4720 HFONT old_font;
4721
4722 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4723 menu_logfont.lfWeight = FW_BOLD;
4724 menu_font = CreateFontIndirect (&menu_logfont);
4725 old_font = SelectObject (hdc, menu_font);
4726
4727 /* Always draw title as if not selected. */
4728 ExtTextOut (hdc,
4729 pDis->rcItem.left
4730 + GetSystemMetrics (SM_CXMENUCHECK),
4731 pDis->rcItem.top,
4732 ETO_OPAQUE, &pDis->rcItem,
4733 title, strlen (title), NULL);
4734
4735 SelectObject (hdc, old_font);
4736 DeleteObject (menu_font);
4737 }
4738 return TRUE;
4739 }
4740 }
4741 return 0;
4742
4743 #if 0
4744 /* Still not right - can't distinguish between clicks in the
4745 client area of the frame from clicks forwarded from the scroll
4746 bars - may have to hook WM_NCHITTEST to remember the mouse
4747 position and then check if it is in the client area ourselves. */
4748 case WM_MOUSEACTIVATE:
4749 /* Discard the mouse click that activates a frame, allowing the
4750 user to click anywhere without changing point (or worse!).
4751 Don't eat mouse clicks on scrollbars though!! */
4752 if (LOWORD (lParam) == HTCLIENT )
4753 return MA_ACTIVATEANDEAT;
4754 goto dflt;
4755 #endif
4756
4757 case WM_ACTIVATEAPP:
4758 case WM_ACTIVATE:
4759 case WM_WINDOWPOSCHANGED:
4760 case WM_SHOWWINDOW:
4761 /* Inform lisp thread that a frame might have just been obscured
4762 or exposed, so should recheck visibility of all frames. */
4763 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4764 goto dflt;
4765
4766 case WM_SETFOCUS:
4767 dpyinfo->faked_key = 0;
4768 reset_modifiers ();
4769 register_hot_keys (hwnd);
4770 goto command;
4771 case WM_KILLFOCUS:
4772 unregister_hot_keys (hwnd);
4773 button_state = 0;
4774 ReleaseCapture ();
4775 case WM_MOVE:
4776 case WM_SIZE:
4777 case WM_COMMAND:
4778 command:
4779 wmsg.dwModifiers = w32_get_modifiers ();
4780 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4781 goto dflt;
4782
4783 case WM_CLOSE:
4784 wmsg.dwModifiers = w32_get_modifiers ();
4785 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4786 return 0;
4787
4788 case WM_WINDOWPOSCHANGING:
4789 {
4790 WINDOWPLACEMENT wp;
4791 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4792
4793 wp.length = sizeof (WINDOWPLACEMENT);
4794 GetWindowPlacement (hwnd, &wp);
4795
4796 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4797 {
4798 RECT rect;
4799 int wdiff;
4800 int hdiff;
4801 DWORD font_width;
4802 DWORD line_height;
4803 DWORD internal_border;
4804 DWORD scrollbar_extra;
4805 RECT wr;
4806
4807 wp.length = sizeof(wp);
4808 GetWindowRect (hwnd, &wr);
4809
4810 enter_crit ();
4811
4812 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4813 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4814 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4815 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
4816
4817 leave_crit ();
4818
4819 memset (&rect, 0, sizeof (rect));
4820 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4821 GetMenu (hwnd) != NULL);
4822
4823 /* Force width and height of client area to be exact
4824 multiples of the character cell dimensions. */
4825 wdiff = (lppos->cx - (rect.right - rect.left)
4826 - 2 * internal_border - scrollbar_extra)
4827 % font_width;
4828 hdiff = (lppos->cy - (rect.bottom - rect.top)
4829 - 2 * internal_border)
4830 % line_height;
4831
4832 if (wdiff || hdiff)
4833 {
4834 /* For right/bottom sizing we can just fix the sizes.
4835 However for top/left sizing we will need to fix the X
4836 and Y positions as well. */
4837
4838 lppos->cx -= wdiff;
4839 lppos->cy -= hdiff;
4840
4841 if (wp.showCmd != SW_SHOWMAXIMIZED
4842 && (lppos->flags & SWP_NOMOVE) == 0)
4843 {
4844 if (lppos->x != wr.left || lppos->y != wr.top)
4845 {
4846 lppos->x += wdiff;
4847 lppos->y += hdiff;
4848 }
4849 else
4850 {
4851 lppos->flags |= SWP_NOMOVE;
4852 }
4853 }
4854
4855 return 0;
4856 }
4857 }
4858 }
4859
4860 goto dflt;
4861
4862 case WM_GETMINMAXINFO:
4863 /* Hack to correct bug that allows Emacs frames to be resized
4864 below the Minimum Tracking Size. */
4865 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
4866 return 0;
4867
4868 case WM_EMACS_CREATESCROLLBAR:
4869 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
4870 (struct scroll_bar *) lParam);
4871
4872 case WM_EMACS_SHOWWINDOW:
4873 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4874
4875 case WM_EMACS_SETFOREGROUND:
4876 {
4877 HWND foreground_window;
4878 DWORD foreground_thread, retval;
4879
4880 /* On NT 5.0, and apparently Windows 98, it is necessary to
4881 attach to the thread that currently has focus in order to
4882 pull the focus away from it. */
4883 foreground_window = GetForegroundWindow ();
4884 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4885 if (!foreground_window
4886 || foreground_thread == GetCurrentThreadId ()
4887 || !AttachThreadInput (GetCurrentThreadId (),
4888 foreground_thread, TRUE))
4889 foreground_thread = 0;
4890
4891 retval = SetForegroundWindow ((HWND) wParam);
4892
4893 /* Detach from the previous foreground thread. */
4894 if (foreground_thread)
4895 AttachThreadInput (GetCurrentThreadId (),
4896 foreground_thread, FALSE);
4897
4898 return retval;
4899 }
4900
4901 case WM_EMACS_SETWINDOWPOS:
4902 {
4903 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4904 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4905 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4906 }
4907
4908 case WM_EMACS_DESTROYWINDOW:
4909 DragAcceptFiles ((HWND) wParam, FALSE);
4910 return DestroyWindow ((HWND) wParam);
4911
4912 case WM_EMACS_TRACKPOPUPMENU:
4913 {
4914 UINT flags;
4915 POINT *pos;
4916 int retval;
4917 pos = (POINT *)lParam;
4918 flags = TPM_CENTERALIGN;
4919 if (button_state & LMOUSE)
4920 flags |= TPM_LEFTBUTTON;
4921 else if (button_state & RMOUSE)
4922 flags |= TPM_RIGHTBUTTON;
4923
4924 /* Remember we did a SetCapture on the initial mouse down event,
4925 so for safety, we make sure the capture is cancelled now. */
4926 ReleaseCapture ();
4927 button_state = 0;
4928
4929 /* Use menubar_active to indicate that WM_INITMENU is from
4930 TrackPopupMenu below, and should be ignored. */
4931 f = x_window_to_frame (dpyinfo, hwnd);
4932 if (f)
4933 f->output_data.w32->menubar_active = 1;
4934
4935 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4936 0, hwnd, NULL))
4937 {
4938 MSG amsg;
4939 /* Eat any mouse messages during popupmenu */
4940 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4941 PM_REMOVE));
4942 /* Get the menu selection, if any */
4943 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4944 {
4945 retval = LOWORD (amsg.wParam);
4946 }
4947 else
4948 {
4949 retval = 0;
4950 }
4951 }
4952 else
4953 {
4954 retval = -1;
4955 }
4956
4957 return retval;
4958 }
4959
4960 default:
4961 /* Check for messages registered at runtime. */
4962 if (msg == msh_mousewheel)
4963 {
4964 wmsg.dwModifiers = w32_get_modifiers ();
4965 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4966 return 0;
4967 }
4968
4969 dflt:
4970 return DefWindowProc (hwnd, msg, wParam, lParam);
4971 }
4972
4973
4974 /* The most common default return code for handled messages is 0. */
4975 return 0;
4976 }
4977
4978 void
4979 my_create_window (f)
4980 struct frame * f;
4981 {
4982 MSG msg;
4983
4984 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4985 abort ();
4986 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4987 }
4988
4989 /* Create and set up the w32 window for frame F. */
4990
4991 static void
4992 w32_window (f, window_prompting, minibuffer_only)
4993 struct frame *f;
4994 long window_prompting;
4995 int minibuffer_only;
4996 {
4997 BLOCK_INPUT;
4998
4999 /* Use the resource name as the top-level window name
5000 for looking up resources. Make a non-Lisp copy
5001 for the window manager, so GC relocation won't bother it.
5002
5003 Elsewhere we specify the window name for the window manager. */
5004
5005 {
5006 char *str = (char *) XSTRING (Vx_resource_name)->data;
5007 f->namebuf = (char *) xmalloc (strlen (str) + 1);
5008 strcpy (f->namebuf, str);
5009 }
5010
5011 my_create_window (f);
5012
5013 validate_x_resource_name ();
5014
5015 /* x_set_name normally ignores requests to set the name if the
5016 requested name is the same as the current name. This is the one
5017 place where that assumption isn't correct; f->name is set, but
5018 the server hasn't been told. */
5019 {
5020 Lisp_Object name;
5021 int explicit = f->explicit_name;
5022
5023 f->explicit_name = 0;
5024 name = f->name;
5025 f->name = Qnil;
5026 x_set_name (f, name, explicit);
5027 }
5028
5029 UNBLOCK_INPUT;
5030
5031 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5032 initialize_frame_menubar (f);
5033
5034 if (FRAME_W32_WINDOW (f) == 0)
5035 error ("Unable to create window");
5036 }
5037
5038 /* Handle the icon stuff for this window. Perhaps later we might
5039 want an x_set_icon_position which can be called interactively as
5040 well. */
5041
5042 static void
5043 x_icon (f, parms)
5044 struct frame *f;
5045 Lisp_Object parms;
5046 {
5047 Lisp_Object icon_x, icon_y;
5048
5049 /* Set the position of the icon. Note that Windows 95 groups all
5050 icons in the tray. */
5051 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5052 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5053 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5054 {
5055 CHECK_NUMBER (icon_x, 0);
5056 CHECK_NUMBER (icon_y, 0);
5057 }
5058 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5059 error ("Both left and top icon corners of icon must be specified");
5060
5061 BLOCK_INPUT;
5062
5063 if (! EQ (icon_x, Qunbound))
5064 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5065
5066 #if 0 /* TODO */
5067 /* Start up iconic or window? */
5068 x_wm_set_window_state
5069 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5070 ? IconicState
5071 : NormalState));
5072
5073 x_text_icon (f, (char *) XSTRING ((!NILP (f->icon_name)
5074 ? f->icon_name
5075 : f->name))->data);
5076 #endif
5077
5078 UNBLOCK_INPUT;
5079 }
5080
5081
5082 static void
5083 x_make_gc (f)
5084 struct frame *f;
5085 {
5086 XGCValues gc_values;
5087
5088 BLOCK_INPUT;
5089
5090 /* Create the GC's of this frame.
5091 Note that many default values are used. */
5092
5093 /* Normal video */
5094 gc_values.font = f->output_data.w32->font;
5095
5096 /* Cursor has cursor-color background, background-color foreground. */
5097 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5098 gc_values.background = f->output_data.w32->cursor_pixel;
5099 f->output_data.w32->cursor_gc
5100 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5101 (GCFont | GCForeground | GCBackground),
5102 &gc_values);
5103
5104 /* Reliefs. */
5105 f->output_data.w32->white_relief.gc = 0;
5106 f->output_data.w32->black_relief.gc = 0;
5107
5108 UNBLOCK_INPUT;
5109 }
5110
5111
5112 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5113 1, 1, 0,
5114 "Make a new window, which is called a \"frame\" in Emacs terms.\n\
5115 Returns an Emacs frame object.\n\
5116 ALIST is an alist of frame parameters.\n\
5117 If the parameters specify that the frame should not have a minibuffer,\n\
5118 and do not specify a specific minibuffer window to use,\n\
5119 then `default-minibuffer-frame' must be a frame whose minibuffer can\n\
5120 be shared by the new frame.\n\
5121 \n\
5122 This function is an internal primitive--use `make-frame' instead.")
5123 (parms)
5124 Lisp_Object parms;
5125 {
5126 struct frame *f;
5127 Lisp_Object frame, tem;
5128 Lisp_Object name;
5129 int minibuffer_only = 0;
5130 long window_prompting = 0;
5131 int width, height;
5132 int count = specpdl_ptr - specpdl;
5133 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5134 Lisp_Object display;
5135 struct w32_display_info *dpyinfo = NULL;
5136 Lisp_Object parent;
5137 struct kboard *kb;
5138
5139 check_w32 ();
5140
5141 /* Use this general default value to start with
5142 until we know if this frame has a specified name. */
5143 Vx_resource_name = Vinvocation_name;
5144
5145 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5146 if (EQ (display, Qunbound))
5147 display = Qnil;
5148 dpyinfo = check_x_display_info (display);
5149 #ifdef MULTI_KBOARD
5150 kb = dpyinfo->kboard;
5151 #else
5152 kb = &the_only_kboard;
5153 #endif
5154
5155 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5156 if (!STRINGP (name)
5157 && ! EQ (name, Qunbound)
5158 && ! NILP (name))
5159 error ("Invalid frame name--not a string or nil");
5160
5161 if (STRINGP (name))
5162 Vx_resource_name = name;
5163
5164 /* See if parent window is specified. */
5165 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5166 if (EQ (parent, Qunbound))
5167 parent = Qnil;
5168 if (! NILP (parent))
5169 CHECK_NUMBER (parent, 0);
5170
5171 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5172 /* No need to protect DISPLAY because that's not used after passing
5173 it to make_frame_without_minibuffer. */
5174 frame = Qnil;
5175 GCPRO4 (parms, parent, name, frame);
5176 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5177 RES_TYPE_SYMBOL);
5178 if (EQ (tem, Qnone) || NILP (tem))
5179 f = make_frame_without_minibuffer (Qnil, kb, display);
5180 else if (EQ (tem, Qonly))
5181 {
5182 f = make_minibuffer_frame ();
5183 minibuffer_only = 1;
5184 }
5185 else if (WINDOWP (tem))
5186 f = make_frame_without_minibuffer (tem, kb, display);
5187 else
5188 f = make_frame (1);
5189
5190 XSETFRAME (frame, f);
5191
5192 /* Note that Windows does support scroll bars. */
5193 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5194 /* By default, make scrollbars the system standard width. */
5195 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5196
5197 f->output_method = output_w32;
5198 f->output_data.w32 =
5199 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5200 bzero (f->output_data.w32, sizeof (struct w32_output));
5201
5202 FRAME_FONTSET (f) = -1;
5203
5204 f->icon_name
5205 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5206 if (! STRINGP (f->icon_name))
5207 f->icon_name = Qnil;
5208
5209 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5210 #ifdef MULTI_KBOARD
5211 FRAME_KBOARD (f) = kb;
5212 #endif
5213
5214 /* Specify the parent under which to make this window. */
5215
5216 if (!NILP (parent))
5217 {
5218 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5219 f->output_data.w32->explicit_parent = 1;
5220 }
5221 else
5222 {
5223 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5224 f->output_data.w32->explicit_parent = 0;
5225 }
5226
5227 /* Set the name; the functions to which we pass f expect the name to
5228 be set. */
5229 if (EQ (name, Qunbound) || NILP (name))
5230 {
5231 f->name = build_string (dpyinfo->w32_id_name);
5232 f->explicit_name = 0;
5233 }
5234 else
5235 {
5236 f->name = name;
5237 f->explicit_name = 1;
5238 /* use the frame's title when getting resources for this frame. */
5239 specbind (Qx_resource_name, name);
5240 }
5241
5242 /* Extract the window parameters from the supplied values
5243 that are needed to determine window geometry. */
5244 {
5245 Lisp_Object font;
5246
5247 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5248
5249 BLOCK_INPUT;
5250 /* First, try whatever font the caller has specified. */
5251 if (STRINGP (font))
5252 {
5253 tem = Fquery_fontset (font, Qnil);
5254 if (STRINGP (tem))
5255 font = x_new_fontset (f, XSTRING (tem)->data);
5256 else
5257 font = x_new_font (f, XSTRING (font)->data);
5258 }
5259 /* Try out a font which we hope has bold and italic variations. */
5260 if (!STRINGP (font))
5261 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5262 if (! STRINGP (font))
5263 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5264 /* If those didn't work, look for something which will at least work. */
5265 if (! STRINGP (font))
5266 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5267 UNBLOCK_INPUT;
5268 if (! STRINGP (font))
5269 font = build_string ("Fixedsys");
5270
5271 x_default_parameter (f, parms, Qfont, font,
5272 "font", "Font", RES_TYPE_STRING);
5273 }
5274
5275 x_default_parameter (f, parms, Qborder_width, make_number (2),
5276 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5277 /* This defaults to 2 in order to match xterm. We recognize either
5278 internalBorderWidth or internalBorder (which is what xterm calls
5279 it). */
5280 if (NILP (Fassq (Qinternal_border_width, parms)))
5281 {
5282 Lisp_Object value;
5283
5284 value = w32_get_arg (parms, Qinternal_border_width,
5285 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5286 if (! EQ (value, Qunbound))
5287 parms = Fcons (Fcons (Qinternal_border_width, value),
5288 parms);
5289 }
5290 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5291 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5292 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5293 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5294 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5295
5296 /* Also do the stuff which must be set before the window exists. */
5297 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5298 "foreground", "Foreground", RES_TYPE_STRING);
5299 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5300 "background", "Background", RES_TYPE_STRING);
5301 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5302 "pointerColor", "Foreground", RES_TYPE_STRING);
5303 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5304 "cursorColor", "Foreground", RES_TYPE_STRING);
5305 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5306 "borderColor", "BorderColor", RES_TYPE_STRING);
5307 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5308 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5309 x_default_parameter (f, parms, Qline_spacing, Qnil,
5310 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5311
5312
5313 /* Init faces before x_default_parameter is called for scroll-bar
5314 parameters because that function calls x_set_scroll_bar_width,
5315 which calls change_frame_size, which calls Fset_window_buffer,
5316 which runs hooks, which call Fvertical_motion. At the end, we
5317 end up in init_iterator with a null face cache, which should not
5318 happen. */
5319 init_frame_faces (f);
5320
5321 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5322 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5323 x_default_parameter (f, parms, Qtool_bar_lines, make_number (0),
5324 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5325 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5326 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5327 x_default_parameter (f, parms, Qtitle, Qnil,
5328 "title", "Title", RES_TYPE_STRING);
5329
5330 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5331 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5332 window_prompting = x_figure_window_size (f, parms);
5333
5334 if (window_prompting & XNegative)
5335 {
5336 if (window_prompting & YNegative)
5337 f->output_data.w32->win_gravity = SouthEastGravity;
5338 else
5339 f->output_data.w32->win_gravity = NorthEastGravity;
5340 }
5341 else
5342 {
5343 if (window_prompting & YNegative)
5344 f->output_data.w32->win_gravity = SouthWestGravity;
5345 else
5346 f->output_data.w32->win_gravity = NorthWestGravity;
5347 }
5348
5349 f->output_data.w32->size_hint_flags = window_prompting;
5350
5351 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5352 f->no_split = minibuffer_only || EQ (tem, Qt);
5353
5354 /* Create the window. Add the tool-bar height to the initial frame
5355 height so that the user gets a text display area of the size he
5356 specified with -g or via the registry. Later changes of the
5357 tool-bar height don't change the frame size. This is done so that
5358 users can create tall Emacs frames without having to guess how
5359 tall the tool-bar will get. */
5360 f->height += FRAME_TOOL_BAR_LINES (f);
5361 w32_window (f, window_prompting, minibuffer_only);
5362 x_icon (f, parms);
5363
5364 x_make_gc (f);
5365
5366 /* Now consider the frame official. */
5367 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5368 Vframe_list = Fcons (frame, Vframe_list);
5369
5370 /* We need to do this after creating the window, so that the
5371 icon-creation functions can say whose icon they're describing. */
5372 x_default_parameter (f, parms, Qicon_type, Qnil,
5373 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5374
5375 x_default_parameter (f, parms, Qauto_raise, Qnil,
5376 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5377 x_default_parameter (f, parms, Qauto_lower, Qnil,
5378 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5379 x_default_parameter (f, parms, Qcursor_type, Qbox,
5380 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5381 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5382 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5383
5384 /* Dimensions, especially f->height, must be done via change_frame_size.
5385 Change will not be effected unless different from the current
5386 f->height. */
5387 width = f->width;
5388 height = f->height;
5389 f->height = 0;
5390 SET_FRAME_WIDTH (f, 0);
5391 change_frame_size (f, height, width, 1, 0, 0);
5392
5393 /* Tell the server what size and position, etc, we want, and how
5394 badly we want them. This should be done after we have the menu
5395 bar so that its size can be taken into account. */
5396 BLOCK_INPUT;
5397 x_wm_set_size_hint (f, window_prompting, 0);
5398 UNBLOCK_INPUT;
5399
5400 /* Set up faces after all frame parameters are known. This call
5401 also merges in face attributes specified for new frames. If we
5402 don't do this, the `menu' face for instance won't have the right
5403 colors, and the menu bar won't appear in the specified colors for
5404 new frames. */
5405 call1 (Qface_set_after_frame_default, frame);
5406
5407 /* Make the window appear on the frame and enable display, unless
5408 the caller says not to. However, with explicit parent, Emacs
5409 cannot control visibility, so don't try. */
5410 if (! f->output_data.w32->explicit_parent)
5411 {
5412 Lisp_Object visibility;
5413
5414 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5415 if (EQ (visibility, Qunbound))
5416 visibility = Qt;
5417
5418 if (EQ (visibility, Qicon))
5419 x_iconify_frame (f);
5420 else if (! NILP (visibility))
5421 x_make_frame_visible (f);
5422 else
5423 /* Must have been Qnil. */
5424 ;
5425 }
5426 UNGCPRO;
5427 return unbind_to (count, frame);
5428 }
5429
5430 /* FRAME is used only to get a handle on the X display. We don't pass the
5431 display info directly because we're called from frame.c, which doesn't
5432 know about that structure. */
5433 Lisp_Object
5434 x_get_focus_frame (frame)
5435 struct frame *frame;
5436 {
5437 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5438 Lisp_Object xfocus;
5439 if (! dpyinfo->w32_focus_frame)
5440 return Qnil;
5441
5442 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5443 return xfocus;
5444 }
5445
5446 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5447 "Give FRAME input focus, raising to foreground if necessary.")
5448 (frame)
5449 Lisp_Object frame;
5450 {
5451 x_focus_on_frame (check_x_frame (frame));
5452 return Qnil;
5453 }
5454
5455 \f
5456 /* Return the charset portion of a font name. */
5457 char * xlfd_charset_of_font (char * fontname)
5458 {
5459 char *charset, *encoding;
5460
5461 encoding = strrchr(fontname, '-');
5462 if (!encoding)
5463 return NULL;
5464
5465 *encoding = 0;
5466 charset = strrchr(fontname, '-');
5467 *encoding = '-';
5468
5469 if (!charset || strcmp(charset, "-*-*") == 0)
5470 return NULL;
5471
5472 return charset + 1;
5473 }
5474
5475 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5476 int size, char* filename);
5477 BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len, char * charset);
5478
5479 struct font_info *
5480 w32_load_system_font (f,fontname,size)
5481 struct frame *f;
5482 char * fontname;
5483 int size;
5484 {
5485 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5486 Lisp_Object font_names;
5487
5488 /* Get a list of all the fonts that match this name. Once we
5489 have a list of matching fonts, we compare them against the fonts
5490 we already have loaded by comparing names. */
5491 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5492
5493 if (!NILP (font_names))
5494 {
5495 Lisp_Object tail;
5496 int i;
5497
5498 /* First check if any are already loaded, as that is cheaper
5499 than loading another one. */
5500 for (i = 0; i < dpyinfo->n_fonts; i++)
5501 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5502 if (dpyinfo->font_table[i].name
5503 && (!strcmp (dpyinfo->font_table[i].name,
5504 XSTRING (XCAR (tail))->data)
5505 || !strcmp (dpyinfo->font_table[i].full_name,
5506 XSTRING (XCAR (tail))->data)))
5507 return (dpyinfo->font_table + i);
5508
5509 fontname = (char *) XSTRING (XCAR (font_names))->data;
5510 }
5511 else if (w32_strict_fontnames)
5512 {
5513 /* If EnumFontFamiliesEx was available, we got a full list of
5514 fonts back so stop now to avoid the possibility of loading a
5515 random font. If we had to fall back to EnumFontFamilies, the
5516 list is incomplete, so continue whether the font we want was
5517 listed or not. */
5518 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5519 FARPROC enum_font_families_ex
5520 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5521 if (enum_font_families_ex)
5522 return NULL;
5523 }
5524
5525 /* Load the font and add it to the table. */
5526 {
5527 char *full_name, *encoding, *charset;
5528 XFontStruct *font;
5529 struct font_info *fontp;
5530 LOGFONT lf;
5531 BOOL ok;
5532 int i;
5533
5534 if (!fontname || !x_to_w32_font (fontname, &lf))
5535 return (NULL);
5536
5537 if (!*lf.lfFaceName)
5538 /* If no name was specified for the font, we get a random font
5539 from CreateFontIndirect - this is not particularly
5540 desirable, especially since CreateFontIndirect does not
5541 fill out the missing name in lf, so we never know what we
5542 ended up with. */
5543 return NULL;
5544
5545 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5546 bzero (font, sizeof (*font));
5547
5548 /* Set bdf to NULL to indicate that this is a Windows font. */
5549 font->bdf = NULL;
5550
5551 BLOCK_INPUT;
5552
5553 font->hfont = CreateFontIndirect (&lf);
5554
5555 if (font->hfont == NULL)
5556 {
5557 ok = FALSE;
5558 }
5559 else
5560 {
5561 HDC hdc;
5562 HANDLE oldobj;
5563 int codepage = w32_codepage_for_font (fontname);
5564
5565 hdc = GetDC (dpyinfo->root_window);
5566 oldobj = SelectObject (hdc, font->hfont);
5567
5568 ok = GetTextMetrics (hdc, &font->tm);
5569 if (codepage == CP_UNICODE)
5570 font->double_byte_p = 1;
5571 else
5572 font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS;
5573
5574 SelectObject (hdc, oldobj);
5575 ReleaseDC (dpyinfo->root_window, hdc);
5576 /* Fill out details in lf according to the font that was
5577 actually loaded. */
5578 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5579 lf.lfWidth = font->tm.tmAveCharWidth;
5580 lf.lfWeight = font->tm.tmWeight;
5581 lf.lfItalic = font->tm.tmItalic;
5582 lf.lfCharSet = font->tm.tmCharSet;
5583 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5584 ? VARIABLE_PITCH : FIXED_PITCH);
5585 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5586 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5587
5588 w32_cache_char_metrics (font);
5589 }
5590
5591 UNBLOCK_INPUT;
5592
5593 if (!ok)
5594 {
5595 w32_unload_font (dpyinfo, font);
5596 return (NULL);
5597 }
5598
5599 /* Find a free slot in the font table. */
5600 for (i = 0; i < dpyinfo->n_fonts; ++i)
5601 if (dpyinfo->font_table[i].name == NULL)
5602 break;
5603
5604 /* If no free slot found, maybe enlarge the font table. */
5605 if (i == dpyinfo->n_fonts
5606 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5607 {
5608 int sz;
5609 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5610 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5611 dpyinfo->font_table
5612 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5613 }
5614
5615 fontp = dpyinfo->font_table + i;
5616 if (i == dpyinfo->n_fonts)
5617 ++dpyinfo->n_fonts;
5618
5619 /* Now fill in the slots of *FONTP. */
5620 BLOCK_INPUT;
5621 fontp->font = font;
5622 fontp->font_idx = i;
5623 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5624 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5625
5626 charset = xlfd_charset_of_font (fontname);
5627
5628 /* Work out the font's full name. */
5629 full_name = (char *)xmalloc (100);
5630 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
5631 fontp->full_name = full_name;
5632 else
5633 {
5634 /* If all else fails - just use the name we used to load it. */
5635 xfree (full_name);
5636 fontp->full_name = fontp->name;
5637 }
5638
5639 fontp->size = FONT_WIDTH (font);
5640 fontp->height = FONT_HEIGHT (font);
5641
5642 /* The slot `encoding' specifies how to map a character
5643 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
5644 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
5645 (0:0x20..0x7F, 1:0xA0..0xFF,
5646 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
5647 2:0xA020..0xFF7F). For the moment, we don't know which charset
5648 uses this font. So, we set information in fontp->encoding[1]
5649 which is never used by any charset. If mapping can't be
5650 decided, set FONT_ENCODING_NOT_DECIDED. */
5651
5652 /* SJIS fonts need to be set to type 4, all others seem to work as
5653 type FONT_ENCODING_NOT_DECIDED. */
5654 encoding = strrchr (fontp->name, '-');
5655 if (encoding && stricmp (encoding+1, "sjis") == 0)
5656 fontp->encoding[1] = 4;
5657 else
5658 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
5659
5660 /* The following three values are set to 0 under W32, which is
5661 what they get set to if XGetFontProperty fails under X. */
5662 fontp->baseline_offset = 0;
5663 fontp->relative_compose = 0;
5664 fontp->default_ascent = 0;
5665
5666 /* Set global flag fonts_changed_p to non-zero if the font loaded
5667 has a character with a smaller width than any other character
5668 before, or if the font loaded has a smalle>r height than any
5669 other font loaded before. If this happens, it will make a
5670 glyph matrix reallocation necessary. */
5671 fonts_changed_p = x_compute_min_glyph_bounds (f);
5672 UNBLOCK_INPUT;
5673 return fontp;
5674 }
5675 }
5676
5677 /* Load font named FONTNAME of size SIZE for frame F, and return a
5678 pointer to the structure font_info while allocating it dynamically.
5679 If loading fails, return NULL. */
5680 struct font_info *
5681 w32_load_font (f,fontname,size)
5682 struct frame *f;
5683 char * fontname;
5684 int size;
5685 {
5686 Lisp_Object bdf_fonts;
5687 struct font_info *retval = NULL;
5688
5689 bdf_fonts = w32_list_bdf_fonts (build_string (fontname));
5690
5691 while (!retval && CONSP (bdf_fonts))
5692 {
5693 char *bdf_name, *bdf_file;
5694 Lisp_Object bdf_pair;
5695
5696 bdf_name = XSTRING (XCAR (bdf_fonts))->data;
5697 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
5698 bdf_file = XSTRING (XCDR (bdf_pair))->data;
5699
5700 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
5701
5702 bdf_fonts = XCDR (bdf_fonts);
5703 }
5704
5705 if (retval)
5706 return retval;
5707
5708 return w32_load_system_font(f, fontname, size);
5709 }
5710
5711
5712 void
5713 w32_unload_font (dpyinfo, font)
5714 struct w32_display_info *dpyinfo;
5715 XFontStruct * font;
5716 {
5717 if (font)
5718 {
5719 if (font->per_char) xfree (font->per_char);
5720 if (font->bdf) w32_free_bdf_font (font->bdf);
5721
5722 if (font->hfont) DeleteObject(font->hfont);
5723 xfree (font);
5724 }
5725 }
5726
5727 /* The font conversion stuff between x and w32 */
5728
5729 /* X font string is as follows (from faces.el)
5730 * (let ((- "[-?]")
5731 * (foundry "[^-]+")
5732 * (family "[^-]+")
5733 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
5734 * (weight\? "\\([^-]*\\)") ; 1
5735 * (slant "\\([ior]\\)") ; 2
5736 * (slant\? "\\([^-]?\\)") ; 2
5737 * (swidth "\\([^-]*\\)") ; 3
5738 * (adstyle "[^-]*") ; 4
5739 * (pixelsize "[0-9]+")
5740 * (pointsize "[0-9][0-9]+")
5741 * (resx "[0-9][0-9]+")
5742 * (resy "[0-9][0-9]+")
5743 * (spacing "[cmp?*]")
5744 * (avgwidth "[0-9]+")
5745 * (registry "[^-]+")
5746 * (encoding "[^-]+")
5747 * )
5748 */
5749
5750 LONG
5751 x_to_w32_weight (lpw)
5752 char * lpw;
5753 {
5754 if (!lpw) return (FW_DONTCARE);
5755
5756 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
5757 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
5758 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
5759 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
5760 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5761 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
5762 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
5763 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
5764 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
5765 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
5766 else
5767 return FW_DONTCARE;
5768 }
5769
5770
5771 char *
5772 w32_to_x_weight (fnweight)
5773 int fnweight;
5774 {
5775 if (fnweight >= FW_HEAVY) return "heavy";
5776 if (fnweight >= FW_EXTRABOLD) return "extrabold";
5777 if (fnweight >= FW_BOLD) return "bold";
5778 if (fnweight >= FW_SEMIBOLD) return "demibold";
5779 if (fnweight >= FW_MEDIUM) return "medium";
5780 if (fnweight >= FW_NORMAL) return "normal";
5781 if (fnweight >= FW_LIGHT) return "light";
5782 if (fnweight >= FW_EXTRALIGHT) return "extralight";
5783 if (fnweight >= FW_THIN) return "thin";
5784 else
5785 return "*";
5786 }
5787
5788 LONG
5789 x_to_w32_charset (lpcs)
5790 char * lpcs;
5791 {
5792 Lisp_Object this_entry, w32_charset;
5793
5794 /* Look through w32-charset-info-alist for the character set.
5795 Format of each entry is
5796 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5797 */
5798 this_entry = Fassoc (build_string(lpcs), Vw32_charset_info_alist);
5799
5800 if (NILP(this_entry))
5801 {
5802 /* At startup, we want iso8859-1 fonts to come up properly. */
5803 if (stricmp(lpcs, "iso8859-1") == 0)
5804 return ANSI_CHARSET;
5805 else
5806 return DEFAULT_CHARSET;
5807 }
5808
5809 w32_charset = Fcar (Fcdr (this_entry));
5810
5811 // Translate Lisp symbol to number.
5812 if (w32_charset == Qw32_charset_ansi)
5813 return ANSI_CHARSET;
5814 if (w32_charset == Qw32_charset_symbol)
5815 return SYMBOL_CHARSET;
5816 if (w32_charset == Qw32_charset_shiftjis)
5817 return SHIFTJIS_CHARSET;
5818 if (w32_charset == Qw32_charset_hangeul)
5819 return HANGEUL_CHARSET;
5820 if (w32_charset == Qw32_charset_chinesebig5)
5821 return CHINESEBIG5_CHARSET;
5822 if (w32_charset == Qw32_charset_gb2312)
5823 return GB2312_CHARSET;
5824 if (w32_charset == Qw32_charset_oem)
5825 return OEM_CHARSET;
5826 #ifdef JOHAB_CHARSET
5827 if (w32_charset == Qw32_charset_johab)
5828 return JOHAB_CHARSET;
5829 if (w32_charset == Qw32_charset_easteurope)
5830 return EASTEUROPE_CHARSET;
5831 if (w32_charset == Qw32_charset_turkish)
5832 return TURKISH_CHARSET;
5833 if (w32_charset == Qw32_charset_baltic)
5834 return BALTIC_CHARSET;
5835 if (w32_charset == Qw32_charset_russian)
5836 return RUSSIAN_CHARSET;
5837 if (w32_charset == Qw32_charset_arabic)
5838 return ARABIC_CHARSET;
5839 if (w32_charset == Qw32_charset_greek)
5840 return GREEK_CHARSET;
5841 if (w32_charset == Qw32_charset_hebrew)
5842 return HEBREW_CHARSET;
5843 if (w32_charset == Qw32_charset_vietnamese)
5844 return VIETNAMESE_CHARSET;
5845 if (w32_charset == Qw32_charset_thai)
5846 return THAI_CHARSET;
5847 if (w32_charset == Qw32_charset_mac)
5848 return MAC_CHARSET;
5849 #endif /* JOHAB_CHARSET */
5850 #ifdef UNICODE_CHARSET
5851 if (w32_charset == Qw32_charset_unicode)
5852 return UNICODE_CHARSET;
5853 #endif
5854
5855 return DEFAULT_CHARSET;
5856 }
5857
5858
5859 char *
5860 w32_to_x_charset (fncharset)
5861 int fncharset;
5862 {
5863 static char buf[16];
5864 Lisp_Object charset_type;
5865
5866 switch (fncharset)
5867 {
5868 case ANSI_CHARSET:
5869 /* Handle startup case of w32-charset-info-alist not
5870 being set up yet. */
5871 if (NILP(Vw32_charset_info_alist))
5872 return "iso8859-1";
5873 charset_type = Qw32_charset_ansi;
5874 break;
5875 case DEFAULT_CHARSET:
5876 charset_type = Qw32_charset_default;
5877 break;
5878 case SYMBOL_CHARSET:
5879 charset_type = Qw32_charset_symbol;
5880 break;
5881 case SHIFTJIS_CHARSET:
5882 charset_type = Qw32_charset_shiftjis;
5883 break;
5884 case HANGEUL_CHARSET:
5885 charset_type = Qw32_charset_hangeul;
5886 break;
5887 case GB2312_CHARSET:
5888 charset_type = Qw32_charset_gb2312;
5889 break;
5890 case CHINESEBIG5_CHARSET:
5891 charset_type = Qw32_charset_chinesebig5;
5892 break;
5893 case OEM_CHARSET:
5894 charset_type = Qw32_charset_oem;
5895 break;
5896
5897 /* More recent versions of Windows (95 and NT4.0) define more
5898 character sets. */
5899 #ifdef EASTEUROPE_CHARSET
5900 case EASTEUROPE_CHARSET:
5901 charset_type = Qw32_charset_easteurope;
5902 break;
5903 case TURKISH_CHARSET:
5904 charset_type = Qw32_charset_turkish;
5905 break;
5906 case BALTIC_CHARSET:
5907 charset_type = Qw32_charset_baltic;
5908 break;
5909 case RUSSIAN_CHARSET:
5910 charset_type = Qw32_charset_russian;
5911 break;
5912 case ARABIC_CHARSET:
5913 charset_type = Qw32_charset_arabic;
5914 break;
5915 case GREEK_CHARSET:
5916 charset_type = Qw32_charset_greek;
5917 break;
5918 case HEBREW_CHARSET:
5919 charset_type = Qw32_charset_hebrew;
5920 break;
5921 case VIETNAMESE_CHARSET:
5922 charset_type = Qw32_charset_vietnamese;
5923 break;
5924 case THAI_CHARSET:
5925 charset_type = Qw32_charset_thai;
5926 break;
5927 case MAC_CHARSET:
5928 charset_type = Qw32_charset_mac;
5929 break;
5930 case JOHAB_CHARSET:
5931 charset_type = Qw32_charset_johab;
5932 break;
5933 #endif
5934
5935 #ifdef UNICODE_CHARSET
5936 case UNICODE_CHARSET:
5937 charset_type = Qw32_charset_unicode;
5938 break;
5939 #endif
5940 default:
5941 /* Encode numerical value of unknown charset. */
5942 sprintf (buf, "*-#%u", fncharset);
5943 return buf;
5944 }
5945
5946 {
5947 Lisp_Object rest;
5948 char * best_match = NULL;
5949
5950 /* Look through w32-charset-info-alist for the character set.
5951 Prefer ISO codepages, and prefer lower numbers in the ISO
5952 range. Only return charsets for codepages which are installed.
5953
5954 Format of each entry is
5955 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5956 */
5957 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5958 {
5959 char * x_charset;
5960 Lisp_Object w32_charset;
5961 Lisp_Object codepage;
5962
5963 Lisp_Object this_entry = XCAR (rest);
5964
5965 /* Skip invalid entries in alist. */
5966 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5967 || !CONSP (XCDR (this_entry))
5968 || !SYMBOLP (XCAR (XCDR (this_entry))))
5969 continue;
5970
5971 x_charset = XSTRING (XCAR (this_entry))->data;
5972 w32_charset = XCAR (XCDR (this_entry));
5973 codepage = XCDR (XCDR (this_entry));
5974
5975 /* Look for Same charset and a valid codepage (or non-int
5976 which means ignore). */
5977 if (w32_charset == charset_type
5978 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5979 || IsValidCodePage (XINT (codepage))))
5980 {
5981 /* If we don't have a match already, then this is the
5982 best. */
5983 if (!best_match)
5984 best_match = x_charset;
5985 /* If this is an ISO codepage, and the best so far isn't,
5986 then this is better. */
5987 else if (stricmp (best_match, "iso") != 0
5988 && stricmp (x_charset, "iso") == 0)
5989 best_match = x_charset;
5990 /* If both are ISO8859 codepages, choose the one with the
5991 lowest number in the encoding field. */
5992 else if (stricmp (best_match, "iso8859-") == 0
5993 && stricmp (x_charset, "iso8859-") == 0)
5994 {
5995 int best_enc = atoi (best_match + 8);
5996 int this_enc = atoi (x_charset + 8);
5997 if (this_enc > 0 && this_enc < best_enc)
5998 best_match = x_charset;
5999 }
6000 }
6001 }
6002
6003 /* If no match, encode the numeric value. */
6004 if (!best_match)
6005 {
6006 sprintf (buf, "*-#%u", fncharset);
6007 return buf;
6008 }
6009
6010 strncpy(buf, best_match, 15);
6011 buf[15] = '\0';
6012 return buf;
6013 }
6014 }
6015
6016
6017 /* Get the Windows codepage corresponding to the specified font. The
6018 charset info in the font name is used to look up
6019 w32-charset-to-codepage-alist. */
6020 int
6021 w32_codepage_for_font (char *fontname)
6022 {
6023 Lisp_Object codepage, entry;
6024 char *charset_str, *charset, *end;
6025
6026 if (NILP (Vw32_charset_info_alist))
6027 return CP_DEFAULT;
6028
6029 /* Extract charset part of font string. */
6030 charset = xlfd_charset_of_font (fontname);
6031
6032 if (!charset)
6033 return CP_INVALID;
6034
6035 charset_str = (char *) alloca (strlen (charset));
6036 strcpy (charset_str, charset);
6037
6038 /* Remove leading "*-". */
6039 if (strncmp ("*-", charset_str, 2) == 0)
6040 charset = charset_str + 2;
6041 else
6042 charset = charset_str;
6043
6044 /* Stop match at wildcard (including preceding '-'). */
6045 if (end = strchr (charset, '*'))
6046 {
6047 if (end > charset && *(end-1) == '-')
6048 end--;
6049 *end = '\0';
6050 }
6051
6052 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6053 if (NILP (entry))
6054 return CP_INVALID;
6055
6056 codepage = Fcdr (Fcdr (entry));
6057
6058 if (NILP (codepage))
6059 return CP_8BIT;
6060 else if (XFASTINT (codepage) == XFASTINT (Qt))
6061 return CP_UNICODE;
6062 else if (INTEGERP (codepage))
6063 return XINT (codepage);
6064 else
6065 return CP_INVALID;
6066 }
6067
6068
6069 BOOL
6070 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6071 LOGFONT * lplogfont;
6072 char * lpxstr;
6073 int len;
6074 char * specific_charset;
6075 {
6076 char* fonttype;
6077 char *fontname;
6078 char height_pixels[8];
6079 char height_dpi[8];
6080 char width_pixels[8];
6081 char *fontname_dash;
6082 int display_resy = one_w32_display_info.resy;
6083 int display_resx = one_w32_display_info.resx;
6084 int bufsz;
6085 struct coding_system coding;
6086
6087 if (!lpxstr) abort ();
6088
6089 if (!lplogfont)
6090 return FALSE;
6091
6092 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6093 fonttype = "raster";
6094 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6095 fonttype = "outline";
6096 else
6097 fonttype = "unknown";
6098
6099 setup_coding_system (Fcheck_coding_system (Vw32_system_coding_system),
6100 &coding);
6101 coding.src_multibyte = 0;
6102 coding.dst_multibyte = 1;
6103 coding.mode |= CODING_MODE_LAST_BLOCK;
6104 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6105
6106 fontname = alloca(sizeof(*fontname) * bufsz);
6107 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6108 strlen(lplogfont->lfFaceName), bufsz - 1);
6109 *(fontname + coding.produced) = '\0';
6110
6111 /* Replace dashes with underscores so the dashes are not
6112 misinterpreted. */
6113 fontname_dash = fontname;
6114 while (fontname_dash = strchr (fontname_dash, '-'))
6115 *fontname_dash = '_';
6116
6117 if (lplogfont->lfHeight)
6118 {
6119 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6120 sprintf (height_dpi, "%u",
6121 abs (lplogfont->lfHeight) * 720 / display_resy);
6122 }
6123 else
6124 {
6125 strcpy (height_pixels, "*");
6126 strcpy (height_dpi, "*");
6127 }
6128 if (lplogfont->lfWidth)
6129 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6130 else
6131 strcpy (width_pixels, "*");
6132
6133 _snprintf (lpxstr, len - 1,
6134 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6135 fonttype, /* foundry */
6136 fontname, /* family */
6137 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6138 lplogfont->lfItalic?'i':'r', /* slant */
6139 /* setwidth name */
6140 /* add style name */
6141 height_pixels, /* pixel size */
6142 height_dpi, /* point size */
6143 display_resx, /* resx */
6144 display_resy, /* resy */
6145 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6146 ? 'p' : 'c', /* spacing */
6147 width_pixels, /* avg width */
6148 specific_charset ? specific_charset
6149 : w32_to_x_charset (lplogfont->lfCharSet)
6150 /* charset registry and encoding */
6151 );
6152
6153 lpxstr[len - 1] = 0; /* just to be sure */
6154 return (TRUE);
6155 }
6156
6157 BOOL
6158 x_to_w32_font (lpxstr, lplogfont)
6159 char * lpxstr;
6160 LOGFONT * lplogfont;
6161 {
6162 struct coding_system coding;
6163
6164 if (!lplogfont) return (FALSE);
6165
6166 memset (lplogfont, 0, sizeof (*lplogfont));
6167
6168 /* Set default value for each field. */
6169 #if 1
6170 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6171 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6172 lplogfont->lfQuality = DEFAULT_QUALITY;
6173 #else
6174 /* go for maximum quality */
6175 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6176 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6177 lplogfont->lfQuality = PROOF_QUALITY;
6178 #endif
6179
6180 lplogfont->lfCharSet = DEFAULT_CHARSET;
6181 lplogfont->lfWeight = FW_DONTCARE;
6182 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6183
6184 if (!lpxstr)
6185 return FALSE;
6186
6187 /* Provide a simple escape mechanism for specifying Windows font names
6188 * directly -- if font spec does not beginning with '-', assume this
6189 * format:
6190 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6191 */
6192
6193 if (*lpxstr == '-')
6194 {
6195 int fields, tem;
6196 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6197 width[10], resy[10], remainder[20];
6198 char * encoding;
6199 int dpi = one_w32_display_info.resy;
6200
6201 fields = sscanf (lpxstr,
6202 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%19s",
6203 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6204 if (fields == EOF) return (FALSE);
6205
6206 /* If wildcards cover more than one field, we don't know which
6207 field is which, so don't fill any in. */
6208
6209 if (fields < 9)
6210 fields = 0;
6211
6212 if (fields > 0 && name[0] != '*')
6213 {
6214 int bufsize;
6215 unsigned char *buf;
6216
6217 setup_coding_system
6218 (Fcheck_coding_system (Vw32_system_coding_system), &coding);
6219 coding.src_multibyte = 1;
6220 coding.dst_multibyte = 1;
6221 bufsize = encoding_buffer_size (&coding, strlen (name));
6222 buf = (unsigned char *) alloca (bufsize);
6223 coding.mode |= CODING_MODE_LAST_BLOCK;
6224 encode_coding (&coding, name, buf, strlen (name), bufsize);
6225 if (coding.produced >= LF_FACESIZE)
6226 coding.produced = LF_FACESIZE - 1;
6227 buf[coding.produced] = 0;
6228 strcpy (lplogfont->lfFaceName, buf);
6229 }
6230 else
6231 {
6232 lplogfont->lfFaceName[0] = '\0';
6233 }
6234
6235 fields--;
6236
6237 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6238
6239 fields--;
6240
6241 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6242
6243 fields--;
6244
6245 if (fields > 0 && pixels[0] != '*')
6246 lplogfont->lfHeight = atoi (pixels);
6247
6248 fields--;
6249 fields--;
6250 if (fields > 0 && resy[0] != '*')
6251 {
6252 tem = atoi (resy);
6253 if (tem > 0) dpi = tem;
6254 }
6255
6256 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6257 lplogfont->lfHeight = atoi (height) * dpi / 720;
6258
6259 if (fields > 0)
6260 lplogfont->lfPitchAndFamily =
6261 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6262
6263 fields--;
6264
6265 if (fields > 0 && width[0] != '*')
6266 lplogfont->lfWidth = atoi (width) / 10;
6267
6268 fields--;
6269
6270 /* Strip the trailing '-' if present. (it shouldn't be, as it
6271 fails the test against xlfd-tight-regexp in fontset.el). */
6272 {
6273 int len = strlen (remainder);
6274 if (len > 0 && remainder[len-1] == '-')
6275 remainder[len-1] = 0;
6276 }
6277 encoding = remainder;
6278 if (strncmp (encoding, "*-", 2) == 0)
6279 encoding += 2;
6280 lplogfont->lfCharSet = x_to_w32_charset (fields > 0 ? encoding : "");
6281 }
6282 else
6283 {
6284 int fields;
6285 char name[100], height[10], width[10], weight[20];
6286
6287 fields = sscanf (lpxstr,
6288 "%99[^:]:%9[^:]:%9[^:]:%19s",
6289 name, height, width, weight);
6290
6291 if (fields == EOF) return (FALSE);
6292
6293 if (fields > 0)
6294 {
6295 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6296 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6297 }
6298 else
6299 {
6300 lplogfont->lfFaceName[0] = 0;
6301 }
6302
6303 fields--;
6304
6305 if (fields > 0)
6306 lplogfont->lfHeight = atoi (height);
6307
6308 fields--;
6309
6310 if (fields > 0)
6311 lplogfont->lfWidth = atoi (width);
6312
6313 fields--;
6314
6315 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6316 }
6317
6318 /* This makes TrueType fonts work better. */
6319 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6320
6321 return (TRUE);
6322 }
6323
6324 /* Strip the pixel height and point height from the given xlfd, and
6325 return the pixel height. If no pixel height is specified, calculate
6326 one from the point height, or if that isn't defined either, return
6327 0 (which usually signifies a scalable font).
6328 */
6329 int xlfd_strip_height (char *fontname)
6330 {
6331 int pixel_height, point_height, dpi, field_number;
6332 char *read_from, *write_to;
6333
6334 xassert (fontname);
6335
6336 pixel_height = field_number = 0;
6337 write_to = NULL;
6338
6339 /* Look for height fields. */
6340 for (read_from = fontname; *read_from; read_from++)
6341 {
6342 if (*read_from == '-')
6343 {
6344 field_number++;
6345 if (field_number == 7) /* Pixel height. */
6346 {
6347 read_from++;
6348 write_to = read_from;
6349
6350 /* Find end of field. */
6351 for (;*read_from && *read_from != '-'; read_from++)
6352 ;
6353
6354 /* Split the fontname at end of field. */
6355 if (*read_from)
6356 {
6357 *read_from = '\0';
6358 read_from++;
6359 }
6360 pixel_height = atoi (write_to);
6361 /* Blank out field. */
6362 if (read_from > write_to)
6363 {
6364 *write_to = '-';
6365 write_to++;
6366 }
6367 /* If the pixel height field is at the end (partial xlfd),
6368 return now. */
6369 else
6370 return pixel_height;
6371
6372 /* If we got a pixel height, the point height can be
6373 ignored. Just blank it out and break now. */
6374 if (pixel_height)
6375 {
6376 /* Find end of point size field. */
6377 for (; *read_from && *read_from != '-'; read_from++)
6378 ;
6379
6380 if (*read_from)
6381 read_from++;
6382
6383 /* Blank out the point size field. */
6384 if (read_from > write_to)
6385 {
6386 *write_to = '-';
6387 write_to++;
6388 }
6389 else
6390 return pixel_height;
6391
6392 break;
6393 }
6394 /* If the point height is already blank, break now. */
6395 if (*read_from == '-')
6396 {
6397 read_from++;
6398 break;
6399 }
6400 }
6401 else if (field_number == 8)
6402 {
6403 /* If we didn't get a pixel height, try to get the point
6404 height and convert that. */
6405 int point_size;
6406 char *point_size_start = read_from++;
6407
6408 /* Find end of field. */
6409 for (; *read_from && *read_from != '-'; read_from++)
6410 ;
6411
6412 if (*read_from)
6413 {
6414 *read_from = '\0';
6415 read_from++;
6416 }
6417
6418 point_size = atoi (point_size_start);
6419
6420 /* Convert to pixel height. */
6421 pixel_height = point_size
6422 * one_w32_display_info.height_in / 720;
6423
6424 /* Blank out this field and break. */
6425 *write_to = '-';
6426 write_to++;
6427 break;
6428 }
6429 }
6430 }
6431
6432 /* Shift the rest of the font spec into place. */
6433 if (write_to && read_from > write_to)
6434 {
6435 for (; *read_from; read_from++, write_to++)
6436 *write_to = *read_from;
6437 *write_to = '\0';
6438 }
6439
6440 return pixel_height;
6441 }
6442
6443 /* Assume parameter 1 is fully qualified, no wildcards. */
6444 BOOL
6445 w32_font_match (fontname, pattern)
6446 char * fontname;
6447 char * pattern;
6448 {
6449 char *regex = alloca (strlen (pattern) * 2);
6450 char *font_name_copy = alloca (strlen (fontname) + 1);
6451 char *ptr;
6452
6453 /* Copy fontname so we can modify it during comparison. */
6454 strcpy (font_name_copy, fontname);
6455
6456 ptr = regex;
6457 *ptr++ = '^';
6458
6459 /* Turn pattern into a regexp and do a regexp match. */
6460 for (; *pattern; pattern++)
6461 {
6462 if (*pattern == '?')
6463 *ptr++ = '.';
6464 else if (*pattern == '*')
6465 {
6466 *ptr++ = '.';
6467 *ptr++ = '*';
6468 }
6469 else
6470 *ptr++ = *pattern;
6471 }
6472 *ptr = '$';
6473 *(ptr + 1) = '\0';
6474
6475 /* Strip out font heights and compare them seperately, since
6476 rounding error can cause mismatches. This also allows a
6477 comparison between a font that declares only a pixel height and a
6478 pattern that declares the point height.
6479 */
6480 {
6481 int font_height, pattern_height;
6482
6483 font_height = xlfd_strip_height (font_name_copy);
6484 pattern_height = xlfd_strip_height (regex);
6485
6486 /* Compare now, and don't bother doing expensive regexp matching
6487 if the heights differ. */
6488 if (font_height && pattern_height && (font_height != pattern_height))
6489 return FALSE;
6490 }
6491
6492 return (fast_c_string_match_ignore_case (build_string (regex),
6493 font_name_copy) >= 0);
6494 }
6495
6496 /* Callback functions, and a structure holding info they need, for
6497 listing system fonts on W32. We need one set of functions to do the
6498 job properly, but these don't work on NT 3.51 and earlier, so we
6499 have a second set which don't handle character sets properly to
6500 fall back on.
6501
6502 In both cases, there are two passes made. The first pass gets one
6503 font from each family, the second pass lists all the fonts from
6504 each family. */
6505
6506 typedef struct enumfont_t
6507 {
6508 HDC hdc;
6509 int numFonts;
6510 LOGFONT logfont;
6511 XFontStruct *size_ref;
6512 Lisp_Object *pattern;
6513 Lisp_Object *tail;
6514 } enumfont_t;
6515
6516 int CALLBACK
6517 enum_font_cb2 (lplf, lptm, FontType, lpef)
6518 ENUMLOGFONT * lplf;
6519 NEWTEXTMETRIC * lptm;
6520 int FontType;
6521 enumfont_t * lpef;
6522 {
6523 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
6524 return (1);
6525
6526 /* Check that the character set matches if it was specified */
6527 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
6528 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
6529 return (1);
6530
6531 {
6532 char buf[100];
6533 Lisp_Object width = Qnil;
6534 char *charset = NULL;
6535
6536 /* Truetype fonts do not report their true metrics until loaded */
6537 if (FontType != RASTER_FONTTYPE)
6538 {
6539 if (!NILP (*(lpef->pattern)))
6540 {
6541 /* Scalable fonts are as big as you want them to be. */
6542 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
6543 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
6544 width = make_number (lpef->logfont.lfWidth);
6545 }
6546 else
6547 {
6548 lplf->elfLogFont.lfHeight = 0;
6549 lplf->elfLogFont.lfWidth = 0;
6550 }
6551 }
6552
6553 /* Make sure the height used here is the same as everywhere
6554 else (ie character height, not cell height). */
6555 if (lplf->elfLogFont.lfHeight > 0)
6556 {
6557 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
6558 if (FontType == RASTER_FONTTYPE)
6559 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
6560 else
6561 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
6562 }
6563
6564 if (!NILP (*(lpef->pattern)))
6565 {
6566 charset = xlfd_charset_of_font (XSTRING(*(lpef->pattern))->data);
6567
6568 /* Ensure that charset is valid for this font. */
6569 if (charset
6570 && (x_to_w32_charset (charset) != lplf->elfLogFont.lfCharSet))
6571 charset = NULL;
6572 }
6573
6574 /* TODO: List all relevant charsets if charset not specified. */
6575 if (!w32_to_x_font (&(lplf->elfLogFont), buf, 100, charset))
6576 return (0);
6577
6578 if (NILP (*(lpef->pattern))
6579 || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
6580 {
6581 *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
6582 lpef->tail = &(XCDR (*lpef->tail));
6583 lpef->numFonts++;
6584 }
6585 }
6586
6587 return (1);
6588 }
6589
6590 int CALLBACK
6591 enum_font_cb1 (lplf, lptm, FontType, lpef)
6592 ENUMLOGFONT * lplf;
6593 NEWTEXTMETRIC * lptm;
6594 int FontType;
6595 enumfont_t * lpef;
6596 {
6597 return EnumFontFamilies (lpef->hdc,
6598 lplf->elfLogFont.lfFaceName,
6599 (FONTENUMPROC) enum_font_cb2,
6600 (LPARAM) lpef);
6601 }
6602
6603
6604 int CALLBACK
6605 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6606 ENUMLOGFONTEX * lplf;
6607 NEWTEXTMETRICEX * lptm;
6608 int font_type;
6609 enumfont_t * lpef;
6610 {
6611 /* We are not interested in the extra info we get back from the 'Ex
6612 version - only the fact that we get character set variations
6613 enumerated seperately. */
6614 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6615 font_type, lpef);
6616 }
6617
6618 int CALLBACK
6619 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6620 ENUMLOGFONTEX * lplf;
6621 NEWTEXTMETRICEX * lptm;
6622 int font_type;
6623 enumfont_t * lpef;
6624 {
6625 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6626 FARPROC enum_font_families_ex
6627 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6628 /* We don't really expect EnumFontFamiliesEx to disappear once we
6629 get here, so don't bother handling it gracefully. */
6630 if (enum_font_families_ex == NULL)
6631 error ("gdi32.dll has disappeared!");
6632 return enum_font_families_ex (lpef->hdc,
6633 &lplf->elfLogFont,
6634 (FONTENUMPROC) enum_fontex_cb2,
6635 (LPARAM) lpef, 0);
6636 }
6637
6638 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6639 and xterm.c in Emacs 20.3) */
6640
6641 Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6642 {
6643 char *fontname, *ptnstr;
6644 Lisp_Object list, tem, newlist = Qnil;
6645 int n_fonts = 0;
6646
6647 list = Vw32_bdf_filename_alist;
6648 ptnstr = XSTRING (pattern)->data;
6649
6650 for ( ; CONSP (list); list = XCDR (list))
6651 {
6652 tem = XCAR (list);
6653 if (CONSP (tem))
6654 fontname = XSTRING (XCAR (tem))->data;
6655 else if (STRINGP (tem))
6656 fontname = XSTRING (tem)->data;
6657 else
6658 continue;
6659
6660 if (w32_font_match (fontname, ptnstr))
6661 {
6662 newlist = Fcons (XCAR (tem), newlist);
6663 n_fonts++;
6664 if (n_fonts >= max_names)
6665 break;
6666 }
6667 }
6668
6669 return newlist;
6670 }
6671
6672 Lisp_Object w32_list_synthesized_fonts (FRAME_PTR f, Lisp_Object pattern,
6673 int size, int max_names);
6674
6675 /* Return a list of names of available fonts matching PATTERN on frame
6676 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6677 to be listed. Frame F NULL means we have not yet created any
6678 frame, which means we can't get proper size info, as we don't have
6679 a device context to use for GetTextMetrics.
6680 MAXNAMES sets a limit on how many fonts to match. */
6681
6682 Lisp_Object
6683 w32_list_fonts (FRAME_PTR f, Lisp_Object pattern, int size, int maxnames )
6684 {
6685 Lisp_Object patterns, key = Qnil, tem, tpat;
6686 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6687 struct w32_display_info *dpyinfo = &one_w32_display_info;
6688 int n_fonts = 0;
6689
6690 patterns = Fassoc (pattern, Valternate_fontname_alist);
6691 if (NILP (patterns))
6692 patterns = Fcons (pattern, Qnil);
6693
6694 for (; CONSP (patterns); patterns = XCDR (patterns))
6695 {
6696 enumfont_t ef;
6697 int codepage;
6698
6699 tpat = XCAR (patterns);
6700
6701 if (!STRINGP (tpat))
6702 continue;
6703
6704 /* Avoid expensive EnumFontFamilies functions if we are not
6705 going to be able to output one of these anyway. */
6706 codepage = w32_codepage_for_font (XSTRING (tpat)->data);
6707 if (codepage != CP_8BIT && codepage != CP_UNICODE
6708 && codepage != CP_DEFAULT && !IsValidCodePage(codepage))
6709 continue;
6710
6711 /* See if we cached the result for this particular query.
6712 The cache is an alist of the form:
6713 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6714 */
6715 if (tem = XCDR (dpyinfo->name_list_element),
6716 !NILP (list = Fassoc (tpat, tem)))
6717 {
6718 list = Fcdr_safe (list);
6719 /* We have a cached list. Don't have to get the list again. */
6720 goto label_cached;
6721 }
6722
6723 BLOCK_INPUT;
6724 /* At first, put PATTERN in the cache. */
6725 list = Qnil;
6726 ef.pattern = &tpat;
6727 ef.tail = &list;
6728 ef.numFonts = 0;
6729
6730 /* Use EnumFontFamiliesEx where it is available, as it knows
6731 about character sets. Fall back to EnumFontFamilies for
6732 older versions of NT that don't support the 'Ex function. */
6733 x_to_w32_font (XSTRING (tpat)->data, &ef.logfont);
6734 {
6735 LOGFONT font_match_pattern;
6736 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6737 FARPROC enum_font_families_ex
6738 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6739
6740 /* We do our own pattern matching so we can handle wildcards. */
6741 font_match_pattern.lfFaceName[0] = 0;
6742 font_match_pattern.lfPitchAndFamily = 0;
6743 /* We can use the charset, because if it is a wildcard it will
6744 be DEFAULT_CHARSET anyway. */
6745 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6746
6747 ef.hdc = GetDC (dpyinfo->root_window);
6748
6749 if (enum_font_families_ex)
6750 enum_font_families_ex (ef.hdc,
6751 &font_match_pattern,
6752 (FONTENUMPROC) enum_fontex_cb1,
6753 (LPARAM) &ef, 0);
6754 else
6755 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6756 (LPARAM)&ef);
6757
6758 ReleaseDC (dpyinfo->root_window, ef.hdc);
6759 }
6760
6761 UNBLOCK_INPUT;
6762
6763 /* Make a list of the fonts we got back.
6764 Store that in the font cache for the display. */
6765 XCDR (dpyinfo->name_list_element)
6766 = Fcons (Fcons (tpat, list),
6767 XCDR (dpyinfo->name_list_element));
6768
6769 label_cached:
6770 if (NILP (list)) continue; /* Try the remaining alternatives. */
6771
6772 newlist = second_best = Qnil;
6773
6774 /* Make a list of the fonts that have the right width. */
6775 for (; CONSP (list); list = XCDR (list))
6776 {
6777 int found_size;
6778 tem = XCAR (list);
6779
6780 if (!CONSP (tem))
6781 continue;
6782 if (NILP (XCAR (tem)))
6783 continue;
6784 if (!size)
6785 {
6786 newlist = Fcons (XCAR (tem), newlist);
6787 n_fonts++;
6788 if (n_fonts >= maxnames)
6789 break;
6790 else
6791 continue;
6792 }
6793 if (!INTEGERP (XCDR (tem)))
6794 {
6795 /* Since we don't yet know the size of the font, we must
6796 load it and try GetTextMetrics. */
6797 W32FontStruct thisinfo;
6798 LOGFONT lf;
6799 HDC hdc;
6800 HANDLE oldobj;
6801
6802 if (!x_to_w32_font (XSTRING (XCAR (tem))->data, &lf))
6803 continue;
6804
6805 BLOCK_INPUT;
6806 thisinfo.bdf = NULL;
6807 thisinfo.hfont = CreateFontIndirect (&lf);
6808 if (thisinfo.hfont == NULL)
6809 continue;
6810
6811 hdc = GetDC (dpyinfo->root_window);
6812 oldobj = SelectObject (hdc, thisinfo.hfont);
6813 if (GetTextMetrics (hdc, &thisinfo.tm))
6814 XCDR (tem) = make_number (FONT_WIDTH (&thisinfo));
6815 else
6816 XCDR (tem) = make_number (0);
6817 SelectObject (hdc, oldobj);
6818 ReleaseDC (dpyinfo->root_window, hdc);
6819 DeleteObject(thisinfo.hfont);
6820 UNBLOCK_INPUT;
6821 }
6822 found_size = XINT (XCDR (tem));
6823 if (found_size == size)
6824 {
6825 newlist = Fcons (XCAR (tem), newlist);
6826 n_fonts++;
6827 if (n_fonts >= maxnames)
6828 break;
6829 }
6830 /* keep track of the closest matching size in case
6831 no exact match is found. */
6832 else if (found_size > 0)
6833 {
6834 if (NILP (second_best))
6835 second_best = tem;
6836
6837 else if (found_size < size)
6838 {
6839 if (XINT (XCDR (second_best)) > size
6840 || XINT (XCDR (second_best)) < found_size)
6841 second_best = tem;
6842 }
6843 else
6844 {
6845 if (XINT (XCDR (second_best)) > size
6846 && XINT (XCDR (second_best)) >
6847 found_size)
6848 second_best = tem;
6849 }
6850 }
6851 }
6852
6853 if (!NILP (newlist))
6854 break;
6855 else if (!NILP (second_best))
6856 {
6857 newlist = Fcons (XCAR (second_best), Qnil);
6858 break;
6859 }
6860 }
6861
6862 /* Include any bdf fonts. */
6863 if (n_fonts < maxnames)
6864 {
6865 Lisp_Object combined[2];
6866 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6867 combined[1] = newlist;
6868 newlist = Fnconc(2, combined);
6869 }
6870
6871 /* If we can't find a font that matches, check if Windows would be
6872 able to synthesize it from a different style. */
6873 if (NILP (newlist) && !NILP (Vw32_enable_synthesized_fonts))
6874 newlist = w32_list_synthesized_fonts (f, pattern, size, maxnames);
6875
6876 return newlist;
6877 }
6878
6879 Lisp_Object
6880 w32_list_synthesized_fonts (f, pattern, size, max_names)
6881 FRAME_PTR f;
6882 Lisp_Object pattern;
6883 int size;
6884 int max_names;
6885 {
6886 int fields;
6887 char *full_pattn, *new_pattn, foundary[50], family[50], *pattn_part2;
6888 char style[20], slant;
6889 Lisp_Object matches, match, tem, synthed_matches = Qnil;
6890
6891 full_pattn = XSTRING (pattern)->data;
6892
6893 pattn_part2 = alloca (XSTRING (pattern)->size);
6894 /* Allow some space for wildcard expansion. */
6895 new_pattn = alloca (XSTRING (pattern)->size + 100);
6896
6897 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%19[^-]-%c-%s",
6898 foundary, family, style, &slant, pattn_part2);
6899 if (fields == EOF || fields < 5)
6900 return Qnil;
6901
6902 /* If the style and slant are wildcards already there is no point
6903 checking again (and we don't want to keep recursing). */
6904 if (*style == '*' && slant == '*')
6905 return Qnil;
6906
6907 sprintf (new_pattn, "-%s-%s-*-*-%s", foundary, family, pattn_part2);
6908
6909 matches = w32_list_fonts (f, build_string (new_pattn), size, max_names);
6910
6911 for ( ; CONSP (matches); matches = XCDR (matches))
6912 {
6913 tem = XCAR (matches);
6914 if (!STRINGP (tem))
6915 continue;
6916
6917 full_pattn = XSTRING (tem)->data;
6918 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%*[^-]-%*c-%s",
6919 foundary, family, pattn_part2);
6920 if (fields == EOF || fields < 3)
6921 continue;
6922
6923 sprintf (new_pattn, "-%s-%s-%s-%c-%s", foundary, family, style,
6924 slant, pattn_part2);
6925
6926 synthed_matches = Fcons (build_string (new_pattn),
6927 synthed_matches);
6928 }
6929
6930 return synthed_matches;
6931 }
6932
6933
6934 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6935 struct font_info *
6936 w32_get_font_info (f, font_idx)
6937 FRAME_PTR f;
6938 int font_idx;
6939 {
6940 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6941 }
6942
6943
6944 struct font_info*
6945 w32_query_font (struct frame *f, char *fontname)
6946 {
6947 int i;
6948 struct font_info *pfi;
6949
6950 pfi = FRAME_W32_FONT_TABLE (f);
6951
6952 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6953 {
6954 if (strcmp(pfi->name, fontname) == 0) return pfi;
6955 }
6956
6957 return NULL;
6958 }
6959
6960 /* Find a CCL program for a font specified by FONTP, and set the member
6961 `encoder' of the structure. */
6962
6963 void
6964 w32_find_ccl_program (fontp)
6965 struct font_info *fontp;
6966 {
6967 Lisp_Object list, elt;
6968
6969 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6970 {
6971 elt = XCAR (list);
6972 if (CONSP (elt)
6973 && STRINGP (XCAR (elt))
6974 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6975 >= 0))
6976 break;
6977 }
6978 if (! NILP (list))
6979 {
6980 struct ccl_program *ccl
6981 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6982
6983 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6984 xfree (ccl);
6985 else
6986 fontp->font_encoder = ccl;
6987 }
6988 }
6989
6990 \f
6991 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6992 1, 1, 0,
6993 "Return a list of BDF fonts in DIR, suitable for appending to\n\
6994 w32-bdf-filename-alist. Fonts which do not contain an xlfd description\n\
6995 will not be included in the list. DIR may be a list of directories.")
6996 (directory)
6997 Lisp_Object directory;
6998 {
6999 Lisp_Object list = Qnil;
7000 struct gcpro gcpro1, gcpro2;
7001
7002 if (!CONSP (directory))
7003 return w32_find_bdf_fonts_in_dir (directory);
7004
7005 for ( ; CONSP (directory); directory = XCDR (directory))
7006 {
7007 Lisp_Object pair[2];
7008 pair[0] = list;
7009 pair[1] = Qnil;
7010 GCPRO2 (directory, list);
7011 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7012 list = Fnconc( 2, pair );
7013 UNGCPRO;
7014 }
7015 return list;
7016 }
7017
7018 /* Find BDF files in a specified directory. (use GCPRO when calling,
7019 as this calls lisp to get a directory listing). */
7020 Lisp_Object w32_find_bdf_fonts_in_dir( Lisp_Object directory )
7021 {
7022 Lisp_Object filelist, list = Qnil;
7023 char fontname[100];
7024
7025 if (!STRINGP(directory))
7026 return Qnil;
7027
7028 filelist = Fdirectory_files (directory, Qt,
7029 build_string (".*\\.[bB][dD][fF]"), Qt);
7030
7031 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7032 {
7033 Lisp_Object filename = XCAR (filelist);
7034 if (w32_BDF_to_x_font (XSTRING (filename)->data, fontname, 100))
7035 store_in_alist (&list, build_string (fontname), filename);
7036 }
7037 return list;
7038 }
7039
7040 \f
7041 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7042 "Internal function called by `color-defined-p', which see.")
7043 (color, frame)
7044 Lisp_Object color, frame;
7045 {
7046 XColor foo;
7047 FRAME_PTR f = check_x_frame (frame);
7048
7049 CHECK_STRING (color, 1);
7050
7051 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7052 return Qt;
7053 else
7054 return Qnil;
7055 }
7056
7057 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7058 "Internal function called by `color-values', which see.")
7059 (color, frame)
7060 Lisp_Object color, frame;
7061 {
7062 XColor foo;
7063 FRAME_PTR f = check_x_frame (frame);
7064
7065 CHECK_STRING (color, 1);
7066
7067 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
7068 {
7069 Lisp_Object rgb[3];
7070
7071 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7072 | GetRValue (foo.pixel));
7073 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7074 | GetGValue (foo.pixel));
7075 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7076 | GetBValue (foo.pixel));
7077 return Flist (3, rgb);
7078 }
7079 else
7080 return Qnil;
7081 }
7082
7083 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7084 "Internal function called by `display-color-p', which see.")
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) <= 2)
7091 return Qnil;
7092
7093 return Qt;
7094 }
7095
7096 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
7097 0, 1, 0,
7098 "Return t if the X display supports shades of gray.\n\
7099 Note that color displays do support shades of gray.\n\
7100 The optional argument DISPLAY specifies which display to ask about.\n\
7101 DISPLAY should be either a frame or a display name (a string).\n\
7102 If omitted or nil, that stands for the selected frame's display.")
7103 (display)
7104 Lisp_Object display;
7105 {
7106 struct w32_display_info *dpyinfo = check_x_display_info (display);
7107
7108 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7109 return Qnil;
7110
7111 return Qt;
7112 }
7113
7114 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
7115 0, 1, 0,
7116 "Returns the width in pixels of the X display DISPLAY.\n\
7117 The optional argument DISPLAY specifies which display to ask about.\n\
7118 DISPLAY should be either a frame or a display name (a string).\n\
7119 If omitted or nil, that stands for the selected frame's display.")
7120 (display)
7121 Lisp_Object display;
7122 {
7123 struct w32_display_info *dpyinfo = check_x_display_info (display);
7124
7125 return make_number (dpyinfo->width);
7126 }
7127
7128 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7129 Sx_display_pixel_height, 0, 1, 0,
7130 "Returns the height in pixels of the X display DISPLAY.\n\
7131 The optional argument DISPLAY specifies which display to ask about.\n\
7132 DISPLAY should be either a frame or a display name (a string).\n\
7133 If omitted or nil, that stands for the selected frame's display.")
7134 (display)
7135 Lisp_Object display;
7136 {
7137 struct w32_display_info *dpyinfo = check_x_display_info (display);
7138
7139 return make_number (dpyinfo->height);
7140 }
7141
7142 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7143 0, 1, 0,
7144 "Returns the number of bitplanes of the display DISPLAY.\n\
7145 The optional argument DISPLAY specifies which display to ask about.\n\
7146 DISPLAY should be either a frame or a display name (a string).\n\
7147 If omitted or nil, that stands for the selected frame's display.")
7148 (display)
7149 Lisp_Object display;
7150 {
7151 struct w32_display_info *dpyinfo = check_x_display_info (display);
7152
7153 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7154 }
7155
7156 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7157 0, 1, 0,
7158 "Returns the number of color cells of the display DISPLAY.\n\
7159 The optional argument DISPLAY specifies which display to ask about.\n\
7160 DISPLAY should be either a frame or a display name (a string).\n\
7161 If omitted or nil, that stands for the selected frame's display.")
7162 (display)
7163 Lisp_Object display;
7164 {
7165 struct w32_display_info *dpyinfo = check_x_display_info (display);
7166 HDC hdc;
7167 int cap;
7168
7169 hdc = GetDC (dpyinfo->root_window);
7170 if (dpyinfo->has_palette)
7171 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7172 else
7173 cap = GetDeviceCaps (hdc,NUMCOLORS);
7174
7175 ReleaseDC (dpyinfo->root_window, hdc);
7176
7177 return make_number (cap);
7178 }
7179
7180 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7181 Sx_server_max_request_size,
7182 0, 1, 0,
7183 "Returns the maximum request size of the server of display DISPLAY.\n\
7184 The optional argument DISPLAY specifies which display to ask about.\n\
7185 DISPLAY should be either a frame or a display name (a string).\n\
7186 If omitted or nil, that stands for the selected frame's display.")
7187 (display)
7188 Lisp_Object display;
7189 {
7190 struct w32_display_info *dpyinfo = check_x_display_info (display);
7191
7192 return make_number (1);
7193 }
7194
7195 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7196 "Returns the vendor ID string of the W32 system (Microsoft).\n\
7197 The optional argument DISPLAY specifies which display to ask about.\n\
7198 DISPLAY should be either a frame or a display name (a string).\n\
7199 If omitted or nil, that stands for the selected frame's display.")
7200 (display)
7201 Lisp_Object display;
7202 {
7203 return build_string ("Microsoft Corp.");
7204 }
7205
7206 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7207 "Returns the version numbers of the server of display DISPLAY.\n\
7208 The value is a list of three integers: the major and minor\n\
7209 version numbers, and the vendor-specific release\n\
7210 number. See also the function `x-server-vendor'.\n\n\
7211 The optional argument DISPLAY specifies which display to ask about.\n\
7212 DISPLAY should be either a frame or a display name (a string).\n\
7213 If omitted or nil, that stands for the selected frame's display.")
7214 (display)
7215 Lisp_Object display;
7216 {
7217 return Fcons (make_number (w32_major_version),
7218 Fcons (make_number (w32_minor_version),
7219 Fcons (make_number (w32_build_number), Qnil)));
7220 }
7221
7222 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7223 "Returns the number of screens on the server of display DISPLAY.\n\
7224 The optional argument DISPLAY specifies which display to ask about.\n\
7225 DISPLAY should be either a frame or a display name (a string).\n\
7226 If omitted or nil, that stands for the selected frame's display.")
7227 (display)
7228 Lisp_Object display;
7229 {
7230 return make_number (1);
7231 }
7232
7233 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
7234 "Returns the height in millimeters of the X display DISPLAY.\n\
7235 The optional argument DISPLAY specifies which display to ask about.\n\
7236 DISPLAY should be either a frame or a display name (a string).\n\
7237 If omitted or nil, that stands for the selected frame's display.")
7238 (display)
7239 Lisp_Object display;
7240 {
7241 struct w32_display_info *dpyinfo = check_x_display_info (display);
7242 HDC hdc;
7243 int cap;
7244
7245 hdc = GetDC (dpyinfo->root_window);
7246
7247 cap = GetDeviceCaps (hdc, VERTSIZE);
7248
7249 ReleaseDC (dpyinfo->root_window, hdc);
7250
7251 return make_number (cap);
7252 }
7253
7254 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7255 "Returns the width in millimeters of the X display DISPLAY.\n\
7256 The optional argument DISPLAY specifies which display to ask about.\n\
7257 DISPLAY should be either a frame or a display name (a string).\n\
7258 If omitted or nil, that stands for the selected frame's display.")
7259 (display)
7260 Lisp_Object display;
7261 {
7262 struct w32_display_info *dpyinfo = check_x_display_info (display);
7263
7264 HDC hdc;
7265 int cap;
7266
7267 hdc = GetDC (dpyinfo->root_window);
7268
7269 cap = GetDeviceCaps (hdc, HORZSIZE);
7270
7271 ReleaseDC (dpyinfo->root_window, hdc);
7272
7273 return make_number (cap);
7274 }
7275
7276 DEFUN ("x-display-backing-store", Fx_display_backing_store,
7277 Sx_display_backing_store, 0, 1, 0,
7278 "Returns an indication of whether display DISPLAY does backing store.\n\
7279 The value may be `always', `when-mapped', or `not-useful'.\n\
7280 The optional argument DISPLAY specifies which display to ask about.\n\
7281 DISPLAY should be either a frame or a display name (a string).\n\
7282 If omitted or nil, that stands for the selected frame's display.")
7283 (display)
7284 Lisp_Object display;
7285 {
7286 return intern ("not-useful");
7287 }
7288
7289 DEFUN ("x-display-visual-class", Fx_display_visual_class,
7290 Sx_display_visual_class, 0, 1, 0,
7291 "Returns the visual class of the display DISPLAY.\n\
7292 The value is one of the symbols `static-gray', `gray-scale',\n\
7293 `static-color', `pseudo-color', `true-color', or `direct-color'.\n\n\
7294 The optional argument DISPLAY specifies which display to ask about.\n\
7295 DISPLAY should be either a frame or a display name (a string).\n\
7296 If omitted or nil, that stands for the selected frame's display.")
7297 (display)
7298 Lisp_Object display;
7299 {
7300 struct w32_display_info *dpyinfo = check_x_display_info (display);
7301
7302 #if 0
7303 switch (dpyinfo->visual->class)
7304 {
7305 case StaticGray: return (intern ("static-gray"));
7306 case GrayScale: return (intern ("gray-scale"));
7307 case StaticColor: return (intern ("static-color"));
7308 case PseudoColor: return (intern ("pseudo-color"));
7309 case TrueColor: return (intern ("true-color"));
7310 case DirectColor: return (intern ("direct-color"));
7311 default:
7312 error ("Display has an unknown visual class");
7313 }
7314 #endif
7315
7316 error ("Display has an unknown visual class");
7317 }
7318
7319 DEFUN ("x-display-save-under", Fx_display_save_under,
7320 Sx_display_save_under, 0, 1, 0,
7321 "Returns t if the display DISPLAY supports the save-under feature.\n\
7322 The optional argument DISPLAY specifies which display to ask about.\n\
7323 DISPLAY should be either a frame or a display name (a string).\n\
7324 If omitted or nil, that stands for the selected frame's display.")
7325 (display)
7326 Lisp_Object display;
7327 {
7328 return Qnil;
7329 }
7330 \f
7331 int
7332 x_pixel_width (f)
7333 register struct frame *f;
7334 {
7335 return PIXEL_WIDTH (f);
7336 }
7337
7338 int
7339 x_pixel_height (f)
7340 register struct frame *f;
7341 {
7342 return PIXEL_HEIGHT (f);
7343 }
7344
7345 int
7346 x_char_width (f)
7347 register struct frame *f;
7348 {
7349 return FONT_WIDTH (f->output_data.w32->font);
7350 }
7351
7352 int
7353 x_char_height (f)
7354 register struct frame *f;
7355 {
7356 return f->output_data.w32->line_height;
7357 }
7358
7359 int
7360 x_screen_planes (f)
7361 register struct frame *f;
7362 {
7363 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7364 }
7365 \f
7366 /* Return the display structure for the display named NAME.
7367 Open a new connection if necessary. */
7368
7369 struct w32_display_info *
7370 x_display_info_for_name (name)
7371 Lisp_Object name;
7372 {
7373 Lisp_Object names;
7374 struct w32_display_info *dpyinfo;
7375
7376 CHECK_STRING (name, 0);
7377
7378 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7379 dpyinfo;
7380 dpyinfo = dpyinfo->next, names = XCDR (names))
7381 {
7382 Lisp_Object tem;
7383 tem = Fstring_equal (XCAR (XCAR (names)), name);
7384 if (!NILP (tem))
7385 return dpyinfo;
7386 }
7387
7388 /* Use this general default value to start with. */
7389 Vx_resource_name = Vinvocation_name;
7390
7391 validate_x_resource_name ();
7392
7393 dpyinfo = w32_term_init (name, (unsigned char *)0,
7394 (char *) XSTRING (Vx_resource_name)->data);
7395
7396 if (dpyinfo == 0)
7397 error ("Cannot connect to server %s", XSTRING (name)->data);
7398
7399 w32_in_use = 1;
7400 XSETFASTINT (Vwindow_system_version, 3);
7401
7402 return dpyinfo;
7403 }
7404
7405 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7406 1, 3, 0, "Open a connection to a server.\n\
7407 DISPLAY is the name of the display to connect to.\n\
7408 Optional second arg XRM-STRING is a string of resources in xrdb format.\n\
7409 If the optional third arg MUST-SUCCEED is non-nil,\n\
7410 terminate Emacs if we can't open the connection.")
7411 (display, xrm_string, must_succeed)
7412 Lisp_Object display, xrm_string, must_succeed;
7413 {
7414 unsigned char *xrm_option;
7415 struct w32_display_info *dpyinfo;
7416
7417 CHECK_STRING (display, 0);
7418 if (! NILP (xrm_string))
7419 CHECK_STRING (xrm_string, 1);
7420
7421 if (! EQ (Vwindow_system, intern ("w32")))
7422 error ("Not using Microsoft Windows");
7423
7424 /* Allow color mapping to be defined externally; first look in user's
7425 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
7426 {
7427 Lisp_Object color_file;
7428 struct gcpro gcpro1;
7429
7430 color_file = build_string("~/rgb.txt");
7431
7432 GCPRO1 (color_file);
7433
7434 if (NILP (Ffile_readable_p (color_file)))
7435 color_file =
7436 Fexpand_file_name (build_string ("rgb.txt"),
7437 Fsymbol_value (intern ("data-directory")));
7438
7439 Vw32_color_map = Fw32_load_color_file (color_file);
7440
7441 UNGCPRO;
7442 }
7443 if (NILP (Vw32_color_map))
7444 Vw32_color_map = Fw32_default_color_map ();
7445
7446 if (! NILP (xrm_string))
7447 xrm_option = (unsigned char *) XSTRING (xrm_string)->data;
7448 else
7449 xrm_option = (unsigned char *) 0;
7450
7451 /* Use this general default value to start with. */
7452 /* First remove .exe suffix from invocation-name - it looks ugly. */
7453 {
7454 char basename[ MAX_PATH ], *str;
7455
7456 strcpy (basename, XSTRING (Vinvocation_name)->data);
7457 str = strrchr (basename, '.');
7458 if (str) *str = 0;
7459 Vinvocation_name = build_string (basename);
7460 }
7461 Vx_resource_name = Vinvocation_name;
7462
7463 validate_x_resource_name ();
7464
7465 /* This is what opens the connection and sets x_current_display.
7466 This also initializes many symbols, such as those used for input. */
7467 dpyinfo = w32_term_init (display, xrm_option,
7468 (char *) XSTRING (Vx_resource_name)->data);
7469
7470 if (dpyinfo == 0)
7471 {
7472 if (!NILP (must_succeed))
7473 fatal ("Cannot connect to server %s.\n",
7474 XSTRING (display)->data);
7475 else
7476 error ("Cannot connect to server %s", XSTRING (display)->data);
7477 }
7478
7479 w32_in_use = 1;
7480
7481 XSETFASTINT (Vwindow_system_version, 3);
7482 return Qnil;
7483 }
7484
7485 DEFUN ("x-close-connection", Fx_close_connection,
7486 Sx_close_connection, 1, 1, 0,
7487 "Close the connection to DISPLAY's server.\n\
7488 For DISPLAY, specify either a frame or a display name (a string).\n\
7489 If DISPLAY is nil, that stands for the selected frame's display.")
7490 (display)
7491 Lisp_Object display;
7492 {
7493 struct w32_display_info *dpyinfo = check_x_display_info (display);
7494 int i;
7495
7496 if (dpyinfo->reference_count > 0)
7497 error ("Display still has frames on it");
7498
7499 BLOCK_INPUT;
7500 /* Free the fonts in the font table. */
7501 for (i = 0; i < dpyinfo->n_fonts; i++)
7502 if (dpyinfo->font_table[i].name)
7503 {
7504 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
7505 xfree (dpyinfo->font_table[i].full_name);
7506 xfree (dpyinfo->font_table[i].name);
7507 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
7508 }
7509 x_destroy_all_bitmaps (dpyinfo);
7510
7511 x_delete_display (dpyinfo);
7512 UNBLOCK_INPUT;
7513
7514 return Qnil;
7515 }
7516
7517 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
7518 "Return the list of display names that Emacs has connections to.")
7519 ()
7520 {
7521 Lisp_Object tail, result;
7522
7523 result = Qnil;
7524 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
7525 result = Fcons (XCAR (XCAR (tail)), result);
7526
7527 return result;
7528 }
7529
7530 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7531 "If ON is non-nil, report errors as soon as the erring request is made.\n\
7532 If ON is nil, allow buffering of requests.\n\
7533 This is a noop on W32 systems.\n\
7534 The optional second argument DISPLAY specifies which display to act on.\n\
7535 DISPLAY should be either a frame or a display name (a string).\n\
7536 If DISPLAY is omitted or nil, that stands for the selected frame's display.")
7537 (on, display)
7538 Lisp_Object display, on;
7539 {
7540 return Qnil;
7541 }
7542
7543 \f
7544 \f
7545 /***********************************************************************
7546 Image types
7547 ***********************************************************************/
7548
7549 /* Value is the number of elements of vector VECTOR. */
7550
7551 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
7552
7553 /* List of supported image types. Use define_image_type to add new
7554 types. Use lookup_image_type to find a type for a given symbol. */
7555
7556 static struct image_type *image_types;
7557
7558 /* The symbol `image' which is the car of the lists used to represent
7559 images in Lisp. */
7560
7561 extern Lisp_Object Qimage;
7562
7563 /* The symbol `xbm' which is used as the type symbol for XBM images. */
7564
7565 Lisp_Object Qxbm;
7566
7567 /* Keywords. */
7568
7569 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
7570 extern Lisp_Object QCdata;
7571 Lisp_Object QCtype, QCascent, QCmargin, QCrelief;
7572 Lisp_Object QCalgorithm, QCcolor_symbols, QCheuristic_mask;
7573 Lisp_Object QCindex;
7574
7575 /* Other symbols. */
7576
7577 Lisp_Object Qlaplace;
7578
7579 /* Time in seconds after which images should be removed from the cache
7580 if not displayed. */
7581
7582 Lisp_Object Vimage_cache_eviction_delay;
7583
7584 /* Function prototypes. */
7585
7586 static void define_image_type P_ ((struct image_type *type));
7587 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
7588 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
7589 static void x_laplace P_ ((struct frame *, struct image *));
7590 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
7591 Lisp_Object));
7592
7593
7594 /* Define a new image type from TYPE. This adds a copy of TYPE to
7595 image_types and adds the symbol *TYPE->type to Vimage_types. */
7596
7597 static void
7598 define_image_type (type)
7599 struct image_type *type;
7600 {
7601 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
7602 The initialized data segment is read-only. */
7603 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
7604 bcopy (type, p, sizeof *p);
7605 p->next = image_types;
7606 image_types = p;
7607 Vimage_types = Fcons (*p->type, Vimage_types);
7608 }
7609
7610
7611 /* Look up image type SYMBOL, and return a pointer to its image_type
7612 structure. Value is null if SYMBOL is not a known image type. */
7613
7614 static INLINE struct image_type *
7615 lookup_image_type (symbol)
7616 Lisp_Object symbol;
7617 {
7618 struct image_type *type;
7619
7620 for (type = image_types; type; type = type->next)
7621 if (EQ (symbol, *type->type))
7622 break;
7623
7624 return type;
7625 }
7626
7627
7628 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
7629 valid image specification is a list whose car is the symbol
7630 `image', and whose rest is a property list. The property list must
7631 contain a value for key `:type'. That value must be the name of a
7632 supported image type. The rest of the property list depends on the
7633 image type. */
7634
7635 int
7636 valid_image_p (object)
7637 Lisp_Object object;
7638 {
7639 int valid_p = 0;
7640
7641 if (CONSP (object) && EQ (XCAR (object), Qimage))
7642 {
7643 Lisp_Object symbol = Fplist_get (XCDR (object), QCtype);
7644 struct image_type *type = lookup_image_type (symbol);
7645
7646 if (type)
7647 valid_p = type->valid_p (object);
7648 }
7649
7650 return valid_p;
7651 }
7652
7653
7654 /* Log error message with format string FORMAT and argument ARG.
7655 Signaling an error, e.g. when an image cannot be loaded, is not a
7656 good idea because this would interrupt redisplay, and the error
7657 message display would lead to another redisplay. This function
7658 therefore simply displays a message. */
7659
7660 static void
7661 image_error (format, arg1, arg2)
7662 char *format;
7663 Lisp_Object arg1, arg2;
7664 {
7665 add_to_log (format, arg1, arg2);
7666 }
7667
7668
7669 \f
7670 /***********************************************************************
7671 Image specifications
7672 ***********************************************************************/
7673
7674 enum image_value_type
7675 {
7676 IMAGE_DONT_CHECK_VALUE_TYPE,
7677 IMAGE_STRING_VALUE,
7678 IMAGE_SYMBOL_VALUE,
7679 IMAGE_POSITIVE_INTEGER_VALUE,
7680 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
7681 IMAGE_ASCENT_VALUE,
7682 IMAGE_INTEGER_VALUE,
7683 IMAGE_FUNCTION_VALUE,
7684 IMAGE_NUMBER_VALUE,
7685 IMAGE_BOOL_VALUE
7686 };
7687
7688 /* Structure used when parsing image specifications. */
7689
7690 struct image_keyword
7691 {
7692 /* Name of keyword. */
7693 char *name;
7694
7695 /* The type of value allowed. */
7696 enum image_value_type type;
7697
7698 /* Non-zero means key must be present. */
7699 int mandatory_p;
7700
7701 /* Used to recognize duplicate keywords in a property list. */
7702 int count;
7703
7704 /* The value that was found. */
7705 Lisp_Object value;
7706 };
7707
7708
7709 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7710 int, Lisp_Object));
7711 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7712
7713
7714 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
7715 has the format (image KEYWORD VALUE ...). One of the keyword/
7716 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7717 image_keywords structures of size NKEYWORDS describing other
7718 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7719
7720 static int
7721 parse_image_spec (spec, keywords, nkeywords, type)
7722 Lisp_Object spec;
7723 struct image_keyword *keywords;
7724 int nkeywords;
7725 Lisp_Object type;
7726 {
7727 int i;
7728 Lisp_Object plist;
7729
7730 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7731 return 0;
7732
7733 plist = XCDR (spec);
7734 while (CONSP (plist))
7735 {
7736 Lisp_Object key, value;
7737
7738 /* First element of a pair must be a symbol. */
7739 key = XCAR (plist);
7740 plist = XCDR (plist);
7741 if (!SYMBOLP (key))
7742 return 0;
7743
7744 /* There must follow a value. */
7745 if (!CONSP (plist))
7746 return 0;
7747 value = XCAR (plist);
7748 plist = XCDR (plist);
7749
7750 /* Find key in KEYWORDS. Error if not found. */
7751 for (i = 0; i < nkeywords; ++i)
7752 if (strcmp (keywords[i].name, XSYMBOL (key)->name->data) == 0)
7753 break;
7754
7755 if (i == nkeywords)
7756 continue;
7757
7758 /* Record that we recognized the keyword. If a keywords
7759 was found more than once, it's an error. */
7760 keywords[i].value = value;
7761 ++keywords[i].count;
7762
7763 if (keywords[i].count > 1)
7764 return 0;
7765
7766 /* Check type of value against allowed type. */
7767 switch (keywords[i].type)
7768 {
7769 case IMAGE_STRING_VALUE:
7770 if (!STRINGP (value))
7771 return 0;
7772 break;
7773
7774 case IMAGE_SYMBOL_VALUE:
7775 if (!SYMBOLP (value))
7776 return 0;
7777 break;
7778
7779 case IMAGE_POSITIVE_INTEGER_VALUE:
7780 if (!INTEGERP (value) || XINT (value) <= 0)
7781 return 0;
7782 break;
7783
7784 case IMAGE_ASCENT_VALUE:
7785 if (SYMBOLP (value) && EQ (value, Qcenter))
7786 break;
7787 else if (INTEGERP (value)
7788 && XINT (value) >= 0
7789 && XINT (value) <= 100)
7790 break;
7791 return 0;
7792
7793 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7794 if (!INTEGERP (value) || XINT (value) < 0)
7795 return 0;
7796 break;
7797
7798 case IMAGE_DONT_CHECK_VALUE_TYPE:
7799 break;
7800
7801 case IMAGE_FUNCTION_VALUE:
7802 value = indirect_function (value);
7803 if (SUBRP (value)
7804 || COMPILEDP (value)
7805 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7806 break;
7807 return 0;
7808
7809 case IMAGE_NUMBER_VALUE:
7810 if (!INTEGERP (value) && !FLOATP (value))
7811 return 0;
7812 break;
7813
7814 case IMAGE_INTEGER_VALUE:
7815 if (!INTEGERP (value))
7816 return 0;
7817 break;
7818
7819 case IMAGE_BOOL_VALUE:
7820 if (!NILP (value) && !EQ (value, Qt))
7821 return 0;
7822 break;
7823
7824 default:
7825 abort ();
7826 break;
7827 }
7828
7829 if (EQ (key, QCtype) && !EQ (type, value))
7830 return 0;
7831 }
7832
7833 /* Check that all mandatory fields are present. */
7834 for (i = 0; i < nkeywords; ++i)
7835 if (keywords[i].mandatory_p && keywords[i].count == 0)
7836 return 0;
7837
7838 return NILP (plist);
7839 }
7840
7841
7842 /* Return the value of KEY in image specification SPEC. Value is nil
7843 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7844 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7845
7846 static Lisp_Object
7847 image_spec_value (spec, key, found)
7848 Lisp_Object spec, key;
7849 int *found;
7850 {
7851 Lisp_Object tail;
7852
7853 xassert (valid_image_p (spec));
7854
7855 for (tail = XCDR (spec);
7856 CONSP (tail) && CONSP (XCDR (tail));
7857 tail = XCDR (XCDR (tail)))
7858 {
7859 if (EQ (XCAR (tail), key))
7860 {
7861 if (found)
7862 *found = 1;
7863 return XCAR (XCDR (tail));
7864 }
7865 }
7866
7867 if (found)
7868 *found = 0;
7869 return Qnil;
7870 }
7871
7872
7873
7874 \f
7875 /***********************************************************************
7876 Image type independent image structures
7877 ***********************************************************************/
7878
7879 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7880 static void free_image P_ ((struct frame *f, struct image *img));
7881
7882
7883 /* Allocate and return a new image structure for image specification
7884 SPEC. SPEC has a hash value of HASH. */
7885
7886 static struct image *
7887 make_image (spec, hash)
7888 Lisp_Object spec;
7889 unsigned hash;
7890 {
7891 struct image *img = (struct image *) xmalloc (sizeof *img);
7892
7893 xassert (valid_image_p (spec));
7894 bzero (img, sizeof *img);
7895 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7896 xassert (img->type != NULL);
7897 img->spec = spec;
7898 img->data.lisp_val = Qnil;
7899 img->ascent = DEFAULT_IMAGE_ASCENT;
7900 img->hash = hash;
7901 return img;
7902 }
7903
7904
7905 /* Free image IMG which was used on frame F, including its resources. */
7906
7907 static void
7908 free_image (f, img)
7909 struct frame *f;
7910 struct image *img;
7911 {
7912 if (img)
7913 {
7914 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7915
7916 /* Remove IMG from the hash table of its cache. */
7917 if (img->prev)
7918 img->prev->next = img->next;
7919 else
7920 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7921
7922 if (img->next)
7923 img->next->prev = img->prev;
7924
7925 c->images[img->id] = NULL;
7926
7927 /* Free resources, then free IMG. */
7928 img->type->free (f, img);
7929 xfree (img);
7930 }
7931 }
7932
7933
7934 /* Prepare image IMG for display on frame F. Must be called before
7935 drawing an image. */
7936
7937 void
7938 prepare_image_for_display (f, img)
7939 struct frame *f;
7940 struct image *img;
7941 {
7942 EMACS_TIME t;
7943
7944 /* We're about to display IMG, so set its timestamp to `now'. */
7945 EMACS_GET_TIME (t);
7946 img->timestamp = EMACS_SECS (t);
7947
7948 /* If IMG doesn't have a pixmap yet, load it now, using the image
7949 type dependent loader function. */
7950 if (img->pixmap == 0 && !img->load_failed_p)
7951 img->load_failed_p = img->type->load (f, img) == 0;
7952 }
7953
7954
7955 /* Value is the number of pixels for the ascent of image IMG when
7956 drawn in face FACE. */
7957
7958 int
7959 image_ascent (img, face)
7960 struct image *img;
7961 struct face *face;
7962 {
7963 int height = img->height + img->margin;
7964 int ascent;
7965
7966 if (img->ascent == CENTERED_IMAGE_ASCENT)
7967 {
7968 if (face->font)
7969 ascent = height / 2 - (FONT_DESCENT(face->font)
7970 - FONT_BASE(face->font)) / 2;
7971 else
7972 ascent = height / 2;
7973 }
7974 else
7975 ascent = height * img->ascent / 100.0;
7976
7977 return ascent;
7978 }
7979
7980
7981 \f
7982 /***********************************************************************
7983 Helper functions for X image types
7984 ***********************************************************************/
7985
7986 static void x_clear_image P_ ((struct frame *f, struct image *img));
7987 static unsigned long x_alloc_image_color P_ ((struct frame *f,
7988 struct image *img,
7989 Lisp_Object color_name,
7990 unsigned long dflt));
7991
7992 /* Free X resources of image IMG which is used on frame F. */
7993
7994 static void
7995 x_clear_image (f, img)
7996 struct frame *f;
7997 struct image *img;
7998 {
7999 #if 0 /* TODO: W32 image support */
8000
8001 if (img->pixmap)
8002 {
8003 BLOCK_INPUT;
8004 XFreePixmap (NULL, img->pixmap);
8005 img->pixmap = 0;
8006 UNBLOCK_INPUT;
8007 }
8008
8009 if (img->ncolors)
8010 {
8011 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8012
8013 /* If display has an immutable color map, freeing colors is not
8014 necessary and some servers don't allow it. So don't do it. */
8015 if (class != StaticColor
8016 && class != StaticGray
8017 && class != TrueColor)
8018 {
8019 Colormap cmap;
8020 BLOCK_INPUT;
8021 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8022 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8023 img->ncolors, 0);
8024 UNBLOCK_INPUT;
8025 }
8026
8027 xfree (img->colors);
8028 img->colors = NULL;
8029 img->ncolors = 0;
8030 }
8031 #endif
8032 }
8033
8034
8035 /* Allocate color COLOR_NAME for image IMG on frame F. If color
8036 cannot be allocated, use DFLT. Add a newly allocated color to
8037 IMG->colors, so that it can be freed again. Value is the pixel
8038 color. */
8039
8040 static unsigned long
8041 x_alloc_image_color (f, img, color_name, dflt)
8042 struct frame *f;
8043 struct image *img;
8044 Lisp_Object color_name;
8045 unsigned long dflt;
8046 {
8047 #if 0 /* TODO: allocing colors. */
8048 XColor color;
8049 unsigned long result;
8050
8051 xassert (STRINGP (color_name));
8052
8053 if (w32_defined_color (f, XSTRING (color_name)->data, &color, 1))
8054 {
8055 /* This isn't called frequently so we get away with simply
8056 reallocating the color vector to the needed size, here. */
8057 ++img->ncolors;
8058 img->colors =
8059 (unsigned long *) xrealloc (img->colors,
8060 img->ncolors * sizeof *img->colors);
8061 img->colors[img->ncolors - 1] = color.pixel;
8062 result = color.pixel;
8063 }
8064 else
8065 result = dflt;
8066 return result;
8067 #endif
8068 return 0;
8069 }
8070
8071
8072 \f
8073 /***********************************************************************
8074 Image Cache
8075 ***********************************************************************/
8076
8077 static void cache_image P_ ((struct frame *f, struct image *img));
8078
8079
8080 /* Return a new, initialized image cache that is allocated from the
8081 heap. Call free_image_cache to free an image cache. */
8082
8083 struct image_cache *
8084 make_image_cache ()
8085 {
8086 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8087 int size;
8088
8089 bzero (c, sizeof *c);
8090 c->size = 50;
8091 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8092 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8093 c->buckets = (struct image **) xmalloc (size);
8094 bzero (c->buckets, size);
8095 return c;
8096 }
8097
8098
8099 /* Free image cache of frame F. Be aware that X frames share images
8100 caches. */
8101
8102 void
8103 free_image_cache (f)
8104 struct frame *f;
8105 {
8106 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8107 if (c)
8108 {
8109 int i;
8110
8111 /* Cache should not be referenced by any frame when freed. */
8112 xassert (c->refcount == 0);
8113
8114 for (i = 0; i < c->used; ++i)
8115 free_image (f, c->images[i]);
8116 xfree (c->images);
8117 xfree (c);
8118 xfree (c->buckets);
8119 FRAME_X_IMAGE_CACHE (f) = NULL;
8120 }
8121 }
8122
8123
8124 /* Clear image cache of frame F. FORCE_P non-zero means free all
8125 images. FORCE_P zero means clear only images that haven't been
8126 displayed for some time. Should be called from time to time to
8127 reduce the number of loaded images. If image-eviction-seconds is
8128 non-nil, this frees images in the cache which weren't displayed for
8129 at least that many seconds. */
8130
8131 void
8132 clear_image_cache (f, force_p)
8133 struct frame *f;
8134 int force_p;
8135 {
8136 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8137
8138 if (c && INTEGERP (Vimage_cache_eviction_delay))
8139 {
8140 EMACS_TIME t;
8141 unsigned long old;
8142 int i, any_freed_p = 0;
8143
8144 EMACS_GET_TIME (t);
8145 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8146
8147 for (i = 0; i < c->used; ++i)
8148 {
8149 struct image *img = c->images[i];
8150 if (img != NULL
8151 && (force_p
8152 || (img->timestamp > old)))
8153 {
8154 free_image (f, img);
8155 any_freed_p = 1;
8156 }
8157 }
8158
8159 /* We may be clearing the image cache because, for example,
8160 Emacs was iconified for a longer period of time. In that
8161 case, current matrices may still contain references to
8162 images freed above. So, clear these matrices. */
8163 if (any_freed_p)
8164 {
8165 clear_current_matrices (f);
8166 ++windows_or_buffers_changed;
8167 }
8168 }
8169 }
8170
8171
8172 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
8173 0, 1, 0,
8174 "Clear the image cache of FRAME.\n\
8175 FRAME nil or omitted means use the selected frame.\n\
8176 FRAME t means clear the image caches of all frames.")
8177 (frame)
8178 Lisp_Object frame;
8179 {
8180 if (EQ (frame, Qt))
8181 {
8182 Lisp_Object tail;
8183
8184 FOR_EACH_FRAME (tail, frame)
8185 if (FRAME_W32_P (XFRAME (frame)))
8186 clear_image_cache (XFRAME (frame), 1);
8187 }
8188 else
8189 clear_image_cache (check_x_frame (frame), 1);
8190
8191 return Qnil;
8192 }
8193
8194
8195 /* Return the id of image with Lisp specification SPEC on frame F.
8196 SPEC must be a valid Lisp image specification (see valid_image_p). */
8197
8198 int
8199 lookup_image (f, spec)
8200 struct frame *f;
8201 Lisp_Object spec;
8202 {
8203 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8204 struct image *img;
8205 int i;
8206 unsigned hash;
8207 struct gcpro gcpro1;
8208 EMACS_TIME now;
8209
8210 /* F must be a window-system frame, and SPEC must be a valid image
8211 specification. */
8212 xassert (FRAME_WINDOW_P (f));
8213 xassert (valid_image_p (spec));
8214
8215 GCPRO1 (spec);
8216
8217 /* Look up SPEC in the hash table of the image cache. */
8218 hash = sxhash (spec, 0);
8219 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
8220
8221 for (img = c->buckets[i]; img; img = img->next)
8222 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
8223 break;
8224
8225 /* If not found, create a new image and cache it. */
8226 if (img == NULL)
8227 {
8228 img = make_image (spec, hash);
8229 cache_image (f, img);
8230 img->load_failed_p = img->type->load (f, img) == 0;
8231 xassert (!interrupt_input_blocked);
8232
8233 /* If we can't load the image, and we don't have a width and
8234 height, use some arbitrary width and height so that we can
8235 draw a rectangle for it. */
8236 if (img->load_failed_p)
8237 {
8238 Lisp_Object value;
8239
8240 value = image_spec_value (spec, QCwidth, NULL);
8241 img->width = (INTEGERP (value)
8242 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
8243 value = image_spec_value (spec, QCheight, NULL);
8244 img->height = (INTEGERP (value)
8245 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
8246 }
8247 else
8248 {
8249 /* Handle image type independent image attributes
8250 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF'. */
8251 Lisp_Object ascent, margin, relief, algorithm, heuristic_mask;
8252 Lisp_Object file;
8253
8254 ascent = image_spec_value (spec, QCascent, NULL);
8255 if (INTEGERP (ascent))
8256 img->ascent = XFASTINT (ascent);
8257 else if (EQ (ascent, Qcenter))
8258 img->ascent = CENTERED_IMAGE_ASCENT;
8259
8260 margin = image_spec_value (spec, QCmargin, NULL);
8261 if (INTEGERP (margin) && XINT (margin) >= 0)
8262 img->margin = XFASTINT (margin);
8263
8264 relief = image_spec_value (spec, QCrelief, NULL);
8265 if (INTEGERP (relief))
8266 {
8267 img->relief = XINT (relief);
8268 img->margin += abs (img->relief);
8269 }
8270
8271 /* Should we apply a Laplace edge-detection algorithm? */
8272 algorithm = image_spec_value (spec, QCalgorithm, NULL);
8273 if (img->pixmap && EQ (algorithm, Qlaplace))
8274 x_laplace (f, img);
8275
8276 /* Should we built a mask heuristically? */
8277 heuristic_mask = image_spec_value (spec, QCheuristic_mask, NULL);
8278 if (img->pixmap && !img->mask && !NILP (heuristic_mask))
8279 x_build_heuristic_mask (f, img, heuristic_mask);
8280 }
8281 }
8282
8283 /* We're using IMG, so set its timestamp to `now'. */
8284 EMACS_GET_TIME (now);
8285 img->timestamp = EMACS_SECS (now);
8286
8287 UNGCPRO;
8288
8289 /* Value is the image id. */
8290 return img->id;
8291 }
8292
8293
8294 /* Cache image IMG in the image cache of frame F. */
8295
8296 static void
8297 cache_image (f, img)
8298 struct frame *f;
8299 struct image *img;
8300 {
8301 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8302 int i;
8303
8304 /* Find a free slot in c->images. */
8305 for (i = 0; i < c->used; ++i)
8306 if (c->images[i] == NULL)
8307 break;
8308
8309 /* If no free slot found, maybe enlarge c->images. */
8310 if (i == c->used && c->used == c->size)
8311 {
8312 c->size *= 2;
8313 c->images = (struct image **) xrealloc (c->images,
8314 c->size * sizeof *c->images);
8315 }
8316
8317 /* Add IMG to c->images, and assign IMG an id. */
8318 c->images[i] = img;
8319 img->id = i;
8320 if (i == c->used)
8321 ++c->used;
8322
8323 /* Add IMG to the cache's hash table. */
8324 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8325 img->next = c->buckets[i];
8326 if (img->next)
8327 img->next->prev = img;
8328 img->prev = NULL;
8329 c->buckets[i] = img;
8330 }
8331
8332
8333 /* Call FN on every image in the image cache of frame F. Used to mark
8334 Lisp Objects in the image cache. */
8335
8336 void
8337 forall_images_in_image_cache (f, fn)
8338 struct frame *f;
8339 void (*fn) P_ ((struct image *img));
8340 {
8341 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8342 {
8343 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8344 if (c)
8345 {
8346 int i;
8347 for (i = 0; i < c->used; ++i)
8348 if (c->images[i])
8349 fn (c->images[i]);
8350 }
8351 }
8352 }
8353
8354
8355 \f
8356 /***********************************************************************
8357 W32 support code
8358 ***********************************************************************/
8359
8360 #if 0 /* TODO: W32 specific image code. */
8361
8362 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8363 XImage **, Pixmap *));
8364 static void x_destroy_x_image P_ ((XImage *));
8365 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8366
8367
8368 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8369 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8370 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
8371 via xmalloc. Print error messages via image_error if an error
8372 occurs. Value is non-zero if successful. */
8373
8374 static int
8375 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8376 struct frame *f;
8377 int width, height, depth;
8378 XImage **ximg;
8379 Pixmap *pixmap;
8380 {
8381 #if 0 /* TODO: Image support for W32 */
8382 Display *display = FRAME_W32_DISPLAY (f);
8383 Screen *screen = FRAME_X_SCREEN (f);
8384 Window window = FRAME_W32_WINDOW (f);
8385
8386 xassert (interrupt_input_blocked);
8387
8388 if (depth <= 0)
8389 depth = DefaultDepthOfScreen (screen);
8390 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
8391 depth, ZPixmap, 0, NULL, width, height,
8392 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
8393 if (*ximg == NULL)
8394 {
8395 image_error ("Unable to allocate X image", Qnil, Qnil);
8396 return 0;
8397 }
8398
8399 /* Allocate image raster. */
8400 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
8401
8402 /* Allocate a pixmap of the same size. */
8403 *pixmap = XCreatePixmap (display, window, width, height, depth);
8404 if (*pixmap == 0)
8405 {
8406 x_destroy_x_image (*ximg);
8407 *ximg = NULL;
8408 image_error ("Unable to create X pixmap", Qnil, Qnil);
8409 return 0;
8410 }
8411 #endif
8412 return 1;
8413 }
8414
8415
8416 /* Destroy XImage XIMG. Free XIMG->data. */
8417
8418 static void
8419 x_destroy_x_image (ximg)
8420 XImage *ximg;
8421 {
8422 xassert (interrupt_input_blocked);
8423 if (ximg)
8424 {
8425 xfree (ximg->data);
8426 ximg->data = NULL;
8427 XDestroyImage (ximg);
8428 }
8429 }
8430
8431
8432 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8433 are width and height of both the image and pixmap. */
8434
8435 static void
8436 x_put_x_image (f, ximg, pixmap, width, height)
8437 struct frame *f;
8438 XImage *ximg;
8439 Pixmap pixmap;
8440 {
8441 GC gc;
8442
8443 xassert (interrupt_input_blocked);
8444 gc = XCreateGC (NULL, pixmap, 0, NULL);
8445 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
8446 XFreeGC (NULL, gc);
8447 }
8448
8449 #endif
8450
8451 \f
8452 /***********************************************************************
8453 Searching files
8454 ***********************************************************************/
8455
8456 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
8457
8458 /* Find image file FILE. Look in data-directory, then
8459 x-bitmap-file-path. Value is the full name of the file found, or
8460 nil if not found. */
8461
8462 static Lisp_Object
8463 x_find_image_file (file)
8464 Lisp_Object file;
8465 {
8466 Lisp_Object file_found, search_path;
8467 struct gcpro gcpro1, gcpro2;
8468 int fd;
8469
8470 file_found = Qnil;
8471 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8472 GCPRO2 (file_found, search_path);
8473
8474 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
8475 fd = openp (search_path, file, "", &file_found, 0);
8476
8477 if (fd == -1)
8478 file_found = Qnil;
8479 else
8480 close (fd);
8481
8482 UNGCPRO;
8483 return file_found;
8484 }
8485
8486
8487 \f
8488 /***********************************************************************
8489 XBM images
8490 ***********************************************************************/
8491
8492 static int xbm_load P_ ((struct frame *f, struct image *img));
8493 static int xbm_load_image_from_file P_ ((struct frame *f, struct image *img,
8494 Lisp_Object file));
8495 static int xbm_image_p P_ ((Lisp_Object object));
8496 static int xbm_read_bitmap_file_data P_ ((char *, int *, int *,
8497 unsigned char **));
8498
8499
8500 /* Indices of image specification fields in xbm_format, below. */
8501
8502 enum xbm_keyword_index
8503 {
8504 XBM_TYPE,
8505 XBM_FILE,
8506 XBM_WIDTH,
8507 XBM_HEIGHT,
8508 XBM_DATA,
8509 XBM_FOREGROUND,
8510 XBM_BACKGROUND,
8511 XBM_ASCENT,
8512 XBM_MARGIN,
8513 XBM_RELIEF,
8514 XBM_ALGORITHM,
8515 XBM_HEURISTIC_MASK,
8516 XBM_LAST
8517 };
8518
8519 /* Vector of image_keyword structures describing the format
8520 of valid XBM image specifications. */
8521
8522 static struct image_keyword xbm_format[XBM_LAST] =
8523 {
8524 {":type", IMAGE_SYMBOL_VALUE, 1},
8525 {":file", IMAGE_STRING_VALUE, 0},
8526 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8527 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8528 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8529 {":foreground", IMAGE_STRING_VALUE, 0},
8530 {":background", IMAGE_STRING_VALUE, 0},
8531 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8532 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8533 {":relief", IMAGE_INTEGER_VALUE, 0},
8534 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8535 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8536 };
8537
8538 /* Structure describing the image type XBM. */
8539
8540 static struct image_type xbm_type =
8541 {
8542 &Qxbm,
8543 xbm_image_p,
8544 xbm_load,
8545 x_clear_image,
8546 NULL
8547 };
8548
8549 /* Tokens returned from xbm_scan. */
8550
8551 enum xbm_token
8552 {
8553 XBM_TK_IDENT = 256,
8554 XBM_TK_NUMBER
8555 };
8556
8557
8558 /* Return non-zero if OBJECT is a valid XBM-type image specification.
8559 A valid specification is a list starting with the symbol `image'
8560 The rest of the list is a property list which must contain an
8561 entry `:type xbm..
8562
8563 If the specification specifies a file to load, it must contain
8564 an entry `:file FILENAME' where FILENAME is a string.
8565
8566 If the specification is for a bitmap loaded from memory it must
8567 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8568 WIDTH and HEIGHT are integers > 0. DATA may be:
8569
8570 1. a string large enough to hold the bitmap data, i.e. it must
8571 have a size >= (WIDTH + 7) / 8 * HEIGHT
8572
8573 2. a bool-vector of size >= WIDTH * HEIGHT
8574
8575 3. a vector of strings or bool-vectors, one for each line of the
8576 bitmap.
8577
8578 Both the file and data forms may contain the additional entries
8579 `:background COLOR' and `:foreground COLOR'. If not present,
8580 foreground and background of the frame on which the image is
8581 displayed, is used. */
8582
8583 static int
8584 xbm_image_p (object)
8585 Lisp_Object object;
8586 {
8587 struct image_keyword kw[XBM_LAST];
8588
8589 bcopy (xbm_format, kw, sizeof kw);
8590 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8591 return 0;
8592
8593 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8594
8595 if (kw[XBM_FILE].count)
8596 {
8597 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8598 return 0;
8599 }
8600 else
8601 {
8602 Lisp_Object data;
8603 int width, height;
8604
8605 /* Entries for `:width', `:height' and `:data' must be present. */
8606 if (!kw[XBM_WIDTH].count
8607 || !kw[XBM_HEIGHT].count
8608 || !kw[XBM_DATA].count)
8609 return 0;
8610
8611 data = kw[XBM_DATA].value;
8612 width = XFASTINT (kw[XBM_WIDTH].value);
8613 height = XFASTINT (kw[XBM_HEIGHT].value);
8614
8615 /* Check type of data, and width and height against contents of
8616 data. */
8617 if (VECTORP (data))
8618 {
8619 int i;
8620
8621 /* Number of elements of the vector must be >= height. */
8622 if (XVECTOR (data)->size < height)
8623 return 0;
8624
8625 /* Each string or bool-vector in data must be large enough
8626 for one line of the image. */
8627 for (i = 0; i < height; ++i)
8628 {
8629 Lisp_Object elt = XVECTOR (data)->contents[i];
8630
8631 if (STRINGP (elt))
8632 {
8633 if (XSTRING (elt)->size
8634 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8635 return 0;
8636 }
8637 else if (BOOL_VECTOR_P (elt))
8638 {
8639 if (XBOOL_VECTOR (elt)->size < width)
8640 return 0;
8641 }
8642 else
8643 return 0;
8644 }
8645 }
8646 else if (STRINGP (data))
8647 {
8648 if (XSTRING (data)->size
8649 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8650 return 0;
8651 }
8652 else if (BOOL_VECTOR_P (data))
8653 {
8654 if (XBOOL_VECTOR (data)->size < width * height)
8655 return 0;
8656 }
8657 else
8658 return 0;
8659 }
8660
8661 /* Baseline must be a value between 0 and 100 (a percentage). */
8662 if (kw[XBM_ASCENT].count
8663 && XFASTINT (kw[XBM_ASCENT].value) > 100)
8664 return 0;
8665
8666 return 1;
8667 }
8668
8669
8670 /* Scan a bitmap file. FP is the stream to read from. Value is
8671 either an enumerator from enum xbm_token, or a character for a
8672 single-character token, or 0 at end of file. If scanning an
8673 identifier, store the lexeme of the identifier in SVAL. If
8674 scanning a number, store its value in *IVAL. */
8675
8676 static int
8677 xbm_scan (fp, sval, ival)
8678 FILE *fp;
8679 char *sval;
8680 int *ival;
8681 {
8682 int c;
8683
8684 /* Skip white space. */
8685 while ((c = fgetc (fp)) != EOF && isspace (c))
8686 ;
8687
8688 if (c == EOF)
8689 c = 0;
8690 else if (isdigit (c))
8691 {
8692 int value = 0, digit;
8693
8694 if (c == '0')
8695 {
8696 c = fgetc (fp);
8697 if (c == 'x' || c == 'X')
8698 {
8699 while ((c = fgetc (fp)) != EOF)
8700 {
8701 if (isdigit (c))
8702 digit = c - '0';
8703 else if (c >= 'a' && c <= 'f')
8704 digit = c - 'a' + 10;
8705 else if (c >= 'A' && c <= 'F')
8706 digit = c - 'A' + 10;
8707 else
8708 break;
8709 value = 16 * value + digit;
8710 }
8711 }
8712 else if (isdigit (c))
8713 {
8714 value = c - '0';
8715 while ((c = fgetc (fp)) != EOF
8716 && isdigit (c))
8717 value = 8 * value + c - '0';
8718 }
8719 }
8720 else
8721 {
8722 value = c - '0';
8723 while ((c = fgetc (fp)) != EOF
8724 && isdigit (c))
8725 value = 10 * value + c - '0';
8726 }
8727
8728 if (c != EOF)
8729 ungetc (c, fp);
8730 *ival = value;
8731 c = XBM_TK_NUMBER;
8732 }
8733 else if (isalpha (c) || c == '_')
8734 {
8735 *sval++ = c;
8736 while ((c = fgetc (fp)) != EOF
8737 && (isalnum (c) || c == '_'))
8738 *sval++ = c;
8739 *sval = 0;
8740 if (c != EOF)
8741 ungetc (c, fp);
8742 c = XBM_TK_IDENT;
8743 }
8744
8745 return c;
8746 }
8747
8748
8749 /* Replacement for XReadBitmapFileData which isn't available under old
8750 X versions. FILE is the name of the bitmap file to read. Set
8751 *WIDTH and *HEIGHT to the width and height of the image. Return in
8752 *DATA the bitmap data allocated with xmalloc. Value is non-zero if
8753 successful. */
8754
8755 static int
8756 xbm_read_bitmap_file_data (file, width, height, data)
8757 char *file;
8758 int *width, *height;
8759 unsigned char **data;
8760 {
8761 FILE *fp;
8762 char buffer[BUFSIZ];
8763 int padding_p = 0;
8764 int v10 = 0;
8765 int bytes_per_line, i, nbytes;
8766 unsigned char *p;
8767 int value;
8768 int LA1;
8769
8770 #define match() \
8771 LA1 = xbm_scan (fp, buffer, &value)
8772
8773 #define expect(TOKEN) \
8774 if (LA1 != (TOKEN)) \
8775 goto failure; \
8776 else \
8777 match ()
8778
8779 #define expect_ident(IDENT) \
8780 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8781 match (); \
8782 else \
8783 goto failure
8784
8785 fp = fopen (file, "r");
8786 if (fp == NULL)
8787 return 0;
8788
8789 *width = *height = -1;
8790 *data = NULL;
8791 LA1 = xbm_scan (fp, buffer, &value);
8792
8793 /* Parse defines for width, height and hot-spots. */
8794 while (LA1 == '#')
8795 {
8796 match ();
8797 expect_ident ("define");
8798 expect (XBM_TK_IDENT);
8799
8800 if (LA1 == XBM_TK_NUMBER);
8801 {
8802 char *p = strrchr (buffer, '_');
8803 p = p ? p + 1 : buffer;
8804 if (strcmp (p, "width") == 0)
8805 *width = value;
8806 else if (strcmp (p, "height") == 0)
8807 *height = value;
8808 }
8809 expect (XBM_TK_NUMBER);
8810 }
8811
8812 if (*width < 0 || *height < 0)
8813 goto failure;
8814
8815 /* Parse bits. Must start with `static'. */
8816 expect_ident ("static");
8817 if (LA1 == XBM_TK_IDENT)
8818 {
8819 if (strcmp (buffer, "unsigned") == 0)
8820 {
8821 match ();
8822 expect_ident ("char");
8823 }
8824 else if (strcmp (buffer, "short") == 0)
8825 {
8826 match ();
8827 v10 = 1;
8828 if (*width % 16 && *width % 16 < 9)
8829 padding_p = 1;
8830 }
8831 else if (strcmp (buffer, "char") == 0)
8832 match ();
8833 else
8834 goto failure;
8835 }
8836 else
8837 goto failure;
8838
8839 expect (XBM_TK_IDENT);
8840 expect ('[');
8841 expect (']');
8842 expect ('=');
8843 expect ('{');
8844
8845 bytes_per_line = (*width + 7) / 8 + padding_p;
8846 nbytes = bytes_per_line * *height;
8847 p = *data = (char *) xmalloc (nbytes);
8848
8849 if (v10)
8850 {
8851
8852 for (i = 0; i < nbytes; i += 2)
8853 {
8854 int val = value;
8855 expect (XBM_TK_NUMBER);
8856
8857 *p++ = val;
8858 if (!padding_p || ((i + 2) % bytes_per_line))
8859 *p++ = value >> 8;
8860
8861 if (LA1 == ',' || LA1 == '}')
8862 match ();
8863 else
8864 goto failure;
8865 }
8866 }
8867 else
8868 {
8869 for (i = 0; i < nbytes; ++i)
8870 {
8871 int val = value;
8872 expect (XBM_TK_NUMBER);
8873
8874 *p++ = val;
8875
8876 if (LA1 == ',' || LA1 == '}')
8877 match ();
8878 else
8879 goto failure;
8880 }
8881 }
8882
8883 fclose (fp);
8884 return 1;
8885
8886 failure:
8887
8888 fclose (fp);
8889 if (*data)
8890 {
8891 xfree (*data);
8892 *data = NULL;
8893 }
8894 return 0;
8895
8896 #undef match
8897 #undef expect
8898 #undef expect_ident
8899 }
8900
8901
8902 /* Load XBM image IMG which will be displayed on frame F from file
8903 SPECIFIED_FILE. Value is non-zero if successful. */
8904
8905 static int
8906 xbm_load_image_from_file (f, img, specified_file)
8907 struct frame *f;
8908 struct image *img;
8909 Lisp_Object specified_file;
8910 {
8911 int rc;
8912 unsigned char *data;
8913 int success_p = 0;
8914 Lisp_Object file;
8915 struct gcpro gcpro1;
8916
8917 xassert (STRINGP (specified_file));
8918 file = Qnil;
8919 GCPRO1 (file);
8920
8921 file = x_find_image_file (specified_file);
8922 if (!STRINGP (file))
8923 {
8924 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8925 UNGCPRO;
8926 return 0;
8927 }
8928
8929 rc = xbm_read_bitmap_file_data (XSTRING (file)->data, &img->width,
8930 &img->height, &data);
8931 if (rc)
8932 {
8933 int depth = one_w32_display_info.n_cbits;
8934 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8935 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8936 Lisp_Object value;
8937
8938 xassert (img->width > 0 && img->height > 0);
8939
8940 /* Get foreground and background colors, maybe allocate colors. */
8941 value = image_spec_value (img->spec, QCforeground, NULL);
8942 if (!NILP (value))
8943 foreground = x_alloc_image_color (f, img, value, foreground);
8944
8945 value = image_spec_value (img->spec, QCbackground, NULL);
8946 if (!NILP (value))
8947 background = x_alloc_image_color (f, img, value, background);
8948
8949 #if 0 /* TODO : Port image display to W32 */
8950 BLOCK_INPUT;
8951 img->pixmap
8952 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
8953 FRAME_W32_WINDOW (f),
8954 data,
8955 img->width, img->height,
8956 foreground, background,
8957 depth);
8958 xfree (data);
8959
8960 if (img->pixmap == 0)
8961 {
8962 x_clear_image (f, img);
8963 image_error ("Unable to create X pixmap for `%s'", file, Qnil);
8964 }
8965 else
8966 success_p = 1;
8967
8968 UNBLOCK_INPUT;
8969 #endif
8970 }
8971 else
8972 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8973
8974 UNGCPRO;
8975 return success_p;
8976 }
8977
8978
8979 /* Fill image IMG which is used on frame F with pixmap data. Value is
8980 non-zero if successful. */
8981
8982 static int
8983 xbm_load (f, img)
8984 struct frame *f;
8985 struct image *img;
8986 {
8987 int success_p = 0;
8988 Lisp_Object file_name;
8989
8990 xassert (xbm_image_p (img->spec));
8991
8992 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8993 file_name = image_spec_value (img->spec, QCfile, NULL);
8994 if (STRINGP (file_name))
8995 success_p = xbm_load_image_from_file (f, img, file_name);
8996 else
8997 {
8998 struct image_keyword fmt[XBM_LAST];
8999 Lisp_Object data;
9000 int depth;
9001 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
9002 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
9003 char *bits;
9004 int parsed_p;
9005
9006 /* Parse the list specification. */
9007 bcopy (xbm_format, fmt, sizeof fmt);
9008 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
9009 xassert (parsed_p);
9010
9011 /* Get specified width, and height. */
9012 img->width = XFASTINT (fmt[XBM_WIDTH].value);
9013 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
9014 xassert (img->width > 0 && img->height > 0);
9015
9016 BLOCK_INPUT;
9017
9018 if (fmt[XBM_ASCENT].count)
9019 img->ascent = XFASTINT (fmt[XBM_ASCENT].value);
9020
9021 /* Get foreground and background colors, maybe allocate colors. */
9022 if (fmt[XBM_FOREGROUND].count)
9023 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
9024 foreground);
9025 if (fmt[XBM_BACKGROUND].count)
9026 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
9027 background);
9028
9029 /* Set bits to the bitmap image data. */
9030 data = fmt[XBM_DATA].value;
9031 if (VECTORP (data))
9032 {
9033 int i;
9034 char *p;
9035 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
9036
9037 p = bits = (char *) alloca (nbytes * img->height);
9038 for (i = 0; i < img->height; ++i, p += nbytes)
9039 {
9040 Lisp_Object line = XVECTOR (data)->contents[i];
9041 if (STRINGP (line))
9042 bcopy (XSTRING (line)->data, p, nbytes);
9043 else
9044 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
9045 }
9046 }
9047 else if (STRINGP (data))
9048 bits = XSTRING (data)->data;
9049 else
9050 bits = XBOOL_VECTOR (data)->data;
9051
9052 #if 0 /* TODO : W32 XPM code */
9053 /* Create the pixmap. */
9054 depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
9055 img->pixmap
9056 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
9057 FRAME_W32_WINDOW (f),
9058 bits,
9059 img->width, img->height,
9060 foreground, background,
9061 depth);
9062 #endif /* TODO */
9063
9064 if (img->pixmap)
9065 success_p = 1;
9066 else
9067 {
9068 image_error ("Unable to create pixmap for XBM image `%s'",
9069 img->spec, Qnil);
9070 x_clear_image (f, img);
9071 }
9072
9073 UNBLOCK_INPUT;
9074 }
9075
9076 return success_p;
9077 }
9078
9079
9080 \f
9081 /***********************************************************************
9082 XPM images
9083 ***********************************************************************/
9084
9085 #if HAVE_XPM
9086
9087 static int xpm_image_p P_ ((Lisp_Object object));
9088 static int xpm_load P_ ((struct frame *f, struct image *img));
9089 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
9090
9091 #include "X11/xpm.h"
9092
9093 /* The symbol `xpm' identifying XPM-format images. */
9094
9095 Lisp_Object Qxpm;
9096
9097 /* Indices of image specification fields in xpm_format, below. */
9098
9099 enum xpm_keyword_index
9100 {
9101 XPM_TYPE,
9102 XPM_FILE,
9103 XPM_DATA,
9104 XPM_ASCENT,
9105 XPM_MARGIN,
9106 XPM_RELIEF,
9107 XPM_ALGORITHM,
9108 XPM_HEURISTIC_MASK,
9109 XPM_COLOR_SYMBOLS,
9110 XPM_LAST
9111 };
9112
9113 /* Vector of image_keyword structures describing the format
9114 of valid XPM image specifications. */
9115
9116 static struct image_keyword xpm_format[XPM_LAST] =
9117 {
9118 {":type", IMAGE_SYMBOL_VALUE, 1},
9119 {":file", IMAGE_STRING_VALUE, 0},
9120 {":data", IMAGE_STRING_VALUE, 0},
9121 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9122 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9123 {":relief", IMAGE_INTEGER_VALUE, 0},
9124 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9125 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9126 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9127 };
9128
9129 /* Structure describing the image type XBM. */
9130
9131 static struct image_type xpm_type =
9132 {
9133 &Qxpm,
9134 xpm_image_p,
9135 xpm_load,
9136 x_clear_image,
9137 NULL
9138 };
9139
9140
9141 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9142 for XPM images. Such a list must consist of conses whose car and
9143 cdr are strings. */
9144
9145 static int
9146 xpm_valid_color_symbols_p (color_symbols)
9147 Lisp_Object color_symbols;
9148 {
9149 while (CONSP (color_symbols))
9150 {
9151 Lisp_Object sym = XCAR (color_symbols);
9152 if (!CONSP (sym)
9153 || !STRINGP (XCAR (sym))
9154 || !STRINGP (XCDR (sym)))
9155 break;
9156 color_symbols = XCDR (color_symbols);
9157 }
9158
9159 return NILP (color_symbols);
9160 }
9161
9162
9163 /* Value is non-zero if OBJECT is a valid XPM image specification. */
9164
9165 static int
9166 xpm_image_p (object)
9167 Lisp_Object object;
9168 {
9169 struct image_keyword fmt[XPM_LAST];
9170 bcopy (xpm_format, fmt, sizeof fmt);
9171 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9172 /* Either `:file' or `:data' must be present. */
9173 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9174 /* Either no `:color-symbols' or it's a list of conses
9175 whose car and cdr are strings. */
9176 && (fmt[XPM_COLOR_SYMBOLS].count == 0
9177 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
9178 && (fmt[XPM_ASCENT].count == 0
9179 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
9180 }
9181
9182
9183 /* Load image IMG which will be displayed on frame F. Value is
9184 non-zero if successful. */
9185
9186 static int
9187 xpm_load (f, img)
9188 struct frame *f;
9189 struct image *img;
9190 {
9191 int rc, i;
9192 XpmAttributes attrs;
9193 Lisp_Object specified_file, color_symbols;
9194
9195 /* Configure the XPM lib. Use the visual of frame F. Allocate
9196 close colors. Return colors allocated. */
9197 bzero (&attrs, sizeof attrs);
9198 attrs.visual = FRAME_X_VISUAL (f);
9199 attrs.colormap = FRAME_X_COLORMAP (f);
9200 attrs.valuemask |= XpmVisual;
9201 attrs.valuemask |= XpmColormap;
9202 attrs.valuemask |= XpmReturnAllocPixels;
9203 #ifdef XpmAllocCloseColors
9204 attrs.alloc_close_colors = 1;
9205 attrs.valuemask |= XpmAllocCloseColors;
9206 #else
9207 attrs.closeness = 600;
9208 attrs.valuemask |= XpmCloseness;
9209 #endif
9210
9211 /* If image specification contains symbolic color definitions, add
9212 these to `attrs'. */
9213 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
9214 if (CONSP (color_symbols))
9215 {
9216 Lisp_Object tail;
9217 XpmColorSymbol *xpm_syms;
9218 int i, size;
9219
9220 attrs.valuemask |= XpmColorSymbols;
9221
9222 /* Count number of symbols. */
9223 attrs.numsymbols = 0;
9224 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
9225 ++attrs.numsymbols;
9226
9227 /* Allocate an XpmColorSymbol array. */
9228 size = attrs.numsymbols * sizeof *xpm_syms;
9229 xpm_syms = (XpmColorSymbol *) alloca (size);
9230 bzero (xpm_syms, size);
9231 attrs.colorsymbols = xpm_syms;
9232
9233 /* Fill the color symbol array. */
9234 for (tail = color_symbols, i = 0;
9235 CONSP (tail);
9236 ++i, tail = XCDR (tail))
9237 {
9238 Lisp_Object name = XCAR (XCAR (tail));
9239 Lisp_Object color = XCDR (XCAR (tail));
9240 xpm_syms[i].name = (char *) alloca (XSTRING (name)->size + 1);
9241 strcpy (xpm_syms[i].name, XSTRING (name)->data);
9242 xpm_syms[i].value = (char *) alloca (XSTRING (color)->size + 1);
9243 strcpy (xpm_syms[i].value, XSTRING (color)->data);
9244 }
9245 }
9246
9247 /* Create a pixmap for the image, either from a file, or from a
9248 string buffer containing data in the same format as an XPM file. */
9249 BLOCK_INPUT;
9250 specified_file = image_spec_value (img->spec, QCfile, NULL);
9251 if (STRINGP (specified_file))
9252 {
9253 Lisp_Object file = x_find_image_file (specified_file);
9254 if (!STRINGP (file))
9255 {
9256 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9257 UNBLOCK_INPUT;
9258 return 0;
9259 }
9260
9261 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
9262 XSTRING (file)->data, &img->pixmap, &img->mask,
9263 &attrs);
9264 }
9265 else
9266 {
9267 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
9268 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
9269 XSTRING (buffer)->data,
9270 &img->pixmap, &img->mask,
9271 &attrs);
9272 }
9273 UNBLOCK_INPUT;
9274
9275 if (rc == XpmSuccess)
9276 {
9277 /* Remember allocated colors. */
9278 img->ncolors = attrs.nalloc_pixels;
9279 img->colors = (unsigned long *) xmalloc (img->ncolors
9280 * sizeof *img->colors);
9281 for (i = 0; i < attrs.nalloc_pixels; ++i)
9282 img->colors[i] = attrs.alloc_pixels[i];
9283
9284 img->width = attrs.width;
9285 img->height = attrs.height;
9286 xassert (img->width > 0 && img->height > 0);
9287
9288 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
9289 BLOCK_INPUT;
9290 XpmFreeAttributes (&attrs);
9291 UNBLOCK_INPUT;
9292 }
9293 else
9294 {
9295 switch (rc)
9296 {
9297 case XpmOpenFailed:
9298 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9299 break;
9300
9301 case XpmFileInvalid:
9302 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9303 break;
9304
9305 case XpmNoMemory:
9306 image_error ("Out of memory (%s)", img->spec, Qnil);
9307 break;
9308
9309 case XpmColorFailed:
9310 image_error ("Color allocation error (%s)", img->spec, Qnil);
9311 break;
9312
9313 default:
9314 image_error ("Unknown error (%s)", img->spec, Qnil);
9315 break;
9316 }
9317 }
9318
9319 return rc == XpmSuccess;
9320 }
9321
9322 #endif /* HAVE_XPM != 0 */
9323
9324 \f
9325 #if 0 /* TODO : Color tables on W32. */
9326 /***********************************************************************
9327 Color table
9328 ***********************************************************************/
9329
9330 /* An entry in the color table mapping an RGB color to a pixel color. */
9331
9332 struct ct_color
9333 {
9334 int r, g, b;
9335 unsigned long pixel;
9336
9337 /* Next in color table collision list. */
9338 struct ct_color *next;
9339 };
9340
9341 /* The bucket vector size to use. Must be prime. */
9342
9343 #define CT_SIZE 101
9344
9345 /* Value is a hash of the RGB color given by R, G, and B. */
9346
9347 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9348
9349 /* The color hash table. */
9350
9351 struct ct_color **ct_table;
9352
9353 /* Number of entries in the color table. */
9354
9355 int ct_colors_allocated;
9356
9357 /* Function prototypes. */
9358
9359 static void init_color_table P_ ((void));
9360 static void free_color_table P_ ((void));
9361 static unsigned long *colors_in_color_table P_ ((int *n));
9362 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9363 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9364
9365
9366 /* Initialize the color table. */
9367
9368 static void
9369 init_color_table ()
9370 {
9371 int size = CT_SIZE * sizeof (*ct_table);
9372 ct_table = (struct ct_color **) xmalloc (size);
9373 bzero (ct_table, size);
9374 ct_colors_allocated = 0;
9375 }
9376
9377
9378 /* Free memory associated with the color table. */
9379
9380 static void
9381 free_color_table ()
9382 {
9383 int i;
9384 struct ct_color *p, *next;
9385
9386 for (i = 0; i < CT_SIZE; ++i)
9387 for (p = ct_table[i]; p; p = next)
9388 {
9389 next = p->next;
9390 xfree (p);
9391 }
9392
9393 xfree (ct_table);
9394 ct_table = NULL;
9395 }
9396
9397
9398 /* Value is a pixel color for RGB color R, G, B on frame F. If an
9399 entry for that color already is in the color table, return the
9400 pixel color of that entry. Otherwise, allocate a new color for R,
9401 G, B, and make an entry in the color table. */
9402
9403 static unsigned long
9404 lookup_rgb_color (f, r, g, b)
9405 struct frame *f;
9406 int r, g, b;
9407 {
9408 unsigned hash = CT_HASH_RGB (r, g, b);
9409 int i = hash % CT_SIZE;
9410 struct ct_color *p;
9411
9412 for (p = ct_table[i]; p; p = p->next)
9413 if (p->r == r && p->g == g && p->b == b)
9414 break;
9415
9416 if (p == NULL)
9417 {
9418 COLORREF color;
9419 Colormap cmap;
9420 int rc;
9421
9422 color = PALETTERGB (r, g, b);
9423
9424 ++ct_colors_allocated;
9425
9426 p = (struct ct_color *) xmalloc (sizeof *p);
9427 p->r = r;
9428 p->g = g;
9429 p->b = b;
9430 p->pixel = color;
9431 p->next = ct_table[i];
9432 ct_table[i] = p;
9433 }
9434
9435 return p->pixel;
9436 }
9437
9438
9439 /* Look up pixel color PIXEL which is used on frame F in the color
9440 table. If not already present, allocate it. Value is PIXEL. */
9441
9442 static unsigned long
9443 lookup_pixel_color (f, pixel)
9444 struct frame *f;
9445 unsigned long pixel;
9446 {
9447 int i = pixel % CT_SIZE;
9448 struct ct_color *p;
9449
9450 for (p = ct_table[i]; p; p = p->next)
9451 if (p->pixel == pixel)
9452 break;
9453
9454 if (p == NULL)
9455 {
9456 XColor color;
9457 Colormap cmap;
9458 int rc;
9459
9460 BLOCK_INPUT;
9461
9462 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9463 color.pixel = pixel;
9464 XQueryColor (NULL, cmap, &color);
9465 rc = x_alloc_nearest_color (f, cmap, &color);
9466 UNBLOCK_INPUT;
9467
9468 if (rc)
9469 {
9470 ++ct_colors_allocated;
9471
9472 p = (struct ct_color *) xmalloc (sizeof *p);
9473 p->r = color.red;
9474 p->g = color.green;
9475 p->b = color.blue;
9476 p->pixel = pixel;
9477 p->next = ct_table[i];
9478 ct_table[i] = p;
9479 }
9480 else
9481 return FRAME_FOREGROUND_PIXEL (f);
9482 }
9483 return p->pixel;
9484 }
9485
9486
9487 /* Value is a vector of all pixel colors contained in the color table,
9488 allocated via xmalloc. Set *N to the number of colors. */
9489
9490 static unsigned long *
9491 colors_in_color_table (n)
9492 int *n;
9493 {
9494 int i, j;
9495 struct ct_color *p;
9496 unsigned long *colors;
9497
9498 if (ct_colors_allocated == 0)
9499 {
9500 *n = 0;
9501 colors = NULL;
9502 }
9503 else
9504 {
9505 colors = (unsigned long *) xmalloc (ct_colors_allocated
9506 * sizeof *colors);
9507 *n = ct_colors_allocated;
9508
9509 for (i = j = 0; i < CT_SIZE; ++i)
9510 for (p = ct_table[i]; p; p = p->next)
9511 colors[j++] = p->pixel;
9512 }
9513
9514 return colors;
9515 }
9516
9517 #endif /* TODO */
9518
9519 \f
9520 /***********************************************************************
9521 Algorithms
9522 ***********************************************************************/
9523
9524 #if 0 /* TODO : W32 versions of low level algorithms */
9525 static void x_laplace_write_row P_ ((struct frame *, long *,
9526 int, XImage *, int));
9527 static void x_laplace_read_row P_ ((struct frame *, Colormap,
9528 XColor *, int, XImage *, int));
9529
9530
9531 /* Fill COLORS with RGB colors from row Y of image XIMG. F is the
9532 frame we operate on, CMAP is the color-map in effect, and WIDTH is
9533 the width of one row in the image. */
9534
9535 static void
9536 x_laplace_read_row (f, cmap, colors, width, ximg, y)
9537 struct frame *f;
9538 Colormap cmap;
9539 XColor *colors;
9540 int width;
9541 XImage *ximg;
9542 int y;
9543 {
9544 int x;
9545
9546 for (x = 0; x < width; ++x)
9547 colors[x].pixel = XGetPixel (ximg, x, y);
9548
9549 XQueryColors (NULL, cmap, colors, width);
9550 }
9551
9552
9553 /* Write row Y of image XIMG. PIXELS is an array of WIDTH longs
9554 containing the pixel colors to write. F is the frame we are
9555 working on. */
9556
9557 static void
9558 x_laplace_write_row (f, pixels, width, ximg, y)
9559 struct frame *f;
9560 long *pixels;
9561 int width;
9562 XImage *ximg;
9563 int y;
9564 {
9565 int x;
9566
9567 for (x = 0; x < width; ++x)
9568 XPutPixel (ximg, x, y, pixels[x]);
9569 }
9570 #endif
9571
9572 /* Transform image IMG which is used on frame F with a Laplace
9573 edge-detection algorithm. The result is an image that can be used
9574 to draw disabled buttons, for example. */
9575
9576 static void
9577 x_laplace (f, img)
9578 struct frame *f;
9579 struct image *img;
9580 {
9581 #if 0 /* TODO : W32 version */
9582 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9583 XImage *ximg, *oimg;
9584 XColor *in[3];
9585 long *out;
9586 Pixmap pixmap;
9587 int x, y, i;
9588 long pixel;
9589 int in_y, out_y, rc;
9590 int mv2 = 45000;
9591
9592 BLOCK_INPUT;
9593
9594 /* Get the X image IMG->pixmap. */
9595 ximg = XGetImage (NULL, img->pixmap,
9596 0, 0, img->width, img->height, ~0, ZPixmap);
9597
9598 /* Allocate 3 input rows, and one output row of colors. */
9599 for (i = 0; i < 3; ++i)
9600 in[i] = (XColor *) alloca (img->width * sizeof (XColor));
9601 out = (long *) alloca (img->width * sizeof (long));
9602
9603 /* Create an X image for output. */
9604 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9605 &oimg, &pixmap);
9606
9607 /* Fill first two rows. */
9608 x_laplace_read_row (f, cmap, in[0], img->width, ximg, 0);
9609 x_laplace_read_row (f, cmap, in[1], img->width, ximg, 1);
9610 in_y = 2;
9611
9612 /* Write first row, all zeros. */
9613 init_color_table ();
9614 pixel = lookup_rgb_color (f, 0, 0, 0);
9615 for (x = 0; x < img->width; ++x)
9616 out[x] = pixel;
9617 x_laplace_write_row (f, out, img->width, oimg, 0);
9618 out_y = 1;
9619
9620 for (y = 2; y < img->height; ++y)
9621 {
9622 int rowa = y % 3;
9623 int rowb = (y + 2) % 3;
9624
9625 x_laplace_read_row (f, cmap, in[rowa], img->width, ximg, in_y++);
9626
9627 for (x = 0; x < img->width - 2; ++x)
9628 {
9629 int r = in[rowa][x].red + mv2 - in[rowb][x + 2].red;
9630 int g = in[rowa][x].green + mv2 - in[rowb][x + 2].green;
9631 int b = in[rowa][x].blue + mv2 - in[rowb][x + 2].blue;
9632
9633 out[x + 1] = lookup_rgb_color (f, r & 0xffff, g & 0xffff,
9634 b & 0xffff);
9635 }
9636
9637 x_laplace_write_row (f, out, img->width, oimg, out_y++);
9638 }
9639
9640 /* Write last line, all zeros. */
9641 for (x = 0; x < img->width; ++x)
9642 out[x] = pixel;
9643 x_laplace_write_row (f, out, img->width, oimg, out_y);
9644
9645 /* Free the input image, and free resources of IMG. */
9646 XDestroyImage (ximg);
9647 x_clear_image (f, img);
9648
9649 /* Put the output image into pixmap, and destroy it. */
9650 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9651 x_destroy_x_image (oimg);
9652
9653 /* Remember new pixmap and colors in IMG. */
9654 img->pixmap = pixmap;
9655 img->colors = colors_in_color_table (&img->ncolors);
9656 free_color_table ();
9657
9658 UNBLOCK_INPUT;
9659 #endif /* TODO */
9660 }
9661
9662
9663 /* Build a mask for image IMG which is used on frame F. FILE is the
9664 name of an image file, for error messages. HOW determines how to
9665 determine the background color of IMG. If it is a list '(R G B)',
9666 with R, G, and B being integers >= 0, take that as the color of the
9667 background. Otherwise, determine the background color of IMG
9668 heuristically. Value is non-zero if successful. */
9669
9670 static int
9671 x_build_heuristic_mask (f, img, how)
9672 struct frame *f;
9673 struct image *img;
9674 Lisp_Object how;
9675 {
9676 #if 0 /* TODO : W32 version */
9677 Display *dpy = FRAME_W32_DISPLAY (f);
9678 XImage *ximg, *mask_img;
9679 int x, y, rc, look_at_corners_p;
9680 unsigned long bg;
9681
9682 BLOCK_INPUT;
9683
9684 /* Create an image and pixmap serving as mask. */
9685 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
9686 &mask_img, &img->mask);
9687 if (!rc)
9688 {
9689 UNBLOCK_INPUT;
9690 return 0;
9691 }
9692
9693 /* Get the X image of IMG->pixmap. */
9694 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
9695 ~0, ZPixmap);
9696
9697 /* Determine the background color of ximg. If HOW is `(R G B)'
9698 take that as color. Otherwise, try to determine the color
9699 heuristically. */
9700 look_at_corners_p = 1;
9701
9702 if (CONSP (how))
9703 {
9704 int rgb[3], i = 0;
9705
9706 while (i < 3
9707 && CONSP (how)
9708 && NATNUMP (XCAR (how)))
9709 {
9710 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9711 how = XCDR (how);
9712 }
9713
9714 if (i == 3 && NILP (how))
9715 {
9716 char color_name[30];
9717 XColor exact, color;
9718 Colormap cmap;
9719
9720 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
9721
9722 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9723 if (XLookupColor (dpy, cmap, color_name, &exact, &color))
9724 {
9725 bg = color.pixel;
9726 look_at_corners_p = 0;
9727 }
9728 }
9729 }
9730
9731 if (look_at_corners_p)
9732 {
9733 unsigned long corners[4];
9734 int i, best_count;
9735
9736 /* Get the colors at the corners of ximg. */
9737 corners[0] = XGetPixel (ximg, 0, 0);
9738 corners[1] = XGetPixel (ximg, img->width - 1, 0);
9739 corners[2] = XGetPixel (ximg, img->width - 1, img->height - 1);
9740 corners[3] = XGetPixel (ximg, 0, img->height - 1);
9741
9742 /* Choose the most frequently found color as background. */
9743 for (i = best_count = 0; i < 4; ++i)
9744 {
9745 int j, n;
9746
9747 for (j = n = 0; j < 4; ++j)
9748 if (corners[i] == corners[j])
9749 ++n;
9750
9751 if (n > best_count)
9752 bg = corners[i], best_count = n;
9753 }
9754 }
9755
9756 /* Set all bits in mask_img to 1 whose color in ximg is different
9757 from the background color bg. */
9758 for (y = 0; y < img->height; ++y)
9759 for (x = 0; x < img->width; ++x)
9760 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
9761
9762 /* Put mask_img into img->mask. */
9763 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
9764 x_destroy_x_image (mask_img);
9765 XDestroyImage (ximg);
9766
9767 UNBLOCK_INPUT;
9768 #endif /* TODO */
9769
9770 return 1;
9771 }
9772
9773
9774 \f
9775 /***********************************************************************
9776 PBM (mono, gray, color)
9777 ***********************************************************************/
9778 #ifdef HAVE_PBM
9779
9780 static int pbm_image_p P_ ((Lisp_Object object));
9781 static int pbm_load P_ ((struct frame *f, struct image *img));
9782 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
9783
9784 /* The symbol `pbm' identifying images of this type. */
9785
9786 Lisp_Object Qpbm;
9787
9788 /* Indices of image specification fields in gs_format, below. */
9789
9790 enum pbm_keyword_index
9791 {
9792 PBM_TYPE,
9793 PBM_FILE,
9794 PBM_DATA,
9795 PBM_ASCENT,
9796 PBM_MARGIN,
9797 PBM_RELIEF,
9798 PBM_ALGORITHM,
9799 PBM_HEURISTIC_MASK,
9800 PBM_LAST
9801 };
9802
9803 /* Vector of image_keyword structures describing the format
9804 of valid user-defined image specifications. */
9805
9806 static struct image_keyword pbm_format[PBM_LAST] =
9807 {
9808 {":type", IMAGE_SYMBOL_VALUE, 1},
9809 {":file", IMAGE_STRING_VALUE, 0},
9810 {":data", IMAGE_STRING_VALUE, 0},
9811 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9812 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9813 {":relief", IMAGE_INTEGER_VALUE, 0},
9814 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9815 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9816 };
9817
9818 /* Structure describing the image type `pbm'. */
9819
9820 static struct image_type pbm_type =
9821 {
9822 &Qpbm,
9823 pbm_image_p,
9824 pbm_load,
9825 x_clear_image,
9826 NULL
9827 };
9828
9829
9830 /* Return non-zero if OBJECT is a valid PBM image specification. */
9831
9832 static int
9833 pbm_image_p (object)
9834 Lisp_Object object;
9835 {
9836 struct image_keyword fmt[PBM_LAST];
9837
9838 bcopy (pbm_format, fmt, sizeof fmt);
9839
9840 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
9841 || (fmt[PBM_ASCENT].count
9842 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
9843 return 0;
9844
9845 /* Must specify either :data or :file. */
9846 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
9847 }
9848
9849
9850 /* Scan a decimal number from *S and return it. Advance *S while
9851 reading the number. END is the end of the string. Value is -1 at
9852 end of input. */
9853
9854 static int
9855 pbm_scan_number (s, end)
9856 unsigned char **s, *end;
9857 {
9858 int c, val = -1;
9859
9860 while (*s < end)
9861 {
9862 /* Skip white-space. */
9863 while (*s < end && (c = *(*s)++, isspace (c)))
9864 ;
9865
9866 if (c == '#')
9867 {
9868 /* Skip comment to end of line. */
9869 while (*s < end && (c = *(*s)++, c != '\n'))
9870 ;
9871 }
9872 else if (isdigit (c))
9873 {
9874 /* Read decimal number. */
9875 val = c - '0';
9876 while (*s < end && (c = *(*s)++, isdigit (c)))
9877 val = 10 * val + c - '0';
9878 break;
9879 }
9880 else
9881 break;
9882 }
9883
9884 return val;
9885 }
9886
9887
9888 /* Read FILE into memory. Value is a pointer to a buffer allocated
9889 with xmalloc holding FILE's contents. Value is null if an error
9890 occured. *SIZE is set to the size of the file. */
9891
9892 static char *
9893 pbm_read_file (file, size)
9894 Lisp_Object file;
9895 int *size;
9896 {
9897 FILE *fp = NULL;
9898 char *buf = NULL;
9899 struct stat st;
9900
9901 if (stat (XSTRING (file)->data, &st) == 0
9902 && (fp = fopen (XSTRING (file)->data, "r")) != NULL
9903 && (buf = (char *) xmalloc (st.st_size),
9904 fread (buf, 1, st.st_size, fp) == st.st_size))
9905 {
9906 *size = st.st_size;
9907 fclose (fp);
9908 }
9909 else
9910 {
9911 if (fp)
9912 fclose (fp);
9913 if (buf)
9914 {
9915 xfree (buf);
9916 buf = NULL;
9917 }
9918 }
9919
9920 return buf;
9921 }
9922
9923
9924 /* Load PBM image IMG for use on frame F. */
9925
9926 static int
9927 pbm_load (f, img)
9928 struct frame *f;
9929 struct image *img;
9930 {
9931 int raw_p, x, y;
9932 int width, height, max_color_idx = 0;
9933 XImage *ximg;
9934 Lisp_Object file, specified_file;
9935 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
9936 struct gcpro gcpro1;
9937 unsigned char *contents = NULL;
9938 unsigned char *end, *p;
9939 int size;
9940
9941 specified_file = image_spec_value (img->spec, QCfile, NULL);
9942 file = Qnil;
9943 GCPRO1 (file);
9944
9945 if (STRINGP (specified_file))
9946 {
9947 file = x_find_image_file (specified_file);
9948 if (!STRINGP (file))
9949 {
9950 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9951 UNGCPRO;
9952 return 0;
9953 }
9954
9955 contents = pbm_read_file (file, &size);
9956 if (contents == NULL)
9957 {
9958 image_error ("Error reading `%s'", file, Qnil);
9959 UNGCPRO;
9960 return 0;
9961 }
9962
9963 p = contents;
9964 end = contents + size;
9965 }
9966 else
9967 {
9968 Lisp_Object data;
9969 data = image_spec_value (img->spec, QCdata, NULL);
9970 p = XSTRING (data)->data;
9971 end = p + STRING_BYTES (XSTRING (data));
9972 }
9973
9974 /* Check magic number. */
9975 if (end - p < 2 || *p++ != 'P')
9976 {
9977 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
9978 error:
9979 xfree (contents);
9980 UNGCPRO;
9981 return 0;
9982 }
9983
9984 switch (*p++)
9985 {
9986 case '1':
9987 raw_p = 0, type = PBM_MONO;
9988 break;
9989
9990 case '2':
9991 raw_p = 0, type = PBM_GRAY;
9992 break;
9993
9994 case '3':
9995 raw_p = 0, type = PBM_COLOR;
9996 break;
9997
9998 case '4':
9999 raw_p = 1, type = PBM_MONO;
10000 break;
10001
10002 case '5':
10003 raw_p = 1, type = PBM_GRAY;
10004 break;
10005
10006 case '6':
10007 raw_p = 1, type = PBM_COLOR;
10008 break;
10009
10010 default:
10011 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10012 goto error;
10013 }
10014
10015 /* Read width, height, maximum color-component. Characters
10016 starting with `#' up to the end of a line are ignored. */
10017 width = pbm_scan_number (&p, end);
10018 height = pbm_scan_number (&p, end);
10019
10020 if (type != PBM_MONO)
10021 {
10022 max_color_idx = pbm_scan_number (&p, end);
10023 if (raw_p && max_color_idx > 255)
10024 max_color_idx = 255;
10025 }
10026
10027 if (width < 0
10028 || height < 0
10029 || (type != PBM_MONO && max_color_idx < 0))
10030 goto error;
10031
10032 BLOCK_INPUT;
10033 if (!x_create_x_image_and_pixmap (f, width, height, 0,
10034 &ximg, &img->pixmap))
10035 {
10036 UNBLOCK_INPUT;
10037 goto error;
10038 }
10039
10040 /* Initialize the color hash table. */
10041 init_color_table ();
10042
10043 if (type == PBM_MONO)
10044 {
10045 int c = 0, g;
10046
10047 for (y = 0; y < height; ++y)
10048 for (x = 0; x < width; ++x)
10049 {
10050 if (raw_p)
10051 {
10052 if ((x & 7) == 0)
10053 c = *p++;
10054 g = c & 0x80;
10055 c <<= 1;
10056 }
10057 else
10058 g = pbm_scan_number (&p, end);
10059
10060 XPutPixel (ximg, x, y, (g
10061 ? FRAME_FOREGROUND_PIXEL (f)
10062 : FRAME_BACKGROUND_PIXEL (f)));
10063 }
10064 }
10065 else
10066 {
10067 for (y = 0; y < height; ++y)
10068 for (x = 0; x < width; ++x)
10069 {
10070 int r, g, b;
10071
10072 if (type == PBM_GRAY)
10073 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
10074 else if (raw_p)
10075 {
10076 r = *p++;
10077 g = *p++;
10078 b = *p++;
10079 }
10080 else
10081 {
10082 r = pbm_scan_number (&p, end);
10083 g = pbm_scan_number (&p, end);
10084 b = pbm_scan_number (&p, end);
10085 }
10086
10087 if (r < 0 || g < 0 || b < 0)
10088 {
10089 xfree (ximg->data);
10090 ximg->data = NULL;
10091 XDestroyImage (ximg);
10092 UNBLOCK_INPUT;
10093 image_error ("Invalid pixel value in image `%s'",
10094 img->spec, Qnil);
10095 goto error;
10096 }
10097
10098 /* RGB values are now in the range 0..max_color_idx.
10099 Scale this to the range 0..0xffff supported by X. */
10100 r = (double) r * 65535 / max_color_idx;
10101 g = (double) g * 65535 / max_color_idx;
10102 b = (double) b * 65535 / max_color_idx;
10103 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10104 }
10105 }
10106
10107 /* Store in IMG->colors the colors allocated for the image, and
10108 free the color table. */
10109 img->colors = colors_in_color_table (&img->ncolors);
10110 free_color_table ();
10111
10112 /* Put the image into a pixmap. */
10113 x_put_x_image (f, ximg, img->pixmap, width, height);
10114 x_destroy_x_image (ximg);
10115 UNBLOCK_INPUT;
10116
10117 img->width = width;
10118 img->height = height;
10119
10120 UNGCPRO;
10121 xfree (contents);
10122 return 1;
10123 }
10124 #endif /* HAVE_PBM */
10125
10126 \f
10127 /***********************************************************************
10128 PNG
10129 ***********************************************************************/
10130
10131 #if HAVE_PNG
10132
10133 #include <png.h>
10134
10135 /* Function prototypes. */
10136
10137 static int png_image_p P_ ((Lisp_Object object));
10138 static int png_load P_ ((struct frame *f, struct image *img));
10139
10140 /* The symbol `png' identifying images of this type. */
10141
10142 Lisp_Object Qpng;
10143
10144 /* Indices of image specification fields in png_format, below. */
10145
10146 enum png_keyword_index
10147 {
10148 PNG_TYPE,
10149 PNG_DATA,
10150 PNG_FILE,
10151 PNG_ASCENT,
10152 PNG_MARGIN,
10153 PNG_RELIEF,
10154 PNG_ALGORITHM,
10155 PNG_HEURISTIC_MASK,
10156 PNG_LAST
10157 };
10158
10159 /* Vector of image_keyword structures describing the format
10160 of valid user-defined image specifications. */
10161
10162 static struct image_keyword png_format[PNG_LAST] =
10163 {
10164 {":type", IMAGE_SYMBOL_VALUE, 1},
10165 {":data", IMAGE_STRING_VALUE, 0},
10166 {":file", IMAGE_STRING_VALUE, 0},
10167 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10168 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10169 {":relief", IMAGE_INTEGER_VALUE, 0},
10170 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10171 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10172 };
10173
10174 /* Structure describing the image type `png'. */
10175
10176 static struct image_type png_type =
10177 {
10178 &Qpng,
10179 png_image_p,
10180 png_load,
10181 x_clear_image,
10182 NULL
10183 };
10184
10185
10186 /* Return non-zero if OBJECT is a valid PNG image specification. */
10187
10188 static int
10189 png_image_p (object)
10190 Lisp_Object object;
10191 {
10192 struct image_keyword fmt[PNG_LAST];
10193 bcopy (png_format, fmt, sizeof fmt);
10194
10195 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
10196 || (fmt[PNG_ASCENT].count
10197 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
10198 return 0;
10199
10200 /* Must specify either the :data or :file keyword. */
10201 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
10202 }
10203
10204
10205 /* Error and warning handlers installed when the PNG library
10206 is initialized. */
10207
10208 static void
10209 my_png_error (png_ptr, msg)
10210 png_struct *png_ptr;
10211 char *msg;
10212 {
10213 xassert (png_ptr != NULL);
10214 image_error ("PNG error: %s", build_string (msg), Qnil);
10215 longjmp (png_ptr->jmpbuf, 1);
10216 }
10217
10218
10219 static void
10220 my_png_warning (png_ptr, msg)
10221 png_struct *png_ptr;
10222 char *msg;
10223 {
10224 xassert (png_ptr != NULL);
10225 image_error ("PNG warning: %s", build_string (msg), Qnil);
10226 }
10227
10228 /* Memory source for PNG decoding. */
10229
10230 struct png_memory_storage
10231 {
10232 unsigned char *bytes; /* The data */
10233 size_t len; /* How big is it? */
10234 int index; /* Where are we? */
10235 };
10236
10237
10238 /* Function set as reader function when reading PNG image from memory.
10239 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
10240 bytes from the input to DATA. */
10241
10242 static void
10243 png_read_from_memory (png_ptr, data, length)
10244 png_structp png_ptr;
10245 png_bytep data;
10246 png_size_t length;
10247 {
10248 struct png_memory_storage *tbr
10249 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
10250
10251 if (length > tbr->len - tbr->index)
10252 png_error (png_ptr, "Read error");
10253
10254 bcopy (tbr->bytes + tbr->index, data, length);
10255 tbr->index = tbr->index + length;
10256 }
10257
10258 /* Load PNG image IMG for use on frame F. Value is non-zero if
10259 successful. */
10260
10261 static int
10262 png_load (f, img)
10263 struct frame *f;
10264 struct image *img;
10265 {
10266 Lisp_Object file, specified_file;
10267 Lisp_Object specified_data;
10268 int x, y, i;
10269 XImage *ximg, *mask_img = NULL;
10270 struct gcpro gcpro1;
10271 png_struct *png_ptr = NULL;
10272 png_info *info_ptr = NULL, *end_info = NULL;
10273 FILE *fp = NULL;
10274 png_byte sig[8];
10275 png_byte *pixels = NULL;
10276 png_byte **rows = NULL;
10277 png_uint_32 width, height;
10278 int bit_depth, color_type, interlace_type;
10279 png_byte channels;
10280 png_uint_32 row_bytes;
10281 int transparent_p;
10282 char *gamma_str;
10283 double screen_gamma, image_gamma;
10284 int intent;
10285 struct png_memory_storage tbr; /* Data to be read */
10286
10287 /* Find out what file to load. */
10288 specified_file = image_spec_value (img->spec, QCfile, NULL);
10289 specified_data = image_spec_value (img->spec, QCdata, NULL);
10290 file = Qnil;
10291 GCPRO1 (file);
10292
10293 if (NILP (specified_data))
10294 {
10295 file = x_find_image_file (specified_file);
10296 if (!STRINGP (file))
10297 {
10298 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10299 UNGCPRO;
10300 return 0;
10301 }
10302
10303 /* Open the image file. */
10304 fp = fopen (XSTRING (file)->data, "rb");
10305 if (!fp)
10306 {
10307 image_error ("Cannot open image file `%s'", file, Qnil);
10308 UNGCPRO;
10309 fclose (fp);
10310 return 0;
10311 }
10312
10313 /* Check PNG signature. */
10314 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
10315 || !png_check_sig (sig, sizeof sig))
10316 {
10317 image_error ("Not a PNG file:` %s'", file, Qnil);
10318 UNGCPRO;
10319 fclose (fp);
10320 return 0;
10321 }
10322 }
10323 else
10324 {
10325 /* Read from memory. */
10326 tbr.bytes = XSTRING (specified_data)->data;
10327 tbr.len = STRING_BYTES (XSTRING (specified_data));
10328 tbr.index = 0;
10329
10330 /* Check PNG signature. */
10331 if (tbr.len < sizeof sig
10332 || !png_check_sig (tbr.bytes, sizeof sig))
10333 {
10334 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10335 UNGCPRO;
10336 return 0;
10337 }
10338
10339 /* Need to skip past the signature. */
10340 tbr.bytes += sizeof (sig);
10341 }
10342
10343 /* Initialize read and info structs for PNG lib. */
10344 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10345 my_png_error, my_png_warning);
10346 if (!png_ptr)
10347 {
10348 if (fp) fclose (fp);
10349 UNGCPRO;
10350 return 0;
10351 }
10352
10353 info_ptr = png_create_info_struct (png_ptr);
10354 if (!info_ptr)
10355 {
10356 png_destroy_read_struct (&png_ptr, NULL, NULL);
10357 if (fp) fclose (fp);
10358 UNGCPRO;
10359 return 0;
10360 }
10361
10362 end_info = png_create_info_struct (png_ptr);
10363 if (!end_info)
10364 {
10365 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
10366 if (fp) fclose (fp);
10367 UNGCPRO;
10368 return 0;
10369 }
10370
10371 /* Set error jump-back. We come back here when the PNG library
10372 detects an error. */
10373 if (setjmp (png_ptr->jmpbuf))
10374 {
10375 error:
10376 if (png_ptr)
10377 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10378 xfree (pixels);
10379 xfree (rows);
10380 if (fp) fclose (fp);
10381 UNGCPRO;
10382 return 0;
10383 }
10384
10385 /* Read image info. */
10386 if (!NILP (specified_data))
10387 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
10388 else
10389 png_init_io (png_ptr, fp);
10390
10391 png_set_sig_bytes (png_ptr, sizeof sig);
10392 png_read_info (png_ptr, info_ptr);
10393 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10394 &interlace_type, NULL, NULL);
10395
10396 /* If image contains simply transparency data, we prefer to
10397 construct a clipping mask. */
10398 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
10399 transparent_p = 1;
10400 else
10401 transparent_p = 0;
10402
10403 /* This function is easier to write if we only have to handle
10404 one data format: RGB or RGBA with 8 bits per channel. Let's
10405 transform other formats into that format. */
10406
10407 /* Strip more than 8 bits per channel. */
10408 if (bit_depth == 16)
10409 png_set_strip_16 (png_ptr);
10410
10411 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10412 if available. */
10413 png_set_expand (png_ptr);
10414
10415 /* Convert grayscale images to RGB. */
10416 if (color_type == PNG_COLOR_TYPE_GRAY
10417 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
10418 png_set_gray_to_rgb (png_ptr);
10419
10420 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
10421 gamma_str = getenv ("SCREEN_GAMMA");
10422 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
10423
10424 /* Tell the PNG lib to handle gamma correction for us. */
10425
10426 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10427 if (png_get_sRGB (png_ptr, info_ptr, &intent))
10428 /* There is a special chunk in the image specifying the gamma. */
10429 png_set_sRGB (png_ptr, info_ptr, intent);
10430 else
10431 #endif
10432 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10433 /* Image contains gamma information. */
10434 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10435 else
10436 /* Use a default of 0.5 for the image gamma. */
10437 png_set_gamma (png_ptr, screen_gamma, 0.5);
10438
10439 /* Handle alpha channel by combining the image with a background
10440 color. Do this only if a real alpha channel is supplied. For
10441 simple transparency, we prefer a clipping mask. */
10442 if (!transparent_p)
10443 {
10444 png_color_16 *image_background;
10445
10446 if (png_get_bKGD (png_ptr, info_ptr, &image_background))
10447 /* Image contains a background color with which to
10448 combine the image. */
10449 png_set_background (png_ptr, image_background,
10450 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
10451 else
10452 {
10453 /* Image does not contain a background color with which
10454 to combine the image data via an alpha channel. Use
10455 the frame's background instead. */
10456 XColor color;
10457 Colormap cmap;
10458 png_color_16 frame_background;
10459
10460 BLOCK_INPUT;
10461 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10462 color.pixel = FRAME_BACKGROUND_PIXEL (f);
10463 XQueryColor (FRAME_W32_DISPLAY (f), cmap, &color);
10464 UNBLOCK_INPUT;
10465
10466 bzero (&frame_background, sizeof frame_background);
10467 frame_background.red = color.red;
10468 frame_background.green = color.green;
10469 frame_background.blue = color.blue;
10470
10471 png_set_background (png_ptr, &frame_background,
10472 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10473 }
10474 }
10475
10476 /* Update info structure. */
10477 png_read_update_info (png_ptr, info_ptr);
10478
10479 /* Get number of channels. Valid values are 1 for grayscale images
10480 and images with a palette, 2 for grayscale images with transparency
10481 information (alpha channel), 3 for RGB images, and 4 for RGB
10482 images with alpha channel, i.e. RGBA. If conversions above were
10483 sufficient we should only have 3 or 4 channels here. */
10484 channels = png_get_channels (png_ptr, info_ptr);
10485 xassert (channels == 3 || channels == 4);
10486
10487 /* Number of bytes needed for one row of the image. */
10488 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
10489
10490 /* Allocate memory for the image. */
10491 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10492 rows = (png_byte **) xmalloc (height * sizeof *rows);
10493 for (i = 0; i < height; ++i)
10494 rows[i] = pixels + i * row_bytes;
10495
10496 /* Read the entire image. */
10497 png_read_image (png_ptr, rows);
10498 png_read_end (png_ptr, info_ptr);
10499 if (fp)
10500 {
10501 fclose (fp);
10502 fp = NULL;
10503 }
10504
10505 BLOCK_INPUT;
10506
10507 /* Create the X image and pixmap. */
10508 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10509 &img->pixmap))
10510 {
10511 UNBLOCK_INPUT;
10512 goto error;
10513 }
10514
10515 /* Create an image and pixmap serving as mask if the PNG image
10516 contains an alpha channel. */
10517 if (channels == 4
10518 && !transparent_p
10519 && !x_create_x_image_and_pixmap (f, width, height, 1,
10520 &mask_img, &img->mask))
10521 {
10522 x_destroy_x_image (ximg);
10523 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
10524 img->pixmap = 0;
10525 UNBLOCK_INPUT;
10526 goto error;
10527 }
10528
10529 /* Fill the X image and mask from PNG data. */
10530 init_color_table ();
10531
10532 for (y = 0; y < height; ++y)
10533 {
10534 png_byte *p = rows[y];
10535
10536 for (x = 0; x < width; ++x)
10537 {
10538 unsigned r, g, b;
10539
10540 r = *p++ << 8;
10541 g = *p++ << 8;
10542 b = *p++ << 8;
10543 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10544
10545 /* An alpha channel, aka mask channel, associates variable
10546 transparency with an image. Where other image formats
10547 support binary transparency---fully transparent or fully
10548 opaque---PNG allows up to 254 levels of partial transparency.
10549 The PNG library implements partial transparency by combining
10550 the image with a specified background color.
10551
10552 I'm not sure how to handle this here nicely: because the
10553 background on which the image is displayed may change, for
10554 real alpha channel support, it would be necessary to create
10555 a new image for each possible background.
10556
10557 What I'm doing now is that a mask is created if we have
10558 boolean transparency information. Otherwise I'm using
10559 the frame's background color to combine the image with. */
10560
10561 if (channels == 4)
10562 {
10563 if (mask_img)
10564 XPutPixel (mask_img, x, y, *p > 0);
10565 ++p;
10566 }
10567 }
10568 }
10569
10570 /* Remember colors allocated for this image. */
10571 img->colors = colors_in_color_table (&img->ncolors);
10572 free_color_table ();
10573
10574 /* Clean up. */
10575 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10576 xfree (rows);
10577 xfree (pixels);
10578
10579 img->width = width;
10580 img->height = height;
10581
10582 /* Put the image into the pixmap, then free the X image and its buffer. */
10583 x_put_x_image (f, ximg, img->pixmap, width, height);
10584 x_destroy_x_image (ximg);
10585
10586 /* Same for the mask. */
10587 if (mask_img)
10588 {
10589 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10590 x_destroy_x_image (mask_img);
10591 }
10592
10593 UNBLOCK_INPUT;
10594 UNGCPRO;
10595 return 1;
10596 }
10597
10598 #endif /* HAVE_PNG != 0 */
10599
10600
10601 \f
10602 /***********************************************************************
10603 JPEG
10604 ***********************************************************************/
10605
10606 #if HAVE_JPEG
10607
10608 /* Work around a warning about HAVE_STDLIB_H being redefined in
10609 jconfig.h. */
10610 #ifdef HAVE_STDLIB_H
10611 #define HAVE_STDLIB_H_1
10612 #undef HAVE_STDLIB_H
10613 #endif /* HAVE_STLIB_H */
10614
10615 #include <jpeglib.h>
10616 #include <jerror.h>
10617 #include <setjmp.h>
10618
10619 #ifdef HAVE_STLIB_H_1
10620 #define HAVE_STDLIB_H 1
10621 #endif
10622
10623 static int jpeg_image_p P_ ((Lisp_Object object));
10624 static int jpeg_load P_ ((struct frame *f, struct image *img));
10625
10626 /* The symbol `jpeg' identifying images of this type. */
10627
10628 Lisp_Object Qjpeg;
10629
10630 /* Indices of image specification fields in gs_format, below. */
10631
10632 enum jpeg_keyword_index
10633 {
10634 JPEG_TYPE,
10635 JPEG_DATA,
10636 JPEG_FILE,
10637 JPEG_ASCENT,
10638 JPEG_MARGIN,
10639 JPEG_RELIEF,
10640 JPEG_ALGORITHM,
10641 JPEG_HEURISTIC_MASK,
10642 JPEG_LAST
10643 };
10644
10645 /* Vector of image_keyword structures describing the format
10646 of valid user-defined image specifications. */
10647
10648 static struct image_keyword jpeg_format[JPEG_LAST] =
10649 {
10650 {":type", IMAGE_SYMBOL_VALUE, 1},
10651 {":data", IMAGE_STRING_VALUE, 0},
10652 {":file", IMAGE_STRING_VALUE, 0},
10653 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10654 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10655 {":relief", IMAGE_INTEGER_VALUE, 0},
10656 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10657 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10658 };
10659
10660 /* Structure describing the image type `jpeg'. */
10661
10662 static struct image_type jpeg_type =
10663 {
10664 &Qjpeg,
10665 jpeg_image_p,
10666 jpeg_load,
10667 x_clear_image,
10668 NULL
10669 };
10670
10671
10672 /* Return non-zero if OBJECT is a valid JPEG image specification. */
10673
10674 static int
10675 jpeg_image_p (object)
10676 Lisp_Object object;
10677 {
10678 struct image_keyword fmt[JPEG_LAST];
10679
10680 bcopy (jpeg_format, fmt, sizeof fmt);
10681
10682 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
10683 || (fmt[JPEG_ASCENT].count
10684 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
10685 return 0;
10686
10687 /* Must specify either the :data or :file keyword. */
10688 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
10689 }
10690
10691
10692 struct my_jpeg_error_mgr
10693 {
10694 struct jpeg_error_mgr pub;
10695 jmp_buf setjmp_buffer;
10696 };
10697
10698 static void
10699 my_error_exit (cinfo)
10700 j_common_ptr cinfo;
10701 {
10702 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
10703 longjmp (mgr->setjmp_buffer, 1);
10704 }
10705
10706 /* Init source method for JPEG data source manager. Called by
10707 jpeg_read_header() before any data is actually read. See
10708 libjpeg.doc from the JPEG lib distribution. */
10709
10710 static void
10711 our_init_source (cinfo)
10712 j_decompress_ptr cinfo;
10713 {
10714 }
10715
10716
10717 /* Fill input buffer method for JPEG data source manager. Called
10718 whenever more data is needed. We read the whole image in one step,
10719 so this only adds a fake end of input marker at the end. */
10720
10721 static boolean
10722 our_fill_input_buffer (cinfo)
10723 j_decompress_ptr cinfo;
10724 {
10725 /* Insert a fake EOI marker. */
10726 struct jpeg_source_mgr *src = cinfo->src;
10727 static JOCTET buffer[2];
10728
10729 buffer[0] = (JOCTET) 0xFF;
10730 buffer[1] = (JOCTET) JPEG_EOI;
10731
10732 src->next_input_byte = buffer;
10733 src->bytes_in_buffer = 2;
10734 return TRUE;
10735 }
10736
10737
10738 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
10739 is the JPEG data source manager. */
10740
10741 static void
10742 our_skip_input_data (cinfo, num_bytes)
10743 j_decompress_ptr cinfo;
10744 long num_bytes;
10745 {
10746 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
10747
10748 if (src)
10749 {
10750 if (num_bytes > src->bytes_in_buffer)
10751 ERREXIT (cinfo, JERR_INPUT_EOF);
10752
10753 src->bytes_in_buffer -= num_bytes;
10754 src->next_input_byte += num_bytes;
10755 }
10756 }
10757
10758
10759 /* Method to terminate data source. Called by
10760 jpeg_finish_decompress() after all data has been processed. */
10761
10762 static void
10763 our_term_source (cinfo)
10764 j_decompress_ptr cinfo;
10765 {
10766 }
10767
10768
10769 /* Set up the JPEG lib for reading an image from DATA which contains
10770 LEN bytes. CINFO is the decompression info structure created for
10771 reading the image. */
10772
10773 static void
10774 jpeg_memory_src (cinfo, data, len)
10775 j_decompress_ptr cinfo;
10776 JOCTET *data;
10777 unsigned int len;
10778 {
10779 struct jpeg_source_mgr *src;
10780
10781 if (cinfo->src == NULL)
10782 {
10783 /* First time for this JPEG object? */
10784 cinfo->src = (struct jpeg_source_mgr *)
10785 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
10786 sizeof (struct jpeg_source_mgr));
10787 src = (struct jpeg_source_mgr *) cinfo->src;
10788 src->next_input_byte = data;
10789 }
10790
10791 src = (struct jpeg_source_mgr *) cinfo->src;
10792 src->init_source = our_init_source;
10793 src->fill_input_buffer = our_fill_input_buffer;
10794 src->skip_input_data = our_skip_input_data;
10795 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
10796 src->term_source = our_term_source;
10797 src->bytes_in_buffer = len;
10798 src->next_input_byte = data;
10799 }
10800
10801
10802 /* Load image IMG for use on frame F. Patterned after example.c
10803 from the JPEG lib. */
10804
10805 static int
10806 jpeg_load (f, img)
10807 struct frame *f;
10808 struct image *img;
10809 {
10810 struct jpeg_decompress_struct cinfo;
10811 struct my_jpeg_error_mgr mgr;
10812 Lisp_Object file, specified_file;
10813 Lisp_Object specified_data;
10814 FILE *fp = NULL;
10815 JSAMPARRAY buffer;
10816 int row_stride, x, y;
10817 XImage *ximg = NULL;
10818 int rc;
10819 unsigned long *colors;
10820 int width, height;
10821 struct gcpro gcpro1;
10822
10823 /* Open the JPEG file. */
10824 specified_file = image_spec_value (img->spec, QCfile, NULL);
10825 specified_data = image_spec_value (img->spec, QCdata, NULL);
10826 file = Qnil;
10827 GCPRO1 (file);
10828
10829 if (NILP (specified_data))
10830 {
10831 file = x_find_image_file (specified_file);
10832 if (!STRINGP (file))
10833 {
10834 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10835 UNGCPRO;
10836 return 0;
10837 }
10838
10839 fp = fopen (XSTRING (file)->data, "r");
10840 if (fp == NULL)
10841 {
10842 image_error ("Cannot open `%s'", file, Qnil);
10843 UNGCPRO;
10844 return 0;
10845 }
10846 }
10847
10848 /* Customize libjpeg's error handling to call my_error_exit when an
10849 error is detected. This function will perform a longjmp. */
10850 mgr.pub.error_exit = my_error_exit;
10851 cinfo.err = jpeg_std_error (&mgr.pub);
10852
10853 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
10854 {
10855 if (rc == 1)
10856 {
10857 /* Called from my_error_exit. Display a JPEG error. */
10858 char buffer[JMSG_LENGTH_MAX];
10859 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
10860 image_error ("Error reading JPEG image `%s': %s", img->spec,
10861 build_string (buffer));
10862 }
10863
10864 /* Close the input file and destroy the JPEG object. */
10865 if (fp)
10866 fclose (fp);
10867 jpeg_destroy_decompress (&cinfo);
10868
10869 BLOCK_INPUT;
10870
10871 /* If we already have an XImage, free that. */
10872 x_destroy_x_image (ximg);
10873
10874 /* Free pixmap and colors. */
10875 x_clear_image (f, img);
10876
10877 UNBLOCK_INPUT;
10878 UNGCPRO;
10879 return 0;
10880 }
10881
10882 /* Create the JPEG decompression object. Let it read from fp.
10883 Read the JPEG image header. */
10884 jpeg_create_decompress (&cinfo);
10885
10886 if (NILP (specified_data))
10887 jpeg_stdio_src (&cinfo, fp);
10888 else
10889 jpeg_memory_src (&cinfo, XSTRING (specified_data)->data,
10890 STRING_BYTES (XSTRING (specified_data)));
10891
10892 jpeg_read_header (&cinfo, TRUE);
10893
10894 /* Customize decompression so that color quantization will be used.
10895 Start decompression. */
10896 cinfo.quantize_colors = TRUE;
10897 jpeg_start_decompress (&cinfo);
10898 width = img->width = cinfo.output_width;
10899 height = img->height = cinfo.output_height;
10900
10901 BLOCK_INPUT;
10902
10903 /* Create X image and pixmap. */
10904 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10905 &img->pixmap))
10906 {
10907 UNBLOCK_INPUT;
10908 longjmp (mgr.setjmp_buffer, 2);
10909 }
10910
10911 /* Allocate colors. When color quantization is used,
10912 cinfo.actual_number_of_colors has been set with the number of
10913 colors generated, and cinfo.colormap is a two-dimensional array
10914 of color indices in the range 0..cinfo.actual_number_of_colors.
10915 No more than 255 colors will be generated. */
10916 {
10917 int i, ir, ig, ib;
10918
10919 if (cinfo.out_color_components > 2)
10920 ir = 0, ig = 1, ib = 2;
10921 else if (cinfo.out_color_components > 1)
10922 ir = 0, ig = 1, ib = 0;
10923 else
10924 ir = 0, ig = 0, ib = 0;
10925
10926 /* Use the color table mechanism because it handles colors that
10927 cannot be allocated nicely. Such colors will be replaced with
10928 a default color, and we don't have to care about which colors
10929 can be freed safely, and which can't. */
10930 init_color_table ();
10931 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
10932 * sizeof *colors);
10933
10934 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
10935 {
10936 /* Multiply RGB values with 255 because X expects RGB values
10937 in the range 0..0xffff. */
10938 int r = cinfo.colormap[ir][i] << 8;
10939 int g = cinfo.colormap[ig][i] << 8;
10940 int b = cinfo.colormap[ib][i] << 8;
10941 colors[i] = lookup_rgb_color (f, r, g, b);
10942 }
10943
10944 /* Remember those colors actually allocated. */
10945 img->colors = colors_in_color_table (&img->ncolors);
10946 free_color_table ();
10947 }
10948
10949 /* Read pixels. */
10950 row_stride = width * cinfo.output_components;
10951 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
10952 row_stride, 1);
10953 for (y = 0; y < height; ++y)
10954 {
10955 jpeg_read_scanlines (&cinfo, buffer, 1);
10956 for (x = 0; x < cinfo.output_width; ++x)
10957 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
10958 }
10959
10960 /* Clean up. */
10961 jpeg_finish_decompress (&cinfo);
10962 jpeg_destroy_decompress (&cinfo);
10963 if (fp)
10964 fclose (fp);
10965
10966 /* Put the image into the pixmap. */
10967 x_put_x_image (f, ximg, img->pixmap, width, height);
10968 x_destroy_x_image (ximg);
10969 UNBLOCK_INPUT;
10970 UNGCPRO;
10971 return 1;
10972 }
10973
10974 #endif /* HAVE_JPEG */
10975
10976
10977 \f
10978 /***********************************************************************
10979 TIFF
10980 ***********************************************************************/
10981
10982 #if HAVE_TIFF
10983
10984 #include <tiffio.h>
10985
10986 static int tiff_image_p P_ ((Lisp_Object object));
10987 static int tiff_load P_ ((struct frame *f, struct image *img));
10988
10989 /* The symbol `tiff' identifying images of this type. */
10990
10991 Lisp_Object Qtiff;
10992
10993 /* Indices of image specification fields in tiff_format, below. */
10994
10995 enum tiff_keyword_index
10996 {
10997 TIFF_TYPE,
10998 TIFF_DATA,
10999 TIFF_FILE,
11000 TIFF_ASCENT,
11001 TIFF_MARGIN,
11002 TIFF_RELIEF,
11003 TIFF_ALGORITHM,
11004 TIFF_HEURISTIC_MASK,
11005 TIFF_LAST
11006 };
11007
11008 /* Vector of image_keyword structures describing the format
11009 of valid user-defined image specifications. */
11010
11011 static struct image_keyword tiff_format[TIFF_LAST] =
11012 {
11013 {":type", IMAGE_SYMBOL_VALUE, 1},
11014 {":data", IMAGE_STRING_VALUE, 0},
11015 {":file", IMAGE_STRING_VALUE, 0},
11016 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11017 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11018 {":relief", IMAGE_INTEGER_VALUE, 0},
11019 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11020 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11021 };
11022
11023 /* Structure describing the image type `tiff'. */
11024
11025 static struct image_type tiff_type =
11026 {
11027 &Qtiff,
11028 tiff_image_p,
11029 tiff_load,
11030 x_clear_image,
11031 NULL
11032 };
11033
11034
11035 /* Return non-zero if OBJECT is a valid TIFF image specification. */
11036
11037 static int
11038 tiff_image_p (object)
11039 Lisp_Object object;
11040 {
11041 struct image_keyword fmt[TIFF_LAST];
11042 bcopy (tiff_format, fmt, sizeof fmt);
11043
11044 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
11045 || (fmt[TIFF_ASCENT].count
11046 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
11047 return 0;
11048
11049 /* Must specify either the :data or :file keyword. */
11050 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
11051 }
11052
11053
11054 /* Reading from a memory buffer for TIFF images Based on the PNG
11055 memory source, but we have to provide a lot of extra functions.
11056 Blah.
11057
11058 We really only need to implement read and seek, but I am not
11059 convinced that the TIFF library is smart enough not to destroy
11060 itself if we only hand it the function pointers we need to
11061 override. */
11062
11063 typedef struct
11064 {
11065 unsigned char *bytes;
11066 size_t len;
11067 int index;
11068 }
11069 tiff_memory_source;
11070
11071 static size_t
11072 tiff_read_from_memory (data, buf, size)
11073 thandle_t data;
11074 tdata_t buf;
11075 tsize_t size;
11076 {
11077 tiff_memory_source *src = (tiff_memory_source *) data;
11078
11079 if (size > src->len - src->index)
11080 return (size_t) -1;
11081 bcopy (src->bytes + src->index, buf, size);
11082 src->index += size;
11083 return size;
11084 }
11085
11086 static size_t
11087 tiff_write_from_memory (data, buf, size)
11088 thandle_t data;
11089 tdata_t buf;
11090 tsize_t size;
11091 {
11092 return (size_t) -1;
11093 }
11094
11095 static toff_t
11096 tiff_seek_in_memory (data, off, whence)
11097 thandle_t data;
11098 toff_t off;
11099 int whence;
11100 {
11101 tiff_memory_source *src = (tiff_memory_source *) data;
11102 int idx;
11103
11104 switch (whence)
11105 {
11106 case SEEK_SET: /* Go from beginning of source. */
11107 idx = off;
11108 break;
11109
11110 case SEEK_END: /* Go from end of source. */
11111 idx = src->len + off;
11112 break;
11113
11114 case SEEK_CUR: /* Go from current position. */
11115 idx = src->index + off;
11116 break;
11117
11118 default: /* Invalid `whence'. */
11119 return -1;
11120 }
11121
11122 if (idx > src->len || idx < 0)
11123 return -1;
11124
11125 src->index = idx;
11126 return src->index;
11127 }
11128
11129 static int
11130 tiff_close_memory (data)
11131 thandle_t data;
11132 {
11133 /* NOOP */
11134 return 0;
11135 }
11136
11137 static int
11138 tiff_mmap_memory (data, pbase, psize)
11139 thandle_t data;
11140 tdata_t *pbase;
11141 toff_t *psize;
11142 {
11143 /* It is already _IN_ memory. */
11144 return 0;
11145 }
11146
11147 static void
11148 tiff_unmap_memory (data, base, size)
11149 thandle_t data;
11150 tdata_t base;
11151 toff_t size;
11152 {
11153 /* We don't need to do this. */
11154 }
11155
11156 static toff_t
11157 tiff_size_of_memory (data)
11158 thandle_t data;
11159 {
11160 return ((tiff_memory_source *) data)->len;
11161 }
11162
11163 /* Load TIFF image IMG for use on frame F. Value is non-zero if
11164 successful. */
11165
11166 static int
11167 tiff_load (f, img)
11168 struct frame *f;
11169 struct image *img;
11170 {
11171 Lisp_Object file, specified_file;
11172 Lisp_Object specified_data;
11173 TIFF *tiff;
11174 int width, height, x, y;
11175 uint32 *buf;
11176 int rc;
11177 XImage *ximg;
11178 struct gcpro gcpro1;
11179 tiff_memory_source memsrc;
11180
11181 specified_file = image_spec_value (img->spec, QCfile, NULL);
11182 specified_data = image_spec_value (img->spec, QCdata, NULL);
11183 file = Qnil;
11184 GCPRO1 (file);
11185
11186 if (NILP (specified_data))
11187 {
11188 /* Read from a file */
11189 file = x_find_image_file (specified_file);
11190 if (!STRINGP (file))
11191 {
11192 image_error ("Cannot find image file `%s'", file, Qnil);
11193 UNGCPRO;
11194 return 0;
11195 }
11196
11197 /* Try to open the image file. */
11198 tiff = TIFFOpen (XSTRING (file)->data, "r");
11199 if (tiff == NULL)
11200 {
11201 image_error ("Cannot open `%s'", file, Qnil);
11202 UNGCPRO;
11203 return 0;
11204 }
11205 }
11206 else
11207 {
11208 /* Memory source! */
11209 memsrc.bytes = XSTRING (specified_data)->data;
11210 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11211 memsrc.index = 0;
11212
11213 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
11214 (TIFFReadWriteProc) tiff_read_from_memory,
11215 (TIFFReadWriteProc) tiff_write_from_memory,
11216 tiff_seek_in_memory,
11217 tiff_close_memory,
11218 tiff_size_of_memory,
11219 tiff_mmap_memory,
11220 tiff_unmap_memory);
11221
11222 if (!tiff)
11223 {
11224 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
11225 UNGCPRO;
11226 return 0;
11227 }
11228 }
11229
11230 /* Get width and height of the image, and allocate a raster buffer
11231 of width x height 32-bit values. */
11232 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
11233 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
11234 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
11235
11236 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
11237 TIFFClose (tiff);
11238 if (!rc)
11239 {
11240 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
11241 xfree (buf);
11242 UNGCPRO;
11243 return 0;
11244 }
11245
11246 BLOCK_INPUT;
11247
11248 /* Create the X image and pixmap. */
11249 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11250 {
11251 UNBLOCK_INPUT;
11252 xfree (buf);
11253 UNGCPRO;
11254 return 0;
11255 }
11256
11257 /* Initialize the color table. */
11258 init_color_table ();
11259
11260 /* Process the pixel raster. Origin is in the lower-left corner. */
11261 for (y = 0; y < height; ++y)
11262 {
11263 uint32 *row = buf + y * width;
11264
11265 for (x = 0; x < width; ++x)
11266 {
11267 uint32 abgr = row[x];
11268 int r = TIFFGetR (abgr) << 8;
11269 int g = TIFFGetG (abgr) << 8;
11270 int b = TIFFGetB (abgr) << 8;
11271 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
11272 }
11273 }
11274
11275 /* Remember the colors allocated for the image. Free the color table. */
11276 img->colors = colors_in_color_table (&img->ncolors);
11277 free_color_table ();
11278
11279 /* Put the image into the pixmap, then free the X image and its buffer. */
11280 x_put_x_image (f, ximg, img->pixmap, width, height);
11281 x_destroy_x_image (ximg);
11282 xfree (buf);
11283 UNBLOCK_INPUT;
11284
11285 img->width = width;
11286 img->height = height;
11287
11288 UNGCPRO;
11289 return 1;
11290 }
11291
11292 #endif /* HAVE_TIFF != 0 */
11293
11294
11295 \f
11296 /***********************************************************************
11297 GIF
11298 ***********************************************************************/
11299
11300 #if HAVE_GIF
11301
11302 #include <gif_lib.h>
11303
11304 static int gif_image_p P_ ((Lisp_Object object));
11305 static int gif_load P_ ((struct frame *f, struct image *img));
11306
11307 /* The symbol `gif' identifying images of this type. */
11308
11309 Lisp_Object Qgif;
11310
11311 /* Indices of image specification fields in gif_format, below. */
11312
11313 enum gif_keyword_index
11314 {
11315 GIF_TYPE,
11316 GIF_DATA,
11317 GIF_FILE,
11318 GIF_ASCENT,
11319 GIF_MARGIN,
11320 GIF_RELIEF,
11321 GIF_ALGORITHM,
11322 GIF_HEURISTIC_MASK,
11323 GIF_IMAGE,
11324 GIF_LAST
11325 };
11326
11327 /* Vector of image_keyword structures describing the format
11328 of valid user-defined image specifications. */
11329
11330 static struct image_keyword gif_format[GIF_LAST] =
11331 {
11332 {":type", IMAGE_SYMBOL_VALUE, 1},
11333 {":data", IMAGE_STRING_VALUE, 0},
11334 {":file", IMAGE_STRING_VALUE, 0},
11335 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11336 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11337 {":relief", IMAGE_INTEGER_VALUE, 0},
11338 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11339 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11340 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
11341 };
11342
11343 /* Structure describing the image type `gif'. */
11344
11345 static struct image_type gif_type =
11346 {
11347 &Qgif,
11348 gif_image_p,
11349 gif_load,
11350 x_clear_image,
11351 NULL
11352 };
11353
11354 /* Return non-zero if OBJECT is a valid GIF image specification. */
11355
11356 static int
11357 gif_image_p (object)
11358 Lisp_Object object;
11359 {
11360 struct image_keyword fmt[GIF_LAST];
11361 bcopy (gif_format, fmt, sizeof fmt);
11362
11363 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
11364 || (fmt[GIF_ASCENT].count
11365 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
11366 return 0;
11367
11368 /* Must specify either the :data or :file keyword. */
11369 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11370 }
11371
11372 /* Reading a GIF image from memory
11373 Based on the PNG memory stuff to a certain extent. */
11374
11375 typedef struct
11376 {
11377 unsigned char *bytes;
11378 size_t len;
11379 int index;
11380 }
11381 gif_memory_source;
11382
11383 /* Make the current memory source available to gif_read_from_memory.
11384 It's done this way because not all versions of libungif support
11385 a UserData field in the GifFileType structure. */
11386 static gif_memory_source *current_gif_memory_src;
11387
11388 static int
11389 gif_read_from_memory (file, buf, len)
11390 GifFileType *file;
11391 GifByteType *buf;
11392 int len;
11393 {
11394 gif_memory_source *src = current_gif_memory_src;
11395
11396 if (len > src->len - src->index)
11397 return -1;
11398
11399 bcopy (src->bytes + src->index, buf, len);
11400 src->index += len;
11401 return len;
11402 }
11403
11404
11405 /* Load GIF image IMG for use on frame F. Value is non-zero if
11406 successful. */
11407
11408 static int
11409 gif_load (f, img)
11410 struct frame *f;
11411 struct image *img;
11412 {
11413 Lisp_Object file, specified_file;
11414 Lisp_Object specified_data;
11415 int rc, width, height, x, y, i;
11416 XImage *ximg;
11417 ColorMapObject *gif_color_map;
11418 unsigned long pixel_colors[256];
11419 GifFileType *gif;
11420 struct gcpro gcpro1;
11421 Lisp_Object image;
11422 int ino, image_left, image_top, image_width, image_height;
11423 gif_memory_source memsrc;
11424 unsigned char *raster;
11425
11426 specified_file = image_spec_value (img->spec, QCfile, NULL);
11427 specified_data = image_spec_value (img->spec, QCdata, NULL);
11428 file = Qnil;
11429 GCPRO1 (file);
11430
11431 if (NILP (specified_data))
11432 {
11433 file = x_find_image_file (specified_file);
11434 if (!STRINGP (file))
11435 {
11436 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11437 UNGCPRO;
11438 return 0;
11439 }
11440
11441 /* Open the GIF file. */
11442 gif = DGifOpenFileName (XSTRING (file)->data);
11443 if (gif == NULL)
11444 {
11445 image_error ("Cannot open `%s'", file, Qnil);
11446 UNGCPRO;
11447 return 0;
11448 }
11449 }
11450 else
11451 {
11452 /* Read from memory! */
11453 current_gif_memory_src = &memsrc;
11454 memsrc.bytes = XSTRING (specified_data)->data;
11455 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11456 memsrc.index = 0;
11457
11458 gif = DGifOpen(&memsrc, gif_read_from_memory);
11459 if (!gif)
11460 {
11461 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11462 UNGCPRO;
11463 return 0;
11464 }
11465 }
11466
11467 /* Read entire contents. */
11468 rc = DGifSlurp (gif);
11469 if (rc == GIF_ERROR)
11470 {
11471 image_error ("Error reading `%s'", img->spec, Qnil);
11472 DGifCloseFile (gif);
11473 UNGCPRO;
11474 return 0;
11475 }
11476
11477 image = image_spec_value (img->spec, QCindex, NULL);
11478 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11479 if (ino >= gif->ImageCount)
11480 {
11481 image_error ("Invalid image number `%s' in image `%s'",
11482 image, img->spec);
11483 DGifCloseFile (gif);
11484 UNGCPRO;
11485 return 0;
11486 }
11487
11488 width = img->width = gif->SWidth;
11489 height = img->height = gif->SHeight;
11490
11491 BLOCK_INPUT;
11492
11493 /* Create the X image and pixmap. */
11494 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11495 {
11496 UNBLOCK_INPUT;
11497 DGifCloseFile (gif);
11498 UNGCPRO;
11499 return 0;
11500 }
11501
11502 /* Allocate colors. */
11503 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11504 if (!gif_color_map)
11505 gif_color_map = gif->SColorMap;
11506 init_color_table ();
11507 bzero (pixel_colors, sizeof pixel_colors);
11508
11509 for (i = 0; i < gif_color_map->ColorCount; ++i)
11510 {
11511 int r = gif_color_map->Colors[i].Red << 8;
11512 int g = gif_color_map->Colors[i].Green << 8;
11513 int b = gif_color_map->Colors[i].Blue << 8;
11514 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
11515 }
11516
11517 img->colors = colors_in_color_table (&img->ncolors);
11518 free_color_table ();
11519
11520 /* Clear the part of the screen image that are not covered by
11521 the image from the GIF file. Full animated GIF support
11522 requires more than can be done here (see the gif89 spec,
11523 disposal methods). Let's simply assume that the part
11524 not covered by a sub-image is in the frame's background color. */
11525 image_top = gif->SavedImages[ino].ImageDesc.Top;
11526 image_left = gif->SavedImages[ino].ImageDesc.Left;
11527 image_width = gif->SavedImages[ino].ImageDesc.Width;
11528 image_height = gif->SavedImages[ino].ImageDesc.Height;
11529
11530 for (y = 0; y < image_top; ++y)
11531 for (x = 0; x < width; ++x)
11532 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11533
11534 for (y = image_top + image_height; y < height; ++y)
11535 for (x = 0; x < width; ++x)
11536 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11537
11538 for (y = image_top; y < image_top + image_height; ++y)
11539 {
11540 for (x = 0; x < image_left; ++x)
11541 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11542 for (x = image_left + image_width; x < width; ++x)
11543 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11544 }
11545
11546 /* Read the GIF image into the X image. We use a local variable
11547 `raster' here because RasterBits below is a char *, and invites
11548 problems with bytes >= 0x80. */
11549 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
11550
11551 if (gif->SavedImages[ino].ImageDesc.Interlace)
11552 {
11553 static int interlace_start[] = {0, 4, 2, 1};
11554 static int interlace_increment[] = {8, 8, 4, 2};
11555 int pass, inc;
11556 int row = interlace_start[0];
11557
11558 pass = 0;
11559
11560 for (y = 0; y < image_height; y++)
11561 {
11562 if (row >= image_height)
11563 {
11564 row = interlace_start[++pass];
11565 while (row >= image_height)
11566 row = interlace_start[++pass];
11567 }
11568
11569 for (x = 0; x < image_width; x++)
11570 {
11571 int i = raster[(y * image_width) + x];
11572 XPutPixel (ximg, x + image_left, row + image_top,
11573 pixel_colors[i]);
11574 }
11575
11576 row += interlace_increment[pass];
11577 }
11578 }
11579 else
11580 {
11581 for (y = 0; y < image_height; ++y)
11582 for (x = 0; x < image_width; ++x)
11583 {
11584 int i = raster[y* image_width + x];
11585 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
11586 }
11587 }
11588
11589 DGifCloseFile (gif);
11590
11591 /* Put the image into the pixmap, then free the X image and its buffer. */
11592 x_put_x_image (f, ximg, img->pixmap, width, height);
11593 x_destroy_x_image (ximg);
11594 UNBLOCK_INPUT;
11595
11596 UNGCPRO;
11597 return 1;
11598 }
11599
11600 #endif /* HAVE_GIF != 0 */
11601
11602
11603 \f
11604 /***********************************************************************
11605 Ghostscript
11606 ***********************************************************************/
11607
11608 #ifdef HAVE_GHOSTSCRIPT
11609 static int gs_image_p P_ ((Lisp_Object object));
11610 static int gs_load P_ ((struct frame *f, struct image *img));
11611 static void gs_clear_image P_ ((struct frame *f, struct image *img));
11612
11613 /* The symbol `postscript' identifying images of this type. */
11614
11615 Lisp_Object Qpostscript;
11616
11617 /* Keyword symbols. */
11618
11619 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
11620
11621 /* Indices of image specification fields in gs_format, below. */
11622
11623 enum gs_keyword_index
11624 {
11625 GS_TYPE,
11626 GS_PT_WIDTH,
11627 GS_PT_HEIGHT,
11628 GS_FILE,
11629 GS_LOADER,
11630 GS_BOUNDING_BOX,
11631 GS_ASCENT,
11632 GS_MARGIN,
11633 GS_RELIEF,
11634 GS_ALGORITHM,
11635 GS_HEURISTIC_MASK,
11636 GS_LAST
11637 };
11638
11639 /* Vector of image_keyword structures describing the format
11640 of valid user-defined image specifications. */
11641
11642 static struct image_keyword gs_format[GS_LAST] =
11643 {
11644 {":type", IMAGE_SYMBOL_VALUE, 1},
11645 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11646 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11647 {":file", IMAGE_STRING_VALUE, 1},
11648 {":loader", IMAGE_FUNCTION_VALUE, 0},
11649 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
11650 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11651 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11652 {":relief", IMAGE_INTEGER_VALUE, 0},
11653 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11654 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11655 };
11656
11657 /* Structure describing the image type `ghostscript'. */
11658
11659 static struct image_type gs_type =
11660 {
11661 &Qpostscript,
11662 gs_image_p,
11663 gs_load,
11664 gs_clear_image,
11665 NULL
11666 };
11667
11668
11669 /* Free X resources of Ghostscript image IMG which is used on frame F. */
11670
11671 static void
11672 gs_clear_image (f, img)
11673 struct frame *f;
11674 struct image *img;
11675 {
11676 /* IMG->data.ptr_val may contain a recorded colormap. */
11677 xfree (img->data.ptr_val);
11678 x_clear_image (f, img);
11679 }
11680
11681
11682 /* Return non-zero if OBJECT is a valid Ghostscript image
11683 specification. */
11684
11685 static int
11686 gs_image_p (object)
11687 Lisp_Object object;
11688 {
11689 struct image_keyword fmt[GS_LAST];
11690 Lisp_Object tem;
11691 int i;
11692
11693 bcopy (gs_format, fmt, sizeof fmt);
11694
11695 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
11696 || (fmt[GS_ASCENT].count
11697 && XFASTINT (fmt[GS_ASCENT].value) > 100))
11698 return 0;
11699
11700 /* Bounding box must be a list or vector containing 4 integers. */
11701 tem = fmt[GS_BOUNDING_BOX].value;
11702 if (CONSP (tem))
11703 {
11704 for (i = 0; i < 4; ++i, tem = XCDR (tem))
11705 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
11706 return 0;
11707 if (!NILP (tem))
11708 return 0;
11709 }
11710 else if (VECTORP (tem))
11711 {
11712 if (XVECTOR (tem)->size != 4)
11713 return 0;
11714 for (i = 0; i < 4; ++i)
11715 if (!INTEGERP (XVECTOR (tem)->contents[i]))
11716 return 0;
11717 }
11718 else
11719 return 0;
11720
11721 return 1;
11722 }
11723
11724
11725 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
11726 if successful. */
11727
11728 static int
11729 gs_load (f, img)
11730 struct frame *f;
11731 struct image *img;
11732 {
11733 char buffer[100];
11734 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
11735 struct gcpro gcpro1, gcpro2;
11736 Lisp_Object frame;
11737 double in_width, in_height;
11738 Lisp_Object pixel_colors = Qnil;
11739
11740 /* Compute pixel size of pixmap needed from the given size in the
11741 image specification. Sizes in the specification are in pt. 1 pt
11742 = 1/72 in, xdpi and ydpi are stored in the frame's X display
11743 info. */
11744 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
11745 in_width = XFASTINT (pt_width) / 72.0;
11746 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
11747 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
11748 in_height = XFASTINT (pt_height) / 72.0;
11749 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
11750
11751 /* Create the pixmap. */
11752 BLOCK_INPUT;
11753 xassert (img->pixmap == 0);
11754 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11755 img->width, img->height,
11756 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
11757 UNBLOCK_INPUT;
11758
11759 if (!img->pixmap)
11760 {
11761 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
11762 return 0;
11763 }
11764
11765 /* Call the loader to fill the pixmap. It returns a process object
11766 if successful. We do not record_unwind_protect here because
11767 other places in redisplay like calling window scroll functions
11768 don't either. Let the Lisp loader use `unwind-protect' instead. */
11769 GCPRO2 (window_and_pixmap_id, pixel_colors);
11770
11771 sprintf (buffer, "%lu %lu",
11772 (unsigned long) FRAME_W32_WINDOW (f),
11773 (unsigned long) img->pixmap);
11774 window_and_pixmap_id = build_string (buffer);
11775
11776 sprintf (buffer, "%lu %lu",
11777 FRAME_FOREGROUND_PIXEL (f),
11778 FRAME_BACKGROUND_PIXEL (f));
11779 pixel_colors = build_string (buffer);
11780
11781 XSETFRAME (frame, f);
11782 loader = image_spec_value (img->spec, QCloader, NULL);
11783 if (NILP (loader))
11784 loader = intern ("gs-load-image");
11785
11786 img->data.lisp_val = call6 (loader, frame, img->spec,
11787 make_number (img->width),
11788 make_number (img->height),
11789 window_and_pixmap_id,
11790 pixel_colors);
11791 UNGCPRO;
11792 return PROCESSP (img->data.lisp_val);
11793 }
11794
11795
11796 /* Kill the Ghostscript process that was started to fill PIXMAP on
11797 frame F. Called from XTread_socket when receiving an event
11798 telling Emacs that Ghostscript has finished drawing. */
11799
11800 void
11801 x_kill_gs_process (pixmap, f)
11802 Pixmap pixmap;
11803 struct frame *f;
11804 {
11805 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
11806 int class, i;
11807 struct image *img;
11808
11809 /* Find the image containing PIXMAP. */
11810 for (i = 0; i < c->used; ++i)
11811 if (c->images[i]->pixmap == pixmap)
11812 break;
11813
11814 /* Kill the GS process. We should have found PIXMAP in the image
11815 cache and its image should contain a process object. */
11816 xassert (i < c->used);
11817 img = c->images[i];
11818 xassert (PROCESSP (img->data.lisp_val));
11819 Fkill_process (img->data.lisp_val, Qnil);
11820 img->data.lisp_val = Qnil;
11821
11822 /* On displays with a mutable colormap, figure out the colors
11823 allocated for the image by looking at the pixels of an XImage for
11824 img->pixmap. */
11825 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
11826 if (class != StaticColor && class != StaticGray && class != TrueColor)
11827 {
11828 XImage *ximg;
11829
11830 BLOCK_INPUT;
11831
11832 /* Try to get an XImage for img->pixmep. */
11833 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
11834 0, 0, img->width, img->height, ~0, ZPixmap);
11835 if (ximg)
11836 {
11837 int x, y;
11838
11839 /* Initialize the color table. */
11840 init_color_table ();
11841
11842 /* For each pixel of the image, look its color up in the
11843 color table. After having done so, the color table will
11844 contain an entry for each color used by the image. */
11845 for (y = 0; y < img->height; ++y)
11846 for (x = 0; x < img->width; ++x)
11847 {
11848 unsigned long pixel = XGetPixel (ximg, x, y);
11849 lookup_pixel_color (f, pixel);
11850 }
11851
11852 /* Record colors in the image. Free color table and XImage. */
11853 img->colors = colors_in_color_table (&img->ncolors);
11854 free_color_table ();
11855 XDestroyImage (ximg);
11856
11857 #if 0 /* This doesn't seem to be the case. If we free the colors
11858 here, we get a BadAccess later in x_clear_image when
11859 freeing the colors. */
11860 /* We have allocated colors once, but Ghostscript has also
11861 allocated colors on behalf of us. So, to get the
11862 reference counts right, free them once. */
11863 if (img->ncolors)
11864 {
11865 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
11866 XFreeColors (FRAME_W32_DISPLAY (f), cmap,
11867 img->colors, img->ncolors, 0);
11868 }
11869 #endif
11870 }
11871 else
11872 image_error ("Cannot get X image of `%s'; colors will not be freed",
11873 img->spec, Qnil);
11874
11875 UNBLOCK_INPUT;
11876 }
11877 }
11878
11879 #endif /* HAVE_GHOSTSCRIPT */
11880
11881 \f
11882 /***********************************************************************
11883 Window properties
11884 ***********************************************************************/
11885
11886 DEFUN ("x-change-window-property", Fx_change_window_property,
11887 Sx_change_window_property, 2, 3, 0,
11888 "Change window property PROP to VALUE on the X window of FRAME.\n\
11889 PROP and VALUE must be strings. FRAME nil or omitted means use the\n\
11890 selected frame. Value is VALUE.")
11891 (prop, value, frame)
11892 Lisp_Object frame, prop, value;
11893 {
11894 #if 0 /* TODO : port window properties to W32 */
11895 struct frame *f = check_x_frame (frame);
11896 Atom prop_atom;
11897
11898 CHECK_STRING (prop, 1);
11899 CHECK_STRING (value, 2);
11900
11901 BLOCK_INPUT;
11902 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11903 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11904 prop_atom, XA_STRING, 8, PropModeReplace,
11905 XSTRING (value)->data, XSTRING (value)->size);
11906
11907 /* Make sure the property is set when we return. */
11908 XFlush (FRAME_W32_DISPLAY (f));
11909 UNBLOCK_INPUT;
11910
11911 #endif /* TODO */
11912
11913 return value;
11914 }
11915
11916
11917 DEFUN ("x-delete-window-property", Fx_delete_window_property,
11918 Sx_delete_window_property, 1, 2, 0,
11919 "Remove window property PROP from X window of FRAME.\n\
11920 FRAME nil or omitted means use the selected frame. Value is PROP.")
11921 (prop, frame)
11922 Lisp_Object prop, frame;
11923 {
11924 #if 0 /* TODO : port window properties to W32 */
11925
11926 struct frame *f = check_x_frame (frame);
11927 Atom prop_atom;
11928
11929 CHECK_STRING (prop, 1);
11930 BLOCK_INPUT;
11931 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11932 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
11933
11934 /* Make sure the property is removed when we return. */
11935 XFlush (FRAME_W32_DISPLAY (f));
11936 UNBLOCK_INPUT;
11937 #endif /* TODO */
11938
11939 return prop;
11940 }
11941
11942
11943 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
11944 1, 2, 0,
11945 "Value is the value of window property PROP on FRAME.\n\
11946 If FRAME is nil or omitted, use the selected frame. Value is nil\n\
11947 if FRAME hasn't a property with name PROP or if PROP has no string\n\
11948 value.")
11949 (prop, frame)
11950 Lisp_Object prop, frame;
11951 {
11952 #if 0 /* TODO : port window properties to W32 */
11953
11954 struct frame *f = check_x_frame (frame);
11955 Atom prop_atom;
11956 int rc;
11957 Lisp_Object prop_value = Qnil;
11958 char *tmp_data = NULL;
11959 Atom actual_type;
11960 int actual_format;
11961 unsigned long actual_size, bytes_remaining;
11962
11963 CHECK_STRING (prop, 1);
11964 BLOCK_INPUT;
11965 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11966 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11967 prop_atom, 0, 0, False, XA_STRING,
11968 &actual_type, &actual_format, &actual_size,
11969 &bytes_remaining, (unsigned char **) &tmp_data);
11970 if (rc == Success)
11971 {
11972 int size = bytes_remaining;
11973
11974 XFree (tmp_data);
11975 tmp_data = NULL;
11976
11977 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11978 prop_atom, 0, bytes_remaining,
11979 False, XA_STRING,
11980 &actual_type, &actual_format,
11981 &actual_size, &bytes_remaining,
11982 (unsigned char **) &tmp_data);
11983 if (rc == Success)
11984 prop_value = make_string (tmp_data, size);
11985
11986 XFree (tmp_data);
11987 }
11988
11989 UNBLOCK_INPUT;
11990
11991 return prop_value;
11992
11993 #endif /* TODO */
11994 return Qnil;
11995 }
11996
11997
11998 \f
11999 /***********************************************************************
12000 Busy cursor
12001 ***********************************************************************/
12002
12003 /* If non-null, an asynchronous timer that, when it expires, displays
12004 a busy cursor on all frames. */
12005
12006 static struct atimer *busy_cursor_atimer;
12007
12008 /* Non-zero means a busy cursor is currently shown. */
12009
12010 static int busy_cursor_shown_p;
12011
12012 /* Number of seconds to wait before displaying a busy cursor. */
12013
12014 static Lisp_Object Vbusy_cursor_delay;
12015
12016 /* Default number of seconds to wait before displaying a busy
12017 cursor. */
12018
12019 #define DEFAULT_BUSY_CURSOR_DELAY 1
12020
12021 /* Function prototypes. */
12022
12023 static void show_busy_cursor P_ ((struct atimer *));
12024 static void hide_busy_cursor P_ ((void));
12025
12026
12027 /* Cancel a currently active busy-cursor timer, and start a new one. */
12028
12029 void
12030 start_busy_cursor ()
12031 {
12032 #if 0 /* TODO: cursor shape changes. */
12033 EMACS_TIME delay;
12034 int secs, usecs = 0;
12035
12036 cancel_busy_cursor ();
12037
12038 if (INTEGERP (Vbusy_cursor_delay)
12039 && XINT (Vbusy_cursor_delay) > 0)
12040 secs = XFASTINT (Vbusy_cursor_delay);
12041 else if (FLOATP (Vbusy_cursor_delay)
12042 && XFLOAT_DATA (Vbusy_cursor_delay) > 0)
12043 {
12044 Lisp_Object tem;
12045 tem = Ftruncate (Vbusy_cursor_delay, Qnil);
12046 secs = XFASTINT (tem);
12047 usecs = (XFLOAT_DATA (Vbusy_cursor_delay) - secs) * 1000000;
12048 }
12049 else
12050 secs = DEFAULT_BUSY_CURSOR_DELAY;
12051
12052 EMACS_SET_SECS_USECS (delay, secs, usecs);
12053 busy_cursor_atimer = start_atimer (ATIMER_RELATIVE, delay,
12054 show_busy_cursor, NULL);
12055 #endif
12056 }
12057
12058
12059 /* Cancel the busy cursor timer if active, hide a busy cursor if
12060 shown. */
12061
12062 void
12063 cancel_busy_cursor ()
12064 {
12065 if (busy_cursor_atimer)
12066 {
12067 cancel_atimer (busy_cursor_atimer);
12068 busy_cursor_atimer = NULL;
12069 }
12070
12071 if (busy_cursor_shown_p)
12072 hide_busy_cursor ();
12073 }
12074
12075
12076 /* Timer function of busy_cursor_atimer. TIMER is equal to
12077 busy_cursor_atimer.
12078
12079 Display a busy cursor on all frames by mapping the frames'
12080 busy_window. Set the busy_p flag in the frames' output_data.x
12081 structure to indicate that a busy cursor is shown on the
12082 frames. */
12083
12084 static void
12085 show_busy_cursor (timer)
12086 struct atimer *timer;
12087 {
12088 #if 0 /* TODO: cursor shape changes. */
12089 /* The timer implementation will cancel this timer automatically
12090 after this function has run. Set busy_cursor_atimer to null
12091 so that we know the timer doesn't have to be canceled. */
12092 busy_cursor_atimer = NULL;
12093
12094 if (!busy_cursor_shown_p)
12095 {
12096 Lisp_Object rest, frame;
12097
12098 BLOCK_INPUT;
12099
12100 FOR_EACH_FRAME (rest, frame)
12101 if (FRAME_X_P (XFRAME (frame)))
12102 {
12103 struct frame *f = XFRAME (frame);
12104
12105 f->output_data.w32->busy_p = 1;
12106
12107 if (!f->output_data.w32->busy_window)
12108 {
12109 unsigned long mask = CWCursor;
12110 XSetWindowAttributes attrs;
12111
12112 attrs.cursor = f->output_data.w32->busy_cursor;
12113
12114 f->output_data.w32->busy_window
12115 = XCreateWindow (FRAME_X_DISPLAY (f),
12116 FRAME_OUTER_WINDOW (f),
12117 0, 0, 32000, 32000, 0, 0,
12118 InputOnly,
12119 CopyFromParent,
12120 mask, &attrs);
12121 }
12122
12123 XMapRaised (FRAME_X_DISPLAY (f), f->output_data.w32->busy_window);
12124 XFlush (FRAME_X_DISPLAY (f));
12125 }
12126
12127 busy_cursor_shown_p = 1;
12128 UNBLOCK_INPUT;
12129 }
12130 #endif
12131 }
12132
12133
12134 /* Hide the busy cursor on all frames, if it is currently shown. */
12135
12136 static void
12137 hide_busy_cursor ()
12138 {
12139 #if 0 /* TODO: cursor shape changes. */
12140 if (busy_cursor_shown_p)
12141 {
12142 Lisp_Object rest, frame;
12143
12144 BLOCK_INPUT;
12145 FOR_EACH_FRAME (rest, frame)
12146 {
12147 struct frame *f = XFRAME (frame);
12148
12149 if (FRAME_X_P (f)
12150 /* Watch out for newly created frames. */
12151 && f->output_data.x->busy_window)
12152 {
12153 XUnmapWindow (FRAME_X_DISPLAY (f), f->output_data.x->busy_window);
12154 /* Sync here because XTread_socket looks at the busy_p flag
12155 that is reset to zero below. */
12156 XSync (FRAME_X_DISPLAY (f), False);
12157 f->output_data.x->busy_p = 0;
12158 }
12159 }
12160
12161 busy_cursor_shown_p = 0;
12162 UNBLOCK_INPUT;
12163 }
12164 #endif
12165 }
12166
12167
12168 \f
12169 /***********************************************************************
12170 Tool tips
12171 ***********************************************************************/
12172
12173 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
12174 Lisp_Object));
12175
12176 /* The frame of a currently visible tooltip, or null. */
12177
12178 struct frame *tip_frame;
12179
12180 /* If non-nil, a timer started that hides the last tooltip when it
12181 fires. */
12182
12183 Lisp_Object tip_timer;
12184 Window tip_window;
12185
12186 /* Create a frame for a tooltip on the display described by DPYINFO.
12187 PARMS is a list of frame parameters. Value is the frame. */
12188
12189 static Lisp_Object
12190 x_create_tip_frame (dpyinfo, parms)
12191 struct w32_display_info *dpyinfo;
12192 Lisp_Object parms;
12193 {
12194 #if 0 /* TODO : w32 version */
12195 struct frame *f;
12196 Lisp_Object frame, tem;
12197 Lisp_Object name;
12198 long window_prompting = 0;
12199 int width, height;
12200 int count = specpdl_ptr - specpdl;
12201 struct gcpro gcpro1, gcpro2, gcpro3;
12202 struct kboard *kb;
12203
12204 check_x ();
12205
12206 /* Use this general default value to start with until we know if
12207 this frame has a specified name. */
12208 Vx_resource_name = Vinvocation_name;
12209
12210 #ifdef MULTI_KBOARD
12211 kb = dpyinfo->kboard;
12212 #else
12213 kb = &the_only_kboard;
12214 #endif
12215
12216 /* Get the name of the frame to use for resource lookup. */
12217 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
12218 if (!STRINGP (name)
12219 && !EQ (name, Qunbound)
12220 && !NILP (name))
12221 error ("Invalid frame name--not a string or nil");
12222 Vx_resource_name = name;
12223
12224 frame = Qnil;
12225 GCPRO3 (parms, name, frame);
12226 tip_frame = f = make_frame (1);
12227 XSETFRAME (frame, f);
12228 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
12229
12230 f->output_method = output_w32;
12231 f->output_data.w32 =
12232 (struct w32_output *) xmalloc (sizeof (struct w32_output));
12233 bzero (f->output_data.w32, sizeof (struct w32_output));
12234 #if 0
12235 f->output_data.w32->icon_bitmap = -1;
12236 #endif
12237 f->output_data.w32->fontset = -1;
12238 f->icon_name = Qnil;
12239
12240 #ifdef MULTI_KBOARD
12241 FRAME_KBOARD (f) = kb;
12242 #endif
12243 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12244 f->output_data.w32->explicit_parent = 0;
12245
12246 /* Set the name; the functions to which we pass f expect the name to
12247 be set. */
12248 if (EQ (name, Qunbound) || NILP (name))
12249 {
12250 f->name = build_string (dpyinfo->x_id_name);
12251 f->explicit_name = 0;
12252 }
12253 else
12254 {
12255 f->name = name;
12256 f->explicit_name = 1;
12257 /* use the frame's title when getting resources for this frame. */
12258 specbind (Qx_resource_name, name);
12259 }
12260
12261 /* Extract the window parameters from the supplied values
12262 that are needed to determine window geometry. */
12263 {
12264 Lisp_Object font;
12265
12266 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12267
12268 BLOCK_INPUT;
12269 /* First, try whatever font the caller has specified. */
12270 if (STRINGP (font))
12271 {
12272 tem = Fquery_fontset (font, Qnil);
12273 if (STRINGP (tem))
12274 font = x_new_fontset (f, XSTRING (tem)->data);
12275 else
12276 font = x_new_font (f, XSTRING (font)->data);
12277 }
12278
12279 /* Try out a font which we hope has bold and italic variations. */
12280 if (!STRINGP (font))
12281 font = x_new_font (f, "-*-courier new-normal-r-*-*-*-100-*-*-*-*-iso8859-1");
12282 if (!STRINGP (font))
12283 font = x_new_font (f, "-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12284 if (! STRINGP (font))
12285 font = x_new_font (f, "-*-*-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
12286 if (! STRINGP (font))
12287 /* This was formerly the first thing tried, but it finds too many fonts
12288 and takes too long. */
12289 font = x_new_font (f, "-*-*-medium-r-*-*-*-*-*-*-c-*-iso8859-1");
12290 /* If those didn't work, look for something which will at least work. */
12291 if (! STRINGP (font))
12292 font = x_new_font (f, "-*-fixed-*-*-*-*-*-140-*-*-c-*-iso8859-1");
12293 UNBLOCK_INPUT;
12294 if (! STRINGP (font))
12295 font = build_string ("fixed");
12296
12297 x_default_parameter (f, parms, Qfont, font,
12298 "font", "Font", RES_TYPE_STRING);
12299 }
12300
12301 x_default_parameter (f, parms, Qborder_width, make_number (2),
12302 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
12303
12304 /* This defaults to 2 in order to match xterm. We recognize either
12305 internalBorderWidth or internalBorder (which is what xterm calls
12306 it). */
12307 if (NILP (Fassq (Qinternal_border_width, parms)))
12308 {
12309 Lisp_Object value;
12310
12311 value = w32_get_arg (parms, Qinternal_border_width,
12312 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12313 if (! EQ (value, Qunbound))
12314 parms = Fcons (Fcons (Qinternal_border_width, value),
12315 parms);
12316 }
12317
12318 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
12319 "internalBorderWidth", "internalBorderWidth",
12320 RES_TYPE_NUMBER);
12321
12322 /* Also do the stuff which must be set before the window exists. */
12323 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12324 "foreground", "Foreground", RES_TYPE_STRING);
12325 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12326 "background", "Background", RES_TYPE_STRING);
12327 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12328 "pointerColor", "Foreground", RES_TYPE_STRING);
12329 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12330 "cursorColor", "Foreground", RES_TYPE_STRING);
12331 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12332 "borderColor", "BorderColor", RES_TYPE_STRING);
12333
12334 /* Init faces before x_default_parameter is called for scroll-bar
12335 parameters because that function calls x_set_scroll_bar_width,
12336 which calls change_frame_size, which calls Fset_window_buffer,
12337 which runs hooks, which call Fvertical_motion. At the end, we
12338 end up in init_iterator with a null face cache, which should not
12339 happen. */
12340 init_frame_faces (f);
12341
12342 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12343 window_prompting = x_figure_window_size (f, parms);
12344
12345 if (window_prompting & XNegative)
12346 {
12347 if (window_prompting & YNegative)
12348 f->output_data.w32->win_gravity = SouthEastGravity;
12349 else
12350 f->output_data.w32->win_gravity = NorthEastGravity;
12351 }
12352 else
12353 {
12354 if (window_prompting & YNegative)
12355 f->output_data.w32->win_gravity = SouthWestGravity;
12356 else
12357 f->output_data.w32->win_gravity = NorthWestGravity;
12358 }
12359
12360 f->output_data.w32->size_hint_flags = window_prompting;
12361 {
12362 XSetWindowAttributes attrs;
12363 unsigned long mask;
12364
12365 BLOCK_INPUT;
12366 mask = CWBackPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask;
12367 /* Window managers looks at the override-redirect flag to
12368 determine whether or net to give windows a decoration (Xlib
12369 3.2.8). */
12370 attrs.override_redirect = True;
12371 attrs.save_under = True;
12372 attrs.background_pixel = FRAME_BACKGROUND_PIXEL (f);
12373 /* Arrange for getting MapNotify and UnmapNotify events. */
12374 attrs.event_mask = StructureNotifyMask;
12375 tip_window
12376 = FRAME_W32_WINDOW (f)
12377 = XCreateWindow (FRAME_W32_DISPLAY (f),
12378 FRAME_W32_DISPLAY_INFO (f)->root_window,
12379 /* x, y, width, height */
12380 0, 0, 1, 1,
12381 /* Border. */
12382 1,
12383 CopyFromParent, InputOutput, CopyFromParent,
12384 mask, &attrs);
12385 UNBLOCK_INPUT;
12386 }
12387
12388 x_make_gc (f);
12389
12390 x_default_parameter (f, parms, Qauto_raise, Qnil,
12391 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12392 x_default_parameter (f, parms, Qauto_lower, Qnil,
12393 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12394 x_default_parameter (f, parms, Qcursor_type, Qbox,
12395 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12396
12397 /* Dimensions, especially f->height, must be done via change_frame_size.
12398 Change will not be effected unless different from the current
12399 f->height. */
12400 width = f->width;
12401 height = f->height;
12402 f->height = 0;
12403 SET_FRAME_WIDTH (f, 0);
12404 change_frame_size (f, height, width, 1, 0, 0);
12405
12406 f->no_split = 1;
12407
12408 UNGCPRO;
12409
12410 /* It is now ok to make the frame official even if we get an error
12411 below. And the frame needs to be on Vframe_list or making it
12412 visible won't work. */
12413 Vframe_list = Fcons (frame, Vframe_list);
12414
12415 /* Now that the frame is official, it counts as a reference to
12416 its display. */
12417 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
12418
12419 return unbind_to (count, frame);
12420 #endif /* TODO */
12421 return Qnil;
12422 }
12423
12424 #ifdef TODO /* Tooltip support not complete. */
12425 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
12426 "Show STRING in a \"tooltip\" window on frame FRAME.\n\
12427 A tooltip window is a small X window displaying a string.\n\
12428 \n\
12429 FRAME nil or omitted means use the selected frame.\n\
12430 \n\
12431 PARMS is an optional list of frame parameters which can be\n\
12432 used to change the tooltip's appearance.\n\
12433 \n\
12434 Automatically hide the tooltip after TIMEOUT seconds.\n\
12435 TIMEOUT nil means use the default timeout of 5 seconds.\n\
12436 \n\
12437 If the list of frame parameters PARAMS contains a `left' parameters,\n\
12438 the tooltip is displayed at that x-position. Otherwise it is\n\
12439 displayed at the mouse position, with offset DX added (default is 5 if\n\
12440 DX isn't specified). Likewise for the y-position; if a `top' frame\n\
12441 parameter is specified, it determines the y-position of the tooltip\n\
12442 window, otherwise it is displayed at the mouse position, with offset\n\
12443 DY added (default is -5).")
12444 (string, frame, parms, timeout, dx, dy)
12445 Lisp_Object string, frame, parms, timeout, dx, dy;
12446 {
12447 struct frame *f;
12448 struct window *w;
12449 Window root, child;
12450 Lisp_Object buffer, top, left;
12451 struct buffer *old_buffer;
12452 struct text_pos pos;
12453 int i, width, height;
12454 int root_x, root_y, win_x, win_y;
12455 unsigned pmask;
12456 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
12457 int old_windows_or_buffers_changed = windows_or_buffers_changed;
12458 int count = specpdl_ptr - specpdl;
12459
12460 specbind (Qinhibit_redisplay, Qt);
12461
12462 GCPRO4 (string, parms, frame, timeout);
12463
12464 CHECK_STRING (string, 0);
12465 f = check_x_frame (frame);
12466 if (NILP (timeout))
12467 timeout = make_number (5);
12468 else
12469 CHECK_NATNUM (timeout, 2);
12470
12471 if (NILP (dx))
12472 dx = make_number (5);
12473 else
12474 CHECK_NUMBER (dx, 5);
12475
12476 if (NILP (dy))
12477 dy = make_number (-5);
12478 else
12479 CHECK_NUMBER (dy, 6);
12480
12481 /* Hide a previous tip, if any. */
12482 Fx_hide_tip ();
12483
12484 /* Add default values to frame parameters. */
12485 if (NILP (Fassq (Qname, parms)))
12486 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
12487 if (NILP (Fassq (Qinternal_border_width, parms)))
12488 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
12489 if (NILP (Fassq (Qborder_width, parms)))
12490 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
12491 if (NILP (Fassq (Qborder_color, parms)))
12492 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
12493 if (NILP (Fassq (Qbackground_color, parms)))
12494 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
12495 parms);
12496
12497 /* Create a frame for the tooltip, and record it in the global
12498 variable tip_frame. */
12499 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms);
12500 tip_frame = f = XFRAME (frame);
12501
12502 /* Set up the frame's root window. Currently we use a size of 80
12503 columns x 40 lines. If someone wants to show a larger tip, he
12504 will loose. I don't think this is a realistic case. */
12505 w = XWINDOW (FRAME_ROOT_WINDOW (f));
12506 w->left = w->top = make_number (0);
12507 w->width = 80;
12508 w->height = 40;
12509 adjust_glyphs (f);
12510 w->pseudo_window_p = 1;
12511
12512 /* Display the tooltip text in a temporary buffer. */
12513 buffer = Fget_buffer_create (build_string (" *tip*"));
12514 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
12515 old_buffer = current_buffer;
12516 set_buffer_internal_1 (XBUFFER (buffer));
12517 Ferase_buffer ();
12518 Finsert (make_number (1), &string);
12519 clear_glyph_matrix (w->desired_matrix);
12520 clear_glyph_matrix (w->current_matrix);
12521 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
12522 try_window (FRAME_ROOT_WINDOW (f), pos);
12523
12524 /* Compute width and height of the tooltip. */
12525 width = height = 0;
12526 for (i = 0; i < w->desired_matrix->nrows; ++i)
12527 {
12528 struct glyph_row *row = &w->desired_matrix->rows[i];
12529 struct glyph *last;
12530 int row_width;
12531
12532 /* Stop at the first empty row at the end. */
12533 if (!row->enabled_p || !row->displays_text_p)
12534 break;
12535
12536 /* Let the row go over the full width of the frame. */
12537 row->full_width_p = 1;
12538
12539 /* There's a glyph at the end of rows that is use to place
12540 the cursor there. Don't include the width of this glyph. */
12541 if (row->used[TEXT_AREA])
12542 {
12543 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
12544 row_width = row->pixel_width - last->pixel_width;
12545 }
12546 else
12547 row_width = row->pixel_width;
12548
12549 height += row->height;
12550 width = max (width, row_width);
12551 }
12552
12553 /* Add the frame's internal border to the width and height the X
12554 window should have. */
12555 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12556 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12557
12558 /* User-specified position? */
12559 left = Fcdr (Fassq (Qleft, parms));
12560 top = Fcdr (Fassq (Qtop, parms));
12561
12562 /* Move the tooltip window where the mouse pointer is. Resize and
12563 show it. */
12564 #if 0 /* TODO : W32 specifics */
12565 BLOCK_INPUT;
12566 XQueryPointer (FRAME_X_DISPLAY (f), FRAME_X_DISPLAY_INFO (f)->root_window,
12567 &root, &child, &root_x, &root_y, &win_x, &win_y, &pmask);
12568 UNBLOCK_INPUT;
12569
12570 root_x += XINT (dx);
12571 root_y += XINT (dy);
12572
12573 if (INTEGERP (left))
12574 root_x = XINT (left);
12575 if (INTEGERP (top))
12576 root_y = XINT (top);
12577
12578 BLOCK_INPUT;
12579 XMoveResizeWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
12580 root_x, root_y - height, width, height);
12581 XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
12582 UNBLOCK_INPUT;
12583 #endif /* TODO */
12584
12585 /* Draw into the window. */
12586 w->must_be_updated_p = 1;
12587 update_single_window (w, 1);
12588
12589 /* Restore original current buffer. */
12590 set_buffer_internal_1 (old_buffer);
12591 windows_or_buffers_changed = old_windows_or_buffers_changed;
12592
12593 /* Let the tip disappear after timeout seconds. */
12594 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
12595 intern ("x-hide-tip"));
12596
12597 UNGCPRO;
12598 return unbind_to (count, Qnil);
12599 }
12600
12601
12602 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
12603 "Hide the current tooltip window, if there is any.\n\
12604 Value is t is tooltip was open, nil otherwise.")
12605 ()
12606 {
12607 int count = specpdl_ptr - specpdl;
12608 int deleted_p = 0;
12609
12610 specbind (Qinhibit_redisplay, Qt);
12611
12612 if (!NILP (tip_timer))
12613 {
12614 call1 (intern ("cancel-timer"), tip_timer);
12615 tip_timer = Qnil;
12616 }
12617
12618 if (tip_frame)
12619 {
12620 Lisp_Object frame;
12621
12622 XSETFRAME (frame, tip_frame);
12623 Fdelete_frame (frame, Qt);
12624 tip_frame = NULL;
12625 deleted_p = 1;
12626 }
12627
12628 return unbind_to (count, deleted_p ? Qt : Qnil);
12629 }
12630 #endif
12631
12632
12633 \f
12634 /***********************************************************************
12635 File selection dialog
12636 ***********************************************************************/
12637
12638 extern Lisp_Object Qfile_name_history;
12639
12640 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
12641 "Read file name, prompting with PROMPT in directory DIR.\n\
12642 Use a file selection dialog.\n\
12643 Select DEFAULT-FILENAME in the dialog's file selection box, if\n\
12644 specified. Don't let the user enter a file name in the file\n\
12645 selection dialog's entry field, if MUSTMATCH is non-nil.")
12646 (prompt, dir, default_filename, mustmatch)
12647 Lisp_Object prompt, dir, default_filename, mustmatch;
12648 {
12649 struct frame *f = SELECTED_FRAME ();
12650 Lisp_Object file = Qnil;
12651 int count = specpdl_ptr - specpdl;
12652 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
12653 char filename[MAX_PATH + 1];
12654 char init_dir[MAX_PATH + 1];
12655 int use_dialog_p = 1;
12656
12657 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
12658 CHECK_STRING (prompt, 0);
12659 CHECK_STRING (dir, 1);
12660
12661 /* Create the dialog with PROMPT as title, using DIR as initial
12662 directory and using "*" as pattern. */
12663 dir = Fexpand_file_name (dir, Qnil);
12664 strncpy (init_dir, XSTRING (dir)->data, MAX_PATH);
12665 init_dir[MAX_PATH] = '\0';
12666 unixtodos_filename (init_dir);
12667
12668 if (STRINGP (default_filename))
12669 {
12670 char *file_name_only;
12671 char *full_path_name = XSTRING (default_filename)->data;
12672
12673 unixtodos_filename (full_path_name);
12674
12675 file_name_only = strrchr (full_path_name, '\\');
12676 if (!file_name_only)
12677 file_name_only = full_path_name;
12678 else
12679 {
12680 file_name_only++;
12681
12682 /* If default_file_name is a directory, don't use the open
12683 file dialog, as it does not support selecting
12684 directories. */
12685 if (!(*file_name_only))
12686 use_dialog_p = 0;
12687 }
12688
12689 strncpy (filename, file_name_only, MAX_PATH);
12690 filename[MAX_PATH] = '\0';
12691 }
12692 else
12693 filename[0] = '\0';
12694
12695 if (use_dialog_p)
12696 {
12697 OPENFILENAME file_details;
12698 char *filename_file;
12699
12700 /* Prevent redisplay. */
12701 specbind (Qinhibit_redisplay, Qt);
12702 BLOCK_INPUT;
12703
12704 bzero (&file_details, sizeof (file_details));
12705 file_details.lStructSize = sizeof (file_details);
12706 file_details.hwndOwner = FRAME_W32_WINDOW (f);
12707 file_details.lpstrFile = filename;
12708 file_details.nMaxFile = sizeof (filename);
12709 file_details.lpstrInitialDir = init_dir;
12710 file_details.lpstrTitle = XSTRING (prompt)->data;
12711 file_details.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
12712
12713 if (!NILP (mustmatch))
12714 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
12715
12716 if (GetOpenFileName (&file_details))
12717 {
12718 dostounix_filename (filename);
12719 file = build_string (filename);
12720 }
12721 else
12722 file = Qnil;
12723
12724 UNBLOCK_INPUT;
12725 file = unbind_to (count, file);
12726 }
12727 /* Open File dialog will not allow folders to be selected, so resort
12728 to minibuffer completing reads for directories. */
12729 else
12730 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
12731 dir, mustmatch, dir, Qfile_name_history,
12732 default_filename, Qnil);
12733
12734 UNGCPRO;
12735
12736 /* Make "Cancel" equivalent to C-g. */
12737 if (NILP (file))
12738 Fsignal (Qquit, Qnil);
12739
12740 return unbind_to (count, file);
12741 }
12742
12743
12744 \f
12745 /***********************************************************************
12746 Tests
12747 ***********************************************************************/
12748
12749 #if GLYPH_DEBUG
12750
12751 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
12752 "Value is non-nil if SPEC is a valid image specification.")
12753 (spec)
12754 Lisp_Object spec;
12755 {
12756 return valid_image_p (spec) ? Qt : Qnil;
12757 }
12758
12759
12760 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
12761 (spec)
12762 Lisp_Object spec;
12763 {
12764 int id = -1;
12765
12766 if (valid_image_p (spec))
12767 id = lookup_image (SELECTED_FRAME (), spec);
12768
12769 debug_print (spec);
12770 return make_number (id);
12771 }
12772
12773 #endif /* GLYPH_DEBUG != 0 */
12774
12775
12776 \f
12777 /***********************************************************************
12778 w32 specialized functions
12779 ***********************************************************************/
12780
12781 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 1, 0,
12782 "This will display the W32 font dialog and return an X font string corresponding to the selection.")
12783 (frame)
12784 Lisp_Object frame;
12785 {
12786 FRAME_PTR f = check_x_frame (frame);
12787 CHOOSEFONT cf;
12788 LOGFONT lf;
12789 TEXTMETRIC tm;
12790 HDC hdc;
12791 HANDLE oldobj;
12792 char buf[100];
12793
12794 bzero (&cf, sizeof (cf));
12795 bzero (&lf, sizeof (lf));
12796
12797 cf.lStructSize = sizeof (cf);
12798 cf.hwndOwner = FRAME_W32_WINDOW (f);
12799 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS;
12800 cf.lpLogFont = &lf;
12801
12802 /* Initialize as much of the font details as we can from the current
12803 default font. */
12804 hdc = GetDC (FRAME_W32_WINDOW (f));
12805 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
12806 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
12807 if (GetTextMetrics (hdc, &tm))
12808 {
12809 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
12810 lf.lfWeight = tm.tmWeight;
12811 lf.lfItalic = tm.tmItalic;
12812 lf.lfUnderline = tm.tmUnderlined;
12813 lf.lfStrikeOut = tm.tmStruckOut;
12814 lf.lfCharSet = tm.tmCharSet;
12815 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
12816 }
12817 SelectObject (hdc, oldobj);
12818 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
12819
12820 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
12821 return Qnil;
12822
12823 return build_string (buf);
12824 }
12825
12826 DEFUN ("w32-send-sys-command", Fw32_send_sys_command, Sw32_send_sys_command, 1, 2, 0,
12827 "Send frame a Windows WM_SYSCOMMAND message of type COMMAND.\n\
12828 Some useful values for command are 0xf030 to maximise frame (0xf020\n\
12829 to minimize), 0xf120 to restore frame to original size, and 0xf100\n\
12830 to activate the menubar for keyboard access. 0xf140 activates the\n\
12831 screen saver if defined.\n\
12832 \n\
12833 If optional parameter FRAME is not specified, use selected frame.")
12834 (command, frame)
12835 Lisp_Object command, frame;
12836 {
12837 WPARAM code;
12838 FRAME_PTR f = check_x_frame (frame);
12839
12840 CHECK_NUMBER (command, 0);
12841
12842 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
12843
12844 return Qnil;
12845 }
12846
12847 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
12848 "Get Windows to perform OPERATION on DOCUMENT.\n\
12849 This is a wrapper around the ShellExecute system function, which\n\
12850 invokes the application registered to handle OPERATION for DOCUMENT.\n\
12851 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be\n\
12852 nil for the default action), and DOCUMENT is typically the name of a\n\
12853 document file or URL, but can also be a program executable to run or\n\
12854 a directory to open in the Windows Explorer.\n\
12855 \n\
12856 If DOCUMENT is a program executable, PARAMETERS can be a string\n\
12857 containing command line parameters, but otherwise should be nil.\n\
12858 \n\
12859 SHOW-FLAG can be used to control whether the invoked application is hidden\n\
12860 or minimized. If SHOW-FLAG is nil, the application is displayed normally,\n\
12861 otherwise it is an integer representing a ShowWindow flag:\n\
12862 \n\
12863 0 - start hidden\n\
12864 1 - start normally\n\
12865 3 - start maximized\n\
12866 6 - start minimized")
12867 (operation, document, parameters, show_flag)
12868 Lisp_Object operation, document, parameters, show_flag;
12869 {
12870 Lisp_Object current_dir;
12871
12872 CHECK_STRING (document, 0);
12873
12874 /* Encode filename and current directory. */
12875 current_dir = ENCODE_FILE (current_buffer->directory);
12876 document = ENCODE_FILE (document);
12877 if ((int) ShellExecute (NULL,
12878 (STRINGP (operation) ?
12879 XSTRING (operation)->data : NULL),
12880 XSTRING (document)->data,
12881 (STRINGP (parameters) ?
12882 XSTRING (parameters)->data : NULL),
12883 XSTRING (current_dir)->data,
12884 (INTEGERP (show_flag) ?
12885 XINT (show_flag) : SW_SHOWDEFAULT))
12886 > 32)
12887 return Qt;
12888 error ("ShellExecute failed");
12889 }
12890
12891 /* Lookup virtual keycode from string representing the name of a
12892 non-ascii keystroke into the corresponding virtual key, using
12893 lispy_function_keys. */
12894 static int
12895 lookup_vk_code (char *key)
12896 {
12897 int i;
12898
12899 for (i = 0; i < 256; i++)
12900 if (lispy_function_keys[i] != 0
12901 && strcmp (lispy_function_keys[i], key) == 0)
12902 return i;
12903
12904 return -1;
12905 }
12906
12907 /* Convert a one-element vector style key sequence to a hot key
12908 definition. */
12909 static int
12910 w32_parse_hot_key (key)
12911 Lisp_Object key;
12912 {
12913 /* Copied from Fdefine_key and store_in_keymap. */
12914 register Lisp_Object c;
12915 int vk_code;
12916 int lisp_modifiers;
12917 int w32_modifiers;
12918 struct gcpro gcpro1;
12919
12920 CHECK_VECTOR (key, 0);
12921
12922 if (XFASTINT (Flength (key)) != 1)
12923 return Qnil;
12924
12925 GCPRO1 (key);
12926
12927 c = Faref (key, make_number (0));
12928
12929 if (CONSP (c) && lucid_event_type_list_p (c))
12930 c = Fevent_convert_list (c);
12931
12932 UNGCPRO;
12933
12934 if (! INTEGERP (c) && ! SYMBOLP (c))
12935 error ("Key definition is invalid");
12936
12937 /* Work out the base key and the modifiers. */
12938 if (SYMBOLP (c))
12939 {
12940 c = parse_modifiers (c);
12941 lisp_modifiers = Fcar (Fcdr (c));
12942 c = Fcar (c);
12943 if (!SYMBOLP (c))
12944 abort ();
12945 vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
12946 }
12947 else if (INTEGERP (c))
12948 {
12949 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
12950 /* Many ascii characters are their own virtual key code. */
12951 vk_code = XINT (c) & CHARACTERBITS;
12952 }
12953
12954 if (vk_code < 0 || vk_code > 255)
12955 return Qnil;
12956
12957 if ((lisp_modifiers & meta_modifier) != 0
12958 && !NILP (Vw32_alt_is_meta))
12959 lisp_modifiers |= alt_modifier;
12960
12961 /* Supply defs missing from mingw32. */
12962 #ifndef MOD_ALT
12963 #define MOD_ALT 0x0001
12964 #define MOD_CONTROL 0x0002
12965 #define MOD_SHIFT 0x0004
12966 #define MOD_WIN 0x0008
12967 #endif
12968
12969 /* Convert lisp modifiers to Windows hot-key form. */
12970 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
12971 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
12972 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
12973 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
12974
12975 return HOTKEY (vk_code, w32_modifiers);
12976 }
12977
12978 DEFUN ("w32-register-hot-key", Fw32_register_hot_key, Sw32_register_hot_key, 1, 1, 0,
12979 "Register KEY as a hot-key combination.\n\
12980 Certain key combinations like Alt-Tab are reserved for system use on\n\
12981 Windows, and therefore are normally intercepted by the system. However,\n\
12982 most of these key combinations can be received by registering them as\n\
12983 hot-keys, overriding their special meaning.\n\
12984 \n\
12985 KEY must be a one element key definition in vector form that would be\n\
12986 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta\n\
12987 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper\n\
12988 is always interpreted as the Windows modifier keys.\n\
12989 \n\
12990 The return value is the hotkey-id if registered, otherwise nil.")
12991 (key)
12992 Lisp_Object key;
12993 {
12994 key = w32_parse_hot_key (key);
12995
12996 if (NILP (Fmemq (key, w32_grabbed_keys)))
12997 {
12998 /* Reuse an empty slot if possible. */
12999 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
13000
13001 /* Safe to add new key to list, even if we have focus. */
13002 if (NILP (item))
13003 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
13004 else
13005 XCAR (item) = key;
13006
13007 /* Notify input thread about new hot-key definition, so that it
13008 takes effect without needing to switch focus. */
13009 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
13010 (WPARAM) key, 0);
13011 }
13012
13013 return key;
13014 }
13015
13016 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key, Sw32_unregister_hot_key, 1, 1, 0,
13017 "Unregister HOTKEY as a hot-key combination.")
13018 (key)
13019 Lisp_Object key;
13020 {
13021 Lisp_Object item;
13022
13023 if (!INTEGERP (key))
13024 key = w32_parse_hot_key (key);
13025
13026 item = Fmemq (key, w32_grabbed_keys);
13027
13028 if (!NILP (item))
13029 {
13030 /* Notify input thread about hot-key definition being removed, so
13031 that it takes effect without needing focus switch. */
13032 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
13033 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
13034 {
13035 MSG msg;
13036 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13037 }
13038 return Qt;
13039 }
13040 return Qnil;
13041 }
13042
13043 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys, Sw32_registered_hot_keys, 0, 0, 0,
13044 "Return list of registered hot-key IDs.")
13045 ()
13046 {
13047 return Fcopy_sequence (w32_grabbed_keys);
13048 }
13049
13050 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key, Sw32_reconstruct_hot_key, 1, 1, 0,
13051 "Convert hot-key ID to a lisp key combination.")
13052 (hotkeyid)
13053 Lisp_Object hotkeyid;
13054 {
13055 int vk_code, w32_modifiers;
13056 Lisp_Object key;
13057
13058 CHECK_NUMBER (hotkeyid, 0);
13059
13060 vk_code = HOTKEY_VK_CODE (hotkeyid);
13061 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
13062
13063 if (lispy_function_keys[vk_code])
13064 key = intern (lispy_function_keys[vk_code]);
13065 else
13066 key = make_number (vk_code);
13067
13068 key = Fcons (key, Qnil);
13069 if (w32_modifiers & MOD_SHIFT)
13070 key = Fcons (Qshift, key);
13071 if (w32_modifiers & MOD_CONTROL)
13072 key = Fcons (Qctrl, key);
13073 if (w32_modifiers & MOD_ALT)
13074 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
13075 if (w32_modifiers & MOD_WIN)
13076 key = Fcons (Qhyper, key);
13077
13078 return key;
13079 }
13080
13081 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key, Sw32_toggle_lock_key, 1, 2, 0,
13082 "Toggle the state of the lock key KEY.\n\
13083 KEY can be `capslock', `kp-numlock', or `scroll'.\n\
13084 If the optional parameter NEW-STATE is a number, then the state of KEY\n\
13085 is set to off if the low bit of NEW-STATE is zero, otherwise on.")
13086 (key, new_state)
13087 Lisp_Object key, new_state;
13088 {
13089 int vk_code;
13090 int cur_state;
13091
13092 if (EQ (key, intern ("capslock")))
13093 vk_code = VK_CAPITAL;
13094 else if (EQ (key, intern ("kp-numlock")))
13095 vk_code = VK_NUMLOCK;
13096 else if (EQ (key, intern ("scroll")))
13097 vk_code = VK_SCROLL;
13098 else
13099 return Qnil;
13100
13101 if (!dwWindowsThreadId)
13102 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
13103
13104 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
13105 (WPARAM) vk_code, (LPARAM) new_state))
13106 {
13107 MSG msg;
13108 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13109 return make_number (msg.wParam);
13110 }
13111 return Qnil;
13112 }
13113 \f
13114 syms_of_w32fns ()
13115 {
13116 /* This is zero if not using MS-Windows. */
13117 w32_in_use = 0;
13118
13119 /* The section below is built by the lisp expression at the top of the file,
13120 just above where these variables are declared. */
13121 /*&&& init symbols here &&&*/
13122 Qauto_raise = intern ("auto-raise");
13123 staticpro (&Qauto_raise);
13124 Qauto_lower = intern ("auto-lower");
13125 staticpro (&Qauto_lower);
13126 Qbar = intern ("bar");
13127 staticpro (&Qbar);
13128 Qborder_color = intern ("border-color");
13129 staticpro (&Qborder_color);
13130 Qborder_width = intern ("border-width");
13131 staticpro (&Qborder_width);
13132 Qbox = intern ("box");
13133 staticpro (&Qbox);
13134 Qcursor_color = intern ("cursor-color");
13135 staticpro (&Qcursor_color);
13136 Qcursor_type = intern ("cursor-type");
13137 staticpro (&Qcursor_type);
13138 Qgeometry = intern ("geometry");
13139 staticpro (&Qgeometry);
13140 Qicon_left = intern ("icon-left");
13141 staticpro (&Qicon_left);
13142 Qicon_top = intern ("icon-top");
13143 staticpro (&Qicon_top);
13144 Qicon_type = intern ("icon-type");
13145 staticpro (&Qicon_type);
13146 Qicon_name = intern ("icon-name");
13147 staticpro (&Qicon_name);
13148 Qinternal_border_width = intern ("internal-border-width");
13149 staticpro (&Qinternal_border_width);
13150 Qleft = intern ("left");
13151 staticpro (&Qleft);
13152 Qright = intern ("right");
13153 staticpro (&Qright);
13154 Qmouse_color = intern ("mouse-color");
13155 staticpro (&Qmouse_color);
13156 Qnone = intern ("none");
13157 staticpro (&Qnone);
13158 Qparent_id = intern ("parent-id");
13159 staticpro (&Qparent_id);
13160 Qscroll_bar_width = intern ("scroll-bar-width");
13161 staticpro (&Qscroll_bar_width);
13162 Qsuppress_icon = intern ("suppress-icon");
13163 staticpro (&Qsuppress_icon);
13164 Qundefined_color = intern ("undefined-color");
13165 staticpro (&Qundefined_color);
13166 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
13167 staticpro (&Qvertical_scroll_bars);
13168 Qvisibility = intern ("visibility");
13169 staticpro (&Qvisibility);
13170 Qwindow_id = intern ("window-id");
13171 staticpro (&Qwindow_id);
13172 Qx_frame_parameter = intern ("x-frame-parameter");
13173 staticpro (&Qx_frame_parameter);
13174 Qx_resource_name = intern ("x-resource-name");
13175 staticpro (&Qx_resource_name);
13176 Quser_position = intern ("user-position");
13177 staticpro (&Quser_position);
13178 Quser_size = intern ("user-size");
13179 staticpro (&Quser_size);
13180 Qscreen_gamma = intern ("screen-gamma");
13181 staticpro (&Qscreen_gamma);
13182 Qline_spacing = intern ("line-spacing");
13183 staticpro (&Qline_spacing);
13184 Qcenter = intern ("center");
13185 staticpro (&Qcenter);
13186 /* This is the end of symbol initialization. */
13187
13188 Qhyper = intern ("hyper");
13189 staticpro (&Qhyper);
13190 Qsuper = intern ("super");
13191 staticpro (&Qsuper);
13192 Qmeta = intern ("meta");
13193 staticpro (&Qmeta);
13194 Qalt = intern ("alt");
13195 staticpro (&Qalt);
13196 Qctrl = intern ("ctrl");
13197 staticpro (&Qctrl);
13198 Qcontrol = intern ("control");
13199 staticpro (&Qcontrol);
13200 Qshift = intern ("shift");
13201 staticpro (&Qshift);
13202
13203 /* Text property `display' should be nonsticky by default. */
13204 Vtext_property_default_nonsticky
13205 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
13206
13207
13208 Qlaplace = intern ("laplace");
13209 staticpro (&Qlaplace);
13210
13211 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
13212 staticpro (&Qface_set_after_frame_default);
13213
13214 Fput (Qundefined_color, Qerror_conditions,
13215 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
13216 Fput (Qundefined_color, Qerror_message,
13217 build_string ("Undefined color"));
13218
13219 staticpro (&w32_grabbed_keys);
13220 w32_grabbed_keys = Qnil;
13221
13222 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
13223 "An array of color name mappings for windows.");
13224 Vw32_color_map = Qnil;
13225
13226 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
13227 "Non-nil if alt key presses are passed on to Windows.\n\
13228 When non-nil, for example, alt pressed and released and then space will\n\
13229 open the System menu. When nil, Emacs silently swallows alt key events.");
13230 Vw32_pass_alt_to_system = Qnil;
13231
13232 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
13233 "Non-nil if the alt key is to be considered the same as the meta key.\n\
13234 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta.");
13235 Vw32_alt_is_meta = Qt;
13236
13237 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
13238 "If non-zero, the virtual key code for an alternative quit key.");
13239 XSETINT (Vw32_quit_key, 0);
13240
13241 DEFVAR_LISP ("w32-pass-lwindow-to-system",
13242 &Vw32_pass_lwindow_to_system,
13243 "Non-nil if the left \"Windows\" key is passed on to Windows.\n\
13244 When non-nil, the Start menu is opened by tapping the key.");
13245 Vw32_pass_lwindow_to_system = Qt;
13246
13247 DEFVAR_LISP ("w32-pass-rwindow-to-system",
13248 &Vw32_pass_rwindow_to_system,
13249 "Non-nil if the right \"Windows\" key is passed on to Windows.\n\
13250 When non-nil, the Start menu is opened by tapping the key.");
13251 Vw32_pass_rwindow_to_system = Qt;
13252
13253 DEFVAR_INT ("w32-phantom-key-code",
13254 &Vw32_phantom_key_code,
13255 "Virtual key code used to generate \"phantom\" key presses.\n\
13256 Value is a number between 0 and 255.\n\
13257 \n\
13258 Phantom key presses are generated in order to stop the system from\n\
13259 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or\n\
13260 `w32-pass-rwindow-to-system' is nil.");
13261 /* Although 255 is technically not a valid key code, it works and
13262 means that this hack won't interfere with any real key code. */
13263 Vw32_phantom_key_code = 255;
13264
13265 DEFVAR_LISP ("w32-enable-num-lock",
13266 &Vw32_enable_num_lock,
13267 "Non-nil if Num Lock should act normally.\n\
13268 Set to nil to see Num Lock as the key `kp-numlock'.");
13269 Vw32_enable_num_lock = Qt;
13270
13271 DEFVAR_LISP ("w32-enable-caps-lock",
13272 &Vw32_enable_caps_lock,
13273 "Non-nil if Caps Lock should act normally.\n\
13274 Set to nil to see Caps Lock as the key `capslock'.");
13275 Vw32_enable_caps_lock = Qt;
13276
13277 DEFVAR_LISP ("w32-scroll-lock-modifier",
13278 &Vw32_scroll_lock_modifier,
13279 "Modifier to use for the Scroll Lock on state.\n\
13280 The value can be hyper, super, meta, alt, control or shift for the\n\
13281 respective modifier, or nil to see Scroll Lock as the key `scroll'.\n\
13282 Any other value will cause the key to be ignored.");
13283 Vw32_scroll_lock_modifier = Qt;
13284
13285 DEFVAR_LISP ("w32-lwindow-modifier",
13286 &Vw32_lwindow_modifier,
13287 "Modifier to use for the left \"Windows\" key.\n\
13288 The value can be hyper, super, meta, alt, control or shift for the\n\
13289 respective modifier, or nil to appear as the key `lwindow'.\n\
13290 Any other value will cause the key to be ignored.");
13291 Vw32_lwindow_modifier = Qnil;
13292
13293 DEFVAR_LISP ("w32-rwindow-modifier",
13294 &Vw32_rwindow_modifier,
13295 "Modifier to use for the right \"Windows\" key.\n\
13296 The value can be hyper, super, meta, alt, control or shift for the\n\
13297 respective modifier, or nil to appear as the key `rwindow'.\n\
13298 Any other value will cause the key to be ignored.");
13299 Vw32_rwindow_modifier = Qnil;
13300
13301 DEFVAR_LISP ("w32-apps-modifier",
13302 &Vw32_apps_modifier,
13303 "Modifier to use for the \"Apps\" key.\n\
13304 The value can be hyper, super, meta, alt, control or shift for the\n\
13305 respective modifier, or nil to appear as the key `apps'.\n\
13306 Any other value will cause the key to be ignored.");
13307 Vw32_apps_modifier = Qnil;
13308
13309 DEFVAR_LISP ("w32-enable-synthesized-fonts", &Vw32_enable_synthesized_fonts,
13310 "Non-nil enables selection of artificially italicized and bold fonts.");
13311 Vw32_enable_synthesized_fonts = Qnil;
13312
13313 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
13314 "Non-nil enables Windows palette management to map colors exactly.");
13315 Vw32_enable_palette = Qt;
13316
13317 DEFVAR_INT ("w32-mouse-button-tolerance",
13318 &Vw32_mouse_button_tolerance,
13319 "Analogue of double click interval for faking middle mouse events.\n\
13320 The value is the minimum time in milliseconds that must elapse between\n\
13321 left/right button down events before they are considered distinct events.\n\
13322 If both mouse buttons are depressed within this interval, a middle mouse\n\
13323 button down event is generated instead.");
13324 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
13325
13326 DEFVAR_INT ("w32-mouse-move-interval",
13327 &Vw32_mouse_move_interval,
13328 "Minimum interval between mouse move events.\n\
13329 The value is the minimum time in milliseconds that must elapse between\n\
13330 successive mouse move (or scroll bar drag) events before they are\n\
13331 reported as lisp events.");
13332 XSETINT (Vw32_mouse_move_interval, 0);
13333
13334 init_x_parm_symbols ();
13335
13336 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
13337 "List of directories to search for bitmap files for w32.");
13338 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
13339
13340 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
13341 "The shape of the pointer when over text.\n\
13342 Changing the value does not affect existing frames\n\
13343 unless you set the mouse color.");
13344 Vx_pointer_shape = Qnil;
13345
13346 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
13347 "The name Emacs uses to look up resources; for internal use only.\n\
13348 `x-get-resource' uses this as the first component of the instance name\n\
13349 when requesting resource values.\n\
13350 Emacs initially sets `x-resource-name' to the name under which Emacs\n\
13351 was invoked, or to the value specified with the `-name' or `-rn'\n\
13352 switches, if present.");
13353 Vx_resource_name = Qnil;
13354
13355 Vx_nontext_pointer_shape = Qnil;
13356
13357 Vx_mode_pointer_shape = Qnil;
13358
13359 DEFVAR_LISP ("x-busy-pointer-shape", &Vx_busy_pointer_shape,
13360 "The shape of the pointer when Emacs is busy.\n\
13361 This variable takes effect when you create a new frame\n\
13362 or when you set the mouse color.");
13363 Vx_busy_pointer_shape = Qnil;
13364
13365 DEFVAR_BOOL ("display-busy-cursor", &display_busy_cursor_p,
13366 "Non-zero means Emacs displays a busy cursor on window systems.");
13367 display_busy_cursor_p = 1;
13368
13369 DEFVAR_LISP ("busy-cursor-delay", &Vbusy_cursor_delay,
13370 "*Seconds to wait before displaying a busy-cursor.\n\
13371 Value must be an integer or float.");
13372 Vbusy_cursor_delay = make_number (DEFAULT_BUSY_CURSOR_DELAY);
13373
13374 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
13375 &Vx_sensitive_text_pointer_shape,
13376 "The shape of the pointer when over mouse-sensitive text.\n\
13377 This variable takes effect when you create a new frame\n\
13378 or when you set the mouse color.");
13379 Vx_sensitive_text_pointer_shape = Qnil;
13380
13381 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
13382 &Vx_window_horizontal_drag_shape,
13383 "Pointer shape to use for indicating a window can be dragged horizontally.\n\
13384 This variable takes effect when you create a new frame\n\
13385 or when you set the mouse color.");
13386 Vx_window_horizontal_drag_shape = Qnil;
13387
13388 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
13389 "A string indicating the foreground color of the cursor box.");
13390 Vx_cursor_fore_pixel = Qnil;
13391
13392 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
13393 "Non-nil if no window manager is in use.\n\
13394 Emacs doesn't try to figure this out; this is always nil\n\
13395 unless you set it to something else.");
13396 /* We don't have any way to find this out, so set it to nil
13397 and maybe the user would like to set it to t. */
13398 Vx_no_window_manager = Qnil;
13399
13400 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
13401 &Vx_pixel_size_width_font_regexp,
13402 "Regexp matching a font name whose width is the same as `PIXEL_SIZE'.\n\
13403 \n\
13404 Since Emacs gets width of a font matching with this regexp from\n\
13405 PIXEL_SIZE field of the name, font finding mechanism gets faster for\n\
13406 such a font. This is especially effective for such large fonts as\n\
13407 Chinese, Japanese, and Korean.");
13408 Vx_pixel_size_width_font_regexp = Qnil;
13409
13410 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
13411 "Time after which cached images are removed from the cache.\n\
13412 When an image has not been displayed this many seconds, remove it\n\
13413 from the image cache. Value must be an integer or nil with nil\n\
13414 meaning don't clear the cache.");
13415 Vimage_cache_eviction_delay = make_number (30 * 60);
13416
13417 DEFVAR_LISP ("w32-bdf-filename-alist",
13418 &Vw32_bdf_filename_alist,
13419 "List of bdf fonts and their corresponding filenames.");
13420 Vw32_bdf_filename_alist = Qnil;
13421
13422 DEFVAR_BOOL ("w32-strict-fontnames",
13423 &w32_strict_fontnames,
13424 "Non-nil means only use fonts that are exact matches for those requested.\n\
13425 Default is nil, which allows old fontnames that are not XLFD compliant,\n\
13426 and allows third-party CJK display to work by specifying false charset\n\
13427 fields to trick Emacs into translating to Big5, SJIS etc.\n\
13428 Setting this to t will prevent wrong fonts being selected when\n\
13429 fontsets are automatically created.");
13430 w32_strict_fontnames = 0;
13431
13432 DEFVAR_BOOL ("w32-strict-painting",
13433 &w32_strict_painting,
13434 "Non-nil means use strict rules for repainting frames.\n\
13435 Set this to nil to get the old behaviour for repainting; this should\n\
13436 only be necessary if the default setting causes problems.");
13437 w32_strict_painting = 1;
13438
13439 DEFVAR_LISP ("w32-system-coding-system",
13440 &Vw32_system_coding_system,
13441 "Coding system used by Windows system functions, such as for font names.");
13442 Vw32_system_coding_system = Qnil;
13443
13444 DEFVAR_LISP ("w32-charset-info-alist",
13445 &Vw32_charset_info_alist,
13446 "Alist linking Emacs character sets to Windows fonts\n\
13447 and codepages. Each entry should be of the form:\n\
13448 \n\
13449 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))\n\
13450 \n\
13451 where CHARSET_NAME is a string used in font names to identify the charset,\n\
13452 WINDOWS_CHARSET is a symbol that can be one of:\n\
13453 w32-charset-ansi, w32-charset-default, w32-charset-symbol,\n\
13454 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,\n\
13455 w32-charset-chinesebig5, "
13456 #ifdef JOHAB_CHARSET
13457 "w32-charset-johab, w32-charset-hebrew,\n\
13458 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,\n\
13459 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,\n\
13460 w32-charset-russian, w32-charset-mac, w32-charset-baltic,\n"
13461 #endif
13462 #ifdef UNICODE_CHARSET
13463 "w32-charset-unicode, "
13464 #endif
13465 "or w32-charset-oem.\n\
13466 CODEPAGE should be an integer specifying the codepage that should be used\n\
13467 to display the character set, t to do no translation and output as Unicode,\n\
13468 or nil to do no translation and output as 8 bit (or multibyte on far-east\n\
13469 versions of Windows) characters.");
13470 Vw32_charset_info_alist = Qnil;
13471
13472 staticpro (&Qw32_charset_ansi);
13473 Qw32_charset_ansi = intern ("w32-charset-ansi");
13474 staticpro (&Qw32_charset_symbol);
13475 Qw32_charset_symbol = intern ("w32-charset-symbol");
13476 staticpro (&Qw32_charset_shiftjis);
13477 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
13478 staticpro (&Qw32_charset_hangeul);
13479 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
13480 staticpro (&Qw32_charset_chinesebig5);
13481 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
13482 staticpro (&Qw32_charset_gb2312);
13483 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
13484 staticpro (&Qw32_charset_oem);
13485 Qw32_charset_oem = intern ("w32-charset-oem");
13486
13487 #ifdef JOHAB_CHARSET
13488 {
13489 static int w32_extra_charsets_defined = 1;
13490 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined, "");
13491
13492 staticpro (&Qw32_charset_johab);
13493 Qw32_charset_johab = intern ("w32-charset-johab");
13494 staticpro (&Qw32_charset_easteurope);
13495 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
13496 staticpro (&Qw32_charset_turkish);
13497 Qw32_charset_turkish = intern ("w32-charset-turkish");
13498 staticpro (&Qw32_charset_baltic);
13499 Qw32_charset_baltic = intern ("w32-charset-baltic");
13500 staticpro (&Qw32_charset_russian);
13501 Qw32_charset_russian = intern ("w32-charset-russian");
13502 staticpro (&Qw32_charset_arabic);
13503 Qw32_charset_arabic = intern ("w32-charset-arabic");
13504 staticpro (&Qw32_charset_greek);
13505 Qw32_charset_greek = intern ("w32-charset-greek");
13506 staticpro (&Qw32_charset_hebrew);
13507 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
13508 staticpro (&Qw32_charset_vietnamese);
13509 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
13510 staticpro (&Qw32_charset_thai);
13511 Qw32_charset_thai = intern ("w32-charset-thai");
13512 staticpro (&Qw32_charset_mac);
13513 Qw32_charset_mac = intern ("w32-charset-mac");
13514 }
13515 #endif
13516
13517 #ifdef UNICODE_CHARSET
13518 {
13519 static int w32_unicode_charset_defined = 1;
13520 DEFVAR_BOOL ("w32-unicode-charset-defined",
13521 &w32_unicode_charset_defined, "");
13522
13523 staticpro (&Qw32_charset_unicode);
13524 Qw32_charset_unicode = intern ("w32-charset-unicode");
13525 #endif
13526
13527 defsubr (&Sx_get_resource);
13528 #if 0 /* TODO: Port to W32 */
13529 defsubr (&Sx_change_window_property);
13530 defsubr (&Sx_delete_window_property);
13531 defsubr (&Sx_window_property);
13532 #endif
13533 defsubr (&Sxw_display_color_p);
13534 defsubr (&Sx_display_grayscale_p);
13535 defsubr (&Sxw_color_defined_p);
13536 defsubr (&Sxw_color_values);
13537 defsubr (&Sx_server_max_request_size);
13538 defsubr (&Sx_server_vendor);
13539 defsubr (&Sx_server_version);
13540 defsubr (&Sx_display_pixel_width);
13541 defsubr (&Sx_display_pixel_height);
13542 defsubr (&Sx_display_mm_width);
13543 defsubr (&Sx_display_mm_height);
13544 defsubr (&Sx_display_screens);
13545 defsubr (&Sx_display_planes);
13546 defsubr (&Sx_display_color_cells);
13547 defsubr (&Sx_display_visual_class);
13548 defsubr (&Sx_display_backing_store);
13549 defsubr (&Sx_display_save_under);
13550 defsubr (&Sx_parse_geometry);
13551 defsubr (&Sx_create_frame);
13552 defsubr (&Sx_open_connection);
13553 defsubr (&Sx_close_connection);
13554 defsubr (&Sx_display_list);
13555 defsubr (&Sx_synchronize);
13556
13557 /* W32 specific functions */
13558
13559 defsubr (&Sw32_focus_frame);
13560 defsubr (&Sw32_select_font);
13561 defsubr (&Sw32_define_rgb_color);
13562 defsubr (&Sw32_default_color_map);
13563 defsubr (&Sw32_load_color_file);
13564 defsubr (&Sw32_send_sys_command);
13565 defsubr (&Sw32_shell_execute);
13566 defsubr (&Sw32_register_hot_key);
13567 defsubr (&Sw32_unregister_hot_key);
13568 defsubr (&Sw32_registered_hot_keys);
13569 defsubr (&Sw32_reconstruct_hot_key);
13570 defsubr (&Sw32_toggle_lock_key);
13571 defsubr (&Sw32_find_bdf_fonts);
13572
13573 /* Setting callback functions for fontset handler. */
13574 get_font_info_func = w32_get_font_info;
13575
13576 #if 0 /* This function pointer doesn't seem to be used anywhere.
13577 And the pointer assigned has the wrong type, anyway. */
13578 list_fonts_func = w32_list_fonts;
13579 #endif
13580
13581 load_font_func = w32_load_font;
13582 find_ccl_program_func = w32_find_ccl_program;
13583 query_font_func = w32_query_font;
13584 set_frame_fontset_func = x_set_font;
13585 check_window_system_func = check_w32;
13586
13587 #if 0 /* TODO Image support for W32 */
13588 /* Images. */
13589 Qxbm = intern ("xbm");
13590 staticpro (&Qxbm);
13591 QCtype = intern (":type");
13592 staticpro (&QCtype);
13593 QCalgorithm = intern (":algorithm");
13594 staticpro (&QCalgorithm);
13595 QCheuristic_mask = intern (":heuristic-mask");
13596 staticpro (&QCheuristic_mask);
13597 QCcolor_symbols = intern (":color-symbols");
13598 staticpro (&QCcolor_symbols);
13599 QCascent = intern (":ascent");
13600 staticpro (&QCascent);
13601 QCmargin = intern (":margin");
13602 staticpro (&QCmargin);
13603 QCrelief = intern (":relief");
13604 staticpro (&QCrelief);
13605 Qpostscript = intern ("postscript");
13606 staticpro (&Qpostscript);
13607 QCloader = intern (":loader");
13608 staticpro (&QCloader);
13609 QCbounding_box = intern (":bounding-box");
13610 staticpro (&QCbounding_box);
13611 QCpt_width = intern (":pt-width");
13612 staticpro (&QCpt_width);
13613 QCpt_height = intern (":pt-height");
13614 staticpro (&QCpt_height);
13615 QCindex = intern (":index");
13616 staticpro (&QCindex);
13617 Qpbm = intern ("pbm");
13618 staticpro (&Qpbm);
13619
13620 #if HAVE_XPM
13621 Qxpm = intern ("xpm");
13622 staticpro (&Qxpm);
13623 #endif
13624
13625 #if HAVE_JPEG
13626 Qjpeg = intern ("jpeg");
13627 staticpro (&Qjpeg);
13628 #endif
13629
13630 #if HAVE_TIFF
13631 Qtiff = intern ("tiff");
13632 staticpro (&Qtiff);
13633 #endif
13634
13635 #if HAVE_GIF
13636 Qgif = intern ("gif");
13637 staticpro (&Qgif);
13638 #endif
13639
13640 #if HAVE_PNG
13641 Qpng = intern ("png");
13642 staticpro (&Qpng);
13643 #endif
13644
13645 defsubr (&Sclear_image_cache);
13646
13647 #if GLYPH_DEBUG
13648 defsubr (&Simagep);
13649 defsubr (&Slookup_image);
13650 #endif
13651 #endif /* TODO */
13652
13653 busy_cursor_atimer = NULL;
13654 busy_cursor_shown_p = 0;
13655 #ifdef TODO /* Tooltip support not complete. */
13656 defsubr (&Sx_show_tip);
13657 defsubr (&Sx_hide_tip);
13658 #endif
13659 staticpro (&tip_timer);
13660 tip_timer = Qnil;
13661
13662 defsubr (&Sx_file_dialog);
13663 }
13664
13665
13666 void
13667 init_xfns ()
13668 {
13669 image_types = NULL;
13670 Vimage_types = Qnil;
13671
13672 #if 0 /* TODO : Image support for W32 */
13673 define_image_type (&xbm_type);
13674 define_image_type (&gs_type);
13675 define_image_type (&pbm_type);
13676
13677 #if HAVE_XPM
13678 define_image_type (&xpm_type);
13679 #endif
13680
13681 #if HAVE_JPEG
13682 define_image_type (&jpeg_type);
13683 #endif
13684
13685 #if HAVE_TIFF
13686 define_image_type (&tiff_type);
13687 #endif
13688
13689 #if HAVE_GIF
13690 define_image_type (&gif_type);
13691 #endif
13692
13693 #if HAVE_PNG
13694 define_image_type (&png_type);
13695 #endif
13696 #endif /* TODO */
13697 }
13698
13699 #undef abort
13700
13701 void
13702 w32_abort()
13703 {
13704 int button;
13705 button = MessageBox (NULL,
13706 "A fatal error has occurred!\n\n"
13707 "Select Abort to exit, Retry to debug, Ignore to continue",
13708 "Emacs Abort Dialog",
13709 MB_ICONEXCLAMATION | MB_TASKMODAL
13710 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
13711 switch (button)
13712 {
13713 case IDRETRY:
13714 DebugBreak ();
13715 break;
13716 case IDIGNORE:
13717 break;
13718 case IDABORT:
13719 default:
13720 abort ();
13721 break;
13722 }
13723 }
13724
13725 /* For convenience when debugging. */
13726 int
13727 w32_last_error()
13728 {
13729 return GetLastError ();
13730 }