Add arch taglines
[bpt/emacs.git] / src / w32fns.c
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 92, 93, 94, 95, 1996, 1997, 1998, 1999, 2000, 2001
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
21
22 /* Added by Kevin Gallo */
23
24 #include <config.h>
25
26 #include <signal.h>
27 #include <stdio.h>
28 #include <limits.h>
29 #include <errno.h>
30
31 #include "lisp.h"
32 #include "charset.h"
33 #include "dispextern.h"
34 #include "w32term.h"
35 #include "keyboard.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "buffer.h"
39 #include "fontset.h"
40 #include "intervals.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "w32heap.h"
44 #include "termhooks.h"
45 #include "coding.h"
46 #include "ccl.h"
47 #include "systime.h"
48
49 #include "bitmaps/gray.xbm"
50
51 #include <commdlg.h>
52 #include <shellapi.h>
53 #include <ctype.h>
54
55 #include <dlgs.h>
56 #define FILE_NAME_TEXT_FIELD edt1
57
58 void syms_of_w32fns ();
59 void globals_of_w32fns ();
60 static void init_external_image_libraries ();
61
62 extern void free_frame_menubar ();
63 extern double atof ();
64 extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
65 extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
66 extern void w32_free_menu_strings P_ ((HWND));
67
68 extern int quit_char;
69
70 extern char *lispy_function_keys[];
71
72 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
73 it, and including `bitmaps/gray' more than once is a problem when
74 config.h defines `static' as an empty replacement string. */
75
76 int gray_bitmap_width = gray_width;
77 int gray_bitmap_height = gray_height;
78 unsigned char *gray_bitmap_bits = gray_bits;
79
80 /* The colormap for converting color names to RGB values */
81 Lisp_Object Vw32_color_map;
82
83 /* Non nil if alt key presses are passed on to Windows. */
84 Lisp_Object Vw32_pass_alt_to_system;
85
86 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
87 to alt_modifier. */
88 Lisp_Object Vw32_alt_is_meta;
89
90 /* If non-zero, the windows virtual key code for an alternative quit key. */
91 Lisp_Object Vw32_quit_key;
92
93 /* Non nil if left window key events are passed on to Windows (this only
94 affects whether "tapping" the key opens the Start menu). */
95 Lisp_Object Vw32_pass_lwindow_to_system;
96
97 /* Non nil if right window key events are passed on to Windows (this
98 only affects whether "tapping" the key opens the Start menu). */
99 Lisp_Object Vw32_pass_rwindow_to_system;
100
101 /* Virtual key code used to generate "phantom" key presses in order
102 to stop system from acting on Windows key events. */
103 Lisp_Object Vw32_phantom_key_code;
104
105 /* Modifier associated with the left "Windows" key, or nil to act as a
106 normal key. */
107 Lisp_Object Vw32_lwindow_modifier;
108
109 /* Modifier associated with the right "Windows" key, or nil to act as a
110 normal key. */
111 Lisp_Object Vw32_rwindow_modifier;
112
113 /* Modifier associated with the "Apps" key, or nil to act as a normal
114 key. */
115 Lisp_Object Vw32_apps_modifier;
116
117 /* Value is nil if Num Lock acts as a function key. */
118 Lisp_Object Vw32_enable_num_lock;
119
120 /* Value is nil if Caps Lock acts as a function key. */
121 Lisp_Object Vw32_enable_caps_lock;
122
123 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
124 Lisp_Object Vw32_scroll_lock_modifier;
125
126 /* Switch to control whether we inhibit requests for synthesized bold
127 and italic versions of fonts. */
128 int w32_enable_synthesized_fonts;
129
130 /* Enable palette management. */
131 Lisp_Object Vw32_enable_palette;
132
133 /* Control how close left/right button down events must be to
134 be converted to a middle button down event. */
135 Lisp_Object Vw32_mouse_button_tolerance;
136
137 /* Minimum interval between mouse movement (and scroll bar drag)
138 events that are passed on to the event loop. */
139 Lisp_Object Vw32_mouse_move_interval;
140
141 /* Flag to indicate if XBUTTON events should be passed on to Windows. */
142 int w32_pass_extra_mouse_buttons_to_system;
143
144 /* Non nil if no window manager is in use. */
145 Lisp_Object Vx_no_window_manager;
146
147 /* Non-zero means we're allowed to display a hourglass pointer. */
148
149 int display_hourglass_p;
150
151 /* The background and shape of the mouse pointer, and shape when not
152 over text or in the modeline. */
153
154 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
155 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape, Vx_hand_shape;
156
157 /* The shape when over mouse-sensitive text. */
158
159 Lisp_Object Vx_sensitive_text_pointer_shape;
160
161 #ifndef IDC_HAND
162 #define IDC_HAND MAKEINTRESOURCE(32649)
163 #endif
164
165 /* Color of chars displayed in cursor box. */
166
167 Lisp_Object Vx_cursor_fore_pixel;
168
169 /* Nonzero if using Windows. */
170
171 static int w32_in_use;
172
173 /* Search path for bitmap files. */
174
175 Lisp_Object Vx_bitmap_file_path;
176
177 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
178
179 Lisp_Object Vx_pixel_size_width_font_regexp;
180
181 /* Alist of bdf fonts and the files that define them. */
182 Lisp_Object Vw32_bdf_filename_alist;
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 Lisp_Object Qnone;
200 Lisp_Object Qsuppress_icon;
201 Lisp_Object Qundefined_color;
202 Lisp_Object Qcenter;
203 Lisp_Object Qcancel_timer;
204 Lisp_Object Qhyper;
205 Lisp_Object Qsuper;
206 Lisp_Object Qmeta;
207 Lisp_Object Qalt;
208 Lisp_Object Qctrl;
209 Lisp_Object Qcontrol;
210 Lisp_Object Qshift;
211
212 Lisp_Object Qw32_charset_ansi;
213 Lisp_Object Qw32_charset_default;
214 Lisp_Object Qw32_charset_symbol;
215 Lisp_Object Qw32_charset_shiftjis;
216 Lisp_Object Qw32_charset_hangeul;
217 Lisp_Object Qw32_charset_gb2312;
218 Lisp_Object Qw32_charset_chinesebig5;
219 Lisp_Object Qw32_charset_oem;
220
221 #ifndef JOHAB_CHARSET
222 #define JOHAB_CHARSET 130
223 #endif
224 #ifdef JOHAB_CHARSET
225 Lisp_Object Qw32_charset_easteurope;
226 Lisp_Object Qw32_charset_turkish;
227 Lisp_Object Qw32_charset_baltic;
228 Lisp_Object Qw32_charset_russian;
229 Lisp_Object Qw32_charset_arabic;
230 Lisp_Object Qw32_charset_greek;
231 Lisp_Object Qw32_charset_hebrew;
232 Lisp_Object Qw32_charset_vietnamese;
233 Lisp_Object Qw32_charset_thai;
234 Lisp_Object Qw32_charset_johab;
235 Lisp_Object Qw32_charset_mac;
236 #endif
237
238 #ifdef UNICODE_CHARSET
239 Lisp_Object Qw32_charset_unicode;
240 #endif
241
242 /* Prefix for system colors. */
243 #define SYSTEM_COLOR_PREFIX "System"
244 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
245
246 /* State variables for emulating a three button mouse. */
247 #define LMOUSE 1
248 #define MMOUSE 2
249 #define RMOUSE 4
250
251 static int button_state = 0;
252 static W32Msg saved_mouse_button_msg;
253 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
254 static W32Msg saved_mouse_move_msg;
255 static unsigned mouse_move_timer = 0;
256
257 /* Window that is tracking the mouse. */
258 static HWND track_mouse_window;
259
260 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
261 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
262
263 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
264 ClipboardSequence_Proc clipboard_sequence_fn = NULL;
265
266 /* W95 mousewheel handler */
267 unsigned int msh_mousewheel = 0;
268
269 /* Timers */
270 #define MOUSE_BUTTON_ID 1
271 #define MOUSE_MOVE_ID 2
272 #define MENU_FREE_ID 3
273 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
274 is received. */
275 #define MENU_FREE_DELAY 1000
276 static unsigned menu_free_timer = 0;
277
278 /* The below are defined in frame.c. */
279
280 extern Lisp_Object Vwindow_system_version;
281
282 #ifdef GLYPH_DEBUG
283 int image_cache_refcount, dpyinfo_refcount;
284 #endif
285
286
287 /* From w32term.c. */
288 extern Lisp_Object Vw32_num_mouse_buttons;
289 extern Lisp_Object Vw32_recognize_altgr;
290
291 extern HWND w32_system_caret_hwnd;
292
293 extern int w32_system_caret_height;
294 extern int w32_system_caret_x;
295 extern int w32_system_caret_y;
296 extern int w32_use_visible_system_caret;
297
298 static HWND w32_visible_system_caret_hwnd;
299
300 \f
301 /* Error if we are not connected to MS-Windows. */
302 void
303 check_w32 ()
304 {
305 if (! w32_in_use)
306 error ("MS-Windows not in use or not initialized");
307 }
308
309 /* Nonzero if we can use mouse menus.
310 You should not call this unless HAVE_MENUS is defined. */
311
312 int
313 have_menus_p ()
314 {
315 return w32_in_use;
316 }
317
318 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
319 and checking validity for W32. */
320
321 FRAME_PTR
322 check_x_frame (frame)
323 Lisp_Object frame;
324 {
325 FRAME_PTR f;
326
327 if (NILP (frame))
328 frame = selected_frame;
329 CHECK_LIVE_FRAME (frame);
330 f = XFRAME (frame);
331 if (! FRAME_W32_P (f))
332 error ("non-w32 frame used");
333 return f;
334 }
335
336 /* Let the user specify a display with a frame.
337 nil stands for the selected frame--or, if that is not a w32 frame,
338 the first display on the list. */
339
340 struct w32_display_info *
341 check_x_display_info (frame)
342 Lisp_Object frame;
343 {
344 if (NILP (frame))
345 {
346 struct frame *sf = XFRAME (selected_frame);
347
348 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
349 return FRAME_W32_DISPLAY_INFO (sf);
350 else
351 return &one_w32_display_info;
352 }
353 else if (STRINGP (frame))
354 return x_display_info_for_name (frame);
355 else
356 {
357 FRAME_PTR f;
358
359 CHECK_LIVE_FRAME (frame);
360 f = XFRAME (frame);
361 if (! FRAME_W32_P (f))
362 error ("non-w32 frame used");
363 return FRAME_W32_DISPLAY_INFO (f);
364 }
365 }
366 \f
367 /* Return the Emacs frame-object corresponding to an w32 window.
368 It could be the frame's main window or an icon window. */
369
370 /* This function can be called during GC, so use GC_xxx type test macros. */
371
372 struct frame *
373 x_window_to_frame (dpyinfo, wdesc)
374 struct w32_display_info *dpyinfo;
375 HWND wdesc;
376 {
377 Lisp_Object tail, frame;
378 struct frame *f;
379
380 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
381 {
382 frame = XCAR (tail);
383 if (!GC_FRAMEP (frame))
384 continue;
385 f = XFRAME (frame);
386 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
387 continue;
388 if (f->output_data.w32->hourglass_window == wdesc)
389 return f;
390
391 if (FRAME_W32_WINDOW (f) == wdesc)
392 return f;
393 }
394 return 0;
395 }
396
397 \f
398
399 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
400 id, which is just an int that this section returns. Bitmaps are
401 reference counted so they can be shared among frames.
402
403 Bitmap indices are guaranteed to be > 0, so a negative number can
404 be used to indicate no bitmap.
405
406 If you use x_create_bitmap_from_data, then you must keep track of
407 the bitmaps yourself. That is, creating a bitmap from the same
408 data more than once will not be caught. */
409
410
411 /* Functions to access the contents of a bitmap, given an id. */
412
413 int
414 x_bitmap_height (f, id)
415 FRAME_PTR f;
416 int id;
417 {
418 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
419 }
420
421 int
422 x_bitmap_width (f, id)
423 FRAME_PTR f;
424 int id;
425 {
426 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
427 }
428
429 int
430 x_bitmap_pixmap (f, id)
431 FRAME_PTR f;
432 int id;
433 {
434 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
435 }
436
437
438 /* Allocate a new bitmap record. Returns index of new record. */
439
440 static int
441 x_allocate_bitmap_record (f)
442 FRAME_PTR f;
443 {
444 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
445 int i;
446
447 if (dpyinfo->bitmaps == NULL)
448 {
449 dpyinfo->bitmaps_size = 10;
450 dpyinfo->bitmaps
451 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
452 dpyinfo->bitmaps_last = 1;
453 return 1;
454 }
455
456 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
457 return ++dpyinfo->bitmaps_last;
458
459 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
460 if (dpyinfo->bitmaps[i].refcount == 0)
461 return i + 1;
462
463 dpyinfo->bitmaps_size *= 2;
464 dpyinfo->bitmaps
465 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
466 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
467 return ++dpyinfo->bitmaps_last;
468 }
469
470 /* Add one reference to the reference count of the bitmap with id ID. */
471
472 void
473 x_reference_bitmap (f, id)
474 FRAME_PTR f;
475 int id;
476 {
477 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
478 }
479
480 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
481
482 int
483 x_create_bitmap_from_data (f, bits, width, height)
484 struct frame *f;
485 char *bits;
486 unsigned int width, height;
487 {
488 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
489 Pixmap bitmap;
490 int id;
491
492 bitmap = CreateBitmap (width, height,
493 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
494 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
495 bits);
496
497 if (! bitmap)
498 return -1;
499
500 id = x_allocate_bitmap_record (f);
501 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
502 dpyinfo->bitmaps[id - 1].file = NULL;
503 dpyinfo->bitmaps[id - 1].hinst = NULL;
504 dpyinfo->bitmaps[id - 1].refcount = 1;
505 dpyinfo->bitmaps[id - 1].depth = 1;
506 dpyinfo->bitmaps[id - 1].height = height;
507 dpyinfo->bitmaps[id - 1].width = width;
508
509 return id;
510 }
511
512 /* Create bitmap from file FILE for frame F. */
513
514 int
515 x_create_bitmap_from_file (f, file)
516 struct frame *f;
517 Lisp_Object file;
518 {
519 return -1;
520 #if 0 /* TODO : bitmap support */
521 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
522 unsigned int width, height;
523 HBITMAP bitmap;
524 int xhot, yhot, result, id;
525 Lisp_Object found;
526 int fd;
527 char *filename;
528 HINSTANCE hinst;
529
530 /* Look for an existing bitmap with the same name. */
531 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
532 {
533 if (dpyinfo->bitmaps[id].refcount
534 && dpyinfo->bitmaps[id].file
535 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
536 {
537 ++dpyinfo->bitmaps[id].refcount;
538 return id + 1;
539 }
540 }
541
542 /* Search bitmap-file-path for the file, if appropriate. */
543 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
544 if (fd < 0)
545 return -1;
546 emacs_close (fd);
547
548 filename = (char *) SDATA (found);
549
550 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
551
552 if (hinst == NULL)
553 return -1;
554
555
556 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
557 filename, &width, &height, &bitmap, &xhot, &yhot);
558 if (result != BitmapSuccess)
559 return -1;
560
561 id = x_allocate_bitmap_record (f);
562 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
563 dpyinfo->bitmaps[id - 1].refcount = 1;
564 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SCHARS (file) + 1);
565 dpyinfo->bitmaps[id - 1].depth = 1;
566 dpyinfo->bitmaps[id - 1].height = height;
567 dpyinfo->bitmaps[id - 1].width = width;
568 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
569
570 return id;
571 #endif /* TODO */
572 }
573
574 /* Remove reference to bitmap with id number ID. */
575
576 void
577 x_destroy_bitmap (f, id)
578 FRAME_PTR f;
579 int id;
580 {
581 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
582
583 if (id > 0)
584 {
585 --dpyinfo->bitmaps[id - 1].refcount;
586 if (dpyinfo->bitmaps[id - 1].refcount == 0)
587 {
588 BLOCK_INPUT;
589 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
590 if (dpyinfo->bitmaps[id - 1].file)
591 {
592 xfree (dpyinfo->bitmaps[id - 1].file);
593 dpyinfo->bitmaps[id - 1].file = NULL;
594 }
595 UNBLOCK_INPUT;
596 }
597 }
598 }
599
600 /* Free all the bitmaps for the display specified by DPYINFO. */
601
602 static void
603 x_destroy_all_bitmaps (dpyinfo)
604 struct w32_display_info *dpyinfo;
605 {
606 int i;
607 for (i = 0; i < dpyinfo->bitmaps_last; i++)
608 if (dpyinfo->bitmaps[i].refcount > 0)
609 {
610 DeleteObject (dpyinfo->bitmaps[i].pixmap);
611 if (dpyinfo->bitmaps[i].file)
612 xfree (dpyinfo->bitmaps[i].file);
613 }
614 dpyinfo->bitmaps_last = 0;
615 }
616 \f
617 BOOL my_show_window P_ ((struct frame *, HWND, int));
618 void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
619 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
620 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
621
622 /* TODO: Native Input Method support; see x_create_im. */
623 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
624 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
625 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
626 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
627 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
628 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
629 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
630 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
631 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
632 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
633 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
634 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
635 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
636 Lisp_Object));
637
638
639 \f
640
641 /* Store the screen positions of frame F into XPTR and YPTR.
642 These are the positions of the containing window manager window,
643 not Emacs's own window. */
644
645 void
646 x_real_positions (f, xptr, yptr)
647 FRAME_PTR f;
648 int *xptr, *yptr;
649 {
650 POINT pt;
651 RECT rect;
652
653 GetClientRect(FRAME_W32_WINDOW(f), &rect);
654 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
655
656 pt.x = rect.left;
657 pt.y = rect.top;
658
659 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
660
661 /* Remember x_pixels_diff and y_pixels_diff. */
662 f->x_pixels_diff = pt.x - rect.left;
663 f->y_pixels_diff = pt.y - rect.top;
664
665 *xptr = pt.x;
666 *yptr = pt.y;
667 }
668
669 \f
670
671 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
672 Sw32_define_rgb_color, 4, 4, 0,
673 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
674 This adds or updates a named color to w32-color-map, making it
675 available for use. The original entry's RGB ref is returned, or nil
676 if the entry is new. */)
677 (red, green, blue, name)
678 Lisp_Object red, green, blue, name;
679 {
680 Lisp_Object rgb;
681 Lisp_Object oldrgb = Qnil;
682 Lisp_Object entry;
683
684 CHECK_NUMBER (red);
685 CHECK_NUMBER (green);
686 CHECK_NUMBER (blue);
687 CHECK_STRING (name);
688
689 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
690
691 BLOCK_INPUT;
692
693 /* replace existing entry in w32-color-map or add new entry. */
694 entry = Fassoc (name, Vw32_color_map);
695 if (NILP (entry))
696 {
697 entry = Fcons (name, rgb);
698 Vw32_color_map = Fcons (entry, Vw32_color_map);
699 }
700 else
701 {
702 oldrgb = Fcdr (entry);
703 Fsetcdr (entry, rgb);
704 }
705
706 UNBLOCK_INPUT;
707
708 return (oldrgb);
709 }
710
711 DEFUN ("w32-load-color-file", Fw32_load_color_file,
712 Sw32_load_color_file, 1, 1, 0,
713 doc: /* Create an alist of color entries from an external file.
714 Assign this value to w32-color-map to replace the existing color map.
715
716 The file should define one named RGB color per line like so:
717 R G B name
718 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
719 (filename)
720 Lisp_Object filename;
721 {
722 FILE *fp;
723 Lisp_Object cmap = Qnil;
724 Lisp_Object abspath;
725
726 CHECK_STRING (filename);
727 abspath = Fexpand_file_name (filename, Qnil);
728
729 fp = fopen (SDATA (filename), "rt");
730 if (fp)
731 {
732 char buf[512];
733 int red, green, blue;
734 int num;
735
736 BLOCK_INPUT;
737
738 while (fgets (buf, sizeof (buf), fp) != NULL) {
739 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
740 {
741 char *name = buf + num;
742 num = strlen (name) - 1;
743 if (name[num] == '\n')
744 name[num] = 0;
745 cmap = Fcons (Fcons (build_string (name),
746 make_number (RGB (red, green, blue))),
747 cmap);
748 }
749 }
750 fclose (fp);
751
752 UNBLOCK_INPUT;
753 }
754
755 return cmap;
756 }
757
758 /* The default colors for the w32 color map */
759 typedef struct colormap_t
760 {
761 char *name;
762 COLORREF colorref;
763 } colormap_t;
764
765 colormap_t w32_color_map[] =
766 {
767 {"snow" , PALETTERGB (255,250,250)},
768 {"ghost white" , PALETTERGB (248,248,255)},
769 {"GhostWhite" , PALETTERGB (248,248,255)},
770 {"white smoke" , PALETTERGB (245,245,245)},
771 {"WhiteSmoke" , PALETTERGB (245,245,245)},
772 {"gainsboro" , PALETTERGB (220,220,220)},
773 {"floral white" , PALETTERGB (255,250,240)},
774 {"FloralWhite" , PALETTERGB (255,250,240)},
775 {"old lace" , PALETTERGB (253,245,230)},
776 {"OldLace" , PALETTERGB (253,245,230)},
777 {"linen" , PALETTERGB (250,240,230)},
778 {"antique white" , PALETTERGB (250,235,215)},
779 {"AntiqueWhite" , PALETTERGB (250,235,215)},
780 {"papaya whip" , PALETTERGB (255,239,213)},
781 {"PapayaWhip" , PALETTERGB (255,239,213)},
782 {"blanched almond" , PALETTERGB (255,235,205)},
783 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
784 {"bisque" , PALETTERGB (255,228,196)},
785 {"peach puff" , PALETTERGB (255,218,185)},
786 {"PeachPuff" , PALETTERGB (255,218,185)},
787 {"navajo white" , PALETTERGB (255,222,173)},
788 {"NavajoWhite" , PALETTERGB (255,222,173)},
789 {"moccasin" , PALETTERGB (255,228,181)},
790 {"cornsilk" , PALETTERGB (255,248,220)},
791 {"ivory" , PALETTERGB (255,255,240)},
792 {"lemon chiffon" , PALETTERGB (255,250,205)},
793 {"LemonChiffon" , PALETTERGB (255,250,205)},
794 {"seashell" , PALETTERGB (255,245,238)},
795 {"honeydew" , PALETTERGB (240,255,240)},
796 {"mint cream" , PALETTERGB (245,255,250)},
797 {"MintCream" , PALETTERGB (245,255,250)},
798 {"azure" , PALETTERGB (240,255,255)},
799 {"alice blue" , PALETTERGB (240,248,255)},
800 {"AliceBlue" , PALETTERGB (240,248,255)},
801 {"lavender" , PALETTERGB (230,230,250)},
802 {"lavender blush" , PALETTERGB (255,240,245)},
803 {"LavenderBlush" , PALETTERGB (255,240,245)},
804 {"misty rose" , PALETTERGB (255,228,225)},
805 {"MistyRose" , PALETTERGB (255,228,225)},
806 {"white" , PALETTERGB (255,255,255)},
807 {"black" , PALETTERGB ( 0, 0, 0)},
808 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
809 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
810 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
811 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
812 {"dim gray" , PALETTERGB (105,105,105)},
813 {"DimGray" , PALETTERGB (105,105,105)},
814 {"dim grey" , PALETTERGB (105,105,105)},
815 {"DimGrey" , PALETTERGB (105,105,105)},
816 {"slate gray" , PALETTERGB (112,128,144)},
817 {"SlateGray" , PALETTERGB (112,128,144)},
818 {"slate grey" , PALETTERGB (112,128,144)},
819 {"SlateGrey" , PALETTERGB (112,128,144)},
820 {"light slate gray" , PALETTERGB (119,136,153)},
821 {"LightSlateGray" , PALETTERGB (119,136,153)},
822 {"light slate grey" , PALETTERGB (119,136,153)},
823 {"LightSlateGrey" , PALETTERGB (119,136,153)},
824 {"gray" , PALETTERGB (190,190,190)},
825 {"grey" , PALETTERGB (190,190,190)},
826 {"light grey" , PALETTERGB (211,211,211)},
827 {"LightGrey" , PALETTERGB (211,211,211)},
828 {"light gray" , PALETTERGB (211,211,211)},
829 {"LightGray" , PALETTERGB (211,211,211)},
830 {"midnight blue" , PALETTERGB ( 25, 25,112)},
831 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
832 {"navy" , PALETTERGB ( 0, 0,128)},
833 {"navy blue" , PALETTERGB ( 0, 0,128)},
834 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
835 {"cornflower blue" , PALETTERGB (100,149,237)},
836 {"CornflowerBlue" , PALETTERGB (100,149,237)},
837 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
838 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
839 {"slate blue" , PALETTERGB (106, 90,205)},
840 {"SlateBlue" , PALETTERGB (106, 90,205)},
841 {"medium slate blue" , PALETTERGB (123,104,238)},
842 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
843 {"light slate blue" , PALETTERGB (132,112,255)},
844 {"LightSlateBlue" , PALETTERGB (132,112,255)},
845 {"medium blue" , PALETTERGB ( 0, 0,205)},
846 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
847 {"royal blue" , PALETTERGB ( 65,105,225)},
848 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
849 {"blue" , PALETTERGB ( 0, 0,255)},
850 {"dodger blue" , PALETTERGB ( 30,144,255)},
851 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
852 {"deep sky blue" , PALETTERGB ( 0,191,255)},
853 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
854 {"sky blue" , PALETTERGB (135,206,235)},
855 {"SkyBlue" , PALETTERGB (135,206,235)},
856 {"light sky blue" , PALETTERGB (135,206,250)},
857 {"LightSkyBlue" , PALETTERGB (135,206,250)},
858 {"steel blue" , PALETTERGB ( 70,130,180)},
859 {"SteelBlue" , PALETTERGB ( 70,130,180)},
860 {"light steel blue" , PALETTERGB (176,196,222)},
861 {"LightSteelBlue" , PALETTERGB (176,196,222)},
862 {"light blue" , PALETTERGB (173,216,230)},
863 {"LightBlue" , PALETTERGB (173,216,230)},
864 {"powder blue" , PALETTERGB (176,224,230)},
865 {"PowderBlue" , PALETTERGB (176,224,230)},
866 {"pale turquoise" , PALETTERGB (175,238,238)},
867 {"PaleTurquoise" , PALETTERGB (175,238,238)},
868 {"dark turquoise" , PALETTERGB ( 0,206,209)},
869 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
870 {"medium turquoise" , PALETTERGB ( 72,209,204)},
871 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
872 {"turquoise" , PALETTERGB ( 64,224,208)},
873 {"cyan" , PALETTERGB ( 0,255,255)},
874 {"light cyan" , PALETTERGB (224,255,255)},
875 {"LightCyan" , PALETTERGB (224,255,255)},
876 {"cadet blue" , PALETTERGB ( 95,158,160)},
877 {"CadetBlue" , PALETTERGB ( 95,158,160)},
878 {"medium aquamarine" , PALETTERGB (102,205,170)},
879 {"MediumAquamarine" , PALETTERGB (102,205,170)},
880 {"aquamarine" , PALETTERGB (127,255,212)},
881 {"dark green" , PALETTERGB ( 0,100, 0)},
882 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
883 {"dark olive green" , PALETTERGB ( 85,107, 47)},
884 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
885 {"dark sea green" , PALETTERGB (143,188,143)},
886 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
887 {"sea green" , PALETTERGB ( 46,139, 87)},
888 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
889 {"medium sea green" , PALETTERGB ( 60,179,113)},
890 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
891 {"light sea green" , PALETTERGB ( 32,178,170)},
892 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
893 {"pale green" , PALETTERGB (152,251,152)},
894 {"PaleGreen" , PALETTERGB (152,251,152)},
895 {"spring green" , PALETTERGB ( 0,255,127)},
896 {"SpringGreen" , PALETTERGB ( 0,255,127)},
897 {"lawn green" , PALETTERGB (124,252, 0)},
898 {"LawnGreen" , PALETTERGB (124,252, 0)},
899 {"green" , PALETTERGB ( 0,255, 0)},
900 {"chartreuse" , PALETTERGB (127,255, 0)},
901 {"medium spring green" , PALETTERGB ( 0,250,154)},
902 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
903 {"green yellow" , PALETTERGB (173,255, 47)},
904 {"GreenYellow" , PALETTERGB (173,255, 47)},
905 {"lime green" , PALETTERGB ( 50,205, 50)},
906 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
907 {"yellow green" , PALETTERGB (154,205, 50)},
908 {"YellowGreen" , PALETTERGB (154,205, 50)},
909 {"forest green" , PALETTERGB ( 34,139, 34)},
910 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
911 {"olive drab" , PALETTERGB (107,142, 35)},
912 {"OliveDrab" , PALETTERGB (107,142, 35)},
913 {"dark khaki" , PALETTERGB (189,183,107)},
914 {"DarkKhaki" , PALETTERGB (189,183,107)},
915 {"khaki" , PALETTERGB (240,230,140)},
916 {"pale goldenrod" , PALETTERGB (238,232,170)},
917 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
918 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
919 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
920 {"light yellow" , PALETTERGB (255,255,224)},
921 {"LightYellow" , PALETTERGB (255,255,224)},
922 {"yellow" , PALETTERGB (255,255, 0)},
923 {"gold" , PALETTERGB (255,215, 0)},
924 {"light goldenrod" , PALETTERGB (238,221,130)},
925 {"LightGoldenrod" , PALETTERGB (238,221,130)},
926 {"goldenrod" , PALETTERGB (218,165, 32)},
927 {"dark goldenrod" , PALETTERGB (184,134, 11)},
928 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
929 {"rosy brown" , PALETTERGB (188,143,143)},
930 {"RosyBrown" , PALETTERGB (188,143,143)},
931 {"indian red" , PALETTERGB (205, 92, 92)},
932 {"IndianRed" , PALETTERGB (205, 92, 92)},
933 {"saddle brown" , PALETTERGB (139, 69, 19)},
934 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
935 {"sienna" , PALETTERGB (160, 82, 45)},
936 {"peru" , PALETTERGB (205,133, 63)},
937 {"burlywood" , PALETTERGB (222,184,135)},
938 {"beige" , PALETTERGB (245,245,220)},
939 {"wheat" , PALETTERGB (245,222,179)},
940 {"sandy brown" , PALETTERGB (244,164, 96)},
941 {"SandyBrown" , PALETTERGB (244,164, 96)},
942 {"tan" , PALETTERGB (210,180,140)},
943 {"chocolate" , PALETTERGB (210,105, 30)},
944 {"firebrick" , PALETTERGB (178,34, 34)},
945 {"brown" , PALETTERGB (165,42, 42)},
946 {"dark salmon" , PALETTERGB (233,150,122)},
947 {"DarkSalmon" , PALETTERGB (233,150,122)},
948 {"salmon" , PALETTERGB (250,128,114)},
949 {"light salmon" , PALETTERGB (255,160,122)},
950 {"LightSalmon" , PALETTERGB (255,160,122)},
951 {"orange" , PALETTERGB (255,165, 0)},
952 {"dark orange" , PALETTERGB (255,140, 0)},
953 {"DarkOrange" , PALETTERGB (255,140, 0)},
954 {"coral" , PALETTERGB (255,127, 80)},
955 {"light coral" , PALETTERGB (240,128,128)},
956 {"LightCoral" , PALETTERGB (240,128,128)},
957 {"tomato" , PALETTERGB (255, 99, 71)},
958 {"orange red" , PALETTERGB (255, 69, 0)},
959 {"OrangeRed" , PALETTERGB (255, 69, 0)},
960 {"red" , PALETTERGB (255, 0, 0)},
961 {"hot pink" , PALETTERGB (255,105,180)},
962 {"HotPink" , PALETTERGB (255,105,180)},
963 {"deep pink" , PALETTERGB (255, 20,147)},
964 {"DeepPink" , PALETTERGB (255, 20,147)},
965 {"pink" , PALETTERGB (255,192,203)},
966 {"light pink" , PALETTERGB (255,182,193)},
967 {"LightPink" , PALETTERGB (255,182,193)},
968 {"pale violet red" , PALETTERGB (219,112,147)},
969 {"PaleVioletRed" , PALETTERGB (219,112,147)},
970 {"maroon" , PALETTERGB (176, 48, 96)},
971 {"medium violet red" , PALETTERGB (199, 21,133)},
972 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
973 {"violet red" , PALETTERGB (208, 32,144)},
974 {"VioletRed" , PALETTERGB (208, 32,144)},
975 {"magenta" , PALETTERGB (255, 0,255)},
976 {"violet" , PALETTERGB (238,130,238)},
977 {"plum" , PALETTERGB (221,160,221)},
978 {"orchid" , PALETTERGB (218,112,214)},
979 {"medium orchid" , PALETTERGB (186, 85,211)},
980 {"MediumOrchid" , PALETTERGB (186, 85,211)},
981 {"dark orchid" , PALETTERGB (153, 50,204)},
982 {"DarkOrchid" , PALETTERGB (153, 50,204)},
983 {"dark violet" , PALETTERGB (148, 0,211)},
984 {"DarkViolet" , PALETTERGB (148, 0,211)},
985 {"blue violet" , PALETTERGB (138, 43,226)},
986 {"BlueViolet" , PALETTERGB (138, 43,226)},
987 {"purple" , PALETTERGB (160, 32,240)},
988 {"medium purple" , PALETTERGB (147,112,219)},
989 {"MediumPurple" , PALETTERGB (147,112,219)},
990 {"thistle" , PALETTERGB (216,191,216)},
991 {"gray0" , PALETTERGB ( 0, 0, 0)},
992 {"grey0" , PALETTERGB ( 0, 0, 0)},
993 {"dark grey" , PALETTERGB (169,169,169)},
994 {"DarkGrey" , PALETTERGB (169,169,169)},
995 {"dark gray" , PALETTERGB (169,169,169)},
996 {"DarkGray" , PALETTERGB (169,169,169)},
997 {"dark blue" , PALETTERGB ( 0, 0,139)},
998 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
999 {"dark cyan" , PALETTERGB ( 0,139,139)},
1000 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1001 {"dark magenta" , PALETTERGB (139, 0,139)},
1002 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1003 {"dark red" , PALETTERGB (139, 0, 0)},
1004 {"DarkRed" , PALETTERGB (139, 0, 0)},
1005 {"light green" , PALETTERGB (144,238,144)},
1006 {"LightGreen" , PALETTERGB (144,238,144)},
1007 };
1008
1009 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1010 0, 0, 0, doc: /* Return the default color map. */)
1011 ()
1012 {
1013 int i;
1014 colormap_t *pc = w32_color_map;
1015 Lisp_Object cmap;
1016
1017 BLOCK_INPUT;
1018
1019 cmap = Qnil;
1020
1021 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1022 pc++, i++)
1023 cmap = Fcons (Fcons (build_string (pc->name),
1024 make_number (pc->colorref)),
1025 cmap);
1026
1027 UNBLOCK_INPUT;
1028
1029 return (cmap);
1030 }
1031
1032 Lisp_Object
1033 w32_to_x_color (rgb)
1034 Lisp_Object rgb;
1035 {
1036 Lisp_Object color;
1037
1038 CHECK_NUMBER (rgb);
1039
1040 BLOCK_INPUT;
1041
1042 color = Frassq (rgb, Vw32_color_map);
1043
1044 UNBLOCK_INPUT;
1045
1046 if (!NILP (color))
1047 return (Fcar (color));
1048 else
1049 return Qnil;
1050 }
1051
1052 COLORREF
1053 w32_color_map_lookup (colorname)
1054 char *colorname;
1055 {
1056 Lisp_Object tail, ret = Qnil;
1057
1058 BLOCK_INPUT;
1059
1060 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1061 {
1062 register Lisp_Object elt, tem;
1063
1064 elt = Fcar (tail);
1065 if (!CONSP (elt)) continue;
1066
1067 tem = Fcar (elt);
1068
1069 if (lstrcmpi (SDATA (tem), colorname) == 0)
1070 {
1071 ret = XUINT (Fcdr (elt));
1072 break;
1073 }
1074
1075 QUIT;
1076 }
1077
1078
1079 UNBLOCK_INPUT;
1080
1081 return ret;
1082 }
1083
1084
1085 static void
1086 add_system_logical_colors_to_map (system_colors)
1087 Lisp_Object *system_colors;
1088 {
1089 HKEY colors_key;
1090
1091 /* Other registry operations are done with input blocked. */
1092 BLOCK_INPUT;
1093
1094 /* Look for "Control Panel/Colors" under User and Machine registry
1095 settings. */
1096 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
1097 KEY_READ, &colors_key) == ERROR_SUCCESS
1098 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
1099 KEY_READ, &colors_key) == ERROR_SUCCESS)
1100 {
1101 /* List all keys. */
1102 char color_buffer[64];
1103 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
1104 int index = 0;
1105 DWORD name_size, color_size;
1106 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
1107
1108 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
1109 color_size = sizeof (color_buffer);
1110
1111 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
1112
1113 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
1114 NULL, NULL, color_buffer, &color_size)
1115 == ERROR_SUCCESS)
1116 {
1117 int r, g, b;
1118 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
1119 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
1120 make_number (RGB (r, g, b))),
1121 *system_colors);
1122
1123 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
1124 color_size = sizeof (color_buffer);
1125 index++;
1126 }
1127 RegCloseKey (colors_key);
1128 }
1129
1130 UNBLOCK_INPUT;
1131 }
1132
1133
1134 COLORREF
1135 x_to_w32_color (colorname)
1136 char * colorname;
1137 {
1138 register Lisp_Object ret = Qnil;
1139
1140 BLOCK_INPUT;
1141
1142 if (colorname[0] == '#')
1143 {
1144 /* Could be an old-style RGB Device specification. */
1145 char *color;
1146 int size;
1147 color = colorname + 1;
1148
1149 size = strlen(color);
1150 if (size == 3 || size == 6 || size == 9 || size == 12)
1151 {
1152 UINT colorval;
1153 int i, pos;
1154 pos = 0;
1155 size /= 3;
1156 colorval = 0;
1157
1158 for (i = 0; i < 3; i++)
1159 {
1160 char *end;
1161 char t;
1162 unsigned long value;
1163
1164 /* The check for 'x' in the following conditional takes into
1165 account the fact that strtol allows a "0x" in front of
1166 our numbers, and we don't. */
1167 if (!isxdigit(color[0]) || color[1] == 'x')
1168 break;
1169 t = color[size];
1170 color[size] = '\0';
1171 value = strtoul(color, &end, 16);
1172 color[size] = t;
1173 if (errno == ERANGE || end - color != size)
1174 break;
1175 switch (size)
1176 {
1177 case 1:
1178 value = value * 0x10;
1179 break;
1180 case 2:
1181 break;
1182 case 3:
1183 value /= 0x10;
1184 break;
1185 case 4:
1186 value /= 0x100;
1187 break;
1188 }
1189 colorval |= (value << pos);
1190 pos += 0x8;
1191 if (i == 2)
1192 {
1193 UNBLOCK_INPUT;
1194 return (colorval);
1195 }
1196 color = end;
1197 }
1198 }
1199 }
1200 else if (strnicmp(colorname, "rgb:", 4) == 0)
1201 {
1202 char *color;
1203 UINT colorval;
1204 int i, pos;
1205 pos = 0;
1206
1207 colorval = 0;
1208 color = colorname + 4;
1209 for (i = 0; i < 3; i++)
1210 {
1211 char *end;
1212 unsigned long value;
1213
1214 /* The check for 'x' in the following conditional takes into
1215 account the fact that strtol allows a "0x" in front of
1216 our numbers, and we don't. */
1217 if (!isxdigit(color[0]) || color[1] == 'x')
1218 break;
1219 value = strtoul(color, &end, 16);
1220 if (errno == ERANGE)
1221 break;
1222 switch (end - color)
1223 {
1224 case 1:
1225 value = value * 0x10 + value;
1226 break;
1227 case 2:
1228 break;
1229 case 3:
1230 value /= 0x10;
1231 break;
1232 case 4:
1233 value /= 0x100;
1234 break;
1235 default:
1236 value = ULONG_MAX;
1237 }
1238 if (value == ULONG_MAX)
1239 break;
1240 colorval |= (value << pos);
1241 pos += 0x8;
1242 if (i == 2)
1243 {
1244 if (*end != '\0')
1245 break;
1246 UNBLOCK_INPUT;
1247 return (colorval);
1248 }
1249 if (*end != '/')
1250 break;
1251 color = end + 1;
1252 }
1253 }
1254 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1255 {
1256 /* This is an RGB Intensity specification. */
1257 char *color;
1258 UINT colorval;
1259 int i, pos;
1260 pos = 0;
1261
1262 colorval = 0;
1263 color = colorname + 5;
1264 for (i = 0; i < 3; i++)
1265 {
1266 char *end;
1267 double value;
1268 UINT val;
1269
1270 value = strtod(color, &end);
1271 if (errno == ERANGE)
1272 break;
1273 if (value < 0.0 || value > 1.0)
1274 break;
1275 val = (UINT)(0x100 * value);
1276 /* We used 0x100 instead of 0xFF to give a continuous
1277 range between 0.0 and 1.0 inclusive. The next statement
1278 fixes the 1.0 case. */
1279 if (val == 0x100)
1280 val = 0xFF;
1281 colorval |= (val << pos);
1282 pos += 0x8;
1283 if (i == 2)
1284 {
1285 if (*end != '\0')
1286 break;
1287 UNBLOCK_INPUT;
1288 return (colorval);
1289 }
1290 if (*end != '/')
1291 break;
1292 color = end + 1;
1293 }
1294 }
1295 /* I am not going to attempt to handle any of the CIE color schemes
1296 or TekHVC, since I don't know the algorithms for conversion to
1297 RGB. */
1298
1299 /* If we fail to lookup the color name in w32_color_map, then check the
1300 colorname to see if it can be crudely approximated: If the X color
1301 ends in a number (e.g., "darkseagreen2"), strip the number and
1302 return the result of looking up the base color name. */
1303 ret = w32_color_map_lookup (colorname);
1304 if (NILP (ret))
1305 {
1306 int len = strlen (colorname);
1307
1308 if (isdigit (colorname[len - 1]))
1309 {
1310 char *ptr, *approx = alloca (len + 1);
1311
1312 strcpy (approx, colorname);
1313 ptr = &approx[len - 1];
1314 while (ptr > approx && isdigit (*ptr))
1315 *ptr-- = '\0';
1316
1317 ret = w32_color_map_lookup (approx);
1318 }
1319 }
1320
1321 UNBLOCK_INPUT;
1322 return ret;
1323 }
1324
1325 void
1326 w32_regenerate_palette (FRAME_PTR f)
1327 {
1328 struct w32_palette_entry * list;
1329 LOGPALETTE * log_palette;
1330 HPALETTE new_palette;
1331 int i;
1332
1333 /* don't bother trying to create palette if not supported */
1334 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1335 return;
1336
1337 log_palette = (LOGPALETTE *)
1338 alloca (sizeof (LOGPALETTE) +
1339 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1340 log_palette->palVersion = 0x300;
1341 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1342
1343 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1344 for (i = 0;
1345 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1346 i++, list = list->next)
1347 log_palette->palPalEntry[i] = list->entry;
1348
1349 new_palette = CreatePalette (log_palette);
1350
1351 enter_crit ();
1352
1353 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1354 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1355 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1356
1357 /* Realize display palette and garbage all frames. */
1358 release_frame_dc (f, get_frame_dc (f));
1359
1360 leave_crit ();
1361 }
1362
1363 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1364 #define SET_W32_COLOR(pe, color) \
1365 do \
1366 { \
1367 pe.peRed = GetRValue (color); \
1368 pe.peGreen = GetGValue (color); \
1369 pe.peBlue = GetBValue (color); \
1370 pe.peFlags = 0; \
1371 } while (0)
1372
1373 #if 0
1374 /* Keep these around in case we ever want to track color usage. */
1375 void
1376 w32_map_color (FRAME_PTR f, COLORREF color)
1377 {
1378 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1379
1380 if (NILP (Vw32_enable_palette))
1381 return;
1382
1383 /* check if color is already mapped */
1384 while (list)
1385 {
1386 if (W32_COLOR (list->entry) == color)
1387 {
1388 ++list->refcount;
1389 return;
1390 }
1391 list = list->next;
1392 }
1393
1394 /* not already mapped, so add to list and recreate Windows palette */
1395 list = (struct w32_palette_entry *)
1396 xmalloc (sizeof (struct w32_palette_entry));
1397 SET_W32_COLOR (list->entry, color);
1398 list->refcount = 1;
1399 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1400 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1401 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1402
1403 /* set flag that palette must be regenerated */
1404 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1405 }
1406
1407 void
1408 w32_unmap_color (FRAME_PTR f, COLORREF color)
1409 {
1410 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1411 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1412
1413 if (NILP (Vw32_enable_palette))
1414 return;
1415
1416 /* check if color is already mapped */
1417 while (list)
1418 {
1419 if (W32_COLOR (list->entry) == color)
1420 {
1421 if (--list->refcount == 0)
1422 {
1423 *prev = list->next;
1424 xfree (list);
1425 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1426 break;
1427 }
1428 else
1429 return;
1430 }
1431 prev = &list->next;
1432 list = list->next;
1433 }
1434
1435 /* set flag that palette must be regenerated */
1436 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1437 }
1438 #endif
1439
1440
1441 /* Gamma-correct COLOR on frame F. */
1442
1443 void
1444 gamma_correct (f, color)
1445 struct frame *f;
1446 COLORREF *color;
1447 {
1448 if (f->gamma)
1449 {
1450 *color = PALETTERGB (
1451 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1452 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1453 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1454 }
1455 }
1456
1457
1458 /* Decide if color named COLOR is valid for the display associated with
1459 the selected frame; if so, return the rgb values in COLOR_DEF.
1460 If ALLOC is nonzero, allocate a new colormap cell. */
1461
1462 int
1463 w32_defined_color (f, color, color_def, alloc)
1464 FRAME_PTR f;
1465 char *color;
1466 XColor *color_def;
1467 int alloc;
1468 {
1469 register Lisp_Object tem;
1470 COLORREF w32_color_ref;
1471
1472 tem = x_to_w32_color (color);
1473
1474 if (!NILP (tem))
1475 {
1476 if (f)
1477 {
1478 /* Apply gamma correction. */
1479 w32_color_ref = XUINT (tem);
1480 gamma_correct (f, &w32_color_ref);
1481 XSETINT (tem, w32_color_ref);
1482 }
1483
1484 /* Map this color to the palette if it is enabled. */
1485 if (!NILP (Vw32_enable_palette))
1486 {
1487 struct w32_palette_entry * entry =
1488 one_w32_display_info.color_list;
1489 struct w32_palette_entry ** prev =
1490 &one_w32_display_info.color_list;
1491
1492 /* check if color is already mapped */
1493 while (entry)
1494 {
1495 if (W32_COLOR (entry->entry) == XUINT (tem))
1496 break;
1497 prev = &entry->next;
1498 entry = entry->next;
1499 }
1500
1501 if (entry == NULL && alloc)
1502 {
1503 /* not already mapped, so add to list */
1504 entry = (struct w32_palette_entry *)
1505 xmalloc (sizeof (struct w32_palette_entry));
1506 SET_W32_COLOR (entry->entry, XUINT (tem));
1507 entry->next = NULL;
1508 *prev = entry;
1509 one_w32_display_info.num_colors++;
1510
1511 /* set flag that palette must be regenerated */
1512 one_w32_display_info.regen_palette = TRUE;
1513 }
1514 }
1515 /* Ensure COLORREF value is snapped to nearest color in (default)
1516 palette by simulating the PALETTERGB macro. This works whether
1517 or not the display device has a palette. */
1518 w32_color_ref = XUINT (tem) | 0x2000000;
1519
1520 color_def->pixel = w32_color_ref;
1521 color_def->red = GetRValue (w32_color_ref) * 256;
1522 color_def->green = GetGValue (w32_color_ref) * 256;
1523 color_def->blue = GetBValue (w32_color_ref) * 256;
1524
1525 return 1;
1526 }
1527 else
1528 {
1529 return 0;
1530 }
1531 }
1532
1533 /* Given a string ARG naming a color, compute a pixel value from it
1534 suitable for screen F.
1535 If F is not a color screen, return DEF (default) regardless of what
1536 ARG says. */
1537
1538 int
1539 x_decode_color (f, arg, def)
1540 FRAME_PTR f;
1541 Lisp_Object arg;
1542 int def;
1543 {
1544 XColor cdef;
1545
1546 CHECK_STRING (arg);
1547
1548 if (strcmp (SDATA (arg), "black") == 0)
1549 return BLACK_PIX_DEFAULT (f);
1550 else if (strcmp (SDATA (arg), "white") == 0)
1551 return WHITE_PIX_DEFAULT (f);
1552
1553 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1554 return def;
1555
1556 /* w32_defined_color is responsible for coping with failures
1557 by looking for a near-miss. */
1558 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1559 return cdef.pixel;
1560
1561 /* defined_color failed; return an ultimate default. */
1562 return def;
1563 }
1564 \f
1565
1566
1567 /* Functions called only from `x_set_frame_param'
1568 to set individual parameters.
1569
1570 If FRAME_W32_WINDOW (f) is 0,
1571 the frame is being created and its window does not exist yet.
1572 In that case, just record the parameter's new value
1573 in the standard place; do not attempt to change the window. */
1574
1575 void
1576 x_set_foreground_color (f, arg, oldval)
1577 struct frame *f;
1578 Lisp_Object arg, oldval;
1579 {
1580 struct w32_output *x = f->output_data.w32;
1581 PIX_TYPE fg, old_fg;
1582
1583 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1584 old_fg = FRAME_FOREGROUND_PIXEL (f);
1585 FRAME_FOREGROUND_PIXEL (f) = fg;
1586
1587 if (FRAME_W32_WINDOW (f) != 0)
1588 {
1589 if (x->cursor_pixel == old_fg)
1590 x->cursor_pixel = fg;
1591
1592 update_face_from_frame_parameter (f, Qforeground_color, arg);
1593 if (FRAME_VISIBLE_P (f))
1594 redraw_frame (f);
1595 }
1596 }
1597
1598 void
1599 x_set_background_color (f, arg, oldval)
1600 struct frame *f;
1601 Lisp_Object arg, oldval;
1602 {
1603 FRAME_BACKGROUND_PIXEL (f)
1604 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1605
1606 if (FRAME_W32_WINDOW (f) != 0)
1607 {
1608 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1609 FRAME_BACKGROUND_PIXEL (f));
1610
1611 update_face_from_frame_parameter (f, Qbackground_color, arg);
1612
1613 if (FRAME_VISIBLE_P (f))
1614 redraw_frame (f);
1615 }
1616 }
1617
1618 void
1619 x_set_mouse_color (f, arg, oldval)
1620 struct frame *f;
1621 Lisp_Object arg, oldval;
1622 {
1623 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1624 int count;
1625 int mask_color;
1626
1627 if (!EQ (Qnil, arg))
1628 f->output_data.w32->mouse_pixel
1629 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1630 mask_color = FRAME_BACKGROUND_PIXEL (f);
1631
1632 /* Don't let pointers be invisible. */
1633 if (mask_color == f->output_data.w32->mouse_pixel
1634 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1635 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1636
1637 #if 0 /* TODO : cursor changes */
1638 BLOCK_INPUT;
1639
1640 /* It's not okay to crash if the user selects a screwy cursor. */
1641 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1642
1643 if (!EQ (Qnil, Vx_pointer_shape))
1644 {
1645 CHECK_NUMBER (Vx_pointer_shape);
1646 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1647 }
1648 else
1649 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1650 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1651
1652 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1653 {
1654 CHECK_NUMBER (Vx_nontext_pointer_shape);
1655 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1656 XINT (Vx_nontext_pointer_shape));
1657 }
1658 else
1659 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1660 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1661
1662 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1663 {
1664 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1665 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1666 XINT (Vx_hourglass_pointer_shape));
1667 }
1668 else
1669 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1670 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1671
1672 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1673 if (!EQ (Qnil, Vx_mode_pointer_shape))
1674 {
1675 CHECK_NUMBER (Vx_mode_pointer_shape);
1676 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1677 XINT (Vx_mode_pointer_shape));
1678 }
1679 else
1680 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1681 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1682
1683 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1684 {
1685 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1686 hand_cursor
1687 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1688 XINT (Vx_sensitive_text_pointer_shape));
1689 }
1690 else
1691 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1692
1693 if (!NILP (Vx_window_horizontal_drag_shape))
1694 {
1695 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1696 horizontal_drag_cursor
1697 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1698 XINT (Vx_window_horizontal_drag_shape));
1699 }
1700 else
1701 horizontal_drag_cursor
1702 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1703
1704 /* Check and report errors with the above calls. */
1705 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1706 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1707
1708 {
1709 XColor fore_color, back_color;
1710
1711 fore_color.pixel = f->output_data.w32->mouse_pixel;
1712 back_color.pixel = mask_color;
1713 XQueryColor (FRAME_W32_DISPLAY (f),
1714 DefaultColormap (FRAME_W32_DISPLAY (f),
1715 DefaultScreen (FRAME_W32_DISPLAY (f))),
1716 &fore_color);
1717 XQueryColor (FRAME_W32_DISPLAY (f),
1718 DefaultColormap (FRAME_W32_DISPLAY (f),
1719 DefaultScreen (FRAME_W32_DISPLAY (f))),
1720 &back_color);
1721 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1722 &fore_color, &back_color);
1723 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1724 &fore_color, &back_color);
1725 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1726 &fore_color, &back_color);
1727 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1728 &fore_color, &back_color);
1729 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1730 &fore_color, &back_color);
1731 }
1732
1733 if (FRAME_W32_WINDOW (f) != 0)
1734 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1735
1736 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1737 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1738 f->output_data.w32->text_cursor = cursor;
1739
1740 if (nontext_cursor != f->output_data.w32->nontext_cursor
1741 && f->output_data.w32->nontext_cursor != 0)
1742 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1743 f->output_data.w32->nontext_cursor = nontext_cursor;
1744
1745 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1746 && f->output_data.w32->hourglass_cursor != 0)
1747 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1748 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1749
1750 if (mode_cursor != f->output_data.w32->modeline_cursor
1751 && f->output_data.w32->modeline_cursor != 0)
1752 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1753 f->output_data.w32->modeline_cursor = mode_cursor;
1754
1755 if (hand_cursor != f->output_data.w32->hand_cursor
1756 && f->output_data.w32->hand_cursor != 0)
1757 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1758 f->output_data.w32->hand_cursor = hand_cursor;
1759
1760 XFlush (FRAME_W32_DISPLAY (f));
1761 UNBLOCK_INPUT;
1762
1763 update_face_from_frame_parameter (f, Qmouse_color, arg);
1764 #endif /* TODO */
1765 }
1766
1767 /* Defined in w32term.c. */
1768 void
1769 x_set_cursor_color (f, arg, oldval)
1770 struct frame *f;
1771 Lisp_Object arg, oldval;
1772 {
1773 unsigned long fore_pixel, pixel;
1774
1775 if (!NILP (Vx_cursor_fore_pixel))
1776 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1777 WHITE_PIX_DEFAULT (f));
1778 else
1779 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1780
1781 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1782
1783 /* Make sure that the cursor color differs from the background color. */
1784 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1785 {
1786 pixel = f->output_data.w32->mouse_pixel;
1787 if (pixel == fore_pixel)
1788 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1789 }
1790
1791 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1792 f->output_data.w32->cursor_pixel = pixel;
1793
1794 if (FRAME_W32_WINDOW (f) != 0)
1795 {
1796 BLOCK_INPUT;
1797 /* Update frame's cursor_gc. */
1798 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1799 f->output_data.w32->cursor_gc->background = pixel;
1800
1801 UNBLOCK_INPUT;
1802
1803 if (FRAME_VISIBLE_P (f))
1804 {
1805 x_update_cursor (f, 0);
1806 x_update_cursor (f, 1);
1807 }
1808 }
1809
1810 update_face_from_frame_parameter (f, Qcursor_color, arg);
1811 }
1812
1813 /* Set the border-color of frame F to pixel value PIX.
1814 Note that this does not fully take effect if done before
1815 F has a window. */
1816
1817 void
1818 x_set_border_pixel (f, pix)
1819 struct frame *f;
1820 int pix;
1821 {
1822
1823 f->output_data.w32->border_pixel = pix;
1824
1825 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1826 {
1827 if (FRAME_VISIBLE_P (f))
1828 redraw_frame (f);
1829 }
1830 }
1831
1832 /* Set the border-color of frame F to value described by ARG.
1833 ARG can be a string naming a color.
1834 The border-color is used for the border that is drawn by the server.
1835 Note that this does not fully take effect if done before
1836 F has a window; it must be redone when the window is created. */
1837
1838 void
1839 x_set_border_color (f, arg, oldval)
1840 struct frame *f;
1841 Lisp_Object arg, oldval;
1842 {
1843 int pix;
1844
1845 CHECK_STRING (arg);
1846 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1847 x_set_border_pixel (f, pix);
1848 update_face_from_frame_parameter (f, Qborder_color, arg);
1849 }
1850
1851
1852 void
1853 x_set_cursor_type (f, arg, oldval)
1854 FRAME_PTR f;
1855 Lisp_Object arg, oldval;
1856 {
1857 set_frame_cursor_types (f, arg);
1858
1859 /* Make sure the cursor gets redrawn. */
1860 cursor_type_changed = 1;
1861 }
1862 \f
1863 void
1864 x_set_icon_type (f, arg, oldval)
1865 struct frame *f;
1866 Lisp_Object arg, oldval;
1867 {
1868 int result;
1869
1870 if (NILP (arg) && NILP (oldval))
1871 return;
1872
1873 if (STRINGP (arg) && STRINGP (oldval)
1874 && EQ (Fstring_equal (oldval, arg), Qt))
1875 return;
1876
1877 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1878 return;
1879
1880 BLOCK_INPUT;
1881
1882 result = x_bitmap_icon (f, arg);
1883 if (result)
1884 {
1885 UNBLOCK_INPUT;
1886 error ("No icon window available");
1887 }
1888
1889 UNBLOCK_INPUT;
1890 }
1891
1892 void
1893 x_set_icon_name (f, arg, oldval)
1894 struct frame *f;
1895 Lisp_Object arg, oldval;
1896 {
1897 if (STRINGP (arg))
1898 {
1899 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1900 return;
1901 }
1902 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
1903 return;
1904
1905 f->icon_name = arg;
1906
1907 #if 0
1908 if (f->output_data.w32->icon_bitmap != 0)
1909 return;
1910
1911 BLOCK_INPUT;
1912
1913 result = x_text_icon (f,
1914 (char *) SDATA ((!NILP (f->icon_name)
1915 ? f->icon_name
1916 : !NILP (f->title)
1917 ? f->title
1918 : f->name)));
1919
1920 if (result)
1921 {
1922 UNBLOCK_INPUT;
1923 error ("No icon window available");
1924 }
1925
1926 /* If the window was unmapped (and its icon was mapped),
1927 the new icon is not mapped, so map the window in its stead. */
1928 if (FRAME_VISIBLE_P (f))
1929 {
1930 #ifdef USE_X_TOOLKIT
1931 XtPopup (f->output_data.w32->widget, XtGrabNone);
1932 #endif
1933 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1934 }
1935
1936 XFlush (FRAME_W32_DISPLAY (f));
1937 UNBLOCK_INPUT;
1938 #endif
1939 }
1940
1941 \f
1942 void
1943 x_set_menu_bar_lines (f, value, oldval)
1944 struct frame *f;
1945 Lisp_Object value, oldval;
1946 {
1947 int nlines;
1948 int olines = FRAME_MENU_BAR_LINES (f);
1949
1950 /* Right now, menu bars don't work properly in minibuf-only frames;
1951 most of the commands try to apply themselves to the minibuffer
1952 frame itself, and get an error because you can't switch buffers
1953 in or split the minibuffer window. */
1954 if (FRAME_MINIBUF_ONLY_P (f))
1955 return;
1956
1957 if (INTEGERP (value))
1958 nlines = XINT (value);
1959 else
1960 nlines = 0;
1961
1962 FRAME_MENU_BAR_LINES (f) = 0;
1963 if (nlines)
1964 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1965 else
1966 {
1967 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1968 free_frame_menubar (f);
1969 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1970
1971 /* Adjust the frame size so that the client (text) dimensions
1972 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1973 set correctly. */
1974 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
1975 do_pending_window_change (0);
1976 }
1977 adjust_glyphs (f);
1978 }
1979
1980
1981 /* Set the number of lines used for the tool bar of frame F to VALUE.
1982 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
1983 is the old number of tool bar lines. This function changes the
1984 height of all windows on frame F to match the new tool bar height.
1985 The frame's height doesn't change. */
1986
1987 void
1988 x_set_tool_bar_lines (f, value, oldval)
1989 struct frame *f;
1990 Lisp_Object value, oldval;
1991 {
1992 int delta, nlines, root_height;
1993 Lisp_Object root_window;
1994
1995 /* Treat tool bars like menu bars. */
1996 if (FRAME_MINIBUF_ONLY_P (f))
1997 return;
1998
1999 /* Use VALUE only if an integer >= 0. */
2000 if (INTEGERP (value) && XINT (value) >= 0)
2001 nlines = XFASTINT (value);
2002 else
2003 nlines = 0;
2004
2005 /* Make sure we redisplay all windows in this frame. */
2006 ++windows_or_buffers_changed;
2007
2008 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2009
2010 /* Don't resize the tool-bar to more than we have room for. */
2011 root_window = FRAME_ROOT_WINDOW (f);
2012 root_height = WINDOW_TOTAL_LINES (XWINDOW (root_window));
2013 if (root_height - delta < 1)
2014 {
2015 delta = root_height - 1;
2016 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2017 }
2018
2019 FRAME_TOOL_BAR_LINES (f) = nlines;
2020 change_window_heights (root_window, delta);
2021 adjust_glyphs (f);
2022
2023 /* We also have to make sure that the internal border at the top of
2024 the frame, below the menu bar or tool bar, is redrawn when the
2025 tool bar disappears. This is so because the internal border is
2026 below the tool bar if one is displayed, but is below the menu bar
2027 if there isn't a tool bar. The tool bar draws into the area
2028 below the menu bar. */
2029 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2030 {
2031 updating_frame = f;
2032 clear_frame ();
2033 clear_current_matrices (f);
2034 updating_frame = NULL;
2035 }
2036
2037 /* If the tool bar gets smaller, the internal border below it
2038 has to be cleared. It was formerly part of the display
2039 of the larger tool bar, and updating windows won't clear it. */
2040 if (delta < 0)
2041 {
2042 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2043 int width = FRAME_PIXEL_WIDTH (f);
2044 int y = nlines * FRAME_LINE_HEIGHT (f);
2045
2046 BLOCK_INPUT;
2047 {
2048 HDC hdc = get_frame_dc (f);
2049 w32_clear_area (f, hdc, 0, y, width, height);
2050 release_frame_dc (f, hdc);
2051 }
2052 UNBLOCK_INPUT;
2053
2054 if (WINDOWP (f->tool_bar_window))
2055 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
2056 }
2057 }
2058
2059
2060 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2061 w32_id_name.
2062
2063 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2064 name; if NAME is a string, set F's name to NAME and set
2065 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2066
2067 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2068 suggesting a new name, which lisp code should override; if
2069 F->explicit_name is set, ignore the new name; otherwise, set it. */
2070
2071 void
2072 x_set_name (f, name, explicit)
2073 struct frame *f;
2074 Lisp_Object name;
2075 int explicit;
2076 {
2077 /* Make sure that requests from lisp code override requests from
2078 Emacs redisplay code. */
2079 if (explicit)
2080 {
2081 /* If we're switching from explicit to implicit, we had better
2082 update the mode lines and thereby update the title. */
2083 if (f->explicit_name && NILP (name))
2084 update_mode_lines = 1;
2085
2086 f->explicit_name = ! NILP (name);
2087 }
2088 else if (f->explicit_name)
2089 return;
2090
2091 /* If NAME is nil, set the name to the w32_id_name. */
2092 if (NILP (name))
2093 {
2094 /* Check for no change needed in this very common case
2095 before we do any consing. */
2096 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2097 SDATA (f->name)))
2098 return;
2099 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2100 }
2101 else
2102 CHECK_STRING (name);
2103
2104 /* Don't change the name if it's already NAME. */
2105 if (! NILP (Fstring_equal (name, f->name)))
2106 return;
2107
2108 f->name = name;
2109
2110 /* For setting the frame title, the title parameter should override
2111 the name parameter. */
2112 if (! NILP (f->title))
2113 name = f->title;
2114
2115 if (FRAME_W32_WINDOW (f))
2116 {
2117 if (STRING_MULTIBYTE (name))
2118 name = ENCODE_SYSTEM (name);
2119
2120 BLOCK_INPUT;
2121 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2122 UNBLOCK_INPUT;
2123 }
2124 }
2125
2126 /* This function should be called when the user's lisp code has
2127 specified a name for the frame; the name will override any set by the
2128 redisplay code. */
2129 void
2130 x_explicitly_set_name (f, arg, oldval)
2131 FRAME_PTR f;
2132 Lisp_Object arg, oldval;
2133 {
2134 x_set_name (f, arg, 1);
2135 }
2136
2137 /* This function should be called by Emacs redisplay code to set the
2138 name; names set this way will never override names set by the user's
2139 lisp code. */
2140 void
2141 x_implicitly_set_name (f, arg, oldval)
2142 FRAME_PTR f;
2143 Lisp_Object arg, oldval;
2144 {
2145 x_set_name (f, arg, 0);
2146 }
2147 \f
2148 /* Change the title of frame F to NAME.
2149 If NAME is nil, use the frame name as the title.
2150
2151 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2152 name; if NAME is a string, set F's name to NAME and set
2153 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2154
2155 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2156 suggesting a new name, which lisp code should override; if
2157 F->explicit_name is set, ignore the new name; otherwise, set it. */
2158
2159 void
2160 x_set_title (f, name, old_name)
2161 struct frame *f;
2162 Lisp_Object name, old_name;
2163 {
2164 /* Don't change the title if it's already NAME. */
2165 if (EQ (name, f->title))
2166 return;
2167
2168 update_mode_lines = 1;
2169
2170 f->title = name;
2171
2172 if (NILP (name))
2173 name = f->name;
2174
2175 if (FRAME_W32_WINDOW (f))
2176 {
2177 if (STRING_MULTIBYTE (name))
2178 name = ENCODE_SYSTEM (name);
2179
2180 BLOCK_INPUT;
2181 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2182 UNBLOCK_INPUT;
2183 }
2184 }
2185
2186
2187 void x_set_scroll_bar_default_width (f)
2188 struct frame *f;
2189 {
2190 int wid = FRAME_COLUMN_WIDTH (f);
2191
2192 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2193 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2194 wid - 1) / wid;
2195 }
2196
2197 \f
2198 /* Subroutines of creating a frame. */
2199
2200
2201 /* Return the value of parameter PARAM.
2202
2203 First search ALIST, then Vdefault_frame_alist, then the X defaults
2204 database, using ATTRIBUTE as the attribute name and CLASS as its class.
2205
2206 Convert the resource to the type specified by desired_type.
2207
2208 If no default is specified, return Qunbound. If you call
2209 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
2210 and don't let it get stored in any Lisp-visible variables! */
2211
2212 static Lisp_Object
2213 w32_get_arg (alist, param, attribute, class, type)
2214 Lisp_Object alist, param;
2215 char *attribute;
2216 char *class;
2217 enum resource_types type;
2218 {
2219 return x_get_arg (check_x_display_info (Qnil),
2220 alist, param, attribute, class, type);
2221 }
2222
2223 \f
2224 Cursor
2225 w32_load_cursor (LPCTSTR name)
2226 {
2227 /* Try first to load cursor from application resource. */
2228 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle(NULL),
2229 name, IMAGE_CURSOR, 0, 0,
2230 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2231 if (!cursor)
2232 {
2233 /* Then try to load a shared predefined cursor. */
2234 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
2235 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2236 }
2237 return cursor;
2238 }
2239
2240 extern LRESULT CALLBACK w32_wnd_proc ();
2241
2242 BOOL
2243 w32_init_class (hinst)
2244 HINSTANCE hinst;
2245 {
2246 WNDCLASS wc;
2247
2248 wc.style = CS_HREDRAW | CS_VREDRAW;
2249 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
2250 wc.cbClsExtra = 0;
2251 wc.cbWndExtra = WND_EXTRA_BYTES;
2252 wc.hInstance = hinst;
2253 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
2254 wc.hCursor = w32_load_cursor (IDC_ARROW);
2255 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
2256 wc.lpszMenuName = NULL;
2257 wc.lpszClassName = EMACS_CLASS;
2258
2259 return (RegisterClass (&wc));
2260 }
2261
2262 HWND
2263 w32_createscrollbar (f, bar)
2264 struct frame *f;
2265 struct scroll_bar * bar;
2266 {
2267 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2268 /* Position and size of scroll bar. */
2269 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
2270 XINT(bar->top),
2271 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
2272 XINT(bar->height),
2273 FRAME_W32_WINDOW (f),
2274 NULL,
2275 hinst,
2276 NULL));
2277 }
2278
2279 void
2280 w32_createwindow (f)
2281 struct frame *f;
2282 {
2283 HWND hwnd;
2284 RECT rect;
2285
2286 rect.left = rect.top = 0;
2287 rect.right = FRAME_PIXEL_WIDTH (f);
2288 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2289
2290 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2291 FRAME_EXTERNAL_MENU_BAR (f));
2292
2293 /* Do first time app init */
2294
2295 if (!hprevinst)
2296 {
2297 w32_init_class (hinst);
2298 }
2299
2300 FRAME_W32_WINDOW (f) = hwnd
2301 = CreateWindow (EMACS_CLASS,
2302 f->namebuf,
2303 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2304 f->left_pos,
2305 f->top_pos,
2306 rect.right - rect.left,
2307 rect.bottom - rect.top,
2308 NULL,
2309 NULL,
2310 hinst,
2311 NULL);
2312
2313 if (hwnd)
2314 {
2315 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2316 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2317 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2318 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->scroll_bar_actual_width);
2319 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2320
2321 /* Enable drag-n-drop. */
2322 DragAcceptFiles (hwnd, TRUE);
2323
2324 /* Do this to discard the default setting specified by our parent. */
2325 ShowWindow (hwnd, SW_HIDE);
2326 }
2327 }
2328
2329 void
2330 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
2331 W32Msg * wmsg;
2332 HWND hwnd;
2333 UINT msg;
2334 WPARAM wParam;
2335 LPARAM lParam;
2336 {
2337 wmsg->msg.hwnd = hwnd;
2338 wmsg->msg.message = msg;
2339 wmsg->msg.wParam = wParam;
2340 wmsg->msg.lParam = lParam;
2341 wmsg->msg.time = GetMessageTime ();
2342
2343 post_msg (wmsg);
2344 }
2345
2346 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2347 between left and right keys as advertised. We test for this
2348 support dynamically, and set a flag when the support is absent. If
2349 absent, we keep track of the left and right control and alt keys
2350 ourselves. This is particularly necessary on keyboards that rely
2351 upon the AltGr key, which is represented as having the left control
2352 and right alt keys pressed. For these keyboards, we need to know
2353 when the left alt key has been pressed in addition to the AltGr key
2354 so that we can properly support M-AltGr-key sequences (such as M-@
2355 on Swedish keyboards). */
2356
2357 #define EMACS_LCONTROL 0
2358 #define EMACS_RCONTROL 1
2359 #define EMACS_LMENU 2
2360 #define EMACS_RMENU 3
2361
2362 static int modifiers[4];
2363 static int modifiers_recorded;
2364 static int modifier_key_support_tested;
2365
2366 static void
2367 test_modifier_support (unsigned int wparam)
2368 {
2369 unsigned int l, r;
2370
2371 if (wparam != VK_CONTROL && wparam != VK_MENU)
2372 return;
2373 if (wparam == VK_CONTROL)
2374 {
2375 l = VK_LCONTROL;
2376 r = VK_RCONTROL;
2377 }
2378 else
2379 {
2380 l = VK_LMENU;
2381 r = VK_RMENU;
2382 }
2383 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2384 modifiers_recorded = 1;
2385 else
2386 modifiers_recorded = 0;
2387 modifier_key_support_tested = 1;
2388 }
2389
2390 static void
2391 record_keydown (unsigned int wparam, unsigned int lparam)
2392 {
2393 int i;
2394
2395 if (!modifier_key_support_tested)
2396 test_modifier_support (wparam);
2397
2398 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2399 return;
2400
2401 if (wparam == VK_CONTROL)
2402 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2403 else
2404 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2405
2406 modifiers[i] = 1;
2407 }
2408
2409 static void
2410 record_keyup (unsigned int wparam, unsigned int lparam)
2411 {
2412 int i;
2413
2414 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2415 return;
2416
2417 if (wparam == VK_CONTROL)
2418 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2419 else
2420 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2421
2422 modifiers[i] = 0;
2423 }
2424
2425 /* Emacs can lose focus while a modifier key has been pressed. When
2426 it regains focus, be conservative and clear all modifiers since
2427 we cannot reconstruct the left and right modifier state. */
2428 static void
2429 reset_modifiers ()
2430 {
2431 SHORT ctrl, alt;
2432
2433 if (GetFocus () == NULL)
2434 /* Emacs doesn't have keyboard focus. Do nothing. */
2435 return;
2436
2437 ctrl = GetAsyncKeyState (VK_CONTROL);
2438 alt = GetAsyncKeyState (VK_MENU);
2439
2440 if (!(ctrl & 0x08000))
2441 /* Clear any recorded control modifier state. */
2442 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2443
2444 if (!(alt & 0x08000))
2445 /* Clear any recorded alt modifier state. */
2446 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2447
2448 /* Update the state of all modifier keys, because modifiers used in
2449 hot-key combinations can get stuck on if Emacs loses focus as a
2450 result of a hot-key being pressed. */
2451 {
2452 BYTE keystate[256];
2453
2454 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2455
2456 GetKeyboardState (keystate);
2457 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2458 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2459 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2460 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2461 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2462 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2463 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2464 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2465 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2466 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2467 SetKeyboardState (keystate);
2468 }
2469 }
2470
2471 /* Synchronize modifier state with what is reported with the current
2472 keystroke. Even if we cannot distinguish between left and right
2473 modifier keys, we know that, if no modifiers are set, then neither
2474 the left or right modifier should be set. */
2475 static void
2476 sync_modifiers ()
2477 {
2478 if (!modifiers_recorded)
2479 return;
2480
2481 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2482 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2483
2484 if (!(GetKeyState (VK_MENU) & 0x8000))
2485 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2486 }
2487
2488 static int
2489 modifier_set (int vkey)
2490 {
2491 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
2492 return (GetKeyState (vkey) & 0x1);
2493 if (!modifiers_recorded)
2494 return (GetKeyState (vkey) & 0x8000);
2495
2496 switch (vkey)
2497 {
2498 case VK_LCONTROL:
2499 return modifiers[EMACS_LCONTROL];
2500 case VK_RCONTROL:
2501 return modifiers[EMACS_RCONTROL];
2502 case VK_LMENU:
2503 return modifiers[EMACS_LMENU];
2504 case VK_RMENU:
2505 return modifiers[EMACS_RMENU];
2506 }
2507 return (GetKeyState (vkey) & 0x8000);
2508 }
2509
2510 /* Convert between the modifier bits W32 uses and the modifier bits
2511 Emacs uses. */
2512
2513 unsigned int
2514 w32_key_to_modifier (int key)
2515 {
2516 Lisp_Object key_mapping;
2517
2518 switch (key)
2519 {
2520 case VK_LWIN:
2521 key_mapping = Vw32_lwindow_modifier;
2522 break;
2523 case VK_RWIN:
2524 key_mapping = Vw32_rwindow_modifier;
2525 break;
2526 case VK_APPS:
2527 key_mapping = Vw32_apps_modifier;
2528 break;
2529 case VK_SCROLL:
2530 key_mapping = Vw32_scroll_lock_modifier;
2531 break;
2532 default:
2533 key_mapping = Qnil;
2534 }
2535
2536 /* NB. This code runs in the input thread, asychronously to the lisp
2537 thread, so we must be careful to ensure access to lisp data is
2538 thread-safe. The following code is safe because the modifier
2539 variable values are updated atomically from lisp and symbols are
2540 not relocated by GC. Also, we don't have to worry about seeing GC
2541 markbits here. */
2542 if (EQ (key_mapping, Qhyper))
2543 return hyper_modifier;
2544 if (EQ (key_mapping, Qsuper))
2545 return super_modifier;
2546 if (EQ (key_mapping, Qmeta))
2547 return meta_modifier;
2548 if (EQ (key_mapping, Qalt))
2549 return alt_modifier;
2550 if (EQ (key_mapping, Qctrl))
2551 return ctrl_modifier;
2552 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2553 return ctrl_modifier;
2554 if (EQ (key_mapping, Qshift))
2555 return shift_modifier;
2556
2557 /* Don't generate any modifier if not explicitly requested. */
2558 return 0;
2559 }
2560
2561 unsigned int
2562 w32_get_modifiers ()
2563 {
2564 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2565 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2566 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2567 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2568 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2569 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2570 (modifier_set (VK_MENU) ?
2571 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2572 }
2573
2574 /* We map the VK_* modifiers into console modifier constants
2575 so that we can use the same routines to handle both console
2576 and window input. */
2577
2578 static int
2579 construct_console_modifiers ()
2580 {
2581 int mods;
2582
2583 mods = 0;
2584 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2585 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2586 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2587 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2588 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2589 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2590 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2591 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2592 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2593 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2594 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2595
2596 return mods;
2597 }
2598
2599 static int
2600 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2601 {
2602 int mods;
2603
2604 /* Convert to emacs modifiers. */
2605 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2606
2607 return mods;
2608 }
2609
2610 unsigned int
2611 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2612 {
2613 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2614 return virt_key;
2615
2616 if (virt_key == VK_RETURN)
2617 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2618
2619 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2620 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2621
2622 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2623 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2624
2625 if (virt_key == VK_CLEAR)
2626 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2627
2628 return virt_key;
2629 }
2630
2631 /* List of special key combinations which w32 would normally capture,
2632 but emacs should grab instead. Not directly visible to lisp, to
2633 simplify synchronization. Each item is an integer encoding a virtual
2634 key code and modifier combination to capture. */
2635 Lisp_Object w32_grabbed_keys;
2636
2637 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
2638 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2639 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2640 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2641
2642 /* Register hot-keys for reserved key combinations when Emacs has
2643 keyboard focus, since this is the only way Emacs can receive key
2644 combinations like Alt-Tab which are used by the system. */
2645
2646 static void
2647 register_hot_keys (hwnd)
2648 HWND hwnd;
2649 {
2650 Lisp_Object keylist;
2651
2652 /* Use GC_CONSP, since we are called asynchronously. */
2653 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2654 {
2655 Lisp_Object key = XCAR (keylist);
2656
2657 /* Deleted entries get set to nil. */
2658 if (!INTEGERP (key))
2659 continue;
2660
2661 RegisterHotKey (hwnd, HOTKEY_ID (key),
2662 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2663 }
2664 }
2665
2666 static void
2667 unregister_hot_keys (hwnd)
2668 HWND hwnd;
2669 {
2670 Lisp_Object keylist;
2671
2672 /* Use GC_CONSP, since we are called asynchronously. */
2673 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2674 {
2675 Lisp_Object key = XCAR (keylist);
2676
2677 if (!INTEGERP (key))
2678 continue;
2679
2680 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2681 }
2682 }
2683
2684 /* Main message dispatch loop. */
2685
2686 static void
2687 w32_msg_pump (deferred_msg * msg_buf)
2688 {
2689 MSG msg;
2690 int result;
2691 HWND focus_window;
2692
2693 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2694
2695 while (GetMessage (&msg, NULL, 0, 0))
2696 {
2697 if (msg.hwnd == NULL)
2698 {
2699 switch (msg.message)
2700 {
2701 case WM_NULL:
2702 /* Produced by complete_deferred_msg; just ignore. */
2703 break;
2704 case WM_EMACS_CREATEWINDOW:
2705 w32_createwindow ((struct frame *) msg.wParam);
2706 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2707 abort ();
2708 break;
2709 case WM_EMACS_SETLOCALE:
2710 SetThreadLocale (msg.wParam);
2711 /* Reply is not expected. */
2712 break;
2713 case WM_EMACS_SETKEYBOARDLAYOUT:
2714 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2715 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2716 result, 0))
2717 abort ();
2718 break;
2719 case WM_EMACS_REGISTER_HOT_KEY:
2720 focus_window = GetFocus ();
2721 if (focus_window != NULL)
2722 RegisterHotKey (focus_window,
2723 HOTKEY_ID (msg.wParam),
2724 HOTKEY_MODIFIERS (msg.wParam),
2725 HOTKEY_VK_CODE (msg.wParam));
2726 /* Reply is not expected. */
2727 break;
2728 case WM_EMACS_UNREGISTER_HOT_KEY:
2729 focus_window = GetFocus ();
2730 if (focus_window != NULL)
2731 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
2732 /* Mark item as erased. NB: this code must be
2733 thread-safe. The next line is okay because the cons
2734 cell is never made into garbage and is not relocated by
2735 GC. */
2736 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
2737 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2738 abort ();
2739 break;
2740 case WM_EMACS_TOGGLE_LOCK_KEY:
2741 {
2742 int vk_code = (int) msg.wParam;
2743 int cur_state = (GetKeyState (vk_code) & 1);
2744 Lisp_Object new_state = (Lisp_Object) msg.lParam;
2745
2746 /* NB: This code must be thread-safe. It is safe to
2747 call NILP because symbols are not relocated by GC,
2748 and pointer here is not touched by GC (so the markbit
2749 can't be set). Numbers are safe because they are
2750 immediate values. */
2751 if (NILP (new_state)
2752 || (NUMBERP (new_state)
2753 && ((XUINT (new_state)) & 1) != cur_state))
2754 {
2755 one_w32_display_info.faked_key = vk_code;
2756
2757 keybd_event ((BYTE) vk_code,
2758 (BYTE) MapVirtualKey (vk_code, 0),
2759 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2760 keybd_event ((BYTE) vk_code,
2761 (BYTE) MapVirtualKey (vk_code, 0),
2762 KEYEVENTF_EXTENDEDKEY | 0, 0);
2763 keybd_event ((BYTE) vk_code,
2764 (BYTE) MapVirtualKey (vk_code, 0),
2765 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2766 cur_state = !cur_state;
2767 }
2768 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2769 cur_state, 0))
2770 abort ();
2771 }
2772 break;
2773 default:
2774 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2775 }
2776 }
2777 else
2778 {
2779 DispatchMessage (&msg);
2780 }
2781
2782 /* Exit nested loop when our deferred message has completed. */
2783 if (msg_buf->completed)
2784 break;
2785 }
2786 }
2787
2788 deferred_msg * deferred_msg_head;
2789
2790 static deferred_msg *
2791 find_deferred_msg (HWND hwnd, UINT msg)
2792 {
2793 deferred_msg * item;
2794
2795 /* Don't actually need synchronization for read access, since
2796 modification of single pointer is always atomic. */
2797 /* enter_crit (); */
2798
2799 for (item = deferred_msg_head; item != NULL; item = item->next)
2800 if (item->w32msg.msg.hwnd == hwnd
2801 && item->w32msg.msg.message == msg)
2802 break;
2803
2804 /* leave_crit (); */
2805
2806 return item;
2807 }
2808
2809 static LRESULT
2810 send_deferred_msg (deferred_msg * msg_buf,
2811 HWND hwnd,
2812 UINT msg,
2813 WPARAM wParam,
2814 LPARAM lParam)
2815 {
2816 /* Only input thread can send deferred messages. */
2817 if (GetCurrentThreadId () != dwWindowsThreadId)
2818 abort ();
2819
2820 /* It is an error to send a message that is already deferred. */
2821 if (find_deferred_msg (hwnd, msg) != NULL)
2822 abort ();
2823
2824 /* Enforced synchronization is not needed because this is the only
2825 function that alters deferred_msg_head, and the following critical
2826 section is guaranteed to only be serially reentered (since only the
2827 input thread can call us). */
2828
2829 /* enter_crit (); */
2830
2831 msg_buf->completed = 0;
2832 msg_buf->next = deferred_msg_head;
2833 deferred_msg_head = msg_buf;
2834 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2835
2836 /* leave_crit (); */
2837
2838 /* Start a new nested message loop to process other messages until
2839 this one is completed. */
2840 w32_msg_pump (msg_buf);
2841
2842 deferred_msg_head = msg_buf->next;
2843
2844 return msg_buf->result;
2845 }
2846
2847 void
2848 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2849 {
2850 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2851
2852 if (msg_buf == NULL)
2853 /* Message may have been cancelled, so don't abort(). */
2854 return;
2855
2856 msg_buf->result = result;
2857 msg_buf->completed = 1;
2858
2859 /* Ensure input thread is woken so it notices the completion. */
2860 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2861 }
2862
2863 void
2864 cancel_all_deferred_msgs ()
2865 {
2866 deferred_msg * item;
2867
2868 /* Don't actually need synchronization for read access, since
2869 modification of single pointer is always atomic. */
2870 /* enter_crit (); */
2871
2872 for (item = deferred_msg_head; item != NULL; item = item->next)
2873 {
2874 item->result = 0;
2875 item->completed = 1;
2876 }
2877
2878 /* leave_crit (); */
2879
2880 /* Ensure input thread is woken so it notices the completion. */
2881 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2882 }
2883
2884 DWORD
2885 w32_msg_worker (dw)
2886 DWORD dw;
2887 {
2888 MSG msg;
2889 deferred_msg dummy_buf;
2890
2891 /* Ensure our message queue is created */
2892
2893 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2894
2895 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2896 abort ();
2897
2898 memset (&dummy_buf, 0, sizeof (dummy_buf));
2899 dummy_buf.w32msg.msg.hwnd = NULL;
2900 dummy_buf.w32msg.msg.message = WM_NULL;
2901
2902 /* This is the inital message loop which should only exit when the
2903 application quits. */
2904 w32_msg_pump (&dummy_buf);
2905
2906 return 0;
2907 }
2908
2909 static void
2910 post_character_message (hwnd, msg, wParam, lParam, modifiers)
2911 HWND hwnd;
2912 UINT msg;
2913 WPARAM wParam;
2914 LPARAM lParam;
2915 DWORD modifiers;
2916
2917 {
2918 W32Msg wmsg;
2919
2920 wmsg.dwModifiers = modifiers;
2921
2922 /* Detect quit_char and set quit-flag directly. Note that we
2923 still need to post a message to ensure the main thread will be
2924 woken up if blocked in sys_select(), but we do NOT want to post
2925 the quit_char message itself (because it will usually be as if
2926 the user had typed quit_char twice). Instead, we post a dummy
2927 message that has no particular effect. */
2928 {
2929 int c = wParam;
2930 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2931 c = make_ctrl_char (c) & 0377;
2932 if (c == quit_char
2933 || (wmsg.dwModifiers == 0 &&
2934 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
2935 {
2936 Vquit_flag = Qt;
2937
2938 /* The choice of message is somewhat arbitrary, as long as
2939 the main thread handler just ignores it. */
2940 msg = WM_NULL;
2941
2942 /* Interrupt any blocking system calls. */
2943 signal_quit ();
2944
2945 /* As a safety precaution, forcibly complete any deferred
2946 messages. This is a kludge, but I don't see any particularly
2947 clean way to handle the situation where a deferred message is
2948 "dropped" in the lisp thread, and will thus never be
2949 completed, eg. by the user trying to activate the menubar
2950 when the lisp thread is busy, and then typing C-g when the
2951 menubar doesn't open promptly (with the result that the
2952 menubar never responds at all because the deferred
2953 WM_INITMENU message is never completed). Another problem
2954 situation is when the lisp thread calls SendMessage (to send
2955 a window manager command) when a message has been deferred;
2956 the lisp thread gets blocked indefinitely waiting for the
2957 deferred message to be completed, which itself is waiting for
2958 the lisp thread to respond.
2959
2960 Note that we don't want to block the input thread waiting for
2961 a reponse from the lisp thread (although that would at least
2962 solve the deadlock problem above), because we want to be able
2963 to receive C-g to interrupt the lisp thread. */
2964 cancel_all_deferred_msgs ();
2965 }
2966 }
2967
2968 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2969 }
2970
2971 /* Main window procedure */
2972
2973 LRESULT CALLBACK
2974 w32_wnd_proc (hwnd, msg, wParam, lParam)
2975 HWND hwnd;
2976 UINT msg;
2977 WPARAM wParam;
2978 LPARAM lParam;
2979 {
2980 struct frame *f;
2981 struct w32_display_info *dpyinfo = &one_w32_display_info;
2982 W32Msg wmsg;
2983 int windows_translate;
2984 int key;
2985
2986 /* Note that it is okay to call x_window_to_frame, even though we are
2987 not running in the main lisp thread, because frame deletion
2988 requires the lisp thread to synchronize with this thread. Thus, if
2989 a frame struct is returned, it can be used without concern that the
2990 lisp thread might make it disappear while we are using it.
2991
2992 NB. Walking the frame list in this thread is safe (as long as
2993 writes of Lisp_Object slots are atomic, which they are on Windows).
2994 Although delete-frame can destructively modify the frame list while
2995 we are walking it, a garbage collection cannot occur until after
2996 delete-frame has synchronized with this thread.
2997
2998 It is also safe to use functions that make GDI calls, such as
2999 w32_clear_rect, because these functions must obtain a DC handle
3000 from the frame struct using get_frame_dc which is thread-aware. */
3001
3002 switch (msg)
3003 {
3004 case WM_ERASEBKGND:
3005 f = x_window_to_frame (dpyinfo, hwnd);
3006 if (f)
3007 {
3008 HDC hdc = get_frame_dc (f);
3009 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
3010 w32_clear_rect (f, hdc, &wmsg.rect);
3011 release_frame_dc (f, hdc);
3012
3013 #if defined (W32_DEBUG_DISPLAY)
3014 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
3015 f,
3016 wmsg.rect.left, wmsg.rect.top,
3017 wmsg.rect.right, wmsg.rect.bottom));
3018 #endif /* W32_DEBUG_DISPLAY */
3019 }
3020 return 1;
3021 case WM_PALETTECHANGED:
3022 /* ignore our own changes */
3023 if ((HWND)wParam != hwnd)
3024 {
3025 f = x_window_to_frame (dpyinfo, hwnd);
3026 if (f)
3027 /* get_frame_dc will realize our palette and force all
3028 frames to be redrawn if needed. */
3029 release_frame_dc (f, get_frame_dc (f));
3030 }
3031 return 0;
3032 case WM_PAINT:
3033 {
3034 PAINTSTRUCT paintStruct;
3035 RECT update_rect;
3036 bzero (&update_rect, sizeof (update_rect));
3037
3038 f = x_window_to_frame (dpyinfo, hwnd);
3039 if (f == 0)
3040 {
3041 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
3042 return 0;
3043 }
3044
3045 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
3046 fails. Apparently this can happen under some
3047 circumstances. */
3048 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
3049 {
3050 enter_crit ();
3051 BeginPaint (hwnd, &paintStruct);
3052
3053 /* The rectangles returned by GetUpdateRect and BeginPaint
3054 do not always match. Play it safe by assuming both areas
3055 are invalid. */
3056 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
3057
3058 #if defined (W32_DEBUG_DISPLAY)
3059 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
3060 f,
3061 wmsg.rect.left, wmsg.rect.top,
3062 wmsg.rect.right, wmsg.rect.bottom));
3063 DebPrint ((" [update region is %d,%d-%d,%d]\n",
3064 update_rect.left, update_rect.top,
3065 update_rect.right, update_rect.bottom));
3066 #endif
3067 EndPaint (hwnd, &paintStruct);
3068 leave_crit ();
3069
3070 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3071
3072 return 0;
3073 }
3074
3075 /* If GetUpdateRect returns 0 (meaning there is no update
3076 region), assume the whole window needs to be repainted. */
3077 GetClientRect(hwnd, &wmsg.rect);
3078 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3079 return 0;
3080 }
3081
3082 case WM_INPUTLANGCHANGE:
3083 /* Inform lisp thread of keyboard layout changes. */
3084 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3085
3086 /* Clear dead keys in the keyboard state; for simplicity only
3087 preserve modifier key states. */
3088 {
3089 int i;
3090 BYTE keystate[256];
3091
3092 GetKeyboardState (keystate);
3093 for (i = 0; i < 256; i++)
3094 if (1
3095 && i != VK_SHIFT
3096 && i != VK_LSHIFT
3097 && i != VK_RSHIFT
3098 && i != VK_CAPITAL
3099 && i != VK_NUMLOCK
3100 && i != VK_SCROLL
3101 && i != VK_CONTROL
3102 && i != VK_LCONTROL
3103 && i != VK_RCONTROL
3104 && i != VK_MENU
3105 && i != VK_LMENU
3106 && i != VK_RMENU
3107 && i != VK_LWIN
3108 && i != VK_RWIN)
3109 keystate[i] = 0;
3110 SetKeyboardState (keystate);
3111 }
3112 goto dflt;
3113
3114 case WM_HOTKEY:
3115 /* Synchronize hot keys with normal input. */
3116 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3117 return (0);
3118
3119 case WM_KEYUP:
3120 case WM_SYSKEYUP:
3121 record_keyup (wParam, lParam);
3122 goto dflt;
3123
3124 case WM_KEYDOWN:
3125 case WM_SYSKEYDOWN:
3126 /* Ignore keystrokes we fake ourself; see below. */
3127 if (dpyinfo->faked_key == wParam)
3128 {
3129 dpyinfo->faked_key = 0;
3130 /* Make sure TranslateMessage sees them though (as long as
3131 they don't produce WM_CHAR messages). This ensures that
3132 indicator lights are toggled promptly on Windows 9x, for
3133 example. */
3134 if (lispy_function_keys[wParam] != 0)
3135 {
3136 windows_translate = 1;
3137 goto translate;
3138 }
3139 return 0;
3140 }
3141
3142 /* Synchronize modifiers with current keystroke. */
3143 sync_modifiers ();
3144 record_keydown (wParam, lParam);
3145 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3146
3147 windows_translate = 0;
3148
3149 switch (wParam)
3150 {
3151 case VK_LWIN:
3152 if (NILP (Vw32_pass_lwindow_to_system))
3153 {
3154 /* Prevent system from acting on keyup (which opens the
3155 Start menu if no other key was pressed) by simulating a
3156 press of Space which we will ignore. */
3157 if (GetAsyncKeyState (wParam) & 1)
3158 {
3159 if (NUMBERP (Vw32_phantom_key_code))
3160 key = XUINT (Vw32_phantom_key_code) & 255;
3161 else
3162 key = VK_SPACE;
3163 dpyinfo->faked_key = key;
3164 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3165 }
3166 }
3167 if (!NILP (Vw32_lwindow_modifier))
3168 return 0;
3169 break;
3170 case VK_RWIN:
3171 if (NILP (Vw32_pass_rwindow_to_system))
3172 {
3173 if (GetAsyncKeyState (wParam) & 1)
3174 {
3175 if (NUMBERP (Vw32_phantom_key_code))
3176 key = XUINT (Vw32_phantom_key_code) & 255;
3177 else
3178 key = VK_SPACE;
3179 dpyinfo->faked_key = key;
3180 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3181 }
3182 }
3183 if (!NILP (Vw32_rwindow_modifier))
3184 return 0;
3185 break;
3186 case VK_APPS:
3187 if (!NILP (Vw32_apps_modifier))
3188 return 0;
3189 break;
3190 case VK_MENU:
3191 if (NILP (Vw32_pass_alt_to_system))
3192 /* Prevent DefWindowProc from activating the menu bar if an
3193 Alt key is pressed and released by itself. */
3194 return 0;
3195 windows_translate = 1;
3196 break;
3197 case VK_CAPITAL:
3198 /* Decide whether to treat as modifier or function key. */
3199 if (NILP (Vw32_enable_caps_lock))
3200 goto disable_lock_key;
3201 windows_translate = 1;
3202 break;
3203 case VK_NUMLOCK:
3204 /* Decide whether to treat as modifier or function key. */
3205 if (NILP (Vw32_enable_num_lock))
3206 goto disable_lock_key;
3207 windows_translate = 1;
3208 break;
3209 case VK_SCROLL:
3210 /* Decide whether to treat as modifier or function key. */
3211 if (NILP (Vw32_scroll_lock_modifier))
3212 goto disable_lock_key;
3213 windows_translate = 1;
3214 break;
3215 disable_lock_key:
3216 /* Ensure the appropriate lock key state (and indicator light)
3217 remains in the same state. We do this by faking another
3218 press of the relevant key. Apparently, this really is the
3219 only way to toggle the state of the indicator lights. */
3220 dpyinfo->faked_key = wParam;
3221 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3222 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3223 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3224 KEYEVENTF_EXTENDEDKEY | 0, 0);
3225 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3226 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3227 /* Ensure indicator lights are updated promptly on Windows 9x
3228 (TranslateMessage apparently does this), after forwarding
3229 input event. */
3230 post_character_message (hwnd, msg, wParam, lParam,
3231 w32_get_key_modifiers (wParam, lParam));
3232 windows_translate = 1;
3233 break;
3234 case VK_CONTROL:
3235 case VK_SHIFT:
3236 case VK_PROCESSKEY: /* Generated by IME. */
3237 windows_translate = 1;
3238 break;
3239 case VK_CANCEL:
3240 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3241 which is confusing for purposes of key binding; convert
3242 VK_CANCEL events into VK_PAUSE events. */
3243 wParam = VK_PAUSE;
3244 break;
3245 case VK_PAUSE:
3246 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3247 for purposes of key binding; convert these back into
3248 VK_NUMLOCK events, at least when we want to see NumLock key
3249 presses. (Note that there is never any possibility that
3250 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3251 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3252 wParam = VK_NUMLOCK;
3253 break;
3254 default:
3255 /* If not defined as a function key, change it to a WM_CHAR message. */
3256 if (lispy_function_keys[wParam] == 0)
3257 {
3258 DWORD modifiers = construct_console_modifiers ();
3259
3260 if (!NILP (Vw32_recognize_altgr)
3261 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3262 {
3263 /* Always let TranslateMessage handle AltGr key chords;
3264 for some reason, ToAscii doesn't always process AltGr
3265 chords correctly. */
3266 windows_translate = 1;
3267 }
3268 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3269 {
3270 /* Handle key chords including any modifiers other
3271 than shift directly, in order to preserve as much
3272 modifier information as possible. */
3273 if ('A' <= wParam && wParam <= 'Z')
3274 {
3275 /* Don't translate modified alphabetic keystrokes,
3276 so the user doesn't need to constantly switch
3277 layout to type control or meta keystrokes when
3278 the normal layout translates alphabetic
3279 characters to non-ascii characters. */
3280 if (!modifier_set (VK_SHIFT))
3281 wParam += ('a' - 'A');
3282 msg = WM_CHAR;
3283 }
3284 else
3285 {
3286 /* Try to handle other keystrokes by determining the
3287 base character (ie. translating the base key plus
3288 shift modifier). */
3289 int add;
3290 int isdead = 0;
3291 KEY_EVENT_RECORD key;
3292
3293 key.bKeyDown = TRUE;
3294 key.wRepeatCount = 1;
3295 key.wVirtualKeyCode = wParam;
3296 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3297 key.uChar.AsciiChar = 0;
3298 key.dwControlKeyState = modifiers;
3299
3300 add = w32_kbd_patch_key (&key);
3301 /* 0 means an unrecognised keycode, negative means
3302 dead key. Ignore both. */
3303 while (--add >= 0)
3304 {
3305 /* Forward asciified character sequence. */
3306 post_character_message
3307 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
3308 w32_get_key_modifiers (wParam, lParam));
3309 w32_kbd_patch_key (&key);
3310 }
3311 return 0;
3312 }
3313 }
3314 else
3315 {
3316 /* Let TranslateMessage handle everything else. */
3317 windows_translate = 1;
3318 }
3319 }
3320 }
3321
3322 translate:
3323 if (windows_translate)
3324 {
3325 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3326
3327 windows_msg.time = GetMessageTime ();
3328 TranslateMessage (&windows_msg);
3329 goto dflt;
3330 }
3331
3332 /* Fall through */
3333
3334 case WM_SYSCHAR:
3335 case WM_CHAR:
3336 post_character_message (hwnd, msg, wParam, lParam,
3337 w32_get_key_modifiers (wParam, lParam));
3338 break;
3339
3340 /* Simulate middle mouse button events when left and right buttons
3341 are used together, but only if user has two button mouse. */
3342 case WM_LBUTTONDOWN:
3343 case WM_RBUTTONDOWN:
3344 if (XINT (Vw32_num_mouse_buttons) > 2)
3345 goto handle_plain_button;
3346
3347 {
3348 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3349 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3350
3351 if (button_state & this)
3352 return 0;
3353
3354 if (button_state == 0)
3355 SetCapture (hwnd);
3356
3357 button_state |= this;
3358
3359 if (button_state & other)
3360 {
3361 if (mouse_button_timer)
3362 {
3363 KillTimer (hwnd, mouse_button_timer);
3364 mouse_button_timer = 0;
3365
3366 /* Generate middle mouse event instead. */
3367 msg = WM_MBUTTONDOWN;
3368 button_state |= MMOUSE;
3369 }
3370 else if (button_state & MMOUSE)
3371 {
3372 /* Ignore button event if we've already generated a
3373 middle mouse down event. This happens if the
3374 user releases and press one of the two buttons
3375 after we've faked a middle mouse event. */
3376 return 0;
3377 }
3378 else
3379 {
3380 /* Flush out saved message. */
3381 post_msg (&saved_mouse_button_msg);
3382 }
3383 wmsg.dwModifiers = w32_get_modifiers ();
3384 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3385
3386 /* Clear message buffer. */
3387 saved_mouse_button_msg.msg.hwnd = 0;
3388 }
3389 else
3390 {
3391 /* Hold onto message for now. */
3392 mouse_button_timer =
3393 SetTimer (hwnd, MOUSE_BUTTON_ID,
3394 XINT (Vw32_mouse_button_tolerance), NULL);
3395 saved_mouse_button_msg.msg.hwnd = hwnd;
3396 saved_mouse_button_msg.msg.message = msg;
3397 saved_mouse_button_msg.msg.wParam = wParam;
3398 saved_mouse_button_msg.msg.lParam = lParam;
3399 saved_mouse_button_msg.msg.time = GetMessageTime ();
3400 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3401 }
3402 }
3403 return 0;
3404
3405 case WM_LBUTTONUP:
3406 case WM_RBUTTONUP:
3407 if (XINT (Vw32_num_mouse_buttons) > 2)
3408 goto handle_plain_button;
3409
3410 {
3411 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3412 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3413
3414 if ((button_state & this) == 0)
3415 return 0;
3416
3417 button_state &= ~this;
3418
3419 if (button_state & MMOUSE)
3420 {
3421 /* Only generate event when second button is released. */
3422 if ((button_state & other) == 0)
3423 {
3424 msg = WM_MBUTTONUP;
3425 button_state &= ~MMOUSE;
3426
3427 if (button_state) abort ();
3428 }
3429 else
3430 return 0;
3431 }
3432 else
3433 {
3434 /* Flush out saved message if necessary. */
3435 if (saved_mouse_button_msg.msg.hwnd)
3436 {
3437 post_msg (&saved_mouse_button_msg);
3438 }
3439 }
3440 wmsg.dwModifiers = w32_get_modifiers ();
3441 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3442
3443 /* Always clear message buffer and cancel timer. */
3444 saved_mouse_button_msg.msg.hwnd = 0;
3445 KillTimer (hwnd, mouse_button_timer);
3446 mouse_button_timer = 0;
3447
3448 if (button_state == 0)
3449 ReleaseCapture ();
3450 }
3451 return 0;
3452
3453 case WM_XBUTTONDOWN:
3454 case WM_XBUTTONUP:
3455 if (w32_pass_extra_mouse_buttons_to_system)
3456 goto dflt;
3457 /* else fall through and process them. */
3458 case WM_MBUTTONDOWN:
3459 case WM_MBUTTONUP:
3460 handle_plain_button:
3461 {
3462 BOOL up;
3463 int button;
3464
3465 if (parse_button (msg, HIWORD (wParam), &button, &up))
3466 {
3467 if (up) ReleaseCapture ();
3468 else SetCapture (hwnd);
3469 button = (button == 0) ? LMOUSE :
3470 ((button == 1) ? MMOUSE : RMOUSE);
3471 if (up)
3472 button_state &= ~button;
3473 else
3474 button_state |= button;
3475 }
3476 }
3477
3478 wmsg.dwModifiers = w32_get_modifiers ();
3479 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3480
3481 /* Need to return true for XBUTTON messages, false for others,
3482 to indicate that we processed the message. */
3483 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3484
3485 case WM_MOUSEMOVE:
3486 /* If the mouse has just moved into the frame, start tracking
3487 it, so we will be notified when it leaves the frame. Mouse
3488 tracking only works under W98 and NT4 and later. On earlier
3489 versions, there is no way of telling when the mouse leaves the
3490 frame, so we just have to put up with help-echo and mouse
3491 highlighting remaining while the frame is not active. */
3492 if (track_mouse_event_fn && !track_mouse_window)
3493 {
3494 TRACKMOUSEEVENT tme;
3495 tme.cbSize = sizeof (tme);
3496 tme.dwFlags = TME_LEAVE;
3497 tme.hwndTrack = hwnd;
3498
3499 track_mouse_event_fn (&tme);
3500 track_mouse_window = hwnd;
3501 }
3502 case WM_VSCROLL:
3503 if (XINT (Vw32_mouse_move_interval) <= 0
3504 || (msg == WM_MOUSEMOVE && button_state == 0))
3505 {
3506 wmsg.dwModifiers = w32_get_modifiers ();
3507 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3508 return 0;
3509 }
3510
3511 /* Hang onto mouse move and scroll messages for a bit, to avoid
3512 sending such events to Emacs faster than it can process them.
3513 If we get more events before the timer from the first message
3514 expires, we just replace the first message. */
3515
3516 if (saved_mouse_move_msg.msg.hwnd == 0)
3517 mouse_move_timer =
3518 SetTimer (hwnd, MOUSE_MOVE_ID,
3519 XINT (Vw32_mouse_move_interval), NULL);
3520
3521 /* Hold onto message for now. */
3522 saved_mouse_move_msg.msg.hwnd = hwnd;
3523 saved_mouse_move_msg.msg.message = msg;
3524 saved_mouse_move_msg.msg.wParam = wParam;
3525 saved_mouse_move_msg.msg.lParam = lParam;
3526 saved_mouse_move_msg.msg.time = GetMessageTime ();
3527 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3528
3529 return 0;
3530
3531 case WM_MOUSEWHEEL:
3532 wmsg.dwModifiers = w32_get_modifiers ();
3533 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3534 return 0;
3535
3536 case WM_DROPFILES:
3537 wmsg.dwModifiers = w32_get_modifiers ();
3538 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3539 return 0;
3540
3541 case WM_TIMER:
3542 /* Flush out saved messages if necessary. */
3543 if (wParam == mouse_button_timer)
3544 {
3545 if (saved_mouse_button_msg.msg.hwnd)
3546 {
3547 post_msg (&saved_mouse_button_msg);
3548 saved_mouse_button_msg.msg.hwnd = 0;
3549 }
3550 KillTimer (hwnd, mouse_button_timer);
3551 mouse_button_timer = 0;
3552 }
3553 else if (wParam == mouse_move_timer)
3554 {
3555 if (saved_mouse_move_msg.msg.hwnd)
3556 {
3557 post_msg (&saved_mouse_move_msg);
3558 saved_mouse_move_msg.msg.hwnd = 0;
3559 }
3560 KillTimer (hwnd, mouse_move_timer);
3561 mouse_move_timer = 0;
3562 }
3563 else if (wParam == menu_free_timer)
3564 {
3565 KillTimer (hwnd, menu_free_timer);
3566 menu_free_timer = 0;
3567 f = x_window_to_frame (dpyinfo, hwnd);
3568 if (!f->output_data.w32->menu_command_in_progress)
3569 {
3570 /* Free memory used by owner-drawn and help-echo strings. */
3571 w32_free_menu_strings (hwnd);
3572 f->output_data.w32->menubar_active = 0;
3573 }
3574 }
3575 return 0;
3576
3577 case WM_NCACTIVATE:
3578 /* Windows doesn't send us focus messages when putting up and
3579 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3580 The only indication we get that something happened is receiving
3581 this message afterwards. So this is a good time to reset our
3582 keyboard modifiers' state. */
3583 reset_modifiers ();
3584 goto dflt;
3585
3586 case WM_INITMENU:
3587 button_state = 0;
3588 ReleaseCapture ();
3589 /* We must ensure menu bar is fully constructed and up to date
3590 before allowing user interaction with it. To achieve this
3591 we send this message to the lisp thread and wait for a
3592 reply (whose value is not actually needed) to indicate that
3593 the menu bar is now ready for use, so we can now return.
3594
3595 To remain responsive in the meantime, we enter a nested message
3596 loop that can process all other messages.
3597
3598 However, we skip all this if the message results from calling
3599 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3600 thread a message because it is blocked on us at this point. We
3601 set menubar_active before calling TrackPopupMenu to indicate
3602 this (there is no possibility of confusion with real menubar
3603 being active). */
3604
3605 f = x_window_to_frame (dpyinfo, hwnd);
3606 if (f
3607 && (f->output_data.w32->menubar_active
3608 /* We can receive this message even in the absence of a
3609 menubar (ie. when the system menu is activated) - in this
3610 case we do NOT want to forward the message, otherwise it
3611 will cause the menubar to suddenly appear when the user
3612 had requested it to be turned off! */
3613 || f->output_data.w32->menubar_widget == NULL))
3614 return 0;
3615
3616 {
3617 deferred_msg msg_buf;
3618
3619 /* Detect if message has already been deferred; in this case
3620 we cannot return any sensible value to ignore this. */
3621 if (find_deferred_msg (hwnd, msg) != NULL)
3622 abort ();
3623
3624 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3625 }
3626
3627 case WM_EXITMENULOOP:
3628 f = x_window_to_frame (dpyinfo, hwnd);
3629
3630 /* If a menu command is not already in progress, check again
3631 after a short delay, since Windows often (always?) sends the
3632 WM_EXITMENULOOP before the corresponding WM_COMMAND message. */
3633 if (f && !f->output_data.w32->menu_command_in_progress)
3634 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3635 goto dflt;
3636
3637 case WM_MENUSELECT:
3638 /* Direct handling of help_echo in menus. Should be safe now
3639 that we generate the help_echo by placing a help event in the
3640 keyboard buffer. */
3641 {
3642 HMENU menu = (HMENU) lParam;
3643 UINT menu_item = (UINT) LOWORD (wParam);
3644 UINT flags = (UINT) HIWORD (wParam);
3645
3646 w32_menu_display_help (hwnd, menu, menu_item, flags);
3647 }
3648 return 0;
3649
3650 case WM_MEASUREITEM:
3651 f = x_window_to_frame (dpyinfo, hwnd);
3652 if (f)
3653 {
3654 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3655
3656 if (pMis->CtlType == ODT_MENU)
3657 {
3658 /* Work out dimensions for popup menu titles. */
3659 char * title = (char *) pMis->itemData;
3660 HDC hdc = GetDC (hwnd);
3661 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3662 LOGFONT menu_logfont;
3663 HFONT old_font;
3664 SIZE size;
3665
3666 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3667 menu_logfont.lfWeight = FW_BOLD;
3668 menu_font = CreateFontIndirect (&menu_logfont);
3669 old_font = SelectObject (hdc, menu_font);
3670
3671 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3672 if (title)
3673 {
3674 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3675 pMis->itemWidth = size.cx;
3676 if (pMis->itemHeight < size.cy)
3677 pMis->itemHeight = size.cy;
3678 }
3679 else
3680 pMis->itemWidth = 0;
3681
3682 SelectObject (hdc, old_font);
3683 DeleteObject (menu_font);
3684 ReleaseDC (hwnd, hdc);
3685 return TRUE;
3686 }
3687 }
3688 return 0;
3689
3690 case WM_DRAWITEM:
3691 f = x_window_to_frame (dpyinfo, hwnd);
3692 if (f)
3693 {
3694 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3695
3696 if (pDis->CtlType == ODT_MENU)
3697 {
3698 /* Draw popup menu title. */
3699 char * title = (char *) pDis->itemData;
3700 if (title)
3701 {
3702 HDC hdc = pDis->hDC;
3703 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3704 LOGFONT menu_logfont;
3705 HFONT old_font;
3706
3707 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3708 menu_logfont.lfWeight = FW_BOLD;
3709 menu_font = CreateFontIndirect (&menu_logfont);
3710 old_font = SelectObject (hdc, menu_font);
3711
3712 /* Always draw title as if not selected. */
3713 ExtTextOut (hdc,
3714 pDis->rcItem.left
3715 + GetSystemMetrics (SM_CXMENUCHECK),
3716 pDis->rcItem.top,
3717 ETO_OPAQUE, &pDis->rcItem,
3718 title, strlen (title), NULL);
3719
3720 SelectObject (hdc, old_font);
3721 DeleteObject (menu_font);
3722 }
3723 return TRUE;
3724 }
3725 }
3726 return 0;
3727
3728 #if 0
3729 /* Still not right - can't distinguish between clicks in the
3730 client area of the frame from clicks forwarded from the scroll
3731 bars - may have to hook WM_NCHITTEST to remember the mouse
3732 position and then check if it is in the client area ourselves. */
3733 case WM_MOUSEACTIVATE:
3734 /* Discard the mouse click that activates a frame, allowing the
3735 user to click anywhere without changing point (or worse!).
3736 Don't eat mouse clicks on scrollbars though!! */
3737 if (LOWORD (lParam) == HTCLIENT )
3738 return MA_ACTIVATEANDEAT;
3739 goto dflt;
3740 #endif
3741
3742 case WM_MOUSELEAVE:
3743 /* No longer tracking mouse. */
3744 track_mouse_window = NULL;
3745
3746 case WM_ACTIVATEAPP:
3747 case WM_ACTIVATE:
3748 case WM_WINDOWPOSCHANGED:
3749 case WM_SHOWWINDOW:
3750 /* Inform lisp thread that a frame might have just been obscured
3751 or exposed, so should recheck visibility of all frames. */
3752 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3753 goto dflt;
3754
3755 case WM_SETFOCUS:
3756 dpyinfo->faked_key = 0;
3757 reset_modifiers ();
3758 register_hot_keys (hwnd);
3759 goto command;
3760 case WM_KILLFOCUS:
3761 unregister_hot_keys (hwnd);
3762 button_state = 0;
3763 ReleaseCapture ();
3764 /* Relinquish the system caret. */
3765 if (w32_system_caret_hwnd)
3766 {
3767 w32_visible_system_caret_hwnd = NULL;
3768 w32_system_caret_hwnd = NULL;
3769 DestroyCaret ();
3770 }
3771 goto command;
3772 case WM_COMMAND:
3773 f = x_window_to_frame (dpyinfo, hwnd);
3774 if (f && HIWORD (wParam) == 0)
3775 {
3776 f->output_data.w32->menu_command_in_progress = 1;
3777 if (menu_free_timer)
3778 {
3779 KillTimer (hwnd, menu_free_timer);
3780 menu_free_timer = 0;
3781 }
3782 }
3783 case WM_MOVE:
3784 case WM_SIZE:
3785 command:
3786 wmsg.dwModifiers = w32_get_modifiers ();
3787 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3788 goto dflt;
3789
3790 case WM_CLOSE:
3791 wmsg.dwModifiers = w32_get_modifiers ();
3792 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3793 return 0;
3794
3795 case WM_WINDOWPOSCHANGING:
3796 /* Don't restrict the sizing of tip frames. */
3797 if (hwnd == tip_window)
3798 return 0;
3799 {
3800 WINDOWPLACEMENT wp;
3801 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3802
3803 wp.length = sizeof (WINDOWPLACEMENT);
3804 GetWindowPlacement (hwnd, &wp);
3805
3806 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
3807 {
3808 RECT rect;
3809 int wdiff;
3810 int hdiff;
3811 DWORD font_width;
3812 DWORD line_height;
3813 DWORD internal_border;
3814 DWORD scrollbar_extra;
3815 RECT wr;
3816
3817 wp.length = sizeof(wp);
3818 GetWindowRect (hwnd, &wr);
3819
3820 enter_crit ();
3821
3822 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3823 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3824 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3825 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3826
3827 leave_crit ();
3828
3829 memset (&rect, 0, sizeof (rect));
3830 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3831 GetMenu (hwnd) != NULL);
3832
3833 /* Force width and height of client area to be exact
3834 multiples of the character cell dimensions. */
3835 wdiff = (lppos->cx - (rect.right - rect.left)
3836 - 2 * internal_border - scrollbar_extra)
3837 % font_width;
3838 hdiff = (lppos->cy - (rect.bottom - rect.top)
3839 - 2 * internal_border)
3840 % line_height;
3841
3842 if (wdiff || hdiff)
3843 {
3844 /* For right/bottom sizing we can just fix the sizes.
3845 However for top/left sizing we will need to fix the X
3846 and Y positions as well. */
3847
3848 lppos->cx -= wdiff;
3849 lppos->cy -= hdiff;
3850
3851 if (wp.showCmd != SW_SHOWMAXIMIZED
3852 && (lppos->flags & SWP_NOMOVE) == 0)
3853 {
3854 if (lppos->x != wr.left || lppos->y != wr.top)
3855 {
3856 lppos->x += wdiff;
3857 lppos->y += hdiff;
3858 }
3859 else
3860 {
3861 lppos->flags |= SWP_NOMOVE;
3862 }
3863 }
3864
3865 return 0;
3866 }
3867 }
3868 }
3869
3870 goto dflt;
3871
3872 case WM_GETMINMAXINFO:
3873 /* Hack to correct bug that allows Emacs frames to be resized
3874 below the Minimum Tracking Size. */
3875 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
3876 /* Hack to allow resizing the Emacs frame above the screen size.
3877 Note that Windows 9x limits coordinates to 16-bits. */
3878 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3879 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3880 return 0;
3881
3882 case WM_SETCURSOR:
3883 if (LOWORD (lParam) == HTCLIENT)
3884 return 0;
3885
3886 goto dflt;
3887
3888 case WM_EMACS_SETCURSOR:
3889 {
3890 Cursor cursor = (Cursor) wParam;
3891 if (cursor)
3892 SetCursor (cursor);
3893 return 0;
3894 }
3895
3896 case WM_EMACS_CREATESCROLLBAR:
3897 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3898 (struct scroll_bar *) lParam);
3899
3900 case WM_EMACS_SHOWWINDOW:
3901 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3902
3903 case WM_EMACS_SETFOREGROUND:
3904 {
3905 HWND foreground_window;
3906 DWORD foreground_thread, retval;
3907
3908 /* On NT 5.0, and apparently Windows 98, it is necessary to
3909 attach to the thread that currently has focus in order to
3910 pull the focus away from it. */
3911 foreground_window = GetForegroundWindow ();
3912 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3913 if (!foreground_window
3914 || foreground_thread == GetCurrentThreadId ()
3915 || !AttachThreadInput (GetCurrentThreadId (),
3916 foreground_thread, TRUE))
3917 foreground_thread = 0;
3918
3919 retval = SetForegroundWindow ((HWND) wParam);
3920
3921 /* Detach from the previous foreground thread. */
3922 if (foreground_thread)
3923 AttachThreadInput (GetCurrentThreadId (),
3924 foreground_thread, FALSE);
3925
3926 return retval;
3927 }
3928
3929 case WM_EMACS_SETWINDOWPOS:
3930 {
3931 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3932 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3933 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3934 }
3935
3936 case WM_EMACS_DESTROYWINDOW:
3937 DragAcceptFiles ((HWND) wParam, FALSE);
3938 return DestroyWindow ((HWND) wParam);
3939
3940 case WM_EMACS_HIDE_CARET:
3941 return HideCaret (hwnd);
3942
3943 case WM_EMACS_SHOW_CARET:
3944 return ShowCaret (hwnd);
3945
3946 case WM_EMACS_DESTROY_CARET:
3947 w32_system_caret_hwnd = NULL;
3948 w32_visible_system_caret_hwnd = NULL;
3949 return DestroyCaret ();
3950
3951 case WM_EMACS_TRACK_CARET:
3952 /* If there is currently no system caret, create one. */
3953 if (w32_system_caret_hwnd == NULL)
3954 {
3955 /* Use the default caret width, and avoid changing it
3956 unneccesarily, as it confuses screen reader software. */
3957 w32_system_caret_hwnd = hwnd;
3958 CreateCaret (hwnd, NULL, 0,
3959 w32_system_caret_height);
3960 }
3961
3962 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3963 return 0;
3964 /* Ensure visible caret gets turned on when requested. */
3965 else if (w32_use_visible_system_caret
3966 && w32_visible_system_caret_hwnd != hwnd)
3967 {
3968 w32_visible_system_caret_hwnd = hwnd;
3969 return ShowCaret (hwnd);
3970 }
3971 /* Ensure visible caret gets turned off when requested. */
3972 else if (!w32_use_visible_system_caret
3973 && w32_visible_system_caret_hwnd)
3974 {
3975 w32_visible_system_caret_hwnd = NULL;
3976 return HideCaret (hwnd);
3977 }
3978 else
3979 return 1;
3980
3981 case WM_EMACS_TRACKPOPUPMENU:
3982 {
3983 UINT flags;
3984 POINT *pos;
3985 int retval;
3986 pos = (POINT *)lParam;
3987 flags = TPM_CENTERALIGN;
3988 if (button_state & LMOUSE)
3989 flags |= TPM_LEFTBUTTON;
3990 else if (button_state & RMOUSE)
3991 flags |= TPM_RIGHTBUTTON;
3992
3993 /* Remember we did a SetCapture on the initial mouse down event,
3994 so for safety, we make sure the capture is cancelled now. */
3995 ReleaseCapture ();
3996 button_state = 0;
3997
3998 /* Use menubar_active to indicate that WM_INITMENU is from
3999 TrackPopupMenu below, and should be ignored. */
4000 f = x_window_to_frame (dpyinfo, hwnd);
4001 if (f)
4002 f->output_data.w32->menubar_active = 1;
4003
4004 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4005 0, hwnd, NULL))
4006 {
4007 MSG amsg;
4008 /* Eat any mouse messages during popupmenu */
4009 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4010 PM_REMOVE));
4011 /* Get the menu selection, if any */
4012 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4013 {
4014 retval = LOWORD (amsg.wParam);
4015 }
4016 else
4017 {
4018 retval = 0;
4019 }
4020 }
4021 else
4022 {
4023 retval = -1;
4024 }
4025
4026 return retval;
4027 }
4028
4029 default:
4030 /* Check for messages registered at runtime. */
4031 if (msg == msh_mousewheel)
4032 {
4033 wmsg.dwModifiers = w32_get_modifiers ();
4034 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4035 return 0;
4036 }
4037
4038 dflt:
4039 return DefWindowProc (hwnd, msg, wParam, lParam);
4040 }
4041
4042
4043 /* The most common default return code for handled messages is 0. */
4044 return 0;
4045 }
4046
4047 void
4048 my_create_window (f)
4049 struct frame * f;
4050 {
4051 MSG msg;
4052
4053 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4054 abort ();
4055 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4056 }
4057
4058
4059 /* Create a tooltip window. Unlike my_create_window, we do not do this
4060 indirectly via the Window thread, as we do not need to process Window
4061 messages for the tooltip. Creating tooltips indirectly also creates
4062 deadlocks when tooltips are created for menu items. */
4063 void
4064 my_create_tip_window (f)
4065 struct frame *f;
4066 {
4067 RECT rect;
4068
4069 rect.left = rect.top = 0;
4070 rect.right = FRAME_PIXEL_WIDTH (f);
4071 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4072
4073 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4074 FRAME_EXTERNAL_MENU_BAR (f));
4075
4076 tip_window = FRAME_W32_WINDOW (f)
4077 = CreateWindow (EMACS_CLASS,
4078 f->namebuf,
4079 f->output_data.w32->dwStyle,
4080 f->left_pos,
4081 f->top_pos,
4082 rect.right - rect.left,
4083 rect.bottom - rect.top,
4084 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4085 NULL,
4086 hinst,
4087 NULL);
4088
4089 if (tip_window)
4090 {
4091 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4092 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4093 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4094 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4095
4096 /* Tip frames have no scrollbars. */
4097 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
4098
4099 /* Do this to discard the default setting specified by our parent. */
4100 ShowWindow (tip_window, SW_HIDE);
4101 }
4102 }
4103
4104
4105 /* Create and set up the w32 window for frame F. */
4106
4107 static void
4108 w32_window (f, window_prompting, minibuffer_only)
4109 struct frame *f;
4110 long window_prompting;
4111 int minibuffer_only;
4112 {
4113 BLOCK_INPUT;
4114
4115 /* Use the resource name as the top-level window name
4116 for looking up resources. Make a non-Lisp copy
4117 for the window manager, so GC relocation won't bother it.
4118
4119 Elsewhere we specify the window name for the window manager. */
4120
4121 {
4122 char *str = (char *) SDATA (Vx_resource_name);
4123 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4124 strcpy (f->namebuf, str);
4125 }
4126
4127 my_create_window (f);
4128
4129 validate_x_resource_name ();
4130
4131 /* x_set_name normally ignores requests to set the name if the
4132 requested name is the same as the current name. This is the one
4133 place where that assumption isn't correct; f->name is set, but
4134 the server hasn't been told. */
4135 {
4136 Lisp_Object name;
4137 int explicit = f->explicit_name;
4138
4139 f->explicit_name = 0;
4140 name = f->name;
4141 f->name = Qnil;
4142 x_set_name (f, name, explicit);
4143 }
4144
4145 UNBLOCK_INPUT;
4146
4147 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4148 initialize_frame_menubar (f);
4149
4150 if (FRAME_W32_WINDOW (f) == 0)
4151 error ("Unable to create window");
4152 }
4153
4154 /* Handle the icon stuff for this window. Perhaps later we might
4155 want an x_set_icon_position which can be called interactively as
4156 well. */
4157
4158 static void
4159 x_icon (f, parms)
4160 struct frame *f;
4161 Lisp_Object parms;
4162 {
4163 Lisp_Object icon_x, icon_y;
4164
4165 /* Set the position of the icon. Note that Windows 95 groups all
4166 icons in the tray. */
4167 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4168 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4169 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4170 {
4171 CHECK_NUMBER (icon_x);
4172 CHECK_NUMBER (icon_y);
4173 }
4174 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4175 error ("Both left and top icon corners of icon must be specified");
4176
4177 BLOCK_INPUT;
4178
4179 if (! EQ (icon_x, Qunbound))
4180 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4181
4182 #if 0 /* TODO */
4183 /* Start up iconic or window? */
4184 x_wm_set_window_state
4185 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4186 ? IconicState
4187 : NormalState));
4188
4189 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
4190 ? f->icon_name
4191 : f->name)));
4192 #endif
4193
4194 UNBLOCK_INPUT;
4195 }
4196
4197
4198 static void
4199 x_make_gc (f)
4200 struct frame *f;
4201 {
4202 XGCValues gc_values;
4203
4204 BLOCK_INPUT;
4205
4206 /* Create the GC's of this frame.
4207 Note that many default values are used. */
4208
4209 /* Normal video */
4210 gc_values.font = FRAME_FONT (f);
4211
4212 /* Cursor has cursor-color background, background-color foreground. */
4213 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4214 gc_values.background = f->output_data.w32->cursor_pixel;
4215 f->output_data.w32->cursor_gc
4216 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4217 (GCFont | GCForeground | GCBackground),
4218 &gc_values);
4219
4220 /* Reliefs. */
4221 f->output_data.w32->white_relief.gc = 0;
4222 f->output_data.w32->black_relief.gc = 0;
4223
4224 UNBLOCK_INPUT;
4225 }
4226
4227
4228 /* Handler for signals raised during x_create_frame and
4229 x_create_top_frame. FRAME is the frame which is partially
4230 constructed. */
4231
4232 static Lisp_Object
4233 unwind_create_frame (frame)
4234 Lisp_Object frame;
4235 {
4236 struct frame *f = XFRAME (frame);
4237
4238 /* If frame is ``official'', nothing to do. */
4239 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
4240 {
4241 #ifdef GLYPH_DEBUG
4242 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4243 #endif
4244
4245 x_free_frame_resources (f);
4246
4247 /* Check that reference counts are indeed correct. */
4248 xassert (dpyinfo->reference_count == dpyinfo_refcount);
4249 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
4250
4251 return Qt;
4252 }
4253
4254 return Qnil;
4255 }
4256
4257
4258 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4259 1, 1, 0,
4260 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4261 Returns an Emacs frame object.
4262 ALIST is an alist of frame parameters.
4263 If the parameters specify that the frame should not have a minibuffer,
4264 and do not specify a specific minibuffer window to use,
4265 then `default-minibuffer-frame' must be a frame whose minibuffer can
4266 be shared by the new frame.
4267
4268 This function is an internal primitive--use `make-frame' instead. */)
4269 (parms)
4270 Lisp_Object parms;
4271 {
4272 struct frame *f;
4273 Lisp_Object frame, tem;
4274 Lisp_Object name;
4275 int minibuffer_only = 0;
4276 long window_prompting = 0;
4277 int width, height;
4278 int count = SPECPDL_INDEX ();
4279 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4280 Lisp_Object display;
4281 struct w32_display_info *dpyinfo = NULL;
4282 Lisp_Object parent;
4283 struct kboard *kb;
4284
4285 check_w32 ();
4286
4287 /* Use this general default value to start with
4288 until we know if this frame has a specified name. */
4289 Vx_resource_name = Vinvocation_name;
4290
4291 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
4292 if (EQ (display, Qunbound))
4293 display = Qnil;
4294 dpyinfo = check_x_display_info (display);
4295 #ifdef MULTI_KBOARD
4296 kb = dpyinfo->kboard;
4297 #else
4298 kb = &the_only_kboard;
4299 #endif
4300
4301 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
4302 if (!STRINGP (name)
4303 && ! EQ (name, Qunbound)
4304 && ! NILP (name))
4305 error ("Invalid frame name--not a string or nil");
4306
4307 if (STRINGP (name))
4308 Vx_resource_name = name;
4309
4310 /* See if parent window is specified. */
4311 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4312 if (EQ (parent, Qunbound))
4313 parent = Qnil;
4314 if (! NILP (parent))
4315 CHECK_NUMBER (parent);
4316
4317 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4318 /* No need to protect DISPLAY because that's not used after passing
4319 it to make_frame_without_minibuffer. */
4320 frame = Qnil;
4321 GCPRO4 (parms, parent, name, frame);
4322 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
4323 RES_TYPE_SYMBOL);
4324 if (EQ (tem, Qnone) || NILP (tem))
4325 f = make_frame_without_minibuffer (Qnil, kb, display);
4326 else if (EQ (tem, Qonly))
4327 {
4328 f = make_minibuffer_frame ();
4329 minibuffer_only = 1;
4330 }
4331 else if (WINDOWP (tem))
4332 f = make_frame_without_minibuffer (tem, kb, display);
4333 else
4334 f = make_frame (1);
4335
4336 XSETFRAME (frame, f);
4337
4338 /* Note that Windows does support scroll bars. */
4339 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
4340
4341 /* By default, make scrollbars the system standard width. */
4342 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4343
4344 f->output_method = output_w32;
4345 f->output_data.w32 =
4346 (struct w32_output *) xmalloc (sizeof (struct w32_output));
4347 bzero (f->output_data.w32, sizeof (struct w32_output));
4348 FRAME_FONTSET (f) = -1;
4349 record_unwind_protect (unwind_create_frame, frame);
4350
4351 f->icon_name
4352 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
4353 if (! STRINGP (f->icon_name))
4354 f->icon_name = Qnil;
4355
4356 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
4357 #ifdef MULTI_KBOARD
4358 FRAME_KBOARD (f) = kb;
4359 #endif
4360
4361 /* Specify the parent under which to make this window. */
4362
4363 if (!NILP (parent))
4364 {
4365 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4366 f->output_data.w32->explicit_parent = 1;
4367 }
4368 else
4369 {
4370 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4371 f->output_data.w32->explicit_parent = 0;
4372 }
4373
4374 /* Set the name; the functions to which we pass f expect the name to
4375 be set. */
4376 if (EQ (name, Qunbound) || NILP (name))
4377 {
4378 f->name = build_string (dpyinfo->w32_id_name);
4379 f->explicit_name = 0;
4380 }
4381 else
4382 {
4383 f->name = name;
4384 f->explicit_name = 1;
4385 /* use the frame's title when getting resources for this frame. */
4386 specbind (Qx_resource_name, name);
4387 }
4388
4389 /* Extract the window parameters from the supplied values
4390 that are needed to determine window geometry. */
4391 {
4392 Lisp_Object font;
4393
4394 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
4395
4396 BLOCK_INPUT;
4397 /* First, try whatever font the caller has specified. */
4398 if (STRINGP (font))
4399 {
4400 tem = Fquery_fontset (font, Qnil);
4401 if (STRINGP (tem))
4402 font = x_new_fontset (f, SDATA (tem));
4403 else
4404 font = x_new_font (f, SDATA (font));
4405 }
4406 /* Try out a font which we hope has bold and italic variations. */
4407 if (!STRINGP (font))
4408 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
4409 if (! STRINGP (font))
4410 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
4411 /* If those didn't work, look for something which will at least work. */
4412 if (! STRINGP (font))
4413 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
4414 UNBLOCK_INPUT;
4415 if (! STRINGP (font))
4416 font = build_string ("Fixedsys");
4417
4418 x_default_parameter (f, parms, Qfont, font,
4419 "font", "Font", RES_TYPE_STRING);
4420 }
4421
4422 x_default_parameter (f, parms, Qborder_width, make_number (2),
4423 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4424 /* This defaults to 2 in order to match xterm. We recognize either
4425 internalBorderWidth or internalBorder (which is what xterm calls
4426 it). */
4427 if (NILP (Fassq (Qinternal_border_width, parms)))
4428 {
4429 Lisp_Object value;
4430
4431 value = w32_get_arg (parms, Qinternal_border_width,
4432 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4433 if (! EQ (value, Qunbound))
4434 parms = Fcons (Fcons (Qinternal_border_width, value),
4435 parms);
4436 }
4437 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4438 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
4439 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4440 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
4441 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4442
4443 /* Also do the stuff which must be set before the window exists. */
4444 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
4445 "foreground", "Foreground", RES_TYPE_STRING);
4446 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
4447 "background", "Background", RES_TYPE_STRING);
4448 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
4449 "pointerColor", "Foreground", RES_TYPE_STRING);
4450 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
4451 "cursorColor", "Foreground", RES_TYPE_STRING);
4452 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
4453 "borderColor", "BorderColor", RES_TYPE_STRING);
4454 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
4455 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4456 x_default_parameter (f, parms, Qline_spacing, Qnil,
4457 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4458 x_default_parameter (f, parms, Qleft_fringe, Qnil,
4459 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4460 x_default_parameter (f, parms, Qright_fringe, Qnil,
4461 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4462
4463
4464 /* Init faces before x_default_parameter is called for scroll-bar
4465 parameters because that function calls x_set_scroll_bar_width,
4466 which calls change_frame_size, which calls Fset_window_buffer,
4467 which runs hooks, which call Fvertical_motion. At the end, we
4468 end up in init_iterator with a null face cache, which should not
4469 happen. */
4470 init_frame_faces (f);
4471
4472 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
4473 "menuBar", "MenuBar", RES_TYPE_NUMBER);
4474 x_default_parameter (f, parms, Qtool_bar_lines, make_number (1),
4475 "toolBar", "ToolBar", RES_TYPE_NUMBER);
4476
4477 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
4478 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4479 x_default_parameter (f, parms, Qtitle, Qnil,
4480 "title", "Title", RES_TYPE_STRING);
4481 x_default_parameter (f, parms, Qfullscreen, Qnil,
4482 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4483
4484 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4485 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4486
4487 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4488 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4489 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4490 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4491 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4492 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4493
4494 window_prompting = x_figure_window_size (f, parms, 1);
4495
4496 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4497 f->no_split = minibuffer_only || EQ (tem, Qt);
4498
4499 w32_window (f, window_prompting, minibuffer_only);
4500 x_icon (f, parms);
4501
4502 x_make_gc (f);
4503
4504 /* Now consider the frame official. */
4505 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
4506 Vframe_list = Fcons (frame, Vframe_list);
4507
4508 /* We need to do this after creating the window, so that the
4509 icon-creation functions can say whose icon they're describing. */
4510 x_default_parameter (f, parms, Qicon_type, Qnil,
4511 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4512
4513 x_default_parameter (f, parms, Qauto_raise, Qnil,
4514 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4515 x_default_parameter (f, parms, Qauto_lower, Qnil,
4516 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4517 x_default_parameter (f, parms, Qcursor_type, Qbox,
4518 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4519 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
4520 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4521
4522 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4523 Change will not be effected unless different from the current
4524 FRAME_LINES (f). */
4525 width = FRAME_COLS (f);
4526 height = FRAME_LINES (f);
4527
4528 FRAME_LINES (f) = 0;
4529 SET_FRAME_COLS (f, 0);
4530 change_frame_size (f, height, width, 1, 0, 0);
4531
4532 /* Tell the server what size and position, etc, we want, and how
4533 badly we want them. This should be done after we have the menu
4534 bar so that its size can be taken into account. */
4535 BLOCK_INPUT;
4536 x_wm_set_size_hint (f, window_prompting, 0);
4537 UNBLOCK_INPUT;
4538
4539 /* Avoid a bug that causes the new frame to never become visible if
4540 an echo area message is displayed during the following call1. */
4541 specbind(Qredisplay_dont_pause, Qt);
4542
4543 /* Set up faces after all frame parameters are known. This call
4544 also merges in face attributes specified for new frames. If we
4545 don't do this, the `menu' face for instance won't have the right
4546 colors, and the menu bar won't appear in the specified colors for
4547 new frames. */
4548 call1 (Qface_set_after_frame_default, frame);
4549
4550 /* Make the window appear on the frame and enable display, unless
4551 the caller says not to. However, with explicit parent, Emacs
4552 cannot control visibility, so don't try. */
4553 if (! f->output_data.w32->explicit_parent)
4554 {
4555 Lisp_Object visibility;
4556
4557 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4558 if (EQ (visibility, Qunbound))
4559 visibility = Qt;
4560
4561 if (EQ (visibility, Qicon))
4562 x_iconify_frame (f);
4563 else if (! NILP (visibility))
4564 x_make_frame_visible (f);
4565 else
4566 /* Must have been Qnil. */
4567 ;
4568 }
4569 UNGCPRO;
4570
4571 /* Make sure windows on this frame appear in calls to next-window
4572 and similar functions. */
4573 Vwindow_list = Qnil;
4574
4575 return unbind_to (count, frame);
4576 }
4577
4578 /* FRAME is used only to get a handle on the X display. We don't pass the
4579 display info directly because we're called from frame.c, which doesn't
4580 know about that structure. */
4581 Lisp_Object
4582 x_get_focus_frame (frame)
4583 struct frame *frame;
4584 {
4585 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
4586 Lisp_Object xfocus;
4587 if (! dpyinfo->w32_focus_frame)
4588 return Qnil;
4589
4590 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4591 return xfocus;
4592 }
4593
4594 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
4595 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
4596 (frame)
4597 Lisp_Object frame;
4598 {
4599 x_focus_on_frame (check_x_frame (frame));
4600 return Qnil;
4601 }
4602
4603 \f
4604 /* Return the charset portion of a font name. */
4605 char * xlfd_charset_of_font (char * fontname)
4606 {
4607 char *charset, *encoding;
4608
4609 encoding = strrchr(fontname, '-');
4610 if (!encoding || encoding == fontname)
4611 return NULL;
4612
4613 for (charset = encoding - 1; charset >= fontname; charset--)
4614 if (*charset == '-')
4615 break;
4616
4617 if (charset == fontname || strcmp(charset, "-*-*") == 0)
4618 return NULL;
4619
4620 return charset + 1;
4621 }
4622
4623 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
4624 int size, char* filename);
4625 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
4626 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
4627 char * charset);
4628 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
4629
4630 static struct font_info *
4631 w32_load_system_font (f,fontname,size)
4632 struct frame *f;
4633 char * fontname;
4634 int size;
4635 {
4636 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4637 Lisp_Object font_names;
4638
4639 /* Get a list of all the fonts that match this name. Once we
4640 have a list of matching fonts, we compare them against the fonts
4641 we already have loaded by comparing names. */
4642 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
4643
4644 if (!NILP (font_names))
4645 {
4646 Lisp_Object tail;
4647 int i;
4648
4649 /* First check if any are already loaded, as that is cheaper
4650 than loading another one. */
4651 for (i = 0; i < dpyinfo->n_fonts; i++)
4652 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
4653 if (dpyinfo->font_table[i].name
4654 && (!strcmp (dpyinfo->font_table[i].name,
4655 SDATA (XCAR (tail)))
4656 || !strcmp (dpyinfo->font_table[i].full_name,
4657 SDATA (XCAR (tail)))))
4658 return (dpyinfo->font_table + i);
4659
4660 fontname = (char *) SDATA (XCAR (font_names));
4661 }
4662 else if (w32_strict_fontnames)
4663 {
4664 /* If EnumFontFamiliesEx was available, we got a full list of
4665 fonts back so stop now to avoid the possibility of loading a
4666 random font. If we had to fall back to EnumFontFamilies, the
4667 list is incomplete, so continue whether the font we want was
4668 listed or not. */
4669 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
4670 FARPROC enum_font_families_ex
4671 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
4672 if (enum_font_families_ex)
4673 return NULL;
4674 }
4675
4676 /* Load the font and add it to the table. */
4677 {
4678 char *full_name, *encoding, *charset;
4679 XFontStruct *font;
4680 struct font_info *fontp;
4681 LOGFONT lf;
4682 BOOL ok;
4683 int codepage;
4684 int i;
4685
4686 if (!fontname || !x_to_w32_font (fontname, &lf))
4687 return (NULL);
4688
4689 if (!*lf.lfFaceName)
4690 /* If no name was specified for the font, we get a random font
4691 from CreateFontIndirect - this is not particularly
4692 desirable, especially since CreateFontIndirect does not
4693 fill out the missing name in lf, so we never know what we
4694 ended up with. */
4695 return NULL;
4696
4697 lf.lfQuality = DEFAULT_QUALITY;
4698
4699 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
4700 bzero (font, sizeof (*font));
4701
4702 /* Set bdf to NULL to indicate that this is a Windows font. */
4703 font->bdf = NULL;
4704
4705 BLOCK_INPUT;
4706
4707 font->hfont = CreateFontIndirect (&lf);
4708
4709 if (font->hfont == NULL)
4710 {
4711 ok = FALSE;
4712 }
4713 else
4714 {
4715 HDC hdc;
4716 HANDLE oldobj;
4717
4718 codepage = w32_codepage_for_font (fontname);
4719
4720 hdc = GetDC (dpyinfo->root_window);
4721 oldobj = SelectObject (hdc, font->hfont);
4722
4723 ok = GetTextMetrics (hdc, &font->tm);
4724 if (codepage == CP_UNICODE)
4725 font->double_byte_p = 1;
4726 else
4727 {
4728 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
4729 don't report themselves as double byte fonts, when
4730 patently they are. So instead of trusting
4731 GetFontLanguageInfo, we check the properties of the
4732 codepage directly, since that is ultimately what we are
4733 working from anyway. */
4734 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
4735 CPINFO cpi = {0};
4736 GetCPInfo (codepage, &cpi);
4737 font->double_byte_p = cpi.MaxCharSize > 1;
4738 }
4739
4740 SelectObject (hdc, oldobj);
4741 ReleaseDC (dpyinfo->root_window, hdc);
4742 /* Fill out details in lf according to the font that was
4743 actually loaded. */
4744 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
4745 lf.lfWidth = font->tm.tmAveCharWidth;
4746 lf.lfWeight = font->tm.tmWeight;
4747 lf.lfItalic = font->tm.tmItalic;
4748 lf.lfCharSet = font->tm.tmCharSet;
4749 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
4750 ? VARIABLE_PITCH : FIXED_PITCH);
4751 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
4752 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
4753
4754 w32_cache_char_metrics (font);
4755 }
4756
4757 UNBLOCK_INPUT;
4758
4759 if (!ok)
4760 {
4761 w32_unload_font (dpyinfo, font);
4762 return (NULL);
4763 }
4764
4765 /* Find a free slot in the font table. */
4766 for (i = 0; i < dpyinfo->n_fonts; ++i)
4767 if (dpyinfo->font_table[i].name == NULL)
4768 break;
4769
4770 /* If no free slot found, maybe enlarge the font table. */
4771 if (i == dpyinfo->n_fonts
4772 && dpyinfo->n_fonts == dpyinfo->font_table_size)
4773 {
4774 int sz;
4775 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
4776 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
4777 dpyinfo->font_table
4778 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
4779 }
4780
4781 fontp = dpyinfo->font_table + i;
4782 if (i == dpyinfo->n_fonts)
4783 ++dpyinfo->n_fonts;
4784
4785 /* Now fill in the slots of *FONTP. */
4786 BLOCK_INPUT;
4787 fontp->font = font;
4788 fontp->font_idx = i;
4789 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
4790 bcopy (fontname, fontp->name, strlen (fontname) + 1);
4791
4792 charset = xlfd_charset_of_font (fontname);
4793
4794 /* Cache the W32 codepage for a font. This makes w32_encode_char
4795 (called for every glyph during redisplay) much faster. */
4796 fontp->codepage = codepage;
4797
4798 /* Work out the font's full name. */
4799 full_name = (char *)xmalloc (100);
4800 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
4801 fontp->full_name = full_name;
4802 else
4803 {
4804 /* If all else fails - just use the name we used to load it. */
4805 xfree (full_name);
4806 fontp->full_name = fontp->name;
4807 }
4808
4809 fontp->size = FONT_WIDTH (font);
4810 fontp->height = FONT_HEIGHT (font);
4811
4812 /* The slot `encoding' specifies how to map a character
4813 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
4814 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
4815 (0:0x20..0x7F, 1:0xA0..0xFF,
4816 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
4817 2:0xA020..0xFF7F). For the moment, we don't know which charset
4818 uses this font. So, we set information in fontp->encoding[1]
4819 which is never used by any charset. If mapping can't be
4820 decided, set FONT_ENCODING_NOT_DECIDED. */
4821
4822 /* SJIS fonts need to be set to type 4, all others seem to work as
4823 type FONT_ENCODING_NOT_DECIDED. */
4824 encoding = strrchr (fontp->name, '-');
4825 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
4826 fontp->encoding[1] = 4;
4827 else
4828 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
4829
4830 /* The following three values are set to 0 under W32, which is
4831 what they get set to if XGetFontProperty fails under X. */
4832 fontp->baseline_offset = 0;
4833 fontp->relative_compose = 0;
4834 fontp->default_ascent = 0;
4835
4836 /* Set global flag fonts_changed_p to non-zero if the font loaded
4837 has a character with a smaller width than any other character
4838 before, or if the font loaded has a smaller height than any
4839 other font loaded before. If this happens, it will make a
4840 glyph matrix reallocation necessary. */
4841 fonts_changed_p |= x_compute_min_glyph_bounds (f);
4842 UNBLOCK_INPUT;
4843 return fontp;
4844 }
4845 }
4846
4847 /* Load font named FONTNAME of size SIZE for frame F, and return a
4848 pointer to the structure font_info while allocating it dynamically.
4849 If loading fails, return NULL. */
4850 struct font_info *
4851 w32_load_font (f,fontname,size)
4852 struct frame *f;
4853 char * fontname;
4854 int size;
4855 {
4856 Lisp_Object bdf_fonts;
4857 struct font_info *retval = NULL;
4858
4859 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
4860
4861 while (!retval && CONSP (bdf_fonts))
4862 {
4863 char *bdf_name, *bdf_file;
4864 Lisp_Object bdf_pair;
4865
4866 bdf_name = SDATA (XCAR (bdf_fonts));
4867 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
4868 bdf_file = SDATA (XCDR (bdf_pair));
4869
4870 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
4871
4872 bdf_fonts = XCDR (bdf_fonts);
4873 }
4874
4875 if (retval)
4876 return retval;
4877
4878 return w32_load_system_font(f, fontname, size);
4879 }
4880
4881
4882 void
4883 w32_unload_font (dpyinfo, font)
4884 struct w32_display_info *dpyinfo;
4885 XFontStruct * font;
4886 {
4887 if (font)
4888 {
4889 if (font->per_char) xfree (font->per_char);
4890 if (font->bdf) w32_free_bdf_font (font->bdf);
4891
4892 if (font->hfont) DeleteObject(font->hfont);
4893 xfree (font);
4894 }
4895 }
4896
4897 /* The font conversion stuff between x and w32 */
4898
4899 /* X font string is as follows (from faces.el)
4900 * (let ((- "[-?]")
4901 * (foundry "[^-]+")
4902 * (family "[^-]+")
4903 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
4904 * (weight\? "\\([^-]*\\)") ; 1
4905 * (slant "\\([ior]\\)") ; 2
4906 * (slant\? "\\([^-]?\\)") ; 2
4907 * (swidth "\\([^-]*\\)") ; 3
4908 * (adstyle "[^-]*") ; 4
4909 * (pixelsize "[0-9]+")
4910 * (pointsize "[0-9][0-9]+")
4911 * (resx "[0-9][0-9]+")
4912 * (resy "[0-9][0-9]+")
4913 * (spacing "[cmp?*]")
4914 * (avgwidth "[0-9]+")
4915 * (registry "[^-]+")
4916 * (encoding "[^-]+")
4917 * )
4918 */
4919
4920 static LONG
4921 x_to_w32_weight (lpw)
4922 char * lpw;
4923 {
4924 if (!lpw) return (FW_DONTCARE);
4925
4926 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
4927 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
4928 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
4929 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
4930 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
4931 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
4932 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
4933 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
4934 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
4935 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
4936 else
4937 return FW_DONTCARE;
4938 }
4939
4940
4941 static char *
4942 w32_to_x_weight (fnweight)
4943 int fnweight;
4944 {
4945 if (fnweight >= FW_HEAVY) return "heavy";
4946 if (fnweight >= FW_EXTRABOLD) return "extrabold";
4947 if (fnweight >= FW_BOLD) return "bold";
4948 if (fnweight >= FW_SEMIBOLD) return "demibold";
4949 if (fnweight >= FW_MEDIUM) return "medium";
4950 if (fnweight >= FW_NORMAL) return "normal";
4951 if (fnweight >= FW_LIGHT) return "light";
4952 if (fnweight >= FW_EXTRALIGHT) return "extralight";
4953 if (fnweight >= FW_THIN) return "thin";
4954 else
4955 return "*";
4956 }
4957
4958 static LONG
4959 x_to_w32_charset (lpcs)
4960 char * lpcs;
4961 {
4962 Lisp_Object this_entry, w32_charset;
4963 char *charset;
4964 int len = strlen (lpcs);
4965
4966 /* Support "*-#nnn" format for unknown charsets. */
4967 if (strncmp (lpcs, "*-#", 3) == 0)
4968 return atoi (lpcs + 3);
4969
4970 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
4971 charset = alloca (len + 1);
4972 strcpy (charset, lpcs);
4973 lpcs = strchr (charset, '*');
4974 if (lpcs)
4975 *lpcs = 0;
4976
4977 /* Look through w32-charset-info-alist for the character set.
4978 Format of each entry is
4979 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
4980 */
4981 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
4982
4983 if (NILP(this_entry))
4984 {
4985 /* At startup, we want iso8859-1 fonts to come up properly. */
4986 if (stricmp(charset, "iso8859-1") == 0)
4987 return ANSI_CHARSET;
4988 else
4989 return DEFAULT_CHARSET;
4990 }
4991
4992 w32_charset = Fcar (Fcdr (this_entry));
4993
4994 /* Translate Lisp symbol to number. */
4995 if (w32_charset == Qw32_charset_ansi)
4996 return ANSI_CHARSET;
4997 if (w32_charset == Qw32_charset_symbol)
4998 return SYMBOL_CHARSET;
4999 if (w32_charset == Qw32_charset_shiftjis)
5000 return SHIFTJIS_CHARSET;
5001 if (w32_charset == Qw32_charset_hangeul)
5002 return HANGEUL_CHARSET;
5003 if (w32_charset == Qw32_charset_chinesebig5)
5004 return CHINESEBIG5_CHARSET;
5005 if (w32_charset == Qw32_charset_gb2312)
5006 return GB2312_CHARSET;
5007 if (w32_charset == Qw32_charset_oem)
5008 return OEM_CHARSET;
5009 #ifdef JOHAB_CHARSET
5010 if (w32_charset == Qw32_charset_johab)
5011 return JOHAB_CHARSET;
5012 if (w32_charset == Qw32_charset_easteurope)
5013 return EASTEUROPE_CHARSET;
5014 if (w32_charset == Qw32_charset_turkish)
5015 return TURKISH_CHARSET;
5016 if (w32_charset == Qw32_charset_baltic)
5017 return BALTIC_CHARSET;
5018 if (w32_charset == Qw32_charset_russian)
5019 return RUSSIAN_CHARSET;
5020 if (w32_charset == Qw32_charset_arabic)
5021 return ARABIC_CHARSET;
5022 if (w32_charset == Qw32_charset_greek)
5023 return GREEK_CHARSET;
5024 if (w32_charset == Qw32_charset_hebrew)
5025 return HEBREW_CHARSET;
5026 if (w32_charset == Qw32_charset_vietnamese)
5027 return VIETNAMESE_CHARSET;
5028 if (w32_charset == Qw32_charset_thai)
5029 return THAI_CHARSET;
5030 if (w32_charset == Qw32_charset_mac)
5031 return MAC_CHARSET;
5032 #endif /* JOHAB_CHARSET */
5033 #ifdef UNICODE_CHARSET
5034 if (w32_charset == Qw32_charset_unicode)
5035 return UNICODE_CHARSET;
5036 #endif
5037
5038 return DEFAULT_CHARSET;
5039 }
5040
5041
5042 static char *
5043 w32_to_x_charset (fncharset)
5044 int fncharset;
5045 {
5046 static char buf[32];
5047 Lisp_Object charset_type;
5048
5049 switch (fncharset)
5050 {
5051 case ANSI_CHARSET:
5052 /* Handle startup case of w32-charset-info-alist not
5053 being set up yet. */
5054 if (NILP(Vw32_charset_info_alist))
5055 return "iso8859-1";
5056 charset_type = Qw32_charset_ansi;
5057 break;
5058 case DEFAULT_CHARSET:
5059 charset_type = Qw32_charset_default;
5060 break;
5061 case SYMBOL_CHARSET:
5062 charset_type = Qw32_charset_symbol;
5063 break;
5064 case SHIFTJIS_CHARSET:
5065 charset_type = Qw32_charset_shiftjis;
5066 break;
5067 case HANGEUL_CHARSET:
5068 charset_type = Qw32_charset_hangeul;
5069 break;
5070 case GB2312_CHARSET:
5071 charset_type = Qw32_charset_gb2312;
5072 break;
5073 case CHINESEBIG5_CHARSET:
5074 charset_type = Qw32_charset_chinesebig5;
5075 break;
5076 case OEM_CHARSET:
5077 charset_type = Qw32_charset_oem;
5078 break;
5079
5080 /* More recent versions of Windows (95 and NT4.0) define more
5081 character sets. */
5082 #ifdef EASTEUROPE_CHARSET
5083 case EASTEUROPE_CHARSET:
5084 charset_type = Qw32_charset_easteurope;
5085 break;
5086 case TURKISH_CHARSET:
5087 charset_type = Qw32_charset_turkish;
5088 break;
5089 case BALTIC_CHARSET:
5090 charset_type = Qw32_charset_baltic;
5091 break;
5092 case RUSSIAN_CHARSET:
5093 charset_type = Qw32_charset_russian;
5094 break;
5095 case ARABIC_CHARSET:
5096 charset_type = Qw32_charset_arabic;
5097 break;
5098 case GREEK_CHARSET:
5099 charset_type = Qw32_charset_greek;
5100 break;
5101 case HEBREW_CHARSET:
5102 charset_type = Qw32_charset_hebrew;
5103 break;
5104 case VIETNAMESE_CHARSET:
5105 charset_type = Qw32_charset_vietnamese;
5106 break;
5107 case THAI_CHARSET:
5108 charset_type = Qw32_charset_thai;
5109 break;
5110 case MAC_CHARSET:
5111 charset_type = Qw32_charset_mac;
5112 break;
5113 case JOHAB_CHARSET:
5114 charset_type = Qw32_charset_johab;
5115 break;
5116 #endif
5117
5118 #ifdef UNICODE_CHARSET
5119 case UNICODE_CHARSET:
5120 charset_type = Qw32_charset_unicode;
5121 break;
5122 #endif
5123 default:
5124 /* Encode numerical value of unknown charset. */
5125 sprintf (buf, "*-#%u", fncharset);
5126 return buf;
5127 }
5128
5129 {
5130 Lisp_Object rest;
5131 char * best_match = NULL;
5132
5133 /* Look through w32-charset-info-alist for the character set.
5134 Prefer ISO codepages, and prefer lower numbers in the ISO
5135 range. Only return charsets for codepages which are installed.
5136
5137 Format of each entry is
5138 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5139 */
5140 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5141 {
5142 char * x_charset;
5143 Lisp_Object w32_charset;
5144 Lisp_Object codepage;
5145
5146 Lisp_Object this_entry = XCAR (rest);
5147
5148 /* Skip invalid entries in alist. */
5149 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5150 || !CONSP (XCDR (this_entry))
5151 || !SYMBOLP (XCAR (XCDR (this_entry))))
5152 continue;
5153
5154 x_charset = SDATA (XCAR (this_entry));
5155 w32_charset = XCAR (XCDR (this_entry));
5156 codepage = XCDR (XCDR (this_entry));
5157
5158 /* Look for Same charset and a valid codepage (or non-int
5159 which means ignore). */
5160 if (w32_charset == charset_type
5161 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5162 || IsValidCodePage (XINT (codepage))))
5163 {
5164 /* If we don't have a match already, then this is the
5165 best. */
5166 if (!best_match)
5167 best_match = x_charset;
5168 /* If this is an ISO codepage, and the best so far isn't,
5169 then this is better. */
5170 else if (strnicmp (best_match, "iso", 3) != 0
5171 && strnicmp (x_charset, "iso", 3) == 0)
5172 best_match = x_charset;
5173 /* If both are ISO8859 codepages, choose the one with the
5174 lowest number in the encoding field. */
5175 else if (strnicmp (best_match, "iso8859-", 8) == 0
5176 && strnicmp (x_charset, "iso8859-", 8) == 0)
5177 {
5178 int best_enc = atoi (best_match + 8);
5179 int this_enc = atoi (x_charset + 8);
5180 if (this_enc > 0 && this_enc < best_enc)
5181 best_match = x_charset;
5182 }
5183 }
5184 }
5185
5186 /* If no match, encode the numeric value. */
5187 if (!best_match)
5188 {
5189 sprintf (buf, "*-#%u", fncharset);
5190 return buf;
5191 }
5192
5193 strncpy(buf, best_match, 31);
5194 buf[31] = '\0';
5195 return buf;
5196 }
5197 }
5198
5199
5200 /* Return all the X charsets that map to a font. */
5201 static Lisp_Object
5202 w32_to_all_x_charsets (fncharset)
5203 int fncharset;
5204 {
5205 static char buf[32];
5206 Lisp_Object charset_type;
5207 Lisp_Object retval = Qnil;
5208
5209 switch (fncharset)
5210 {
5211 case ANSI_CHARSET:
5212 /* Handle startup case of w32-charset-info-alist not
5213 being set up yet. */
5214 if (NILP(Vw32_charset_info_alist))
5215 return Fcons (build_string ("iso8859-1"), Qnil);
5216
5217 charset_type = Qw32_charset_ansi;
5218 break;
5219 case DEFAULT_CHARSET:
5220 charset_type = Qw32_charset_default;
5221 break;
5222 case SYMBOL_CHARSET:
5223 charset_type = Qw32_charset_symbol;
5224 break;
5225 case SHIFTJIS_CHARSET:
5226 charset_type = Qw32_charset_shiftjis;
5227 break;
5228 case HANGEUL_CHARSET:
5229 charset_type = Qw32_charset_hangeul;
5230 break;
5231 case GB2312_CHARSET:
5232 charset_type = Qw32_charset_gb2312;
5233 break;
5234 case CHINESEBIG5_CHARSET:
5235 charset_type = Qw32_charset_chinesebig5;
5236 break;
5237 case OEM_CHARSET:
5238 charset_type = Qw32_charset_oem;
5239 break;
5240
5241 /* More recent versions of Windows (95 and NT4.0) define more
5242 character sets. */
5243 #ifdef EASTEUROPE_CHARSET
5244 case EASTEUROPE_CHARSET:
5245 charset_type = Qw32_charset_easteurope;
5246 break;
5247 case TURKISH_CHARSET:
5248 charset_type = Qw32_charset_turkish;
5249 break;
5250 case BALTIC_CHARSET:
5251 charset_type = Qw32_charset_baltic;
5252 break;
5253 case RUSSIAN_CHARSET:
5254 charset_type = Qw32_charset_russian;
5255 break;
5256 case ARABIC_CHARSET:
5257 charset_type = Qw32_charset_arabic;
5258 break;
5259 case GREEK_CHARSET:
5260 charset_type = Qw32_charset_greek;
5261 break;
5262 case HEBREW_CHARSET:
5263 charset_type = Qw32_charset_hebrew;
5264 break;
5265 case VIETNAMESE_CHARSET:
5266 charset_type = Qw32_charset_vietnamese;
5267 break;
5268 case THAI_CHARSET:
5269 charset_type = Qw32_charset_thai;
5270 break;
5271 case MAC_CHARSET:
5272 charset_type = Qw32_charset_mac;
5273 break;
5274 case JOHAB_CHARSET:
5275 charset_type = Qw32_charset_johab;
5276 break;
5277 #endif
5278
5279 #ifdef UNICODE_CHARSET
5280 case UNICODE_CHARSET:
5281 charset_type = Qw32_charset_unicode;
5282 break;
5283 #endif
5284 default:
5285 /* Encode numerical value of unknown charset. */
5286 sprintf (buf, "*-#%u", fncharset);
5287 return Fcons (build_string (buf), Qnil);
5288 }
5289
5290 {
5291 Lisp_Object rest;
5292 /* Look through w32-charset-info-alist for the character set.
5293 Only return charsets for codepages which are installed.
5294
5295 Format of each entry in Vw32_charset_info_alist is
5296 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5297 */
5298 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5299 {
5300 Lisp_Object x_charset;
5301 Lisp_Object w32_charset;
5302 Lisp_Object codepage;
5303
5304 Lisp_Object this_entry = XCAR (rest);
5305
5306 /* Skip invalid entries in alist. */
5307 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5308 || !CONSP (XCDR (this_entry))
5309 || !SYMBOLP (XCAR (XCDR (this_entry))))
5310 continue;
5311
5312 x_charset = XCAR (this_entry);
5313 w32_charset = XCAR (XCDR (this_entry));
5314 codepage = XCDR (XCDR (this_entry));
5315
5316 /* Look for Same charset and a valid codepage (or non-int
5317 which means ignore). */
5318 if (w32_charset == charset_type
5319 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5320 || IsValidCodePage (XINT (codepage))))
5321 {
5322 retval = Fcons (x_charset, retval);
5323 }
5324 }
5325
5326 /* If no match, encode the numeric value. */
5327 if (NILP (retval))
5328 {
5329 sprintf (buf, "*-#%u", fncharset);
5330 return Fcons (build_string (buf), Qnil);
5331 }
5332
5333 return retval;
5334 }
5335 }
5336
5337 /* Get the Windows codepage corresponding to the specified font. The
5338 charset info in the font name is used to look up
5339 w32-charset-to-codepage-alist. */
5340 int
5341 w32_codepage_for_font (char *fontname)
5342 {
5343 Lisp_Object codepage, entry;
5344 char *charset_str, *charset, *end;
5345
5346 if (NILP (Vw32_charset_info_alist))
5347 return CP_DEFAULT;
5348
5349 /* Extract charset part of font string. */
5350 charset = xlfd_charset_of_font (fontname);
5351
5352 if (!charset)
5353 return CP_UNKNOWN;
5354
5355 charset_str = (char *) alloca (strlen (charset) + 1);
5356 strcpy (charset_str, charset);
5357
5358 #if 0
5359 /* Remove leading "*-". */
5360 if (strncmp ("*-", charset_str, 2) == 0)
5361 charset = charset_str + 2;
5362 else
5363 #endif
5364 charset = charset_str;
5365
5366 /* Stop match at wildcard (including preceding '-'). */
5367 if (end = strchr (charset, '*'))
5368 {
5369 if (end > charset && *(end-1) == '-')
5370 end--;
5371 *end = '\0';
5372 }
5373
5374 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
5375 if (NILP (entry))
5376 return CP_UNKNOWN;
5377
5378 codepage = Fcdr (Fcdr (entry));
5379
5380 if (NILP (codepage))
5381 return CP_8BIT;
5382 else if (XFASTINT (codepage) == XFASTINT (Qt))
5383 return CP_UNICODE;
5384 else if (INTEGERP (codepage))
5385 return XINT (codepage);
5386 else
5387 return CP_UNKNOWN;
5388 }
5389
5390
5391 static BOOL
5392 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
5393 LOGFONT * lplogfont;
5394 char * lpxstr;
5395 int len;
5396 char * specific_charset;
5397 {
5398 char* fonttype;
5399 char *fontname;
5400 char height_pixels[8];
5401 char height_dpi[8];
5402 char width_pixels[8];
5403 char *fontname_dash;
5404 int display_resy = (int) one_w32_display_info.resy;
5405 int display_resx = (int) one_w32_display_info.resx;
5406 int bufsz;
5407 struct coding_system coding;
5408
5409 if (!lpxstr) abort ();
5410
5411 if (!lplogfont)
5412 return FALSE;
5413
5414 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5415 fonttype = "raster";
5416 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5417 fonttype = "outline";
5418 else
5419 fonttype = "unknown";
5420
5421 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
5422 &coding);
5423 coding.src_multibyte = 0;
5424 coding.dst_multibyte = 1;
5425 coding.mode |= CODING_MODE_LAST_BLOCK;
5426 /* We explicitely disable composition handling because selection
5427 data should not contain any composition sequence. */
5428 coding.composing = COMPOSITION_DISABLED;
5429 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
5430
5431 fontname = alloca(sizeof(*fontname) * bufsz);
5432 decode_coding (&coding, lplogfont->lfFaceName, fontname,
5433 strlen(lplogfont->lfFaceName), bufsz - 1);
5434 *(fontname + coding.produced) = '\0';
5435
5436 /* Replace dashes with underscores so the dashes are not
5437 misinterpreted. */
5438 fontname_dash = fontname;
5439 while (fontname_dash = strchr (fontname_dash, '-'))
5440 *fontname_dash = '_';
5441
5442 if (lplogfont->lfHeight)
5443 {
5444 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
5445 sprintf (height_dpi, "%u",
5446 abs (lplogfont->lfHeight) * 720 / display_resy);
5447 }
5448 else
5449 {
5450 strcpy (height_pixels, "*");
5451 strcpy (height_dpi, "*");
5452 }
5453 if (lplogfont->lfWidth)
5454 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5455 else
5456 strcpy (width_pixels, "*");
5457
5458 _snprintf (lpxstr, len - 1,
5459 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5460 fonttype, /* foundry */
5461 fontname, /* family */
5462 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5463 lplogfont->lfItalic?'i':'r', /* slant */
5464 /* setwidth name */
5465 /* add style name */
5466 height_pixels, /* pixel size */
5467 height_dpi, /* point size */
5468 display_resx, /* resx */
5469 display_resy, /* resy */
5470 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5471 ? 'p' : 'c', /* spacing */
5472 width_pixels, /* avg width */
5473 specific_charset ? specific_charset
5474 : w32_to_x_charset (lplogfont->lfCharSet)
5475 /* charset registry and encoding */
5476 );
5477
5478 lpxstr[len - 1] = 0; /* just to be sure */
5479 return (TRUE);
5480 }
5481
5482 static BOOL
5483 x_to_w32_font (lpxstr, lplogfont)
5484 char * lpxstr;
5485 LOGFONT * lplogfont;
5486 {
5487 struct coding_system coding;
5488
5489 if (!lplogfont) return (FALSE);
5490
5491 memset (lplogfont, 0, sizeof (*lplogfont));
5492
5493 /* Set default value for each field. */
5494 #if 1
5495 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5496 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5497 lplogfont->lfQuality = DEFAULT_QUALITY;
5498 #else
5499 /* go for maximum quality */
5500 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5501 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5502 lplogfont->lfQuality = PROOF_QUALITY;
5503 #endif
5504
5505 lplogfont->lfCharSet = DEFAULT_CHARSET;
5506 lplogfont->lfWeight = FW_DONTCARE;
5507 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5508
5509 if (!lpxstr)
5510 return FALSE;
5511
5512 /* Provide a simple escape mechanism for specifying Windows font names
5513 * directly -- if font spec does not beginning with '-', assume this
5514 * format:
5515 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5516 */
5517
5518 if (*lpxstr == '-')
5519 {
5520 int fields, tem;
5521 char name[50], weight[20], slant, pitch, pixels[10], height[10],
5522 width[10], resy[10], remainder[50];
5523 char * encoding;
5524 int dpi = (int) one_w32_display_info.resy;
5525
5526 fields = sscanf (lpxstr,
5527 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
5528 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
5529 if (fields == EOF)
5530 return (FALSE);
5531
5532 /* In the general case when wildcards cover more than one field,
5533 we don't know which field is which, so don't fill any in.
5534 However, we need to cope with this particular form, which is
5535 generated by font_list_1 (invoked by try_font_list):
5536 "-raster-6x10-*-gb2312*-*"
5537 and make sure to correctly parse the charset field. */
5538 if (fields == 3)
5539 {
5540 fields = sscanf (lpxstr,
5541 "-%*[^-]-%49[^-]-*-%49s",
5542 name, remainder);
5543 }
5544 else if (fields < 9)
5545 {
5546 fields = 0;
5547 remainder[0] = 0;
5548 }
5549
5550 if (fields > 0 && name[0] != '*')
5551 {
5552 int bufsize;
5553 unsigned char *buf;
5554
5555 setup_coding_system
5556 (Fcheck_coding_system (Vlocale_coding_system), &coding);
5557 coding.src_multibyte = 1;
5558 coding.dst_multibyte = 1;
5559 bufsize = encoding_buffer_size (&coding, strlen (name));
5560 buf = (unsigned char *) alloca (bufsize);
5561 coding.mode |= CODING_MODE_LAST_BLOCK;
5562 encode_coding (&coding, name, buf, strlen (name), bufsize);
5563 if (coding.produced >= LF_FACESIZE)
5564 coding.produced = LF_FACESIZE - 1;
5565 buf[coding.produced] = 0;
5566 strcpy (lplogfont->lfFaceName, buf);
5567 }
5568 else
5569 {
5570 lplogfont->lfFaceName[0] = '\0';
5571 }
5572
5573 fields--;
5574
5575 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5576
5577 fields--;
5578
5579 lplogfont->lfItalic = (fields > 0 && slant == 'i');
5580
5581 fields--;
5582
5583 if (fields > 0 && pixels[0] != '*')
5584 lplogfont->lfHeight = atoi (pixels);
5585
5586 fields--;
5587 fields--;
5588 if (fields > 0 && resy[0] != '*')
5589 {
5590 tem = atoi (resy);
5591 if (tem > 0) dpi = tem;
5592 }
5593
5594 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
5595 lplogfont->lfHeight = atoi (height) * dpi / 720;
5596
5597 if (fields > 0)
5598 lplogfont->lfPitchAndFamily =
5599 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
5600
5601 fields--;
5602
5603 if (fields > 0 && width[0] != '*')
5604 lplogfont->lfWidth = atoi (width) / 10;
5605
5606 fields--;
5607
5608 /* Strip the trailing '-' if present. (it shouldn't be, as it
5609 fails the test against xlfd-tight-regexp in fontset.el). */
5610 {
5611 int len = strlen (remainder);
5612 if (len > 0 && remainder[len-1] == '-')
5613 remainder[len-1] = 0;
5614 }
5615 encoding = remainder;
5616 #if 0
5617 if (strncmp (encoding, "*-", 2) == 0)
5618 encoding += 2;
5619 #endif
5620 lplogfont->lfCharSet = x_to_w32_charset (encoding);
5621 }
5622 else
5623 {
5624 int fields;
5625 char name[100], height[10], width[10], weight[20];
5626
5627 fields = sscanf (lpxstr,
5628 "%99[^:]:%9[^:]:%9[^:]:%19s",
5629 name, height, width, weight);
5630
5631 if (fields == EOF) return (FALSE);
5632
5633 if (fields > 0)
5634 {
5635 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
5636 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
5637 }
5638 else
5639 {
5640 lplogfont->lfFaceName[0] = 0;
5641 }
5642
5643 fields--;
5644
5645 if (fields > 0)
5646 lplogfont->lfHeight = atoi (height);
5647
5648 fields--;
5649
5650 if (fields > 0)
5651 lplogfont->lfWidth = atoi (width);
5652
5653 fields--;
5654
5655 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5656 }
5657
5658 /* This makes TrueType fonts work better. */
5659 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
5660
5661 return (TRUE);
5662 }
5663
5664 /* Strip the pixel height and point height from the given xlfd, and
5665 return the pixel height. If no pixel height is specified, calculate
5666 one from the point height, or if that isn't defined either, return
5667 0 (which usually signifies a scalable font).
5668 */
5669 static int
5670 xlfd_strip_height (char *fontname)
5671 {
5672 int pixel_height, field_number;
5673 char *read_from, *write_to;
5674
5675 xassert (fontname);
5676
5677 pixel_height = field_number = 0;
5678 write_to = NULL;
5679
5680 /* Look for height fields. */
5681 for (read_from = fontname; *read_from; read_from++)
5682 {
5683 if (*read_from == '-')
5684 {
5685 field_number++;
5686 if (field_number == 7) /* Pixel height. */
5687 {
5688 read_from++;
5689 write_to = read_from;
5690
5691 /* Find end of field. */
5692 for (;*read_from && *read_from != '-'; read_from++)
5693 ;
5694
5695 /* Split the fontname at end of field. */
5696 if (*read_from)
5697 {
5698 *read_from = '\0';
5699 read_from++;
5700 }
5701 pixel_height = atoi (write_to);
5702 /* Blank out field. */
5703 if (read_from > write_to)
5704 {
5705 *write_to = '-';
5706 write_to++;
5707 }
5708 /* If the pixel height field is at the end (partial xlfd),
5709 return now. */
5710 else
5711 return pixel_height;
5712
5713 /* If we got a pixel height, the point height can be
5714 ignored. Just blank it out and break now. */
5715 if (pixel_height)
5716 {
5717 /* Find end of point size field. */
5718 for (; *read_from && *read_from != '-'; read_from++)
5719 ;
5720
5721 if (*read_from)
5722 read_from++;
5723
5724 /* Blank out the point size field. */
5725 if (read_from > write_to)
5726 {
5727 *write_to = '-';
5728 write_to++;
5729 }
5730 else
5731 return pixel_height;
5732
5733 break;
5734 }
5735 /* If the point height is already blank, break now. */
5736 if (*read_from == '-')
5737 {
5738 read_from++;
5739 break;
5740 }
5741 }
5742 else if (field_number == 8)
5743 {
5744 /* If we didn't get a pixel height, try to get the point
5745 height and convert that. */
5746 int point_size;
5747 char *point_size_start = read_from++;
5748
5749 /* Find end of field. */
5750 for (; *read_from && *read_from != '-'; read_from++)
5751 ;
5752
5753 if (*read_from)
5754 {
5755 *read_from = '\0';
5756 read_from++;
5757 }
5758
5759 point_size = atoi (point_size_start);
5760
5761 /* Convert to pixel height. */
5762 pixel_height = point_size
5763 * one_w32_display_info.height_in / 720;
5764
5765 /* Blank out this field and break. */
5766 *write_to = '-';
5767 write_to++;
5768 break;
5769 }
5770 }
5771 }
5772
5773 /* Shift the rest of the font spec into place. */
5774 if (write_to && read_from > write_to)
5775 {
5776 for (; *read_from; read_from++, write_to++)
5777 *write_to = *read_from;
5778 *write_to = '\0';
5779 }
5780
5781 return pixel_height;
5782 }
5783
5784 /* Assume parameter 1 is fully qualified, no wildcards. */
5785 static BOOL
5786 w32_font_match (fontname, pattern)
5787 char * fontname;
5788 char * pattern;
5789 {
5790 char *regex = alloca (strlen (pattern) * 2 + 3);
5791 char *font_name_copy = alloca (strlen (fontname) + 1);
5792 char *ptr;
5793
5794 /* Copy fontname so we can modify it during comparison. */
5795 strcpy (font_name_copy, fontname);
5796
5797 ptr = regex;
5798 *ptr++ = '^';
5799
5800 /* Turn pattern into a regexp and do a regexp match. */
5801 for (; *pattern; pattern++)
5802 {
5803 if (*pattern == '?')
5804 *ptr++ = '.';
5805 else if (*pattern == '*')
5806 {
5807 *ptr++ = '.';
5808 *ptr++ = '*';
5809 }
5810 else
5811 *ptr++ = *pattern;
5812 }
5813 *ptr = '$';
5814 *(ptr + 1) = '\0';
5815
5816 /* Strip out font heights and compare them seperately, since
5817 rounding error can cause mismatches. This also allows a
5818 comparison between a font that declares only a pixel height and a
5819 pattern that declares the point height.
5820 */
5821 {
5822 int font_height, pattern_height;
5823
5824 font_height = xlfd_strip_height (font_name_copy);
5825 pattern_height = xlfd_strip_height (regex);
5826
5827 /* Compare now, and don't bother doing expensive regexp matching
5828 if the heights differ. */
5829 if (font_height && pattern_height && (font_height != pattern_height))
5830 return FALSE;
5831 }
5832
5833 return (fast_c_string_match_ignore_case (build_string (regex),
5834 font_name_copy) >= 0);
5835 }
5836
5837 /* Callback functions, and a structure holding info they need, for
5838 listing system fonts on W32. We need one set of functions to do the
5839 job properly, but these don't work on NT 3.51 and earlier, so we
5840 have a second set which don't handle character sets properly to
5841 fall back on.
5842
5843 In both cases, there are two passes made. The first pass gets one
5844 font from each family, the second pass lists all the fonts from
5845 each family. */
5846
5847 typedef struct enumfont_t
5848 {
5849 HDC hdc;
5850 int numFonts;
5851 LOGFONT logfont;
5852 XFontStruct *size_ref;
5853 Lisp_Object pattern;
5854 Lisp_Object list;
5855 } enumfont_t;
5856
5857
5858 static void
5859 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
5860
5861
5862 static int CALLBACK
5863 enum_font_cb2 (lplf, lptm, FontType, lpef)
5864 ENUMLOGFONT * lplf;
5865 NEWTEXTMETRIC * lptm;
5866 int FontType;
5867 enumfont_t * lpef;
5868 {
5869 /* Ignore struck out and underlined versions of fonts. */
5870 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
5871 return 1;
5872
5873 /* Only return fonts with names starting with @ if they were
5874 explicitly specified, since Microsoft uses an initial @ to
5875 denote fonts for vertical writing, without providing a more
5876 convenient way of identifying them. */
5877 if (lplf->elfLogFont.lfFaceName[0] == '@'
5878 && lpef->logfont.lfFaceName[0] != '@')
5879 return 1;
5880
5881 /* Check that the character set matches if it was specified */
5882 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
5883 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
5884 return 1;
5885
5886 if (FontType == RASTER_FONTTYPE)
5887 {
5888 /* DBCS raster fonts have problems displaying, so skip them. */
5889 int charset = lplf->elfLogFont.lfCharSet;
5890 if (charset == SHIFTJIS_CHARSET
5891 || charset == HANGEUL_CHARSET
5892 || charset == CHINESEBIG5_CHARSET
5893 || charset == GB2312_CHARSET
5894 #ifdef JOHAB_CHARSET
5895 || charset == JOHAB_CHARSET
5896 #endif
5897 )
5898 return 1;
5899 }
5900
5901 {
5902 char buf[100];
5903 Lisp_Object width = Qnil;
5904 Lisp_Object charset_list = Qnil;
5905 char *charset = NULL;
5906
5907 /* Truetype fonts do not report their true metrics until loaded */
5908 if (FontType != RASTER_FONTTYPE)
5909 {
5910 if (!NILP (lpef->pattern))
5911 {
5912 /* Scalable fonts are as big as you want them to be. */
5913 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
5914 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
5915 width = make_number (lpef->logfont.lfWidth);
5916 }
5917 else
5918 {
5919 lplf->elfLogFont.lfHeight = 0;
5920 lplf->elfLogFont.lfWidth = 0;
5921 }
5922 }
5923
5924 /* Make sure the height used here is the same as everywhere
5925 else (ie character height, not cell height). */
5926 if (lplf->elfLogFont.lfHeight > 0)
5927 {
5928 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
5929 if (FontType == RASTER_FONTTYPE)
5930 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
5931 else
5932 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
5933 }
5934
5935 if (!NILP (lpef->pattern))
5936 {
5937 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
5938
5939 /* We already checked charsets above, but DEFAULT_CHARSET
5940 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
5941 if (charset
5942 && strncmp (charset, "*-*", 3) != 0
5943 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
5944 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
5945 return 1;
5946 }
5947
5948 if (charset)
5949 charset_list = Fcons (build_string (charset), Qnil);
5950 else
5951 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
5952
5953 /* Loop through the charsets. */
5954 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
5955 {
5956 Lisp_Object this_charset = Fcar (charset_list);
5957 charset = SDATA (this_charset);
5958
5959 /* List bold and italic variations if w32-enable-synthesized-fonts
5960 is non-nil and this is a plain font. */
5961 if (w32_enable_synthesized_fonts
5962 && lplf->elfLogFont.lfWeight == FW_NORMAL
5963 && lplf->elfLogFont.lfItalic == FALSE)
5964 {
5965 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5966 charset, width);
5967 /* bold. */
5968 lplf->elfLogFont.lfWeight = FW_BOLD;
5969 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5970 charset, width);
5971 /* bold italic. */
5972 lplf->elfLogFont.lfItalic = TRUE;
5973 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5974 charset, width);
5975 /* italic. */
5976 lplf->elfLogFont.lfWeight = FW_NORMAL;
5977 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5978 charset, width);
5979 }
5980 else
5981 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5982 charset, width);
5983 }
5984 }
5985
5986 return 1;
5987 }
5988
5989 static void
5990 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
5991 enumfont_t * lpef;
5992 LOGFONT * logfont;
5993 char * match_charset;
5994 Lisp_Object width;
5995 {
5996 char buf[100];
5997
5998 if (!w32_to_x_font (logfont, buf, 100, match_charset))
5999 return;
6000
6001 if (NILP (lpef->pattern)
6002 || w32_font_match (buf, SDATA (lpef->pattern)))
6003 {
6004 /* Check if we already listed this font. This may happen if
6005 w32_enable_synthesized_fonts is non-nil, and there are real
6006 bold and italic versions of the font. */
6007 Lisp_Object font_name = build_string (buf);
6008 if (NILP (Fmember (font_name, lpef->list)))
6009 {
6010 Lisp_Object entry = Fcons (font_name, width);
6011 lpef->list = Fcons (entry, lpef->list);
6012 lpef->numFonts++;
6013 }
6014 }
6015 }
6016
6017
6018 static int CALLBACK
6019 enum_font_cb1 (lplf, lptm, FontType, lpef)
6020 ENUMLOGFONT * lplf;
6021 NEWTEXTMETRIC * lptm;
6022 int FontType;
6023 enumfont_t * lpef;
6024 {
6025 return EnumFontFamilies (lpef->hdc,
6026 lplf->elfLogFont.lfFaceName,
6027 (FONTENUMPROC) enum_font_cb2,
6028 (LPARAM) lpef);
6029 }
6030
6031
6032 static int CALLBACK
6033 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6034 ENUMLOGFONTEX * lplf;
6035 NEWTEXTMETRICEX * lptm;
6036 int font_type;
6037 enumfont_t * lpef;
6038 {
6039 /* We are not interested in the extra info we get back from the 'Ex
6040 version - only the fact that we get character set variations
6041 enumerated seperately. */
6042 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6043 font_type, lpef);
6044 }
6045
6046 static int CALLBACK
6047 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6048 ENUMLOGFONTEX * lplf;
6049 NEWTEXTMETRICEX * lptm;
6050 int font_type;
6051 enumfont_t * lpef;
6052 {
6053 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6054 FARPROC enum_font_families_ex
6055 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6056 /* We don't really expect EnumFontFamiliesEx to disappear once we
6057 get here, so don't bother handling it gracefully. */
6058 if (enum_font_families_ex == NULL)
6059 error ("gdi32.dll has disappeared!");
6060 return enum_font_families_ex (lpef->hdc,
6061 &lplf->elfLogFont,
6062 (FONTENUMPROC) enum_fontex_cb2,
6063 (LPARAM) lpef, 0);
6064 }
6065
6066 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6067 and xterm.c in Emacs 20.3) */
6068
6069 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6070 {
6071 char *fontname, *ptnstr;
6072 Lisp_Object list, tem, newlist = Qnil;
6073 int n_fonts = 0;
6074
6075 list = Vw32_bdf_filename_alist;
6076 ptnstr = SDATA (pattern);
6077
6078 for ( ; CONSP (list); list = XCDR (list))
6079 {
6080 tem = XCAR (list);
6081 if (CONSP (tem))
6082 fontname = SDATA (XCAR (tem));
6083 else if (STRINGP (tem))
6084 fontname = SDATA (tem);
6085 else
6086 continue;
6087
6088 if (w32_font_match (fontname, ptnstr))
6089 {
6090 newlist = Fcons (XCAR (tem), newlist);
6091 n_fonts++;
6092 if (max_names >= 0 && n_fonts >= max_names)
6093 break;
6094 }
6095 }
6096
6097 return newlist;
6098 }
6099
6100
6101 /* Return a list of names of available fonts matching PATTERN on frame
6102 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6103 to be listed. Frame F NULL means we have not yet created any
6104 frame, which means we can't get proper size info, as we don't have
6105 a device context to use for GetTextMetrics.
6106 MAXNAMES sets a limit on how many fonts to match. If MAXNAMES is
6107 negative, then all matching fonts are returned. */
6108
6109 Lisp_Object
6110 w32_list_fonts (f, pattern, size, maxnames)
6111 struct frame *f;
6112 Lisp_Object pattern;
6113 int size;
6114 int maxnames;
6115 {
6116 Lisp_Object patterns, key = Qnil, tem, tpat;
6117 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6118 struct w32_display_info *dpyinfo = &one_w32_display_info;
6119 int n_fonts = 0;
6120
6121 patterns = Fassoc (pattern, Valternate_fontname_alist);
6122 if (NILP (patterns))
6123 patterns = Fcons (pattern, Qnil);
6124
6125 for (; CONSP (patterns); patterns = XCDR (patterns))
6126 {
6127 enumfont_t ef;
6128 int codepage;
6129
6130 tpat = XCAR (patterns);
6131
6132 if (!STRINGP (tpat))
6133 continue;
6134
6135 /* Avoid expensive EnumFontFamilies functions if we are not
6136 going to be able to output one of these anyway. */
6137 codepage = w32_codepage_for_font (SDATA (tpat));
6138 if (codepage != CP_8BIT && codepage != CP_UNICODE
6139 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6140 && !IsValidCodePage(codepage))
6141 continue;
6142
6143 /* See if we cached the result for this particular query.
6144 The cache is an alist of the form:
6145 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6146 */
6147 if (tem = XCDR (dpyinfo->name_list_element),
6148 !NILP (list = Fassoc (tpat, tem)))
6149 {
6150 list = Fcdr_safe (list);
6151 /* We have a cached list. Don't have to get the list again. */
6152 goto label_cached;
6153 }
6154
6155 BLOCK_INPUT;
6156 /* At first, put PATTERN in the cache. */
6157 ef.pattern = tpat;
6158 ef.list = Qnil;
6159 ef.numFonts = 0;
6160
6161 /* Use EnumFontFamiliesEx where it is available, as it knows
6162 about character sets. Fall back to EnumFontFamilies for
6163 older versions of NT that don't support the 'Ex function. */
6164 x_to_w32_font (SDATA (tpat), &ef.logfont);
6165 {
6166 LOGFONT font_match_pattern;
6167 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6168 FARPROC enum_font_families_ex
6169 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6170
6171 /* We do our own pattern matching so we can handle wildcards. */
6172 font_match_pattern.lfFaceName[0] = 0;
6173 font_match_pattern.lfPitchAndFamily = 0;
6174 /* We can use the charset, because if it is a wildcard it will
6175 be DEFAULT_CHARSET anyway. */
6176 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6177
6178 ef.hdc = GetDC (dpyinfo->root_window);
6179
6180 if (enum_font_families_ex)
6181 enum_font_families_ex (ef.hdc,
6182 &font_match_pattern,
6183 (FONTENUMPROC) enum_fontex_cb1,
6184 (LPARAM) &ef, 0);
6185 else
6186 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6187 (LPARAM)&ef);
6188
6189 ReleaseDC (dpyinfo->root_window, ef.hdc);
6190 }
6191
6192 UNBLOCK_INPUT;
6193 list = ef.list;
6194
6195 /* Make a list of the fonts we got back.
6196 Store that in the font cache for the display. */
6197 XSETCDR (dpyinfo->name_list_element,
6198 Fcons (Fcons (tpat, list),
6199 XCDR (dpyinfo->name_list_element)));
6200
6201 label_cached:
6202 if (NILP (list)) continue; /* Try the remaining alternatives. */
6203
6204 newlist = second_best = Qnil;
6205
6206 /* Make a list of the fonts that have the right width. */
6207 for (; CONSP (list); list = XCDR (list))
6208 {
6209 int found_size;
6210 tem = XCAR (list);
6211
6212 if (!CONSP (tem))
6213 continue;
6214 if (NILP (XCAR (tem)))
6215 continue;
6216 if (!size)
6217 {
6218 newlist = Fcons (XCAR (tem), newlist);
6219 n_fonts++;
6220 if (maxnames >= 0 && n_fonts >= maxnames)
6221 break;
6222 else
6223 continue;
6224 }
6225 if (!INTEGERP (XCDR (tem)))
6226 {
6227 /* Since we don't yet know the size of the font, we must
6228 load it and try GetTextMetrics. */
6229 W32FontStruct thisinfo;
6230 LOGFONT lf;
6231 HDC hdc;
6232 HANDLE oldobj;
6233
6234 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
6235 continue;
6236
6237 BLOCK_INPUT;
6238 thisinfo.bdf = NULL;
6239 thisinfo.hfont = CreateFontIndirect (&lf);
6240 if (thisinfo.hfont == NULL)
6241 continue;
6242
6243 hdc = GetDC (dpyinfo->root_window);
6244 oldobj = SelectObject (hdc, thisinfo.hfont);
6245 if (GetTextMetrics (hdc, &thisinfo.tm))
6246 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
6247 else
6248 XSETCDR (tem, make_number (0));
6249 SelectObject (hdc, oldobj);
6250 ReleaseDC (dpyinfo->root_window, hdc);
6251 DeleteObject(thisinfo.hfont);
6252 UNBLOCK_INPUT;
6253 }
6254 found_size = XINT (XCDR (tem));
6255 if (found_size == size)
6256 {
6257 newlist = Fcons (XCAR (tem), newlist);
6258 n_fonts++;
6259 if (maxnames >= 0 && n_fonts >= maxnames)
6260 break;
6261 }
6262 /* keep track of the closest matching size in case
6263 no exact match is found. */
6264 else if (found_size > 0)
6265 {
6266 if (NILP (second_best))
6267 second_best = tem;
6268
6269 else if (found_size < size)
6270 {
6271 if (XINT (XCDR (second_best)) > size
6272 || XINT (XCDR (second_best)) < found_size)
6273 second_best = tem;
6274 }
6275 else
6276 {
6277 if (XINT (XCDR (second_best)) > size
6278 && XINT (XCDR (second_best)) >
6279 found_size)
6280 second_best = tem;
6281 }
6282 }
6283 }
6284
6285 if (!NILP (newlist))
6286 break;
6287 else if (!NILP (second_best))
6288 {
6289 newlist = Fcons (XCAR (second_best), Qnil);
6290 break;
6291 }
6292 }
6293
6294 /* Include any bdf fonts. */
6295 if (n_fonts < maxnames || maxnames < 0)
6296 {
6297 Lisp_Object combined[2];
6298 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6299 combined[1] = newlist;
6300 newlist = Fnconc(2, combined);
6301 }
6302
6303 return newlist;
6304 }
6305
6306
6307 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6308 struct font_info *
6309 w32_get_font_info (f, font_idx)
6310 FRAME_PTR f;
6311 int font_idx;
6312 {
6313 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6314 }
6315
6316
6317 struct font_info*
6318 w32_query_font (struct frame *f, char *fontname)
6319 {
6320 int i;
6321 struct font_info *pfi;
6322
6323 pfi = FRAME_W32_FONT_TABLE (f);
6324
6325 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6326 {
6327 if (strcmp(pfi->name, fontname) == 0) return pfi;
6328 }
6329
6330 return NULL;
6331 }
6332
6333 /* Find a CCL program for a font specified by FONTP, and set the member
6334 `encoder' of the structure. */
6335
6336 void
6337 w32_find_ccl_program (fontp)
6338 struct font_info *fontp;
6339 {
6340 Lisp_Object list, elt;
6341
6342 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6343 {
6344 elt = XCAR (list);
6345 if (CONSP (elt)
6346 && STRINGP (XCAR (elt))
6347 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6348 >= 0))
6349 break;
6350 }
6351 if (! NILP (list))
6352 {
6353 struct ccl_program *ccl
6354 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6355
6356 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6357 xfree (ccl);
6358 else
6359 fontp->font_encoder = ccl;
6360 }
6361 }
6362
6363 \f
6364 /* Find BDF files in a specified directory. (use GCPRO when calling,
6365 as this calls lisp to get a directory listing). */
6366 static Lisp_Object
6367 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
6368 {
6369 Lisp_Object filelist, list = Qnil;
6370 char fontname[100];
6371
6372 if (!STRINGP(directory))
6373 return Qnil;
6374
6375 filelist = Fdirectory_files (directory, Qt,
6376 build_string (".*\\.[bB][dD][fF]"), Qt);
6377
6378 for ( ; CONSP(filelist); filelist = XCDR (filelist))
6379 {
6380 Lisp_Object filename = XCAR (filelist);
6381 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
6382 store_in_alist (&list, build_string (fontname), filename);
6383 }
6384 return list;
6385 }
6386
6387 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6388 1, 1, 0,
6389 doc: /* Return a list of BDF fonts in DIR.
6390 The list is suitable for appending to w32-bdf-filename-alist. Fonts
6391 which do not contain an xlfd description will not be included in the
6392 list. DIR may be a list of directories. */)
6393 (directory)
6394 Lisp_Object directory;
6395 {
6396 Lisp_Object list = Qnil;
6397 struct gcpro gcpro1, gcpro2;
6398
6399 if (!CONSP (directory))
6400 return w32_find_bdf_fonts_in_dir (directory);
6401
6402 for ( ; CONSP (directory); directory = XCDR (directory))
6403 {
6404 Lisp_Object pair[2];
6405 pair[0] = list;
6406 pair[1] = Qnil;
6407 GCPRO2 (directory, list);
6408 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
6409 list = Fnconc( 2, pair );
6410 UNGCPRO;
6411 }
6412 return list;
6413 }
6414
6415 \f
6416 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6417 doc: /* Internal function called by `color-defined-p', which see. */)
6418 (color, frame)
6419 Lisp_Object color, frame;
6420 {
6421 XColor foo;
6422 FRAME_PTR f = check_x_frame (frame);
6423
6424 CHECK_STRING (color);
6425
6426 if (w32_defined_color (f, SDATA (color), &foo, 0))
6427 return Qt;
6428 else
6429 return Qnil;
6430 }
6431
6432 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6433 doc: /* Internal function called by `color-values', which see. */)
6434 (color, frame)
6435 Lisp_Object color, frame;
6436 {
6437 XColor foo;
6438 FRAME_PTR f = check_x_frame (frame);
6439
6440 CHECK_STRING (color);
6441
6442 if (w32_defined_color (f, SDATA (color), &foo, 0))
6443 {
6444 Lisp_Object rgb[3];
6445
6446 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
6447 | GetRValue (foo.pixel));
6448 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
6449 | GetGValue (foo.pixel));
6450 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
6451 | GetBValue (foo.pixel));
6452 return Flist (3, rgb);
6453 }
6454 else
6455 return Qnil;
6456 }
6457
6458 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6459 doc: /* Internal function called by `display-color-p', which see. */)
6460 (display)
6461 Lisp_Object display;
6462 {
6463 struct w32_display_info *dpyinfo = check_x_display_info (display);
6464
6465 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6466 return Qnil;
6467
6468 return Qt;
6469 }
6470
6471 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6472 Sx_display_grayscale_p, 0, 1, 0,
6473 doc: /* Return t if the X display supports shades of gray.
6474 Note that color displays do support shades of gray.
6475 The optional argument DISPLAY specifies which display to ask about.
6476 DISPLAY should be either a frame or a display name (a string).
6477 If omitted or nil, that stands for the selected frame's display. */)
6478 (display)
6479 Lisp_Object display;
6480 {
6481 struct w32_display_info *dpyinfo = check_x_display_info (display);
6482
6483 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6484 return Qnil;
6485
6486 return Qt;
6487 }
6488
6489 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6490 Sx_display_pixel_width, 0, 1, 0,
6491 doc: /* Returns the width in pixels of DISPLAY.
6492 The optional argument DISPLAY specifies which display to ask about.
6493 DISPLAY should be either a frame or a display name (a string).
6494 If omitted or nil, that stands for the selected frame's display. */)
6495 (display)
6496 Lisp_Object display;
6497 {
6498 struct w32_display_info *dpyinfo = check_x_display_info (display);
6499
6500 return make_number (dpyinfo->width);
6501 }
6502
6503 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6504 Sx_display_pixel_height, 0, 1, 0,
6505 doc: /* Returns the height in pixels of DISPLAY.
6506 The optional argument DISPLAY specifies which display to ask about.
6507 DISPLAY should be either a frame or a display name (a string).
6508 If omitted or nil, that stands for the selected frame's display. */)
6509 (display)
6510 Lisp_Object display;
6511 {
6512 struct w32_display_info *dpyinfo = check_x_display_info (display);
6513
6514 return make_number (dpyinfo->height);
6515 }
6516
6517 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6518 0, 1, 0,
6519 doc: /* Returns the number of bitplanes of DISPLAY.
6520 The optional argument DISPLAY specifies which display to ask about.
6521 DISPLAY should be either a frame or a display name (a string).
6522 If omitted or nil, that stands for the selected frame's display. */)
6523 (display)
6524 Lisp_Object display;
6525 {
6526 struct w32_display_info *dpyinfo = check_x_display_info (display);
6527
6528 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6529 }
6530
6531 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6532 0, 1, 0,
6533 doc: /* Returns the number of color cells of DISPLAY.
6534 The optional argument DISPLAY specifies which display to ask about.
6535 DISPLAY should be either a frame or a display name (a string).
6536 If omitted or nil, that stands for the selected frame's display. */)
6537 (display)
6538 Lisp_Object display;
6539 {
6540 struct w32_display_info *dpyinfo = check_x_display_info (display);
6541 HDC hdc;
6542 int cap;
6543
6544 hdc = GetDC (dpyinfo->root_window);
6545 if (dpyinfo->has_palette)
6546 cap = GetDeviceCaps (hdc,SIZEPALETTE);
6547 else
6548 cap = GetDeviceCaps (hdc,NUMCOLORS);
6549
6550 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
6551 and because probably is more meaningful on Windows anyway */
6552 if (cap < 0)
6553 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
6554
6555 ReleaseDC (dpyinfo->root_window, hdc);
6556
6557 return make_number (cap);
6558 }
6559
6560 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6561 Sx_server_max_request_size,
6562 0, 1, 0,
6563 doc: /* Returns the maximum request size of the server of DISPLAY.
6564 The optional argument DISPLAY specifies which display to ask about.
6565 DISPLAY should be either a frame or a display name (a string).
6566 If omitted or nil, that stands for the selected frame's display. */)
6567 (display)
6568 Lisp_Object display;
6569 {
6570 struct w32_display_info *dpyinfo = check_x_display_info (display);
6571
6572 return make_number (1);
6573 }
6574
6575 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6576 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
6577 The optional argument DISPLAY specifies which display to ask about.
6578 DISPLAY should be either a frame or a display name (a string).
6579 If omitted or nil, that stands for the selected frame's display. */)
6580 (display)
6581 Lisp_Object display;
6582 {
6583 return build_string ("Microsoft Corp.");
6584 }
6585
6586 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6587 doc: /* Returns the version numbers of the server of DISPLAY.
6588 The value is a list of three integers: the major and minor
6589 version numbers, and the vendor-specific release
6590 number. See also the function `x-server-vendor'.
6591
6592 The optional argument DISPLAY specifies which display to ask about.
6593 DISPLAY should be either a frame or a display name (a string).
6594 If omitted or nil, that stands for the selected frame's display. */)
6595 (display)
6596 Lisp_Object display;
6597 {
6598 return Fcons (make_number (w32_major_version),
6599 Fcons (make_number (w32_minor_version),
6600 Fcons (make_number (w32_build_number), Qnil)));
6601 }
6602
6603 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6604 doc: /* Returns the number of screens on the server of DISPLAY.
6605 The optional argument DISPLAY specifies which display to ask about.
6606 DISPLAY should be either a frame or a display name (a string).
6607 If omitted or nil, that stands for the selected frame's display. */)
6608 (display)
6609 Lisp_Object display;
6610 {
6611 return make_number (1);
6612 }
6613
6614 DEFUN ("x-display-mm-height", Fx_display_mm_height,
6615 Sx_display_mm_height, 0, 1, 0,
6616 doc: /* Returns the height in millimeters of DISPLAY.
6617 The optional argument DISPLAY specifies which display to ask about.
6618 DISPLAY should be either a frame or a display name (a string).
6619 If omitted or nil, that stands for the selected frame's display. */)
6620 (display)
6621 Lisp_Object display;
6622 {
6623 struct w32_display_info *dpyinfo = check_x_display_info (display);
6624 HDC hdc;
6625 int cap;
6626
6627 hdc = GetDC (dpyinfo->root_window);
6628
6629 cap = GetDeviceCaps (hdc, VERTSIZE);
6630
6631 ReleaseDC (dpyinfo->root_window, hdc);
6632
6633 return make_number (cap);
6634 }
6635
6636 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6637 doc: /* Returns the width in millimeters of DISPLAY.
6638 The optional argument DISPLAY specifies which display to ask about.
6639 DISPLAY should be either a frame or a display name (a string).
6640 If omitted or nil, that stands for the selected frame's display. */)
6641 (display)
6642 Lisp_Object display;
6643 {
6644 struct w32_display_info *dpyinfo = check_x_display_info (display);
6645
6646 HDC hdc;
6647 int cap;
6648
6649 hdc = GetDC (dpyinfo->root_window);
6650
6651 cap = GetDeviceCaps (hdc, HORZSIZE);
6652
6653 ReleaseDC (dpyinfo->root_window, hdc);
6654
6655 return make_number (cap);
6656 }
6657
6658 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6659 Sx_display_backing_store, 0, 1, 0,
6660 doc: /* Returns an indication of whether DISPLAY does backing store.
6661 The value may be `always', `when-mapped', or `not-useful'.
6662 The optional argument DISPLAY specifies which display to ask about.
6663 DISPLAY should be either a frame or a display name (a string).
6664 If omitted or nil, that stands for the selected frame's display. */)
6665 (display)
6666 Lisp_Object display;
6667 {
6668 return intern ("not-useful");
6669 }
6670
6671 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6672 Sx_display_visual_class, 0, 1, 0,
6673 doc: /* Returns the visual class of DISPLAY.
6674 The value is one of the symbols `static-gray', `gray-scale',
6675 `static-color', `pseudo-color', `true-color', or `direct-color'.
6676
6677 The optional argument DISPLAY specifies which display to ask about.
6678 DISPLAY should be either a frame or a display name (a string).
6679 If omitted or nil, that stands for the selected frame's display. */)
6680 (display)
6681 Lisp_Object display;
6682 {
6683 struct w32_display_info *dpyinfo = check_x_display_info (display);
6684 Lisp_Object result = Qnil;
6685
6686 if (dpyinfo->has_palette)
6687 result = intern ("pseudo-color");
6688 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6689 result = intern ("static-grey");
6690 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6691 result = intern ("static-color");
6692 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6693 result = intern ("true-color");
6694
6695 return result;
6696 }
6697
6698 DEFUN ("x-display-save-under", Fx_display_save_under,
6699 Sx_display_save_under, 0, 1, 0,
6700 doc: /* Returns t if DISPLAY supports the save-under feature.
6701 The optional argument DISPLAY specifies which display to ask about.
6702 DISPLAY should be either a frame or a display name (a string).
6703 If omitted or nil, that stands for the selected frame's display. */)
6704 (display)
6705 Lisp_Object display;
6706 {
6707 return Qnil;
6708 }
6709 \f
6710 int
6711 x_pixel_width (f)
6712 register struct frame *f;
6713 {
6714 return FRAME_PIXEL_WIDTH (f);
6715 }
6716
6717 int
6718 x_pixel_height (f)
6719 register struct frame *f;
6720 {
6721 return FRAME_PIXEL_HEIGHT (f);
6722 }
6723
6724 int
6725 x_char_width (f)
6726 register struct frame *f;
6727 {
6728 return FRAME_COLUMN_WIDTH (f);
6729 }
6730
6731 int
6732 x_char_height (f)
6733 register struct frame *f;
6734 {
6735 return FRAME_LINE_HEIGHT (f);
6736 }
6737
6738 int
6739 x_screen_planes (f)
6740 register struct frame *f;
6741 {
6742 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
6743 }
6744 \f
6745 /* Return the display structure for the display named NAME.
6746 Open a new connection if necessary. */
6747
6748 struct w32_display_info *
6749 x_display_info_for_name (name)
6750 Lisp_Object name;
6751 {
6752 Lisp_Object names;
6753 struct w32_display_info *dpyinfo;
6754
6755 CHECK_STRING (name);
6756
6757 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
6758 dpyinfo;
6759 dpyinfo = dpyinfo->next, names = XCDR (names))
6760 {
6761 Lisp_Object tem;
6762 tem = Fstring_equal (XCAR (XCAR (names)), name);
6763 if (!NILP (tem))
6764 return dpyinfo;
6765 }
6766
6767 /* Use this general default value to start with. */
6768 Vx_resource_name = Vinvocation_name;
6769
6770 validate_x_resource_name ();
6771
6772 dpyinfo = w32_term_init (name, (unsigned char *)0,
6773 (char *) SDATA (Vx_resource_name));
6774
6775 if (dpyinfo == 0)
6776 error ("Cannot connect to server %s", SDATA (name));
6777
6778 w32_in_use = 1;
6779 XSETFASTINT (Vwindow_system_version, 3);
6780
6781 return dpyinfo;
6782 }
6783
6784 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6785 1, 3, 0, doc: /* Open a connection to a server.
6786 DISPLAY is the name of the display to connect to.
6787 Optional second arg XRM-STRING is a string of resources in xrdb format.
6788 If the optional third arg MUST-SUCCEED is non-nil,
6789 terminate Emacs if we can't open the connection. */)
6790 (display, xrm_string, must_succeed)
6791 Lisp_Object display, xrm_string, must_succeed;
6792 {
6793 unsigned char *xrm_option;
6794 struct w32_display_info *dpyinfo;
6795
6796 /* If initialization has already been done, return now to avoid
6797 overwriting critical parts of one_w32_display_info. */
6798 if (w32_in_use)
6799 return Qnil;
6800
6801 CHECK_STRING (display);
6802 if (! NILP (xrm_string))
6803 CHECK_STRING (xrm_string);
6804
6805 if (! EQ (Vwindow_system, intern ("w32")))
6806 error ("Not using Microsoft Windows");
6807
6808 /* Allow color mapping to be defined externally; first look in user's
6809 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6810 {
6811 Lisp_Object color_file;
6812 struct gcpro gcpro1;
6813
6814 color_file = build_string("~/rgb.txt");
6815
6816 GCPRO1 (color_file);
6817
6818 if (NILP (Ffile_readable_p (color_file)))
6819 color_file =
6820 Fexpand_file_name (build_string ("rgb.txt"),
6821 Fsymbol_value (intern ("data-directory")));
6822
6823 Vw32_color_map = Fw32_load_color_file (color_file);
6824
6825 UNGCPRO;
6826 }
6827 if (NILP (Vw32_color_map))
6828 Vw32_color_map = Fw32_default_color_map ();
6829
6830 /* Merge in system logical colors. */
6831 add_system_logical_colors_to_map (&Vw32_color_map);
6832
6833 if (! NILP (xrm_string))
6834 xrm_option = (unsigned char *) SDATA (xrm_string);
6835 else
6836 xrm_option = (unsigned char *) 0;
6837
6838 /* Use this general default value to start with. */
6839 /* First remove .exe suffix from invocation-name - it looks ugly. */
6840 {
6841 char basename[ MAX_PATH ], *str;
6842
6843 strcpy (basename, SDATA (Vinvocation_name));
6844 str = strrchr (basename, '.');
6845 if (str) *str = 0;
6846 Vinvocation_name = build_string (basename);
6847 }
6848 Vx_resource_name = Vinvocation_name;
6849
6850 validate_x_resource_name ();
6851
6852 /* This is what opens the connection and sets x_current_display.
6853 This also initializes many symbols, such as those used for input. */
6854 dpyinfo = w32_term_init (display, xrm_option,
6855 (char *) SDATA (Vx_resource_name));
6856
6857 if (dpyinfo == 0)
6858 {
6859 if (!NILP (must_succeed))
6860 fatal ("Cannot connect to server %s.\n",
6861 SDATA (display));
6862 else
6863 error ("Cannot connect to server %s", SDATA (display));
6864 }
6865
6866 w32_in_use = 1;
6867
6868 XSETFASTINT (Vwindow_system_version, 3);
6869 return Qnil;
6870 }
6871
6872 DEFUN ("x-close-connection", Fx_close_connection,
6873 Sx_close_connection, 1, 1, 0,
6874 doc: /* Close the connection to DISPLAY's server.
6875 For DISPLAY, specify either a frame or a display name (a string).
6876 If DISPLAY is nil, that stands for the selected frame's display. */)
6877 (display)
6878 Lisp_Object display;
6879 {
6880 struct w32_display_info *dpyinfo = check_x_display_info (display);
6881 int i;
6882
6883 if (dpyinfo->reference_count > 0)
6884 error ("Display still has frames on it");
6885
6886 BLOCK_INPUT;
6887 /* Free the fonts in the font table. */
6888 for (i = 0; i < dpyinfo->n_fonts; i++)
6889 if (dpyinfo->font_table[i].name)
6890 {
6891 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
6892 xfree (dpyinfo->font_table[i].full_name);
6893 xfree (dpyinfo->font_table[i].name);
6894 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
6895 }
6896 x_destroy_all_bitmaps (dpyinfo);
6897
6898 x_delete_display (dpyinfo);
6899 UNBLOCK_INPUT;
6900
6901 return Qnil;
6902 }
6903
6904 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6905 doc: /* Return the list of display names that Emacs has connections to. */)
6906 ()
6907 {
6908 Lisp_Object tail, result;
6909
6910 result = Qnil;
6911 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
6912 result = Fcons (XCAR (XCAR (tail)), result);
6913
6914 return result;
6915 }
6916
6917 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6918 doc: /* This is a noop on W32 systems. */)
6919 (on, display)
6920 Lisp_Object display, on;
6921 {
6922 return Qnil;
6923 }
6924
6925 \f
6926 /***********************************************************************
6927 Image types
6928 ***********************************************************************/
6929
6930 /* Value is the number of elements of vector VECTOR. */
6931
6932 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
6933
6934 /* List of supported image types. Use define_image_type to add new
6935 types. Use lookup_image_type to find a type for a given symbol. */
6936
6937 static struct image_type *image_types;
6938
6939 /* The symbol `image' which is the car of the lists used to represent
6940 images in Lisp. */
6941
6942 extern Lisp_Object Qimage;
6943
6944 /* The symbol `xbm' which is used as the type symbol for XBM images. */
6945
6946 Lisp_Object Qxbm;
6947
6948 /* Keywords. */
6949
6950 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
6951 extern Lisp_Object QCdata, QCtype;
6952 Lisp_Object QCascent, QCmargin, QCrelief;
6953 Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
6954 Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
6955
6956 /* Other symbols. */
6957
6958 Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
6959
6960 /* Time in seconds after which images should be removed from the cache
6961 if not displayed. */
6962
6963 Lisp_Object Vimage_cache_eviction_delay;
6964
6965 /* Function prototypes. */
6966
6967 static void define_image_type P_ ((struct image_type *type));
6968 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
6969 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
6970 static void x_laplace P_ ((struct frame *, struct image *));
6971 static void x_emboss P_ ((struct frame *, struct image *));
6972 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
6973 Lisp_Object));
6974
6975
6976 /* Define a new image type from TYPE. This adds a copy of TYPE to
6977 image_types and adds the symbol *TYPE->type to Vimage_types. */
6978
6979 static void
6980 define_image_type (type)
6981 struct image_type *type;
6982 {
6983 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
6984 The initialized data segment is read-only. */
6985 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
6986 bcopy (type, p, sizeof *p);
6987 p->next = image_types;
6988 image_types = p;
6989 Vimage_types = Fcons (*p->type, Vimage_types);
6990 }
6991
6992
6993 /* Look up image type SYMBOL, and return a pointer to its image_type
6994 structure. Value is null if SYMBOL is not a known image type. */
6995
6996 static INLINE struct image_type *
6997 lookup_image_type (symbol)
6998 Lisp_Object symbol;
6999 {
7000 struct image_type *type;
7001
7002 for (type = image_types; type; type = type->next)
7003 if (EQ (symbol, *type->type))
7004 break;
7005
7006 return type;
7007 }
7008
7009
7010 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
7011 valid image specification is a list whose car is the symbol
7012 `image', and whose rest is a property list. The property list must
7013 contain a value for key `:type'. That value must be the name of a
7014 supported image type. The rest of the property list depends on the
7015 image type. */
7016
7017 int
7018 valid_image_p (object)
7019 Lisp_Object object;
7020 {
7021 int valid_p = 0;
7022
7023 if (CONSP (object) && EQ (XCAR (object), Qimage))
7024 {
7025 Lisp_Object tem;
7026
7027 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
7028 if (EQ (XCAR (tem), QCtype))
7029 {
7030 tem = XCDR (tem);
7031 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
7032 {
7033 struct image_type *type;
7034 type = lookup_image_type (XCAR (tem));
7035 if (type)
7036 valid_p = type->valid_p (object);
7037 }
7038
7039 break;
7040 }
7041 }
7042
7043 return valid_p;
7044 }
7045
7046
7047 /* Log error message with format string FORMAT and argument ARG.
7048 Signaling an error, e.g. when an image cannot be loaded, is not a
7049 good idea because this would interrupt redisplay, and the error
7050 message display would lead to another redisplay. This function
7051 therefore simply displays a message. */
7052
7053 static void
7054 image_error (format, arg1, arg2)
7055 char *format;
7056 Lisp_Object arg1, arg2;
7057 {
7058 add_to_log (format, arg1, arg2);
7059 }
7060
7061
7062 \f
7063 /***********************************************************************
7064 Image specifications
7065 ***********************************************************************/
7066
7067 enum image_value_type
7068 {
7069 IMAGE_DONT_CHECK_VALUE_TYPE,
7070 IMAGE_STRING_VALUE,
7071 IMAGE_STRING_OR_NIL_VALUE,
7072 IMAGE_SYMBOL_VALUE,
7073 IMAGE_POSITIVE_INTEGER_VALUE,
7074 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
7075 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
7076 IMAGE_ASCENT_VALUE,
7077 IMAGE_INTEGER_VALUE,
7078 IMAGE_FUNCTION_VALUE,
7079 IMAGE_NUMBER_VALUE,
7080 IMAGE_BOOL_VALUE
7081 };
7082
7083 /* Structure used when parsing image specifications. */
7084
7085 struct image_keyword
7086 {
7087 /* Name of keyword. */
7088 char *name;
7089
7090 /* The type of value allowed. */
7091 enum image_value_type type;
7092
7093 /* Non-zero means key must be present. */
7094 int mandatory_p;
7095
7096 /* Used to recognize duplicate keywords in a property list. */
7097 int count;
7098
7099 /* The value that was found. */
7100 Lisp_Object value;
7101 };
7102
7103
7104 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7105 int, Lisp_Object));
7106 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7107
7108
7109 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
7110 has the format (image KEYWORD VALUE ...). One of the keyword/
7111 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7112 image_keywords structures of size NKEYWORDS describing other
7113 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7114
7115 static int
7116 parse_image_spec (spec, keywords, nkeywords, type)
7117 Lisp_Object spec;
7118 struct image_keyword *keywords;
7119 int nkeywords;
7120 Lisp_Object type;
7121 {
7122 int i;
7123 Lisp_Object plist;
7124
7125 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7126 return 0;
7127
7128 plist = XCDR (spec);
7129 while (CONSP (plist))
7130 {
7131 Lisp_Object key, value;
7132
7133 /* First element of a pair must be a symbol. */
7134 key = XCAR (plist);
7135 plist = XCDR (plist);
7136 if (!SYMBOLP (key))
7137 return 0;
7138
7139 /* There must follow a value. */
7140 if (!CONSP (plist))
7141 return 0;
7142 value = XCAR (plist);
7143 plist = XCDR (plist);
7144
7145 /* Find key in KEYWORDS. Error if not found. */
7146 for (i = 0; i < nkeywords; ++i)
7147 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
7148 break;
7149
7150 if (i == nkeywords)
7151 continue;
7152
7153 /* Record that we recognized the keyword. If a keywords
7154 was found more than once, it's an error. */
7155 keywords[i].value = value;
7156 ++keywords[i].count;
7157
7158 if (keywords[i].count > 1)
7159 return 0;
7160
7161 /* Check type of value against allowed type. */
7162 switch (keywords[i].type)
7163 {
7164 case IMAGE_STRING_VALUE:
7165 if (!STRINGP (value))
7166 return 0;
7167 break;
7168
7169 case IMAGE_STRING_OR_NIL_VALUE:
7170 if (!STRINGP (value) && !NILP (value))
7171 return 0;
7172 break;
7173
7174 case IMAGE_SYMBOL_VALUE:
7175 if (!SYMBOLP (value))
7176 return 0;
7177 break;
7178
7179 case IMAGE_POSITIVE_INTEGER_VALUE:
7180 if (!INTEGERP (value) || XINT (value) <= 0)
7181 return 0;
7182 break;
7183
7184 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
7185 if (INTEGERP (value) && XINT (value) >= 0)
7186 break;
7187 if (CONSP (value)
7188 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
7189 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
7190 break;
7191 return 0;
7192
7193 case IMAGE_ASCENT_VALUE:
7194 if (SYMBOLP (value) && EQ (value, Qcenter))
7195 break;
7196 else if (INTEGERP (value)
7197 && XINT (value) >= 0
7198 && XINT (value) <= 100)
7199 break;
7200 return 0;
7201
7202 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7203 if (!INTEGERP (value) || XINT (value) < 0)
7204 return 0;
7205 break;
7206
7207 case IMAGE_DONT_CHECK_VALUE_TYPE:
7208 break;
7209
7210 case IMAGE_FUNCTION_VALUE:
7211 value = indirect_function (value);
7212 if (SUBRP (value)
7213 || COMPILEDP (value)
7214 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7215 break;
7216 return 0;
7217
7218 case IMAGE_NUMBER_VALUE:
7219 if (!INTEGERP (value) && !FLOATP (value))
7220 return 0;
7221 break;
7222
7223 case IMAGE_INTEGER_VALUE:
7224 if (!INTEGERP (value))
7225 return 0;
7226 break;
7227
7228 case IMAGE_BOOL_VALUE:
7229 if (!NILP (value) && !EQ (value, Qt))
7230 return 0;
7231 break;
7232
7233 default:
7234 abort ();
7235 break;
7236 }
7237
7238 if (EQ (key, QCtype) && !EQ (type, value))
7239 return 0;
7240 }
7241
7242 /* Check that all mandatory fields are present. */
7243 for (i = 0; i < nkeywords; ++i)
7244 if (keywords[i].mandatory_p && keywords[i].count == 0)
7245 return 0;
7246
7247 return NILP (plist);
7248 }
7249
7250
7251 /* Return the value of KEY in image specification SPEC. Value is nil
7252 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7253 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7254
7255 static Lisp_Object
7256 image_spec_value (spec, key, found)
7257 Lisp_Object spec, key;
7258 int *found;
7259 {
7260 Lisp_Object tail;
7261
7262 xassert (valid_image_p (spec));
7263
7264 for (tail = XCDR (spec);
7265 CONSP (tail) && CONSP (XCDR (tail));
7266 tail = XCDR (XCDR (tail)))
7267 {
7268 if (EQ (XCAR (tail), key))
7269 {
7270 if (found)
7271 *found = 1;
7272 return XCAR (XCDR (tail));
7273 }
7274 }
7275
7276 if (found)
7277 *found = 0;
7278 return Qnil;
7279 }
7280
7281
7282 DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
7283 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
7284 PIXELS non-nil means return the size in pixels, otherwise return the
7285 size in canonical character units.
7286 FRAME is the frame on which the image will be displayed. FRAME nil
7287 or omitted means use the selected frame. */)
7288 (spec, pixels, frame)
7289 Lisp_Object spec, pixels, frame;
7290 {
7291 Lisp_Object size;
7292
7293 size = Qnil;
7294 if (valid_image_p (spec))
7295 {
7296 struct frame *f = check_x_frame (frame);
7297 int id = lookup_image (f, spec);
7298 struct image *img = IMAGE_FROM_ID (f, id);
7299 int width = img->width + 2 * img->hmargin;
7300 int height = img->height + 2 * img->vmargin;
7301
7302 if (NILP (pixels))
7303 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
7304 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
7305 else
7306 size = Fcons (make_number (width), make_number (height));
7307 }
7308 else
7309 error ("Invalid image specification");
7310
7311 return size;
7312 }
7313
7314
7315 DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
7316 doc: /* Return t if image SPEC has a mask bitmap.
7317 FRAME is the frame on which the image will be displayed. FRAME nil
7318 or omitted means use the selected frame. */)
7319 (spec, frame)
7320 Lisp_Object spec, frame;
7321 {
7322 Lisp_Object mask;
7323
7324 mask = Qnil;
7325 if (valid_image_p (spec))
7326 {
7327 struct frame *f = check_x_frame (frame);
7328 int id = lookup_image (f, spec);
7329 struct image *img = IMAGE_FROM_ID (f, id);
7330 if (img->mask)
7331 mask = Qt;
7332 }
7333 else
7334 error ("Invalid image specification");
7335
7336 return mask;
7337 }
7338
7339 \f
7340 /***********************************************************************
7341 Image type independent image structures
7342 ***********************************************************************/
7343
7344 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7345 static void free_image P_ ((struct frame *f, struct image *img));
7346 static void x_destroy_x_image P_ ((XImage *));
7347
7348
7349 /* Allocate and return a new image structure for image specification
7350 SPEC. SPEC has a hash value of HASH. */
7351
7352 static struct image *
7353 make_image (spec, hash)
7354 Lisp_Object spec;
7355 unsigned hash;
7356 {
7357 struct image *img = (struct image *) xmalloc (sizeof *img);
7358
7359 xassert (valid_image_p (spec));
7360 bzero (img, sizeof *img);
7361 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7362 xassert (img->type != NULL);
7363 img->spec = spec;
7364 img->data.lisp_val = Qnil;
7365 img->ascent = DEFAULT_IMAGE_ASCENT;
7366 img->hash = hash;
7367 return img;
7368 }
7369
7370
7371 /* Free image IMG which was used on frame F, including its resources. */
7372
7373 static void
7374 free_image (f, img)
7375 struct frame *f;
7376 struct image *img;
7377 {
7378 if (img)
7379 {
7380 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7381
7382 /* Remove IMG from the hash table of its cache. */
7383 if (img->prev)
7384 img->prev->next = img->next;
7385 else
7386 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7387
7388 if (img->next)
7389 img->next->prev = img->prev;
7390
7391 c->images[img->id] = NULL;
7392
7393 /* Free resources, then free IMG. */
7394 img->type->free (f, img);
7395 xfree (img);
7396 }
7397 }
7398
7399
7400 /* Prepare image IMG for display on frame F. Must be called before
7401 drawing an image. */
7402
7403 void
7404 prepare_image_for_display (f, img)
7405 struct frame *f;
7406 struct image *img;
7407 {
7408 EMACS_TIME t;
7409
7410 /* We're about to display IMG, so set its timestamp to `now'. */
7411 EMACS_GET_TIME (t);
7412 img->timestamp = EMACS_SECS (t);
7413
7414 /* If IMG doesn't have a pixmap yet, load it now, using the image
7415 type dependent loader function. */
7416 if (img->pixmap == 0 && !img->load_failed_p)
7417 img->load_failed_p = img->type->load (f, img) == 0;
7418 }
7419
7420
7421 /* Value is the number of pixels for the ascent of image IMG when
7422 drawn in face FACE. */
7423
7424 int
7425 image_ascent (img, face)
7426 struct image *img;
7427 struct face *face;
7428 {
7429 int height = img->height + img->vmargin;
7430 int ascent;
7431
7432 if (img->ascent == CENTERED_IMAGE_ASCENT)
7433 {
7434 if (face->font)
7435 ascent = height / 2 - (FONT_DESCENT(face->font)
7436 - FONT_BASE(face->font)) / 2;
7437 else
7438 ascent = height / 2;
7439 }
7440 else
7441 ascent = (int) (height * img->ascent / 100.0);
7442
7443 return ascent;
7444 }
7445
7446
7447 \f
7448 /* Image background colors. */
7449
7450 /* Find the "best" corner color of a bitmap. XIMG is assumed to a device
7451 context with the bitmap selected. */
7452 static COLORREF
7453 four_corners_best (img_dc, width, height)
7454 HDC img_dc;
7455 unsigned long width, height;
7456 {
7457 COLORREF corners[4], best;
7458 int i, best_count;
7459
7460 /* Get the colors at the corners of img_dc. */
7461 corners[0] = GetPixel (img_dc, 0, 0);
7462 corners[1] = GetPixel (img_dc, width - 1, 0);
7463 corners[2] = GetPixel (img_dc, width - 1, height - 1);
7464 corners[3] = GetPixel (img_dc, 0, height - 1);
7465
7466 /* Choose the most frequently found color as background. */
7467 for (i = best_count = 0; i < 4; ++i)
7468 {
7469 int j, n;
7470
7471 for (j = n = 0; j < 4; ++j)
7472 if (corners[i] == corners[j])
7473 ++n;
7474
7475 if (n > best_count)
7476 best = corners[i], best_count = n;
7477 }
7478
7479 return best;
7480 }
7481
7482 /* Return the `background' field of IMG. If IMG doesn't have one yet,
7483 it is guessed heuristically. If non-zero, IMG_DC is an existing
7484 device context with the image selected to use for the heuristic. */
7485
7486 unsigned long
7487 image_background (img, f, img_dc)
7488 struct image *img;
7489 struct frame *f;
7490 HDC img_dc;
7491 {
7492 if (! img->background_valid)
7493 /* IMG doesn't have a background yet, try to guess a reasonable value. */
7494 {
7495 int free_ximg = !img_dc;
7496 HGDIOBJ prev;
7497
7498 if (free_ximg)
7499 {
7500 HDC frame_dc = get_frame_dc (f);
7501 img_dc = CreateCompatibleDC (frame_dc);
7502 release_frame_dc (f, frame_dc);
7503
7504 prev = SelectObject (img_dc, img->pixmap);
7505 }
7506
7507 img->background = four_corners_best (img_dc, img->width, img->height);
7508
7509 if (free_ximg)
7510 {
7511 SelectObject (img_dc, prev);
7512 DeleteDC (img_dc);
7513 }
7514
7515 img->background_valid = 1;
7516 }
7517
7518 return img->background;
7519 }
7520
7521 /* Return the `background_transparent' field of IMG. If IMG doesn't
7522 have one yet, it is guessed heuristically. If non-zero, MASK is an
7523 existing XImage object to use for the heuristic. */
7524
7525 int
7526 image_background_transparent (img, f, mask)
7527 struct image *img;
7528 struct frame *f;
7529 HDC mask;
7530 {
7531 if (! img->background_transparent_valid)
7532 /* IMG doesn't have a background yet, try to guess a reasonable value. */
7533 {
7534 if (img->mask)
7535 {
7536 int free_mask = !mask;
7537 HGDIOBJ prev;
7538
7539 if (free_mask)
7540 {
7541 HDC frame_dc = get_frame_dc (f);
7542 mask = CreateCompatibleDC (frame_dc);
7543 release_frame_dc (f, frame_dc);
7544
7545 prev = SelectObject (mask, img->mask);
7546 }
7547
7548 img->background_transparent
7549 = !four_corners_best (mask, img->width, img->height);
7550
7551 if (free_mask)
7552 {
7553 SelectObject (mask, prev);
7554 DeleteDC (mask);
7555 }
7556 }
7557 else
7558 img->background_transparent = 0;
7559
7560 img->background_transparent_valid = 1;
7561 }
7562
7563 return img->background_transparent;
7564 }
7565
7566 \f
7567 /***********************************************************************
7568 Helper functions for X image types
7569 ***********************************************************************/
7570
7571 static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
7572 int, int));
7573 static void x_clear_image P_ ((struct frame *f, struct image *img));
7574 static unsigned long x_alloc_image_color P_ ((struct frame *f,
7575 struct image *img,
7576 Lisp_Object color_name,
7577 unsigned long dflt));
7578
7579
7580 /* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
7581 free the pixmap if any. MASK_P non-zero means clear the mask
7582 pixmap if any. COLORS_P non-zero means free colors allocated for
7583 the image, if any. */
7584
7585 static void
7586 x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
7587 struct frame *f;
7588 struct image *img;
7589 int pixmap_p, mask_p, colors_p;
7590 {
7591 if (pixmap_p && img->pixmap)
7592 {
7593 DeleteObject (img->pixmap);
7594 img->pixmap = NULL;
7595 img->background_valid = 0;
7596 }
7597
7598 if (mask_p && img->mask)
7599 {
7600 DeleteObject (img->mask);
7601 img->mask = NULL;
7602 img->background_transparent_valid = 0;
7603 }
7604
7605 if (colors_p && img->ncolors)
7606 {
7607 #if 0 /* TODO: color table support. */
7608 x_free_colors (f, img->colors, img->ncolors);
7609 #endif
7610 xfree (img->colors);
7611 img->colors = NULL;
7612 img->ncolors = 0;
7613 }
7614 }
7615
7616 /* Free X resources of image IMG which is used on frame F. */
7617
7618 static void
7619 x_clear_image (f, img)
7620 struct frame *f;
7621 struct image *img;
7622 {
7623 if (img->pixmap)
7624 {
7625 BLOCK_INPUT;
7626 DeleteObject (img->pixmap);
7627 img->pixmap = 0;
7628 UNBLOCK_INPUT;
7629 }
7630
7631 if (img->ncolors)
7632 {
7633 #if 0 /* TODO: color table support */
7634
7635 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
7636
7637 /* If display has an immutable color map, freeing colors is not
7638 necessary and some servers don't allow it. So don't do it. */
7639 if (class != StaticColor
7640 && class != StaticGray
7641 && class != TrueColor)
7642 {
7643 Colormap cmap;
7644 BLOCK_INPUT;
7645 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
7646 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
7647 img->ncolors, 0);
7648 UNBLOCK_INPUT;
7649 }
7650 #endif
7651
7652 xfree (img->colors);
7653 img->colors = NULL;
7654 img->ncolors = 0;
7655 }
7656 }
7657
7658
7659 /* Allocate color COLOR_NAME for image IMG on frame F. If color
7660 cannot be allocated, use DFLT. Add a newly allocated color to
7661 IMG->colors, so that it can be freed again. Value is the pixel
7662 color. */
7663
7664 static unsigned long
7665 x_alloc_image_color (f, img, color_name, dflt)
7666 struct frame *f;
7667 struct image *img;
7668 Lisp_Object color_name;
7669 unsigned long dflt;
7670 {
7671 XColor color;
7672 unsigned long result;
7673
7674 xassert (STRINGP (color_name));
7675
7676 if (w32_defined_color (f, SDATA (color_name), &color, 1))
7677 {
7678 /* This isn't called frequently so we get away with simply
7679 reallocating the color vector to the needed size, here. */
7680 ++img->ncolors;
7681 img->colors =
7682 (unsigned long *) xrealloc (img->colors,
7683 img->ncolors * sizeof *img->colors);
7684 img->colors[img->ncolors - 1] = color.pixel;
7685 result = color.pixel;
7686 }
7687 else
7688 result = dflt;
7689 return result;
7690 }
7691
7692
7693 \f
7694 /***********************************************************************
7695 Image Cache
7696 ***********************************************************************/
7697
7698 static void cache_image P_ ((struct frame *f, struct image *img));
7699 static void postprocess_image P_ ((struct frame *, struct image *));
7700 static void x_disable_image P_ ((struct frame *, struct image *));
7701
7702
7703 /* Return a new, initialized image cache that is allocated from the
7704 heap. Call free_image_cache to free an image cache. */
7705
7706 struct image_cache *
7707 make_image_cache ()
7708 {
7709 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
7710 int size;
7711
7712 bzero (c, sizeof *c);
7713 c->size = 50;
7714 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
7715 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
7716 c->buckets = (struct image **) xmalloc (size);
7717 bzero (c->buckets, size);
7718 return c;
7719 }
7720
7721
7722 /* Free image cache of frame F. Be aware that X frames share images
7723 caches. */
7724
7725 void
7726 free_image_cache (f)
7727 struct frame *f;
7728 {
7729 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7730 if (c)
7731 {
7732 int i;
7733
7734 /* Cache should not be referenced by any frame when freed. */
7735 xassert (c->refcount == 0);
7736
7737 for (i = 0; i < c->used; ++i)
7738 free_image (f, c->images[i]);
7739 xfree (c->images);
7740 xfree (c);
7741 xfree (c->buckets);
7742 FRAME_X_IMAGE_CACHE (f) = NULL;
7743 }
7744 }
7745
7746
7747 /* Clear image cache of frame F. FORCE_P non-zero means free all
7748 images. FORCE_P zero means clear only images that haven't been
7749 displayed for some time. Should be called from time to time to
7750 reduce the number of loaded images. If image-eviction-seconds is
7751 non-nil, this frees images in the cache which weren't displayed for
7752 at least that many seconds. */
7753
7754 void
7755 clear_image_cache (f, force_p)
7756 struct frame *f;
7757 int force_p;
7758 {
7759 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7760
7761 if (c && INTEGERP (Vimage_cache_eviction_delay))
7762 {
7763 EMACS_TIME t;
7764 unsigned long old;
7765 int i, nfreed;
7766
7767 EMACS_GET_TIME (t);
7768 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
7769
7770 /* Block input so that we won't be interrupted by a SIGIO
7771 while being in an inconsistent state. */
7772 BLOCK_INPUT;
7773
7774 for (i = nfreed = 0; i < c->used; ++i)
7775 {
7776 struct image *img = c->images[i];
7777 if (img != NULL
7778 && (force_p || (img->timestamp < old)))
7779 {
7780 free_image (f, img);
7781 ++nfreed;
7782 }
7783 }
7784
7785 /* We may be clearing the image cache because, for example,
7786 Emacs was iconified for a longer period of time. In that
7787 case, current matrices may still contain references to
7788 images freed above. So, clear these matrices. */
7789 if (nfreed)
7790 {
7791 Lisp_Object tail, frame;
7792
7793 FOR_EACH_FRAME (tail, frame)
7794 {
7795 struct frame *f = XFRAME (frame);
7796 if (FRAME_W32_P (f)
7797 && FRAME_X_IMAGE_CACHE (f) == c)
7798 clear_current_matrices (f);
7799 }
7800
7801 ++windows_or_buffers_changed;
7802 }
7803
7804 UNBLOCK_INPUT;
7805 }
7806 }
7807
7808
7809 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
7810 0, 1, 0,
7811 doc: /* Clear the image cache of FRAME.
7812 FRAME nil or omitted means use the selected frame.
7813 FRAME t means clear the image caches of all frames. */)
7814 (frame)
7815 Lisp_Object frame;
7816 {
7817 if (EQ (frame, Qt))
7818 {
7819 Lisp_Object tail;
7820
7821 FOR_EACH_FRAME (tail, frame)
7822 if (FRAME_W32_P (XFRAME (frame)))
7823 clear_image_cache (XFRAME (frame), 1);
7824 }
7825 else
7826 clear_image_cache (check_x_frame (frame), 1);
7827
7828 return Qnil;
7829 }
7830
7831
7832 /* Compute masks and transform image IMG on frame F, as specified
7833 by the image's specification, */
7834
7835 static void
7836 postprocess_image (f, img)
7837 struct frame *f;
7838 struct image *img;
7839 {
7840 /* Manipulation of the image's mask. */
7841 if (img->pixmap)
7842 {
7843 Lisp_Object conversion, spec;
7844 Lisp_Object mask;
7845
7846 spec = img->spec;
7847
7848 /* `:heuristic-mask t'
7849 `:mask heuristic'
7850 means build a mask heuristically.
7851 `:heuristic-mask (R G B)'
7852 `:mask (heuristic (R G B))'
7853 means build a mask from color (R G B) in the
7854 image.
7855 `:mask nil'
7856 means remove a mask, if any. */
7857
7858 mask = image_spec_value (spec, QCheuristic_mask, NULL);
7859 if (!NILP (mask))
7860 x_build_heuristic_mask (f, img, mask);
7861 else
7862 {
7863 int found_p;
7864
7865 mask = image_spec_value (spec, QCmask, &found_p);
7866
7867 if (EQ (mask, Qheuristic))
7868 x_build_heuristic_mask (f, img, Qt);
7869 else if (CONSP (mask)
7870 && EQ (XCAR (mask), Qheuristic))
7871 {
7872 if (CONSP (XCDR (mask)))
7873 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
7874 else
7875 x_build_heuristic_mask (f, img, XCDR (mask));
7876 }
7877 else if (NILP (mask) && found_p && img->mask)
7878 {
7879 DeleteObject (img->mask);
7880 img->mask = NULL;
7881 }
7882 }
7883
7884
7885 /* Should we apply an image transformation algorithm? */
7886 conversion = image_spec_value (spec, QCconversion, NULL);
7887 if (EQ (conversion, Qdisabled))
7888 x_disable_image (f, img);
7889 else if (EQ (conversion, Qlaplace))
7890 x_laplace (f, img);
7891 else if (EQ (conversion, Qemboss))
7892 x_emboss (f, img);
7893 else if (CONSP (conversion)
7894 && EQ (XCAR (conversion), Qedge_detection))
7895 {
7896 Lisp_Object tem;
7897 tem = XCDR (conversion);
7898 if (CONSP (tem))
7899 x_edge_detection (f, img,
7900 Fplist_get (tem, QCmatrix),
7901 Fplist_get (tem, QCcolor_adjustment));
7902 }
7903 }
7904 }
7905
7906
7907 /* Return the id of image with Lisp specification SPEC on frame F.
7908 SPEC must be a valid Lisp image specification (see valid_image_p). */
7909
7910 int
7911 lookup_image (f, spec)
7912 struct frame *f;
7913 Lisp_Object spec;
7914 {
7915 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7916 struct image *img;
7917 int i;
7918 unsigned hash;
7919 struct gcpro gcpro1;
7920 EMACS_TIME now;
7921
7922 /* F must be a window-system frame, and SPEC must be a valid image
7923 specification. */
7924 xassert (FRAME_WINDOW_P (f));
7925 xassert (valid_image_p (spec));
7926
7927 GCPRO1 (spec);
7928
7929 /* Look up SPEC in the hash table of the image cache. */
7930 hash = sxhash (spec, 0);
7931 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
7932
7933 for (img = c->buckets[i]; img; img = img->next)
7934 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
7935 break;
7936
7937 /* If not found, create a new image and cache it. */
7938 if (img == NULL)
7939 {
7940 extern Lisp_Object Qpostscript;
7941
7942 BLOCK_INPUT;
7943 img = make_image (spec, hash);
7944 cache_image (f, img);
7945 img->load_failed_p = img->type->load (f, img) == 0;
7946
7947 /* If we can't load the image, and we don't have a width and
7948 height, use some arbitrary width and height so that we can
7949 draw a rectangle for it. */
7950 if (img->load_failed_p)
7951 {
7952 Lisp_Object value;
7953
7954 value = image_spec_value (spec, QCwidth, NULL);
7955 img->width = (INTEGERP (value)
7956 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
7957 value = image_spec_value (spec, QCheight, NULL);
7958 img->height = (INTEGERP (value)
7959 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
7960 }
7961 else
7962 {
7963 /* Handle image type independent image attributes
7964 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
7965 `:background COLOR'. */
7966 Lisp_Object ascent, margin, relief, bg;
7967
7968 ascent = image_spec_value (spec, QCascent, NULL);
7969 if (INTEGERP (ascent))
7970 img->ascent = XFASTINT (ascent);
7971 else if (EQ (ascent, Qcenter))
7972 img->ascent = CENTERED_IMAGE_ASCENT;
7973
7974 margin = image_spec_value (spec, QCmargin, NULL);
7975 if (INTEGERP (margin) && XINT (margin) >= 0)
7976 img->vmargin = img->hmargin = XFASTINT (margin);
7977 else if (CONSP (margin) && INTEGERP (XCAR (margin))
7978 && INTEGERP (XCDR (margin)))
7979 {
7980 if (XINT (XCAR (margin)) > 0)
7981 img->hmargin = XFASTINT (XCAR (margin));
7982 if (XINT (XCDR (margin)) > 0)
7983 img->vmargin = XFASTINT (XCDR (margin));
7984 }
7985
7986 relief = image_spec_value (spec, QCrelief, NULL);
7987 if (INTEGERP (relief))
7988 {
7989 img->relief = XINT (relief);
7990 img->hmargin += abs (img->relief);
7991 img->vmargin += abs (img->relief);
7992 }
7993
7994 if (! img->background_valid)
7995 {
7996 bg = image_spec_value (img->spec, QCbackground, NULL);
7997 if (!NILP (bg))
7998 {
7999 img->background
8000 = x_alloc_image_color (f, img, bg,
8001 FRAME_BACKGROUND_PIXEL (f));
8002 img->background_valid = 1;
8003 }
8004 }
8005
8006 /* Do image transformations and compute masks, unless we
8007 don't have the image yet. */
8008 if (!EQ (*img->type->type, Qpostscript))
8009 postprocess_image (f, img);
8010 }
8011
8012 UNBLOCK_INPUT;
8013 xassert (!interrupt_input_blocked);
8014 }
8015
8016 /* We're using IMG, so set its timestamp to `now'. */
8017 EMACS_GET_TIME (now);
8018 img->timestamp = EMACS_SECS (now);
8019
8020 UNGCPRO;
8021
8022 /* Value is the image id. */
8023 return img->id;
8024 }
8025
8026
8027 /* Cache image IMG in the image cache of frame F. */
8028
8029 static void
8030 cache_image (f, img)
8031 struct frame *f;
8032 struct image *img;
8033 {
8034 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8035 int i;
8036
8037 /* Find a free slot in c->images. */
8038 for (i = 0; i < c->used; ++i)
8039 if (c->images[i] == NULL)
8040 break;
8041
8042 /* If no free slot found, maybe enlarge c->images. */
8043 if (i == c->used && c->used == c->size)
8044 {
8045 c->size *= 2;
8046 c->images = (struct image **) xrealloc (c->images,
8047 c->size * sizeof *c->images);
8048 }
8049
8050 /* Add IMG to c->images, and assign IMG an id. */
8051 c->images[i] = img;
8052 img->id = i;
8053 if (i == c->used)
8054 ++c->used;
8055
8056 /* Add IMG to the cache's hash table. */
8057 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8058 img->next = c->buckets[i];
8059 if (img->next)
8060 img->next->prev = img;
8061 img->prev = NULL;
8062 c->buckets[i] = img;
8063 }
8064
8065
8066 /* Call FN on every image in the image cache of frame F. Used to mark
8067 Lisp Objects in the image cache. */
8068
8069 void
8070 forall_images_in_image_cache (f, fn)
8071 struct frame *f;
8072 void (*fn) P_ ((struct image *img));
8073 {
8074 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8075 {
8076 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8077 if (c)
8078 {
8079 int i;
8080 for (i = 0; i < c->used; ++i)
8081 if (c->images[i])
8082 fn (c->images[i]);
8083 }
8084 }
8085 }
8086
8087
8088 \f
8089 /***********************************************************************
8090 W32 support code
8091 ***********************************************************************/
8092
8093 /* Macro for defining functions that will be loaded from image DLLs. */
8094 #define DEF_IMGLIB_FN(func) FARPROC fn_##func
8095
8096 /* Macro for loading those image functions from the library. */
8097 #define LOAD_IMGLIB_FN(lib,func) { \
8098 fn_##func = (void *) GetProcAddress (lib, #func); \
8099 if (!fn_##func) return 0; \
8100 }
8101
8102 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8103 XImage **, Pixmap *));
8104 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8105
8106
8107 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8108 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8109 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
8110 via xmalloc. DEPTH of zero signifies a 24 bit image, otherwise
8111 DEPTH should indicate the bit depth of the image. Print error
8112 messages via image_error if an error occurs. Value is non-zero if
8113 successful. */
8114
8115 static int
8116 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8117 struct frame *f;
8118 int width, height, depth;
8119 XImage **ximg;
8120 Pixmap *pixmap;
8121 {
8122 BITMAPINFOHEADER *header;
8123 HDC hdc;
8124 int scanline_width_bits;
8125 int remainder;
8126 int palette_colors = 0;
8127
8128 if (depth == 0)
8129 depth = 24;
8130
8131 if (depth != 1 && depth != 4 && depth != 8
8132 && depth != 16 && depth != 24 && depth != 32)
8133 {
8134 image_error ("Invalid image bit depth specified", Qnil, Qnil);
8135 return 0;
8136 }
8137
8138 scanline_width_bits = width * depth;
8139 remainder = scanline_width_bits % 32;
8140
8141 if (remainder)
8142 scanline_width_bits += 32 - remainder;
8143
8144 /* Bitmaps with a depth less than 16 need a palette. */
8145 /* BITMAPINFO structure already contains the first RGBQUAD. */
8146 if (depth < 16)
8147 palette_colors = 1 << depth - 1;
8148
8149 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
8150 if (*ximg == NULL)
8151 {
8152 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
8153 return 0;
8154 }
8155
8156 header = &((*ximg)->info.bmiHeader);
8157 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
8158 header->biSize = sizeof (*header);
8159 header->biWidth = width;
8160 header->biHeight = -height; /* negative indicates a top-down bitmap. */
8161 header->biPlanes = 1;
8162 header->biBitCount = depth;
8163 header->biCompression = BI_RGB;
8164 header->biClrUsed = palette_colors;
8165
8166 /* TODO: fill in palette. */
8167 if (depth == 1)
8168 {
8169 (*ximg)->info.bmiColors[0].rgbBlue = 0;
8170 (*ximg)->info.bmiColors[0].rgbGreen = 0;
8171 (*ximg)->info.bmiColors[0].rgbRed = 0;
8172 (*ximg)->info.bmiColors[0].rgbReserved = 0;
8173 (*ximg)->info.bmiColors[1].rgbBlue = 255;
8174 (*ximg)->info.bmiColors[1].rgbGreen = 255;
8175 (*ximg)->info.bmiColors[1].rgbRed = 255;
8176 (*ximg)->info.bmiColors[1].rgbReserved = 0;
8177 }
8178
8179 hdc = get_frame_dc (f);
8180
8181 /* Create a DIBSection and raster array for the bitmap,
8182 and store its handle in *pixmap. */
8183 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
8184 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
8185 &((*ximg)->data), NULL, 0);
8186
8187 /* Realize display palette and garbage all frames. */
8188 release_frame_dc (f, hdc);
8189
8190 if (*pixmap == NULL)
8191 {
8192 DWORD err = GetLastError();
8193 Lisp_Object errcode;
8194 /* All system errors are < 10000, so the following is safe. */
8195 XSETINT (errcode, (int) err);
8196 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
8197 x_destroy_x_image (*ximg);
8198 return 0;
8199 }
8200
8201 return 1;
8202 }
8203
8204
8205 /* Destroy XImage XIMG. Free XIMG->data. */
8206
8207 static void
8208 x_destroy_x_image (ximg)
8209 XImage *ximg;
8210 {
8211 xassert (interrupt_input_blocked);
8212 if (ximg)
8213 {
8214 /* Data will be freed by DestroyObject. */
8215 ximg->data = NULL;
8216 xfree (ximg);
8217 }
8218 }
8219
8220
8221 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8222 are width and height of both the image and pixmap. */
8223
8224 static void
8225 x_put_x_image (f, ximg, pixmap, width, height)
8226 struct frame *f;
8227 XImage *ximg;
8228 Pixmap pixmap;
8229 int width, height;
8230 {
8231 #if 0 /* I don't think this is necessary looking at where it is used. */
8232 HDC hdc = get_frame_dc (f);
8233 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
8234 release_frame_dc (f, hdc);
8235 #endif
8236 }
8237
8238 \f
8239 /***********************************************************************
8240 File Handling
8241 ***********************************************************************/
8242
8243 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
8244 static char *slurp_file P_ ((char *, int *));
8245
8246
8247 /* Find image file FILE. Look in data-directory, then
8248 x-bitmap-file-path. Value is the full name of the file found, or
8249 nil if not found. */
8250
8251 static Lisp_Object
8252 x_find_image_file (file)
8253 Lisp_Object file;
8254 {
8255 Lisp_Object file_found, search_path;
8256 struct gcpro gcpro1, gcpro2;
8257 int fd;
8258
8259 file_found = Qnil;
8260 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8261 GCPRO2 (file_found, search_path);
8262
8263 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
8264 fd = openp (search_path, file, Qnil, &file_found, Qnil);
8265
8266 if (fd == -1)
8267 file_found = Qnil;
8268 else
8269 close (fd);
8270
8271 UNGCPRO;
8272 return file_found;
8273 }
8274
8275
8276 /* Read FILE into memory. Value is a pointer to a buffer allocated
8277 with xmalloc holding FILE's contents. Value is null if an error
8278 occurred. *SIZE is set to the size of the file. */
8279
8280 static char *
8281 slurp_file (file, size)
8282 char *file;
8283 int *size;
8284 {
8285 FILE *fp = NULL;
8286 char *buf = NULL;
8287 struct stat st;
8288
8289 if (stat (file, &st) == 0
8290 && (fp = fopen (file, "rb")) != NULL
8291 && (buf = (char *) xmalloc (st.st_size),
8292 fread (buf, 1, st.st_size, fp) == st.st_size))
8293 {
8294 *size = st.st_size;
8295 fclose (fp);
8296 }
8297 else
8298 {
8299 if (fp)
8300 fclose (fp);
8301 if (buf)
8302 {
8303 xfree (buf);
8304 buf = NULL;
8305 }
8306 }
8307
8308 return buf;
8309 }
8310
8311
8312 \f
8313 /***********************************************************************
8314 XBM images
8315 ***********************************************************************/
8316
8317 static int xbm_scan P_ ((char **, char *, char *, int *));
8318 static int xbm_load P_ ((struct frame *f, struct image *img));
8319 static int xbm_load_image P_ ((struct frame *f, struct image *img,
8320 char *, char *));
8321 static int xbm_image_p P_ ((Lisp_Object object));
8322 static int xbm_read_bitmap_data P_ ((char *, char *, int *, int *,
8323 unsigned char **));
8324 static int xbm_file_p P_ ((Lisp_Object));
8325
8326
8327 /* Indices of image specification fields in xbm_format, below. */
8328
8329 enum xbm_keyword_index
8330 {
8331 XBM_TYPE,
8332 XBM_FILE,
8333 XBM_WIDTH,
8334 XBM_HEIGHT,
8335 XBM_DATA,
8336 XBM_FOREGROUND,
8337 XBM_BACKGROUND,
8338 XBM_ASCENT,
8339 XBM_MARGIN,
8340 XBM_RELIEF,
8341 XBM_ALGORITHM,
8342 XBM_HEURISTIC_MASK,
8343 XBM_MASK,
8344 XBM_LAST
8345 };
8346
8347 /* Vector of image_keyword structures describing the format
8348 of valid XBM image specifications. */
8349
8350 static struct image_keyword xbm_format[XBM_LAST] =
8351 {
8352 {":type", IMAGE_SYMBOL_VALUE, 1},
8353 {":file", IMAGE_STRING_VALUE, 0},
8354 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8355 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8356 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8357 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
8358 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8359 {":ascent", IMAGE_ASCENT_VALUE, 0},
8360 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
8361 {":relief", IMAGE_INTEGER_VALUE, 0},
8362 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8363 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8364 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8365 };
8366
8367 /* Structure describing the image type XBM. */
8368
8369 static struct image_type xbm_type =
8370 {
8371 &Qxbm,
8372 xbm_image_p,
8373 xbm_load,
8374 x_clear_image,
8375 NULL
8376 };
8377
8378 /* Tokens returned from xbm_scan. */
8379
8380 enum xbm_token
8381 {
8382 XBM_TK_IDENT = 256,
8383 XBM_TK_NUMBER
8384 };
8385
8386
8387 /* Return non-zero if OBJECT is a valid XBM-type image specification.
8388 A valid specification is a list starting with the symbol `image'
8389 The rest of the list is a property list which must contain an
8390 entry `:type xbm..
8391
8392 If the specification specifies a file to load, it must contain
8393 an entry `:file FILENAME' where FILENAME is a string.
8394
8395 If the specification is for a bitmap loaded from memory it must
8396 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8397 WIDTH and HEIGHT are integers > 0. DATA may be:
8398
8399 1. a string large enough to hold the bitmap data, i.e. it must
8400 have a size >= (WIDTH + 7) / 8 * HEIGHT
8401
8402 2. a bool-vector of size >= WIDTH * HEIGHT
8403
8404 3. a vector of strings or bool-vectors, one for each line of the
8405 bitmap.
8406
8407 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
8408 may not be specified in this case because they are defined in the
8409 XBM file.
8410
8411 Both the file and data forms may contain the additional entries
8412 `:background COLOR' and `:foreground COLOR'. If not present,
8413 foreground and background of the frame on which the image is
8414 displayed is used. */
8415
8416 static int
8417 xbm_image_p (object)
8418 Lisp_Object object;
8419 {
8420 struct image_keyword kw[XBM_LAST];
8421
8422 bcopy (xbm_format, kw, sizeof kw);
8423 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8424 return 0;
8425
8426 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8427
8428 if (kw[XBM_FILE].count)
8429 {
8430 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8431 return 0;
8432 }
8433 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
8434 {
8435 /* In-memory XBM file. */
8436 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
8437 return 0;
8438 }
8439 else
8440 {
8441 Lisp_Object data;
8442 int width, height;
8443
8444 /* Entries for `:width', `:height' and `:data' must be present. */
8445 if (!kw[XBM_WIDTH].count
8446 || !kw[XBM_HEIGHT].count
8447 || !kw[XBM_DATA].count)
8448 return 0;
8449
8450 data = kw[XBM_DATA].value;
8451 width = XFASTINT (kw[XBM_WIDTH].value);
8452 height = XFASTINT (kw[XBM_HEIGHT].value);
8453
8454 /* Check type of data, and width and height against contents of
8455 data. */
8456 if (VECTORP (data))
8457 {
8458 int i;
8459
8460 /* Number of elements of the vector must be >= height. */
8461 if (XVECTOR (data)->size < height)
8462 return 0;
8463
8464 /* Each string or bool-vector in data must be large enough
8465 for one line of the image. */
8466 for (i = 0; i < height; ++i)
8467 {
8468 Lisp_Object elt = XVECTOR (data)->contents[i];
8469
8470 if (STRINGP (elt))
8471 {
8472 if (SCHARS (elt)
8473 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8474 return 0;
8475 }
8476 else if (BOOL_VECTOR_P (elt))
8477 {
8478 if (XBOOL_VECTOR (elt)->size < width)
8479 return 0;
8480 }
8481 else
8482 return 0;
8483 }
8484 }
8485 else if (STRINGP (data))
8486 {
8487 if (SCHARS (data)
8488 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8489 return 0;
8490 }
8491 else if (BOOL_VECTOR_P (data))
8492 {
8493 if (XBOOL_VECTOR (data)->size < width * height)
8494 return 0;
8495 }
8496 else
8497 return 0;
8498 }
8499
8500 return 1;
8501 }
8502
8503
8504 /* Scan a bitmap file. FP is the stream to read from. Value is
8505 either an enumerator from enum xbm_token, or a character for a
8506 single-character token, or 0 at end of file. If scanning an
8507 identifier, store the lexeme of the identifier in SVAL. If
8508 scanning a number, store its value in *IVAL. */
8509
8510 static int
8511 xbm_scan (s, end, sval, ival)
8512 char **s, *end;
8513 char *sval;
8514 int *ival;
8515 {
8516 int c;
8517
8518 loop:
8519
8520 /* Skip white space. */
8521 while (*s < end && (c = *(*s)++, isspace (c)))
8522 ;
8523
8524 if (*s >= end)
8525 c = 0;
8526 else if (isdigit (c))
8527 {
8528 int value = 0, digit;
8529
8530 if (c == '0' && *s < end)
8531 {
8532 c = *(*s)++;
8533 if (c == 'x' || c == 'X')
8534 {
8535 while (*s < end)
8536 {
8537 c = *(*s)++;
8538 if (isdigit (c))
8539 digit = c - '0';
8540 else if (c >= 'a' && c <= 'f')
8541 digit = c - 'a' + 10;
8542 else if (c >= 'A' && c <= 'F')
8543 digit = c - 'A' + 10;
8544 else
8545 break;
8546 value = 16 * value + digit;
8547 }
8548 }
8549 else if (isdigit (c))
8550 {
8551 value = c - '0';
8552 while (*s < end
8553 && (c = *(*s)++, isdigit (c)))
8554 value = 8 * value + c - '0';
8555 }
8556 }
8557 else
8558 {
8559 value = c - '0';
8560 while (*s < end
8561 && (c = *(*s)++, isdigit (c)))
8562 value = 10 * value + c - '0';
8563 }
8564
8565 if (*s < end)
8566 *s = *s - 1;
8567 *ival = value;
8568 c = XBM_TK_NUMBER;
8569 }
8570 else if (isalpha (c) || c == '_')
8571 {
8572 *sval++ = c;
8573 while (*s < end
8574 && (c = *(*s)++, (isalnum (c) || c == '_')))
8575 *sval++ = c;
8576 *sval = 0;
8577 if (*s < end)
8578 *s = *s - 1;
8579 c = XBM_TK_IDENT;
8580 }
8581 else if (c == '/' && **s == '*')
8582 {
8583 /* C-style comment. */
8584 ++*s;
8585 while (**s && (**s != '*' || *(*s + 1) != '/'))
8586 ++*s;
8587 if (**s)
8588 {
8589 *s += 2;
8590 goto loop;
8591 }
8592 }
8593
8594 return c;
8595 }
8596
8597
8598 /* XBM bits seem to be backward within bytes compared with how
8599 Windows does things. */
8600 static unsigned char reflect_byte (unsigned char orig)
8601 {
8602 int i;
8603 unsigned char reflected = 0x00;
8604 for (i = 0; i < 8; i++)
8605 {
8606 if (orig & (0x01 << i))
8607 reflected |= 0x80 >> i;
8608 }
8609 return reflected;
8610 }
8611
8612
8613 /* Create a Windows bitmap from X bitmap data. */
8614 static HBITMAP
8615 w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
8616 {
8617 int i, j, w1, w2;
8618 char *bits, *p;
8619 HBITMAP bmp;
8620
8621 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
8622 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
8623 bits = (char *) alloca (height * w2);
8624 bzero (bits, height * w2);
8625 for (i = 0; i < height; i++)
8626 {
8627 p = bits + i*w2;
8628 for (j = 0; j < w1; j++)
8629 *p++ = reflect_byte(*data++);
8630 }
8631 bmp = CreateBitmap (width, height, 1, 1, bits);
8632
8633 return bmp;
8634 }
8635
8636
8637 /* Replacement for XReadBitmapFileData which isn't available under old
8638 X versions. CONTENTS is a pointer to a buffer to parse; END is the
8639 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
8640 the image. Return in *DATA the bitmap data allocated with xmalloc.
8641 Value is non-zero if successful. DATA null means just test if
8642 CONTENTS looks like an in-memory XBM file. */
8643
8644 static int
8645 xbm_read_bitmap_data (contents, end, width, height, data)
8646 char *contents, *end;
8647 int *width, *height;
8648 unsigned char **data;
8649 {
8650 char *s = contents;
8651 char buffer[BUFSIZ];
8652 int padding_p = 0;
8653 int v10 = 0;
8654 int bytes_per_line, i, nbytes;
8655 unsigned char *p;
8656 int value;
8657 int LA1;
8658
8659 #define match() \
8660 LA1 = xbm_scan (&s, end, buffer, &value)
8661
8662 #define expect(TOKEN) \
8663 if (LA1 != (TOKEN)) \
8664 goto failure; \
8665 else \
8666 match ()
8667
8668 #define expect_ident(IDENT) \
8669 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8670 match (); \
8671 else \
8672 goto failure
8673
8674 *width = *height = -1;
8675 if (data)
8676 *data = NULL;
8677 LA1 = xbm_scan (&s, end, buffer, &value);
8678
8679 /* Parse defines for width, height and hot-spots. */
8680 while (LA1 == '#')
8681 {
8682 match ();
8683 expect_ident ("define");
8684 expect (XBM_TK_IDENT);
8685
8686 if (LA1 == XBM_TK_NUMBER);
8687 {
8688 char *p = strrchr (buffer, '_');
8689 p = p ? p + 1 : buffer;
8690 if (strcmp (p, "width") == 0)
8691 *width = value;
8692 else if (strcmp (p, "height") == 0)
8693 *height = value;
8694 }
8695 expect (XBM_TK_NUMBER);
8696 }
8697
8698 if (*width < 0 || *height < 0)
8699 goto failure;
8700 else if (data == NULL)
8701 goto success;
8702
8703 /* Parse bits. Must start with `static'. */
8704 expect_ident ("static");
8705 if (LA1 == XBM_TK_IDENT)
8706 {
8707 if (strcmp (buffer, "unsigned") == 0)
8708 {
8709 match ();
8710 expect_ident ("char");
8711 }
8712 else if (strcmp (buffer, "short") == 0)
8713 {
8714 match ();
8715 v10 = 1;
8716 if (*width % 16 && *width % 16 < 9)
8717 padding_p = 1;
8718 }
8719 else if (strcmp (buffer, "char") == 0)
8720 match ();
8721 else
8722 goto failure;
8723 }
8724 else
8725 goto failure;
8726
8727 expect (XBM_TK_IDENT);
8728 expect ('[');
8729 expect (']');
8730 expect ('=');
8731 expect ('{');
8732
8733 bytes_per_line = (*width + 7) / 8 + padding_p;
8734 nbytes = bytes_per_line * *height;
8735 p = *data = (char *) xmalloc (nbytes);
8736
8737 if (v10)
8738 {
8739 for (i = 0; i < nbytes; i += 2)
8740 {
8741 int val = value;
8742 expect (XBM_TK_NUMBER);
8743
8744 *p++ = ~ val;
8745 if (!padding_p || ((i + 2) % bytes_per_line))
8746 *p++ = ~ (value >> 8);
8747
8748 if (LA1 == ',' || LA1 == '}')
8749 match ();
8750 else
8751 goto failure;
8752 }
8753 }
8754 else
8755 {
8756 for (i = 0; i < nbytes; ++i)
8757 {
8758 int val = value;
8759 expect (XBM_TK_NUMBER);
8760
8761 *p++ = ~ val;
8762
8763 if (LA1 == ',' || LA1 == '}')
8764 match ();
8765 else
8766 goto failure;
8767 }
8768 }
8769
8770 success:
8771 return 1;
8772
8773 failure:
8774
8775 if (data && *data)
8776 {
8777 xfree (*data);
8778 *data = NULL;
8779 }
8780 return 0;
8781
8782 #undef match
8783 #undef expect
8784 #undef expect_ident
8785 }
8786
8787 static void convert_mono_to_color_image (f, img, foreground, background)
8788 struct frame *f;
8789 struct image *img;
8790 COLORREF foreground, background;
8791 {
8792 HDC hdc, old_img_dc, new_img_dc;
8793 HGDIOBJ old_prev, new_prev;
8794 HBITMAP new_pixmap;
8795
8796 hdc = get_frame_dc (f);
8797 old_img_dc = CreateCompatibleDC (hdc);
8798 new_img_dc = CreateCompatibleDC (hdc);
8799 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
8800 release_frame_dc (f, hdc);
8801 old_prev = SelectObject (old_img_dc, img->pixmap);
8802 new_prev = SelectObject (new_img_dc, new_pixmap);
8803 SetTextColor (new_img_dc, foreground);
8804 SetBkColor (new_img_dc, background);
8805
8806 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
8807 0, 0, SRCCOPY);
8808
8809 SelectObject (old_img_dc, old_prev);
8810 SelectObject (new_img_dc, new_prev);
8811 DeleteDC (old_img_dc);
8812 DeleteDC (new_img_dc);
8813 DeleteObject (img->pixmap);
8814 if (new_pixmap == 0)
8815 fprintf (stderr, "Failed to convert image to color.\n");
8816 else
8817 img->pixmap = new_pixmap;
8818 }
8819
8820 /* Load XBM image IMG which will be displayed on frame F from buffer
8821 CONTENTS. END is the end of the buffer. Value is non-zero if
8822 successful. */
8823
8824 static int
8825 xbm_load_image (f, img, contents, end)
8826 struct frame *f;
8827 struct image *img;
8828 char *contents, *end;
8829 {
8830 int rc;
8831 unsigned char *data;
8832 int success_p = 0;
8833
8834 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
8835 if (rc)
8836 {
8837 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8838 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8839 int non_default_colors = 0;
8840 Lisp_Object value;
8841
8842 xassert (img->width > 0 && img->height > 0);
8843
8844 /* Get foreground and background colors, maybe allocate colors. */
8845 value = image_spec_value (img->spec, QCforeground, NULL);
8846 if (!NILP (value))
8847 {
8848 foreground = x_alloc_image_color (f, img, value, foreground);
8849 non_default_colors = 1;
8850 }
8851 value = image_spec_value (img->spec, QCbackground, NULL);
8852 if (!NILP (value))
8853 {
8854 background = x_alloc_image_color (f, img, value, background);
8855 img->background = background;
8856 img->background_valid = 1;
8857 non_default_colors = 1;
8858 }
8859 img->pixmap
8860 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
8861
8862 /* If colors were specified, transfer the bitmap to a color one. */
8863 if (non_default_colors)
8864 convert_mono_to_color_image (f, img, foreground, background);
8865
8866 xfree (data);
8867
8868 if (img->pixmap == 0)
8869 {
8870 x_clear_image (f, img);
8871 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
8872 }
8873 else
8874 success_p = 1;
8875 }
8876 else
8877 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8878
8879 return success_p;
8880 }
8881
8882
8883 /* Value is non-zero if DATA looks like an in-memory XBM file. */
8884
8885 static int
8886 xbm_file_p (data)
8887 Lisp_Object data;
8888 {
8889 int w, h;
8890 return (STRINGP (data)
8891 && xbm_read_bitmap_data (SDATA (data),
8892 (SDATA (data)
8893 + SBYTES (data)),
8894 &w, &h, NULL));
8895 }
8896
8897
8898 /* Fill image IMG which is used on frame F with pixmap data. Value is
8899 non-zero if successful. */
8900
8901 static int
8902 xbm_load (f, img)
8903 struct frame *f;
8904 struct image *img;
8905 {
8906 int success_p = 0;
8907 Lisp_Object file_name;
8908
8909 xassert (xbm_image_p (img->spec));
8910
8911 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8912 file_name = image_spec_value (img->spec, QCfile, NULL);
8913 if (STRINGP (file_name))
8914 {
8915 Lisp_Object file;
8916 char *contents;
8917 int size;
8918 struct gcpro gcpro1;
8919
8920 file = x_find_image_file (file_name);
8921 GCPRO1 (file);
8922 if (!STRINGP (file))
8923 {
8924 image_error ("Cannot find image file `%s'", file_name, Qnil);
8925 UNGCPRO;
8926 return 0;
8927 }
8928
8929 contents = slurp_file (SDATA (file), &size);
8930 if (contents == NULL)
8931 {
8932 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8933 UNGCPRO;
8934 return 0;
8935 }
8936
8937 success_p = xbm_load_image (f, img, contents, contents + size);
8938 UNGCPRO;
8939 }
8940 else
8941 {
8942 struct image_keyword fmt[XBM_LAST];
8943 Lisp_Object data;
8944 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8945 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8946 int non_default_colors = 0;
8947 char *bits;
8948 int parsed_p;
8949 int in_memory_file_p = 0;
8950
8951 /* See if data looks like an in-memory XBM file. */
8952 data = image_spec_value (img->spec, QCdata, NULL);
8953 in_memory_file_p = xbm_file_p (data);
8954
8955 /* Parse the image specification. */
8956 bcopy (xbm_format, fmt, sizeof fmt);
8957 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
8958 xassert (parsed_p);
8959
8960 /* Get specified width, and height. */
8961 if (!in_memory_file_p)
8962 {
8963 img->width = XFASTINT (fmt[XBM_WIDTH].value);
8964 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
8965 xassert (img->width > 0 && img->height > 0);
8966 }
8967
8968 /* Get foreground and background colors, maybe allocate colors. */
8969 if (fmt[XBM_FOREGROUND].count
8970 && STRINGP (fmt[XBM_FOREGROUND].value))
8971 {
8972 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
8973 foreground);
8974 non_default_colors = 1;
8975 }
8976
8977 if (fmt[XBM_BACKGROUND].count
8978 && STRINGP (fmt[XBM_BACKGROUND].value))
8979 {
8980 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
8981 background);
8982 non_default_colors = 1;
8983 }
8984
8985 if (in_memory_file_p)
8986 success_p = xbm_load_image (f, img, SDATA (data),
8987 (SDATA (data)
8988 + SBYTES (data)));
8989 else
8990 {
8991 if (VECTORP (data))
8992 {
8993 int i;
8994 char *p;
8995 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
8996
8997 p = bits = (char *) alloca (nbytes * img->height);
8998 for (i = 0; i < img->height; ++i, p += nbytes)
8999 {
9000 Lisp_Object line = XVECTOR (data)->contents[i];
9001 if (STRINGP (line))
9002 bcopy (SDATA (line), p, nbytes);
9003 else
9004 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
9005 }
9006 }
9007 else if (STRINGP (data))
9008 bits = SDATA (data);
9009 else
9010 bits = XBOOL_VECTOR (data)->data;
9011
9012 /* Create the pixmap. */
9013 img->pixmap
9014 = w32_create_pixmap_from_bitmap_data (img->width, img->height,
9015 bits);
9016
9017 /* If colors were specified, transfer the bitmap to a color one. */
9018 if (non_default_colors)
9019 convert_mono_to_color_image (f, img, foreground, background);
9020
9021 if (img->pixmap)
9022 success_p = 1;
9023 else
9024 {
9025 image_error ("Unable to create pixmap for XBM image `%s'",
9026 img->spec, Qnil);
9027 x_clear_image (f, img);
9028 }
9029 }
9030 }
9031
9032 return success_p;
9033 }
9034
9035
9036 \f
9037 /***********************************************************************
9038 XPM images
9039 ***********************************************************************/
9040
9041 #if HAVE_XPM
9042
9043 static int xpm_image_p P_ ((Lisp_Object object));
9044 static int xpm_load P_ ((struct frame *f, struct image *img));
9045 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
9046
9047 /* Indicate to xpm.h that we don't have Xlib. */
9048 #define FOR_MSW
9049 /* simx.h in xpm defines XColor and XImage differently than Emacs. */
9050 #define XColor xpm_XColor
9051 #define XImage xpm_XImage
9052 #define PIXEL_ALREADY_TYPEDEFED
9053 #include "X11/xpm.h"
9054 #undef FOR_MSW
9055 #undef XColor
9056 #undef XImage
9057 #undef PIXEL_ALREADY_TYPEDEFED
9058
9059 /* The symbol `xpm' identifying XPM-format images. */
9060
9061 Lisp_Object Qxpm;
9062
9063 /* Indices of image specification fields in xpm_format, below. */
9064
9065 enum xpm_keyword_index
9066 {
9067 XPM_TYPE,
9068 XPM_FILE,
9069 XPM_DATA,
9070 XPM_ASCENT,
9071 XPM_MARGIN,
9072 XPM_RELIEF,
9073 XPM_ALGORITHM,
9074 XPM_HEURISTIC_MASK,
9075 XPM_MASK,
9076 XPM_COLOR_SYMBOLS,
9077 XPM_BACKGROUND,
9078 XPM_LAST
9079 };
9080
9081 /* Vector of image_keyword structures describing the format
9082 of valid XPM image specifications. */
9083
9084 static struct image_keyword xpm_format[XPM_LAST] =
9085 {
9086 {":type", IMAGE_SYMBOL_VALUE, 1},
9087 {":file", IMAGE_STRING_VALUE, 0},
9088 {":data", IMAGE_STRING_VALUE, 0},
9089 {":ascent", IMAGE_ASCENT_VALUE, 0},
9090 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9091 {":relief", IMAGE_INTEGER_VALUE, 0},
9092 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9093 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9094 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9095 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9096 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
9097 };
9098
9099 /* Structure describing the image type XPM. */
9100
9101 static struct image_type xpm_type =
9102 {
9103 &Qxpm,
9104 xpm_image_p,
9105 xpm_load,
9106 x_clear_image,
9107 NULL
9108 };
9109
9110
9111 /* XPM library details. */
9112
9113 DEF_IMGLIB_FN (XpmFreeAttributes);
9114 DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
9115 DEF_IMGLIB_FN (XpmReadFileToImage);
9116 DEF_IMGLIB_FN (XImageFree);
9117
9118
9119 static int
9120 init_xpm_functions (library)
9121 HMODULE library;
9122 {
9123 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
9124 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
9125 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
9126 LOAD_IMGLIB_FN (library, XImageFree);
9127
9128 return 1;
9129 }
9130
9131 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9132 for XPM images. Such a list must consist of conses whose car and
9133 cdr are strings. */
9134
9135 static int
9136 xpm_valid_color_symbols_p (color_symbols)
9137 Lisp_Object color_symbols;
9138 {
9139 while (CONSP (color_symbols))
9140 {
9141 Lisp_Object sym = XCAR (color_symbols);
9142 if (!CONSP (sym)
9143 || !STRINGP (XCAR (sym))
9144 || !STRINGP (XCDR (sym)))
9145 break;
9146 color_symbols = XCDR (color_symbols);
9147 }
9148
9149 return NILP (color_symbols);
9150 }
9151
9152
9153 /* Value is non-zero if OBJECT is a valid XPM image specification. */
9154
9155 static int
9156 xpm_image_p (object)
9157 Lisp_Object object;
9158 {
9159 struct image_keyword fmt[XPM_LAST];
9160 bcopy (xpm_format, fmt, sizeof fmt);
9161 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9162 /* Either `:file' or `:data' must be present. */
9163 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9164 /* Either no `:color-symbols' or it's a list of conses
9165 whose car and cdr are strings. */
9166 && (fmt[XPM_COLOR_SYMBOLS].count == 0
9167 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
9168 }
9169
9170
9171 /* Load image IMG which will be displayed on frame F. Value is
9172 non-zero if successful. */
9173
9174 static int
9175 xpm_load (f, img)
9176 struct frame *f;
9177 struct image *img;
9178 {
9179 HDC hdc;
9180 int rc;
9181 XpmAttributes attrs;
9182 Lisp_Object specified_file, color_symbols;
9183 xpm_XImage * xpm_image, * xpm_mask;
9184
9185 /* Configure the XPM lib. Use the visual of frame F. Allocate
9186 close colors. Return colors allocated. */
9187 bzero (&attrs, sizeof attrs);
9188 xpm_image = xpm_mask = NULL;
9189
9190 #if 0
9191 attrs.visual = FRAME_X_VISUAL (f);
9192 attrs.colormap = FRAME_X_COLORMAP (f);
9193 attrs.valuemask |= XpmVisual;
9194 attrs.valuemask |= XpmColormap;
9195 #endif
9196 attrs.valuemask |= XpmReturnAllocPixels;
9197 #ifdef XpmAllocCloseColors
9198 attrs.alloc_close_colors = 1;
9199 attrs.valuemask |= XpmAllocCloseColors;
9200 #else
9201 attrs.closeness = 600;
9202 attrs.valuemask |= XpmCloseness;
9203 #endif
9204
9205 /* If image specification contains symbolic color definitions, add
9206 these to `attrs'. */
9207 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
9208 if (CONSP (color_symbols))
9209 {
9210 Lisp_Object tail;
9211 XpmColorSymbol *xpm_syms;
9212 int i, size;
9213
9214 attrs.valuemask |= XpmColorSymbols;
9215
9216 /* Count number of symbols. */
9217 attrs.numsymbols = 0;
9218 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
9219 ++attrs.numsymbols;
9220
9221 /* Allocate an XpmColorSymbol array. */
9222 size = attrs.numsymbols * sizeof *xpm_syms;
9223 xpm_syms = (XpmColorSymbol *) alloca (size);
9224 bzero (xpm_syms, size);
9225 attrs.colorsymbols = xpm_syms;
9226
9227 /* Fill the color symbol array. */
9228 for (tail = color_symbols, i = 0;
9229 CONSP (tail);
9230 ++i, tail = XCDR (tail))
9231 {
9232 Lisp_Object name = XCAR (XCAR (tail));
9233 Lisp_Object color = XCDR (XCAR (tail));
9234 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
9235 strcpy (xpm_syms[i].name, SDATA (name));
9236 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
9237 strcpy (xpm_syms[i].value, SDATA (color));
9238 }
9239 }
9240
9241 /* Create a pixmap for the image, either from a file, or from a
9242 string buffer containing data in the same format as an XPM file. */
9243
9244 specified_file = image_spec_value (img->spec, QCfile, NULL);
9245
9246 {
9247 HDC frame_dc = get_frame_dc (f);
9248 hdc = CreateCompatibleDC (frame_dc);
9249 release_frame_dc (f, frame_dc);
9250 }
9251
9252 if (STRINGP (specified_file))
9253 {
9254 Lisp_Object file = x_find_image_file (specified_file);
9255 if (!STRINGP (file))
9256 {
9257 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9258 return 0;
9259 }
9260
9261 /* XpmReadFileToPixmap is not available in the Windows port of
9262 libxpm. But XpmReadFileToImage almost does what we want. */
9263 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
9264 &xpm_image, &xpm_mask,
9265 &attrs);
9266 }
9267 else
9268 {
9269 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
9270 /* XpmCreatePixmapFromBuffer is not available in the Windows port
9271 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
9272 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
9273 &xpm_image, &xpm_mask,
9274 &attrs);
9275 }
9276
9277 if (rc == XpmSuccess)
9278 {
9279 int i;
9280
9281 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
9282 plus some duplicate attributes. */
9283 if (xpm_image && xpm_image->bitmap)
9284 {
9285 img->pixmap = xpm_image->bitmap;
9286 /* XImageFree in libXpm frees XImage struct without destroying
9287 the bitmap, which is what we want. */
9288 fn_XImageFree (xpm_image);
9289 }
9290 if (xpm_mask && xpm_mask->bitmap)
9291 {
9292 /* The mask appears to be inverted compared with what we expect.
9293 TODO: invert our expectations. See other places where we
9294 have to invert bits because our idea of masks is backwards. */
9295 HGDIOBJ old_obj;
9296 old_obj = SelectObject (hdc, xpm_mask->bitmap);
9297
9298 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
9299 SelectObject (hdc, old_obj);
9300
9301 img->mask = xpm_mask->bitmap;
9302 fn_XImageFree (xpm_mask);
9303 DeleteDC (hdc);
9304 }
9305
9306 DeleteDC (hdc);
9307
9308 /* Remember allocated colors. */
9309 img->ncolors = attrs.nalloc_pixels;
9310 img->colors = (unsigned long *) xmalloc (img->ncolors
9311 * sizeof *img->colors);
9312 for (i = 0; i < attrs.nalloc_pixels; ++i)
9313 img->colors[i] = attrs.alloc_pixels[i];
9314
9315 img->width = attrs.width;
9316 img->height = attrs.height;
9317 xassert (img->width > 0 && img->height > 0);
9318
9319 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
9320 fn_XpmFreeAttributes (&attrs);
9321 }
9322 else
9323 {
9324 DeleteDC (hdc);
9325
9326 switch (rc)
9327 {
9328 case XpmOpenFailed:
9329 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9330 break;
9331
9332 case XpmFileInvalid:
9333 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9334 break;
9335
9336 case XpmNoMemory:
9337 image_error ("Out of memory (%s)", img->spec, Qnil);
9338 break;
9339
9340 case XpmColorFailed:
9341 image_error ("Color allocation error (%s)", img->spec, Qnil);
9342 break;
9343
9344 default:
9345 image_error ("Unknown error (%s)", img->spec, Qnil);
9346 break;
9347 }
9348 }
9349
9350 return rc == XpmSuccess;
9351 }
9352
9353 #endif /* HAVE_XPM != 0 */
9354
9355 \f
9356 #if 0 /* TODO : Color tables on W32. */
9357 /***********************************************************************
9358 Color table
9359 ***********************************************************************/
9360
9361 /* An entry in the color table mapping an RGB color to a pixel color. */
9362
9363 struct ct_color
9364 {
9365 int r, g, b;
9366 unsigned long pixel;
9367
9368 /* Next in color table collision list. */
9369 struct ct_color *next;
9370 };
9371
9372 /* The bucket vector size to use. Must be prime. */
9373
9374 #define CT_SIZE 101
9375
9376 /* Value is a hash of the RGB color given by R, G, and B. */
9377
9378 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9379
9380 /* The color hash table. */
9381
9382 struct ct_color **ct_table;
9383
9384 /* Number of entries in the color table. */
9385
9386 int ct_colors_allocated;
9387
9388 /* Function prototypes. */
9389
9390 static void init_color_table P_ ((void));
9391 static void free_color_table P_ ((void));
9392 static unsigned long *colors_in_color_table P_ ((int *n));
9393 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9394 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9395
9396
9397 /* Initialize the color table. */
9398
9399 static void
9400 init_color_table ()
9401 {
9402 int size = CT_SIZE * sizeof (*ct_table);
9403 ct_table = (struct ct_color **) xmalloc (size);
9404 bzero (ct_table, size);
9405 ct_colors_allocated = 0;
9406 }
9407
9408
9409 /* Free memory associated with the color table. */
9410
9411 static void
9412 free_color_table ()
9413 {
9414 int i;
9415 struct ct_color *p, *next;
9416
9417 for (i = 0; i < CT_SIZE; ++i)
9418 for (p = ct_table[i]; p; p = next)
9419 {
9420 next = p->next;
9421 xfree (p);
9422 }
9423
9424 xfree (ct_table);
9425 ct_table = NULL;
9426 }
9427
9428
9429 /* Value is a pixel color for RGB color R, G, B on frame F. If an
9430 entry for that color already is in the color table, return the
9431 pixel color of that entry. Otherwise, allocate a new color for R,
9432 G, B, and make an entry in the color table. */
9433
9434 static unsigned long
9435 lookup_rgb_color (f, r, g, b)
9436 struct frame *f;
9437 int r, g, b;
9438 {
9439 unsigned hash = CT_HASH_RGB (r, g, b);
9440 int i = hash % CT_SIZE;
9441 struct ct_color *p;
9442
9443 for (p = ct_table[i]; p; p = p->next)
9444 if (p->r == r && p->g == g && p->b == b)
9445 break;
9446
9447 if (p == NULL)
9448 {
9449 COLORREF color;
9450 Colormap cmap;
9451 int rc;
9452
9453 color = PALETTERGB (r, g, b);
9454
9455 ++ct_colors_allocated;
9456
9457 p = (struct ct_color *) xmalloc (sizeof *p);
9458 p->r = r;
9459 p->g = g;
9460 p->b = b;
9461 p->pixel = color;
9462 p->next = ct_table[i];
9463 ct_table[i] = p;
9464 }
9465
9466 return p->pixel;
9467 }
9468
9469
9470 /* Look up pixel color PIXEL which is used on frame F in the color
9471 table. If not already present, allocate it. Value is PIXEL. */
9472
9473 static unsigned long
9474 lookup_pixel_color (f, pixel)
9475 struct frame *f;
9476 unsigned long pixel;
9477 {
9478 int i = pixel % CT_SIZE;
9479 struct ct_color *p;
9480
9481 for (p = ct_table[i]; p; p = p->next)
9482 if (p->pixel == pixel)
9483 break;
9484
9485 if (p == NULL)
9486 {
9487 XColor color;
9488 Colormap cmap;
9489 int rc;
9490
9491 BLOCK_INPUT;
9492
9493 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9494 color.pixel = pixel;
9495 XQueryColor (NULL, cmap, &color);
9496 rc = x_alloc_nearest_color (f, cmap, &color);
9497 UNBLOCK_INPUT;
9498
9499 if (rc)
9500 {
9501 ++ct_colors_allocated;
9502
9503 p = (struct ct_color *) xmalloc (sizeof *p);
9504 p->r = color.red;
9505 p->g = color.green;
9506 p->b = color.blue;
9507 p->pixel = pixel;
9508 p->next = ct_table[i];
9509 ct_table[i] = p;
9510 }
9511 else
9512 return FRAME_FOREGROUND_PIXEL (f);
9513 }
9514 return p->pixel;
9515 }
9516
9517
9518 /* Value is a vector of all pixel colors contained in the color table,
9519 allocated via xmalloc. Set *N to the number of colors. */
9520
9521 static unsigned long *
9522 colors_in_color_table (n)
9523 int *n;
9524 {
9525 int i, j;
9526 struct ct_color *p;
9527 unsigned long *colors;
9528
9529 if (ct_colors_allocated == 0)
9530 {
9531 *n = 0;
9532 colors = NULL;
9533 }
9534 else
9535 {
9536 colors = (unsigned long *) xmalloc (ct_colors_allocated
9537 * sizeof *colors);
9538 *n = ct_colors_allocated;
9539
9540 for (i = j = 0; i < CT_SIZE; ++i)
9541 for (p = ct_table[i]; p; p = p->next)
9542 colors[j++] = p->pixel;
9543 }
9544
9545 return colors;
9546 }
9547
9548 #endif /* TODO */
9549
9550 \f
9551 /***********************************************************************
9552 Algorithms
9553 ***********************************************************************/
9554 static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
9555 static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
9556 static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
9557 static void XPutPixel (XImage *, int, int, COLORREF);
9558
9559 /* Non-zero means draw a cross on images having `:conversion
9560 disabled'. */
9561
9562 int cross_disabled_images;
9563
9564 /* Edge detection matrices for different edge-detection
9565 strategies. */
9566
9567 static int emboss_matrix[9] = {
9568 /* x - 1 x x + 1 */
9569 2, -1, 0, /* y - 1 */
9570 -1, 0, 1, /* y */
9571 0, 1, -2 /* y + 1 */
9572 };
9573
9574 static int laplace_matrix[9] = {
9575 /* x - 1 x x + 1 */
9576 1, 0, 0, /* y - 1 */
9577 0, 0, 0, /* y */
9578 0, 0, -1 /* y + 1 */
9579 };
9580
9581 /* Value is the intensity of the color whose red/green/blue values
9582 are R, G, and B. */
9583
9584 #define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
9585
9586
9587 /* On frame F, return an array of XColor structures describing image
9588 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
9589 non-zero means also fill the red/green/blue members of the XColor
9590 structures. Value is a pointer to the array of XColors structures,
9591 allocated with xmalloc; it must be freed by the caller. */
9592
9593 static XColor *
9594 x_to_xcolors (f, img, rgb_p)
9595 struct frame *f;
9596 struct image *img;
9597 int rgb_p;
9598 {
9599 int x, y;
9600 XColor *colors, *p;
9601 HDC hdc, bmpdc;
9602 HGDIOBJ prev;
9603
9604 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
9605
9606 /* Load the image into a memory device context. */
9607 hdc = get_frame_dc (f);
9608 bmpdc = CreateCompatibleDC (hdc);
9609 release_frame_dc (f, hdc);
9610 prev = SelectObject (bmpdc, img->pixmap);
9611
9612 /* Fill the `pixel' members of the XColor array. I wished there
9613 were an easy and portable way to circumvent XGetPixel. */
9614 p = colors;
9615 for (y = 0; y < img->height; ++y)
9616 {
9617 XColor *row = p;
9618
9619 for (x = 0; x < img->width; ++x, ++p)
9620 {
9621 /* TODO: palette support needed here? */
9622 p->pixel = GetPixel (bmpdc, x, y);
9623
9624 if (rgb_p)
9625 {
9626 p->red = 256 * GetRValue (p->pixel);
9627 p->green = 256 * GetGValue (p->pixel);
9628 p->blue = 256 * GetBValue (p->pixel);
9629 }
9630 }
9631 }
9632
9633 SelectObject (bmpdc, prev);
9634 DeleteDC (bmpdc);
9635
9636 return colors;
9637 }
9638
9639 /* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
9640 created with CreateDIBSection, with the pointer to the bit values
9641 stored in ximg->data. */
9642
9643 static void XPutPixel (ximg, x, y, color)
9644 XImage * ximg;
9645 int x, y;
9646 COLORREF color;
9647 {
9648 int width = ximg->info.bmiHeader.biWidth;
9649 int height = ximg->info.bmiHeader.biHeight;
9650 unsigned char * pixel;
9651
9652 /* True color images. */
9653 if (ximg->info.bmiHeader.biBitCount == 24)
9654 {
9655 int rowbytes = width * 3;
9656 /* Ensure scanlines are aligned on 4 byte boundaries. */
9657 if (rowbytes % 4)
9658 rowbytes += 4 - (rowbytes % 4);
9659
9660 pixel = ximg->data + y * rowbytes + x * 3;
9661 /* Windows bitmaps are in BGR order. */
9662 *pixel = GetBValue (color);
9663 *(pixel + 1) = GetGValue (color);
9664 *(pixel + 2) = GetRValue (color);
9665 }
9666 /* Monochrome images. */
9667 else if (ximg->info.bmiHeader.biBitCount == 1)
9668 {
9669 int rowbytes = width / 8;
9670 /* Ensure scanlines are aligned on 4 byte boundaries. */
9671 if (rowbytes % 4)
9672 rowbytes += 4 - (rowbytes % 4);
9673 pixel = ximg->data + y * rowbytes + x / 8;
9674 /* Filter out palette info. */
9675 if (color & 0x00ffffff)
9676 *pixel = *pixel | (1 << x % 8);
9677 else
9678 *pixel = *pixel & ~(1 << x % 8);
9679 }
9680 else
9681 image_error ("XPutPixel: palette image not supported.", Qnil, Qnil);
9682 }
9683
9684 /* Create IMG->pixmap from an array COLORS of XColor structures, whose
9685 RGB members are set. F is the frame on which this all happens.
9686 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
9687
9688 static void
9689 x_from_xcolors (f, img, colors)
9690 struct frame *f;
9691 struct image *img;
9692 XColor *colors;
9693 {
9694 int x, y;
9695 XImage *oimg;
9696 Pixmap pixmap;
9697 XColor *p;
9698 #if 0 /* TODO: color tables. */
9699 init_color_table ();
9700 #endif
9701 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9702 &oimg, &pixmap);
9703 p = colors;
9704 for (y = 0; y < img->height; ++y)
9705 for (x = 0; x < img->width; ++x, ++p)
9706 {
9707 unsigned long pixel;
9708 #if 0 /* TODO: color tables. */
9709 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
9710 #else
9711 pixel = PALETTERGB (p->red / 256, p->green / 256, p->blue / 256);
9712 #endif
9713 XPutPixel (oimg, x, y, pixel);
9714 }
9715
9716 xfree (colors);
9717 x_clear_image_1 (f, img, 1, 0, 1);
9718
9719 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9720 x_destroy_x_image (oimg);
9721 img->pixmap = pixmap;
9722 #if 0 /* TODO: color tables. */
9723 img->colors = colors_in_color_table (&img->ncolors);
9724 free_color_table ();
9725 #endif
9726 }
9727
9728
9729 /* On frame F, perform edge-detection on image IMG.
9730
9731 MATRIX is a nine-element array specifying the transformation
9732 matrix. See emboss_matrix for an example.
9733
9734 COLOR_ADJUST is a color adjustment added to each pixel of the
9735 outgoing image. */
9736
9737 static void
9738 x_detect_edges (f, img, matrix, color_adjust)
9739 struct frame *f;
9740 struct image *img;
9741 int matrix[9], color_adjust;
9742 {
9743 XColor *colors = x_to_xcolors (f, img, 1);
9744 XColor *new, *p;
9745 int x, y, i, sum;
9746
9747 for (i = sum = 0; i < 9; ++i)
9748 sum += abs (matrix[i]);
9749
9750 #define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
9751
9752 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
9753
9754 for (y = 0; y < img->height; ++y)
9755 {
9756 p = COLOR (new, 0, y);
9757 p->red = p->green = p->blue = 0xffff/2;
9758 p = COLOR (new, img->width - 1, y);
9759 p->red = p->green = p->blue = 0xffff/2;
9760 }
9761
9762 for (x = 1; x < img->width - 1; ++x)
9763 {
9764 p = COLOR (new, x, 0);
9765 p->red = p->green = p->blue = 0xffff/2;
9766 p = COLOR (new, x, img->height - 1);
9767 p->red = p->green = p->blue = 0xffff/2;
9768 }
9769
9770 for (y = 1; y < img->height - 1; ++y)
9771 {
9772 p = COLOR (new, 1, y);
9773
9774 for (x = 1; x < img->width - 1; ++x, ++p)
9775 {
9776 int r, g, b, y1, x1;
9777
9778 r = g = b = i = 0;
9779 for (y1 = y - 1; y1 < y + 2; ++y1)
9780 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
9781 if (matrix[i])
9782 {
9783 XColor *t = COLOR (colors, x1, y1);
9784 r += matrix[i] * t->red;
9785 g += matrix[i] * t->green;
9786 b += matrix[i] * t->blue;
9787 }
9788
9789 r = (r / sum + color_adjust) & 0xffff;
9790 g = (g / sum + color_adjust) & 0xffff;
9791 b = (b / sum + color_adjust) & 0xffff;
9792 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
9793 }
9794 }
9795
9796 xfree (colors);
9797 x_from_xcolors (f, img, new);
9798
9799 #undef COLOR
9800 }
9801
9802
9803 /* Perform the pre-defined `emboss' edge-detection on image IMG
9804 on frame F. */
9805
9806 static void
9807 x_emboss (f, img)
9808 struct frame *f;
9809 struct image *img;
9810 {
9811 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
9812 }
9813
9814
9815 /* Transform image IMG which is used on frame F with a Laplace
9816 edge-detection algorithm. The result is an image that can be used
9817 to draw disabled buttons, for example. */
9818
9819 static void
9820 x_laplace (f, img)
9821 struct frame *f;
9822 struct image *img;
9823 {
9824 x_detect_edges (f, img, laplace_matrix, 45000);
9825 }
9826
9827
9828 /* Perform edge-detection on image IMG on frame F, with specified
9829 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
9830
9831 MATRIX must be either
9832
9833 - a list of at least 9 numbers in row-major form
9834 - a vector of at least 9 numbers
9835
9836 COLOR_ADJUST nil means use a default; otherwise it must be a
9837 number. */
9838
9839 static void
9840 x_edge_detection (f, img, matrix, color_adjust)
9841 struct frame *f;
9842 struct image *img;
9843 Lisp_Object matrix, color_adjust;
9844 {
9845 int i = 0;
9846 int trans[9];
9847
9848 if (CONSP (matrix))
9849 {
9850 for (i = 0;
9851 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
9852 ++i, matrix = XCDR (matrix))
9853 trans[i] = XFLOATINT (XCAR (matrix));
9854 }
9855 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
9856 {
9857 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
9858 trans[i] = XFLOATINT (AREF (matrix, i));
9859 }
9860
9861 if (NILP (color_adjust))
9862 color_adjust = make_number (0xffff / 2);
9863
9864 if (i == 9 && NUMBERP (color_adjust))
9865 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
9866 }
9867
9868
9869 /* Transform image IMG on frame F so that it looks disabled. */
9870
9871 static void
9872 x_disable_image (f, img)
9873 struct frame *f;
9874 struct image *img;
9875 {
9876 struct w32_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
9877
9878 if (dpyinfo->n_planes * dpyinfo->n_cbits >= 2)
9879 {
9880 /* Color (or grayscale). Convert to gray, and equalize. Just
9881 drawing such images with a stipple can look very odd, so
9882 we're using this method instead. */
9883 XColor *colors = x_to_xcolors (f, img, 1);
9884 XColor *p, *end;
9885 const int h = 15000;
9886 const int l = 30000;
9887
9888 for (p = colors, end = colors + img->width * img->height;
9889 p < end;
9890 ++p)
9891 {
9892 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
9893 int i2 = (0xffff - h - l) * i / 0xffff + l;
9894 p->red = p->green = p->blue = i2;
9895 }
9896
9897 x_from_xcolors (f, img, colors);
9898 }
9899
9900 /* Draw a cross over the disabled image, if we must or if we
9901 should. */
9902 if (dpyinfo->n_planes * dpyinfo->n_cbits < 2 || cross_disabled_images)
9903 {
9904 HDC hdc, bmpdc;
9905 HGDIOBJ prev;
9906
9907 hdc = get_frame_dc (f);
9908 bmpdc = CreateCompatibleDC (hdc);
9909 release_frame_dc (f, hdc);
9910
9911 prev = SelectObject (bmpdc, img->pixmap);
9912
9913 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
9914 MoveToEx (bmpdc, 0, 0, NULL);
9915 LineTo (bmpdc, img->width - 1, img->height - 1);
9916 MoveToEx (bmpdc, 0, img->height - 1, NULL);
9917 LineTo (bmpdc, img->width - 1, 0);
9918
9919 if (img->mask)
9920 {
9921 SelectObject (bmpdc, img->mask);
9922 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
9923 MoveToEx (bmpdc, 0, 0, NULL);
9924 LineTo (bmpdc, img->width - 1, img->height - 1);
9925 MoveToEx (bmpdc, 0, img->height - 1, NULL);
9926 LineTo (bmpdc, img->width - 1, 0);
9927 }
9928 SelectObject (bmpdc, prev);
9929 DeleteDC (bmpdc);
9930 }
9931 }
9932
9933
9934 /* Build a mask for image IMG which is used on frame F. FILE is the
9935 name of an image file, for error messages. HOW determines how to
9936 determine the background color of IMG. If it is a list '(R G B)',
9937 with R, G, and B being integers >= 0, take that as the color of the
9938 background. Otherwise, determine the background color of IMG
9939 heuristically. Value is non-zero if successful. */
9940
9941 static int
9942 x_build_heuristic_mask (f, img, how)
9943 struct frame *f;
9944 struct image *img;
9945 Lisp_Object how;
9946 {
9947 HDC img_dc, frame_dc;
9948 HGDIOBJ prev;
9949 char *mask_img;
9950 int x, y, rc, use_img_background;
9951 unsigned long bg = 0;
9952 int row_width;
9953
9954 if (img->mask)
9955 {
9956 DeleteObject (img->mask);
9957 img->mask = NULL;
9958 img->background_transparent_valid = 0;
9959 }
9960
9961 /* Create the bit array serving as mask. */
9962 row_width = (img->width + 7) / 8;
9963 mask_img = xmalloc (row_width * img->height);
9964 bzero (mask_img, row_width * img->height);
9965
9966 /* Create a memory device context for IMG->pixmap. */
9967 frame_dc = get_frame_dc (f);
9968 img_dc = CreateCompatibleDC (frame_dc);
9969 release_frame_dc (f, frame_dc);
9970 prev = SelectObject (img_dc, img->pixmap);
9971
9972 /* Determine the background color of img_dc. If HOW is `(R G B)'
9973 take that as color. Otherwise, use the image's background color. */
9974 use_img_background = 1;
9975
9976 if (CONSP (how))
9977 {
9978 int rgb[3], i;
9979
9980 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
9981 {
9982 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9983 how = XCDR (how);
9984 }
9985
9986 if (i == 3 && NILP (how))
9987 {
9988 char color_name[30];
9989 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
9990 bg = x_alloc_image_color (f, img, build_string (color_name), 0)
9991 & 0x00ffffff; /* Filter out palette info. */
9992 use_img_background = 0;
9993 }
9994 }
9995
9996 if (use_img_background)
9997 bg = four_corners_best (img_dc, img->width, img->height);
9998
9999 /* Set all bits in mask_img to 1 whose color in ximg is different
10000 from the background color bg. */
10001 for (y = 0; y < img->height; ++y)
10002 for (x = 0; x < img->width; ++x)
10003 {
10004 COLORREF p = GetPixel (img_dc, x, y);
10005 if (p != bg)
10006 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
10007 }
10008
10009 /* Create the mask image. */
10010 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
10011 mask_img);
10012
10013 /* Fill in the background_transparent field while we have the mask handy. */
10014 SelectObject (img_dc, img->mask);
10015
10016 image_background_transparent (img, f, img_dc);
10017
10018 /* Put mask_img into img->mask. */
10019 x_destroy_x_image ((XImage *)mask_img);
10020 SelectObject (img_dc, prev);
10021 DeleteDC (img_dc);
10022
10023 return 1;
10024 }
10025
10026 \f
10027 /***********************************************************************
10028 PBM (mono, gray, color)
10029 ***********************************************************************/
10030
10031 static int pbm_image_p P_ ((Lisp_Object object));
10032 static int pbm_load P_ ((struct frame *f, struct image *img));
10033 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
10034
10035 /* The symbol `pbm' identifying images of this type. */
10036
10037 Lisp_Object Qpbm;
10038
10039 /* Indices of image specification fields in gs_format, below. */
10040
10041 enum pbm_keyword_index
10042 {
10043 PBM_TYPE,
10044 PBM_FILE,
10045 PBM_DATA,
10046 PBM_ASCENT,
10047 PBM_MARGIN,
10048 PBM_RELIEF,
10049 PBM_ALGORITHM,
10050 PBM_HEURISTIC_MASK,
10051 PBM_MASK,
10052 PBM_FOREGROUND,
10053 PBM_BACKGROUND,
10054 PBM_LAST
10055 };
10056
10057 /* Vector of image_keyword structures describing the format
10058 of valid user-defined image specifications. */
10059
10060 static struct image_keyword pbm_format[PBM_LAST] =
10061 {
10062 {":type", IMAGE_SYMBOL_VALUE, 1},
10063 {":file", IMAGE_STRING_VALUE, 0},
10064 {":data", IMAGE_STRING_VALUE, 0},
10065 {":ascent", IMAGE_ASCENT_VALUE, 0},
10066 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10067 {":relief", IMAGE_INTEGER_VALUE, 0},
10068 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10069 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10070 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10071 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
10072 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
10073 };
10074
10075 /* Structure describing the image type `pbm'. */
10076
10077 static struct image_type pbm_type =
10078 {
10079 &Qpbm,
10080 pbm_image_p,
10081 pbm_load,
10082 x_clear_image,
10083 NULL
10084 };
10085
10086
10087 /* Return non-zero if OBJECT is a valid PBM image specification. */
10088
10089 static int
10090 pbm_image_p (object)
10091 Lisp_Object object;
10092 {
10093 struct image_keyword fmt[PBM_LAST];
10094
10095 bcopy (pbm_format, fmt, sizeof fmt);
10096
10097 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
10098 return 0;
10099
10100 /* Must specify either :data or :file. */
10101 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
10102 }
10103
10104
10105 /* Scan a decimal number from *S and return it. Advance *S while
10106 reading the number. END is the end of the string. Value is -1 at
10107 end of input. */
10108
10109 static int
10110 pbm_scan_number (s, end)
10111 unsigned char **s, *end;
10112 {
10113 int c, val = -1;
10114
10115 while (*s < end)
10116 {
10117 /* Skip white-space. */
10118 while (*s < end && (c = *(*s)++, isspace (c)))
10119 ;
10120
10121 if (c == '#')
10122 {
10123 /* Skip comment to end of line. */
10124 while (*s < end && (c = *(*s)++, c != '\n'))
10125 ;
10126 }
10127 else if (isdigit (c))
10128 {
10129 /* Read decimal number. */
10130 val = c - '0';
10131 while (*s < end && (c = *(*s)++, isdigit (c)))
10132 val = 10 * val + c - '0';
10133 break;
10134 }
10135 else
10136 break;
10137 }
10138
10139 return val;
10140 }
10141
10142
10143 /* Read FILE into memory. Value is a pointer to a buffer allocated
10144 with xmalloc holding FILE's contents. Value is null if an error
10145 occurred. *SIZE is set to the size of the file. */
10146
10147 static char *
10148 pbm_read_file (file, size)
10149 Lisp_Object file;
10150 int *size;
10151 {
10152 FILE *fp = NULL;
10153 char *buf = NULL;
10154 struct stat st;
10155
10156 if (stat (SDATA (file), &st) == 0
10157 && (fp = fopen (SDATA (file), "rb")) != NULL
10158 && (buf = (char *) xmalloc (st.st_size),
10159 fread (buf, 1, st.st_size, fp) == st.st_size))
10160 {
10161 *size = st.st_size;
10162 fclose (fp);
10163 }
10164 else
10165 {
10166 if (fp)
10167 fclose (fp);
10168 if (buf)
10169 {
10170 xfree (buf);
10171 buf = NULL;
10172 }
10173 }
10174
10175 return buf;
10176 }
10177
10178
10179 /* Load PBM image IMG for use on frame F. */
10180
10181 static int
10182 pbm_load (f, img)
10183 struct frame *f;
10184 struct image *img;
10185 {
10186 int raw_p, x, y;
10187 int width, height, max_color_idx = 0;
10188 XImage *ximg;
10189 Lisp_Object file, specified_file;
10190 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
10191 struct gcpro gcpro1;
10192 unsigned char *contents = NULL;
10193 unsigned char *end, *p;
10194 int size;
10195
10196 specified_file = image_spec_value (img->spec, QCfile, NULL);
10197 file = Qnil;
10198 GCPRO1 (file);
10199
10200 if (STRINGP (specified_file))
10201 {
10202 file = x_find_image_file (specified_file);
10203 if (!STRINGP (file))
10204 {
10205 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10206 UNGCPRO;
10207 return 0;
10208 }
10209
10210 contents = slurp_file (SDATA (file), &size);
10211 if (contents == NULL)
10212 {
10213 image_error ("Error reading `%s'", file, Qnil);
10214 UNGCPRO;
10215 return 0;
10216 }
10217
10218 p = contents;
10219 end = contents + size;
10220 }
10221 else
10222 {
10223 Lisp_Object data;
10224 data = image_spec_value (img->spec, QCdata, NULL);
10225 p = SDATA (data);
10226 end = p + SBYTES (data);
10227 }
10228
10229 /* Check magic number. */
10230 if (end - p < 2 || *p++ != 'P')
10231 {
10232 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10233 error:
10234 xfree (contents);
10235 UNGCPRO;
10236 return 0;
10237 }
10238
10239 switch (*p++)
10240 {
10241 case '1':
10242 raw_p = 0, type = PBM_MONO;
10243 break;
10244
10245 case '2':
10246 raw_p = 0, type = PBM_GRAY;
10247 break;
10248
10249 case '3':
10250 raw_p = 0, type = PBM_COLOR;
10251 break;
10252
10253 case '4':
10254 raw_p = 1, type = PBM_MONO;
10255 break;
10256
10257 case '5':
10258 raw_p = 1, type = PBM_GRAY;
10259 break;
10260
10261 case '6':
10262 raw_p = 1, type = PBM_COLOR;
10263 break;
10264
10265 default:
10266 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10267 goto error;
10268 }
10269
10270 /* Read width, height, maximum color-component. Characters
10271 starting with `#' up to the end of a line are ignored. */
10272 width = pbm_scan_number (&p, end);
10273 height = pbm_scan_number (&p, end);
10274
10275 if (type != PBM_MONO)
10276 {
10277 max_color_idx = pbm_scan_number (&p, end);
10278 if (raw_p && max_color_idx > 255)
10279 max_color_idx = 255;
10280 }
10281
10282 if (width < 0
10283 || height < 0
10284 || (type != PBM_MONO && max_color_idx < 0))
10285 goto error;
10286
10287 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
10288 goto error;
10289
10290 #if 0 /* TODO: color tables. */
10291 /* Initialize the color hash table. */
10292 init_color_table ();
10293 #endif
10294
10295 if (type == PBM_MONO)
10296 {
10297 int c = 0, g;
10298 struct image_keyword fmt[PBM_LAST];
10299 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
10300 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
10301
10302 /* Parse the image specification. */
10303 bcopy (pbm_format, fmt, sizeof fmt);
10304 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
10305
10306 /* Get foreground and background colors, maybe allocate colors. */
10307 if (fmt[PBM_FOREGROUND].count
10308 && STRINGP (fmt[PBM_FOREGROUND].value))
10309 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
10310 if (fmt[PBM_BACKGROUND].count
10311 && STRINGP (fmt[PBM_BACKGROUND].value))
10312 {
10313 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
10314 img->background = bg;
10315 img->background_valid = 1;
10316 }
10317
10318 for (y = 0; y < height; ++y)
10319 for (x = 0; x < width; ++x)
10320 {
10321 if (raw_p)
10322 {
10323 if ((x & 7) == 0)
10324 c = *p++;
10325 g = c & 0x80;
10326 c <<= 1;
10327 }
10328 else
10329 g = pbm_scan_number (&p, end);
10330
10331 XPutPixel (ximg, x, y, g ? fg : bg);
10332 }
10333 }
10334 else
10335 {
10336 for (y = 0; y < height; ++y)
10337 for (x = 0; x < width; ++x)
10338 {
10339 int r, g, b;
10340
10341 if (type == PBM_GRAY)
10342 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
10343 else if (raw_p)
10344 {
10345 r = *p++;
10346 g = *p++;
10347 b = *p++;
10348 }
10349 else
10350 {
10351 r = pbm_scan_number (&p, end);
10352 g = pbm_scan_number (&p, end);
10353 b = pbm_scan_number (&p, end);
10354 }
10355
10356 if (r < 0 || g < 0 || b < 0)
10357 {
10358 x_destroy_x_image (ximg);
10359 image_error ("Invalid pixel value in image `%s'",
10360 img->spec, Qnil);
10361 goto error;
10362 }
10363
10364 /* RGB values are now in the range 0..max_color_idx.
10365 Scale this to the range 0..0xff supported by W32. */
10366 r = (int) ((double) r * 255 / max_color_idx);
10367 g = (int) ((double) g * 255 / max_color_idx);
10368 b = (int) ((double) b * 255 / max_color_idx);
10369 XPutPixel (ximg, x, y,
10370 #if 0 /* TODO: color tables. */
10371 lookup_rgb_color (f, r, g, b));
10372 #else
10373 PALETTERGB (r, g, b));
10374 #endif
10375 }
10376 }
10377
10378 #if 0 /* TODO: color tables. */
10379 /* Store in IMG->colors the colors allocated for the image, and
10380 free the color table. */
10381 img->colors = colors_in_color_table (&img->ncolors);
10382 free_color_table ();
10383 #endif
10384 /* Maybe fill in the background field while we have ximg handy. */
10385 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
10386 IMAGE_BACKGROUND (img, f, ximg);
10387
10388 /* Put the image into a pixmap. */
10389 x_put_x_image (f, ximg, img->pixmap, width, height);
10390 x_destroy_x_image (ximg);
10391
10392 img->width = width;
10393 img->height = height;
10394
10395 UNGCPRO;
10396 xfree (contents);
10397 return 1;
10398 }
10399
10400 \f
10401 /***********************************************************************
10402 PNG
10403 ***********************************************************************/
10404
10405 #if HAVE_PNG
10406
10407 #include <png.h>
10408
10409 /* Function prototypes. */
10410
10411 static int png_image_p P_ ((Lisp_Object object));
10412 static int png_load P_ ((struct frame *f, struct image *img));
10413
10414 /* The symbol `png' identifying images of this type. */
10415
10416 Lisp_Object Qpng;
10417
10418 /* Indices of image specification fields in png_format, below. */
10419
10420 enum png_keyword_index
10421 {
10422 PNG_TYPE,
10423 PNG_DATA,
10424 PNG_FILE,
10425 PNG_ASCENT,
10426 PNG_MARGIN,
10427 PNG_RELIEF,
10428 PNG_ALGORITHM,
10429 PNG_HEURISTIC_MASK,
10430 PNG_MASK,
10431 PNG_BACKGROUND,
10432 PNG_LAST
10433 };
10434
10435 /* Vector of image_keyword structures describing the format
10436 of valid user-defined image specifications. */
10437
10438 static struct image_keyword png_format[PNG_LAST] =
10439 {
10440 {":type", IMAGE_SYMBOL_VALUE, 1},
10441 {":data", IMAGE_STRING_VALUE, 0},
10442 {":file", IMAGE_STRING_VALUE, 0},
10443 {":ascent", IMAGE_ASCENT_VALUE, 0},
10444 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10445 {":relief", IMAGE_INTEGER_VALUE, 0},
10446 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10447 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10448 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10449 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
10450 };
10451
10452 /* Structure describing the image type `png'. */
10453
10454 static struct image_type png_type =
10455 {
10456 &Qpng,
10457 png_image_p,
10458 png_load,
10459 x_clear_image,
10460 NULL
10461 };
10462
10463 /* PNG library details. */
10464
10465 DEF_IMGLIB_FN (png_get_io_ptr);
10466 DEF_IMGLIB_FN (png_check_sig);
10467 DEF_IMGLIB_FN (png_create_read_struct);
10468 DEF_IMGLIB_FN (png_create_info_struct);
10469 DEF_IMGLIB_FN (png_destroy_read_struct);
10470 DEF_IMGLIB_FN (png_set_read_fn);
10471 DEF_IMGLIB_FN (png_init_io);
10472 DEF_IMGLIB_FN (png_set_sig_bytes);
10473 DEF_IMGLIB_FN (png_read_info);
10474 DEF_IMGLIB_FN (png_get_IHDR);
10475 DEF_IMGLIB_FN (png_get_valid);
10476 DEF_IMGLIB_FN (png_set_strip_16);
10477 DEF_IMGLIB_FN (png_set_expand);
10478 DEF_IMGLIB_FN (png_set_gray_to_rgb);
10479 DEF_IMGLIB_FN (png_set_background);
10480 DEF_IMGLIB_FN (png_get_bKGD);
10481 DEF_IMGLIB_FN (png_read_update_info);
10482 DEF_IMGLIB_FN (png_get_channels);
10483 DEF_IMGLIB_FN (png_get_rowbytes);
10484 DEF_IMGLIB_FN (png_read_image);
10485 DEF_IMGLIB_FN (png_read_end);
10486 DEF_IMGLIB_FN (png_error);
10487
10488 static int
10489 init_png_functions (library)
10490 HMODULE library;
10491 {
10492 LOAD_IMGLIB_FN (library, png_get_io_ptr);
10493 LOAD_IMGLIB_FN (library, png_check_sig);
10494 LOAD_IMGLIB_FN (library, png_create_read_struct);
10495 LOAD_IMGLIB_FN (library, png_create_info_struct);
10496 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
10497 LOAD_IMGLIB_FN (library, png_set_read_fn);
10498 LOAD_IMGLIB_FN (library, png_init_io);
10499 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
10500 LOAD_IMGLIB_FN (library, png_read_info);
10501 LOAD_IMGLIB_FN (library, png_get_IHDR);
10502 LOAD_IMGLIB_FN (library, png_get_valid);
10503 LOAD_IMGLIB_FN (library, png_set_strip_16);
10504 LOAD_IMGLIB_FN (library, png_set_expand);
10505 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
10506 LOAD_IMGLIB_FN (library, png_set_background);
10507 LOAD_IMGLIB_FN (library, png_get_bKGD);
10508 LOAD_IMGLIB_FN (library, png_read_update_info);
10509 LOAD_IMGLIB_FN (library, png_get_channels);
10510 LOAD_IMGLIB_FN (library, png_get_rowbytes);
10511 LOAD_IMGLIB_FN (library, png_read_image);
10512 LOAD_IMGLIB_FN (library, png_read_end);
10513 LOAD_IMGLIB_FN (library, png_error);
10514 return 1;
10515 }
10516
10517 /* Return non-zero if OBJECT is a valid PNG image specification. */
10518
10519 static int
10520 png_image_p (object)
10521 Lisp_Object object;
10522 {
10523 struct image_keyword fmt[PNG_LAST];
10524 bcopy (png_format, fmt, sizeof fmt);
10525
10526 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
10527 return 0;
10528
10529 /* Must specify either the :data or :file keyword. */
10530 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
10531 }
10532
10533
10534 /* Error and warning handlers installed when the PNG library
10535 is initialized. */
10536
10537 static void
10538 my_png_error (png_ptr, msg)
10539 png_struct *png_ptr;
10540 char *msg;
10541 {
10542 xassert (png_ptr != NULL);
10543 image_error ("PNG error: %s", build_string (msg), Qnil);
10544 longjmp (png_ptr->jmpbuf, 1);
10545 }
10546
10547
10548 static void
10549 my_png_warning (png_ptr, msg)
10550 png_struct *png_ptr;
10551 char *msg;
10552 {
10553 xassert (png_ptr != NULL);
10554 image_error ("PNG warning: %s", build_string (msg), Qnil);
10555 }
10556
10557 /* Memory source for PNG decoding. */
10558
10559 struct png_memory_storage
10560 {
10561 unsigned char *bytes; /* The data */
10562 size_t len; /* How big is it? */
10563 int index; /* Where are we? */
10564 };
10565
10566
10567 /* Function set as reader function when reading PNG image from memory.
10568 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
10569 bytes from the input to DATA. */
10570
10571 static void
10572 png_read_from_memory (png_ptr, data, length)
10573 png_structp png_ptr;
10574 png_bytep data;
10575 png_size_t length;
10576 {
10577 struct png_memory_storage *tbr
10578 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
10579
10580 if (length > tbr->len - tbr->index)
10581 fn_png_error (png_ptr, "Read error");
10582
10583 bcopy (tbr->bytes + tbr->index, data, length);
10584 tbr->index = tbr->index + length;
10585 }
10586
10587 /* Load PNG image IMG for use on frame F. Value is non-zero if
10588 successful. */
10589
10590 static int
10591 png_load (f, img)
10592 struct frame *f;
10593 struct image *img;
10594 {
10595 Lisp_Object file, specified_file;
10596 Lisp_Object specified_data;
10597 int x, y, i;
10598 XImage *ximg, *mask_img = NULL;
10599 struct gcpro gcpro1;
10600 png_struct *png_ptr = NULL;
10601 png_info *info_ptr = NULL, *end_info = NULL;
10602 FILE *volatile fp = NULL;
10603 png_byte sig[8];
10604 png_byte * volatile pixels = NULL;
10605 png_byte ** volatile rows = NULL;
10606 png_uint_32 width, height;
10607 int bit_depth, color_type, interlace_type;
10608 png_byte channels;
10609 png_uint_32 row_bytes;
10610 int transparent_p;
10611 double screen_gamma, image_gamma;
10612 int intent;
10613 struct png_memory_storage tbr; /* Data to be read */
10614
10615 /* Find out what file to load. */
10616 specified_file = image_spec_value (img->spec, QCfile, NULL);
10617 specified_data = image_spec_value (img->spec, QCdata, NULL);
10618 file = Qnil;
10619 GCPRO1 (file);
10620
10621 if (NILP (specified_data))
10622 {
10623 file = x_find_image_file (specified_file);
10624 if (!STRINGP (file))
10625 {
10626 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10627 UNGCPRO;
10628 return 0;
10629 }
10630
10631 /* Open the image file. */
10632 fp = fopen (SDATA (file), "rb");
10633 if (!fp)
10634 {
10635 image_error ("Cannot open image file `%s'", file, Qnil);
10636 UNGCPRO;
10637 fclose (fp);
10638 return 0;
10639 }
10640
10641 /* Check PNG signature. */
10642 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
10643 || !fn_png_check_sig (sig, sizeof sig))
10644 {
10645 image_error ("Not a PNG file: `%s'", file, Qnil);
10646 UNGCPRO;
10647 fclose (fp);
10648 return 0;
10649 }
10650 }
10651 else
10652 {
10653 /* Read from memory. */
10654 tbr.bytes = SDATA (specified_data);
10655 tbr.len = SBYTES (specified_data);
10656 tbr.index = 0;
10657
10658 /* Check PNG signature. */
10659 if (tbr.len < sizeof sig
10660 || !fn_png_check_sig (tbr.bytes, sizeof sig))
10661 {
10662 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10663 UNGCPRO;
10664 return 0;
10665 }
10666
10667 /* Need to skip past the signature. */
10668 tbr.bytes += sizeof (sig);
10669 }
10670
10671 /* Initialize read and info structs for PNG lib. */
10672 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10673 my_png_error, my_png_warning);
10674 if (!png_ptr)
10675 {
10676 if (fp) fclose (fp);
10677 UNGCPRO;
10678 return 0;
10679 }
10680
10681 info_ptr = fn_png_create_info_struct (png_ptr);
10682 if (!info_ptr)
10683 {
10684 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
10685 if (fp) fclose (fp);
10686 UNGCPRO;
10687 return 0;
10688 }
10689
10690 end_info = fn_png_create_info_struct (png_ptr);
10691 if (!end_info)
10692 {
10693 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
10694 if (fp) fclose (fp);
10695 UNGCPRO;
10696 return 0;
10697 }
10698
10699 /* Set error jump-back. We come back here when the PNG library
10700 detects an error. */
10701 if (setjmp (png_ptr->jmpbuf))
10702 {
10703 error:
10704 if (png_ptr)
10705 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10706 xfree (pixels);
10707 xfree (rows);
10708 if (fp) fclose (fp);
10709 UNGCPRO;
10710 return 0;
10711 }
10712
10713 /* Read image info. */
10714 if (!NILP (specified_data))
10715 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
10716 else
10717 fn_png_init_io (png_ptr, fp);
10718
10719 fn_png_set_sig_bytes (png_ptr, sizeof sig);
10720 fn_png_read_info (png_ptr, info_ptr);
10721 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10722 &interlace_type, NULL, NULL);
10723
10724 /* If image contains simply transparency data, we prefer to
10725 construct a clipping mask. */
10726 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
10727 transparent_p = 1;
10728 else
10729 transparent_p = 0;
10730
10731 /* This function is easier to write if we only have to handle
10732 one data format: RGB or RGBA with 8 bits per channel. Let's
10733 transform other formats into that format. */
10734
10735 /* Strip more than 8 bits per channel. */
10736 if (bit_depth == 16)
10737 fn_png_set_strip_16 (png_ptr);
10738
10739 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10740 if available. */
10741 fn_png_set_expand (png_ptr);
10742
10743 /* Convert grayscale images to RGB. */
10744 if (color_type == PNG_COLOR_TYPE_GRAY
10745 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
10746 fn_png_set_gray_to_rgb (png_ptr);
10747
10748 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
10749
10750 #if 0 /* Avoid double gamma correction for PNG images. */
10751 /* Tell the PNG lib to handle gamma correction for us. */
10752 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10753 if (png_get_sRGB (png_ptr, info_ptr, &intent))
10754 /* The libpng documentation says this is right in this case. */
10755 png_set_gamma (png_ptr, screen_gamma, 0.45455);
10756 else
10757 #endif
10758 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10759 /* Image contains gamma information. */
10760 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10761 else
10762 /* Use the standard default for the image gamma. */
10763 png_set_gamma (png_ptr, screen_gamma, 0.45455);
10764 #endif /* if 0 */
10765
10766 /* Handle alpha channel by combining the image with a background
10767 color. Do this only if a real alpha channel is supplied. For
10768 simple transparency, we prefer a clipping mask. */
10769 if (!transparent_p)
10770 {
10771 png_color_16 *image_bg;
10772 Lisp_Object specified_bg
10773 = image_spec_value (img->spec, QCbackground, NULL);
10774
10775 if (STRINGP (specified_bg))
10776 /* The user specified `:background', use that. */
10777 {
10778 COLORREF color;
10779 if (w32_defined_color (f, SDATA (specified_bg), &color, 0))
10780 {
10781 png_color_16 user_bg;
10782
10783 bzero (&user_bg, sizeof user_bg);
10784 user_bg.red = 256 * GetRValue (color);
10785 user_bg.green = 256 * GetGValue (color);
10786 user_bg.blue = 256 * GetBValue (color);
10787
10788 fn_png_set_background (png_ptr, &user_bg,
10789 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10790 }
10791 }
10792 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
10793 /* Image contains a background color with which to
10794 combine the image. */
10795 fn_png_set_background (png_ptr, image_bg,
10796 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
10797 else
10798 {
10799 /* Image does not contain a background color with which
10800 to combine the image data via an alpha channel. Use
10801 the frame's background instead. */
10802 COLORREF color;
10803 png_color_16 frame_background;
10804 color = FRAME_BACKGROUND_PIXEL (f);
10805 #if 0 /* TODO : Colormap support. */
10806 Colormap cmap;
10807
10808 cmap = FRAME_X_COLORMAP (f);
10809 x_query_color (f, &color);
10810 #endif
10811
10812 bzero (&frame_background, sizeof frame_background);
10813 frame_background.red = 256 * GetRValue (color);
10814 frame_background.green = 256 * GetGValue (color);
10815 frame_background.blue = 256 * GetBValue (color);
10816
10817 fn_png_set_background (png_ptr, &frame_background,
10818 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10819 }
10820 }
10821
10822 /* Update info structure. */
10823 fn_png_read_update_info (png_ptr, info_ptr);
10824
10825 /* Get number of channels. Valid values are 1 for grayscale images
10826 and images with a palette, 2 for grayscale images with transparency
10827 information (alpha channel), 3 for RGB images, and 4 for RGB
10828 images with alpha channel, i.e. RGBA. If conversions above were
10829 sufficient we should only have 3 or 4 channels here. */
10830 channels = fn_png_get_channels (png_ptr, info_ptr);
10831 xassert (channels == 3 || channels == 4);
10832
10833 /* Number of bytes needed for one row of the image. */
10834 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
10835
10836 /* Allocate memory for the image. */
10837 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10838 rows = (png_byte **) xmalloc (height * sizeof *rows);
10839 for (i = 0; i < height; ++i)
10840 rows[i] = pixels + i * row_bytes;
10841
10842 /* Read the entire image. */
10843 fn_png_read_image (png_ptr, rows);
10844 fn_png_read_end (png_ptr, info_ptr);
10845 if (fp)
10846 {
10847 fclose (fp);
10848 fp = NULL;
10849 }
10850
10851 /* Create the X image and pixmap. */
10852 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10853 &img->pixmap))
10854 goto error;
10855
10856 /* Create an image and pixmap serving as mask if the PNG image
10857 contains an alpha channel. */
10858 if (channels == 4
10859 && !transparent_p
10860 && !x_create_x_image_and_pixmap (f, width, height, 1,
10861 &mask_img, &img->mask))
10862 {
10863 x_destroy_x_image (ximg);
10864 DeleteObject (img->pixmap);
10865 img->pixmap = 0;
10866 goto error;
10867 }
10868 /* Fill the X image and mask from PNG data. */
10869 #if 0 /* TODO: Color tables. */
10870 init_color_table ();
10871 #endif
10872
10873 for (y = 0; y < height; ++y)
10874 {
10875 png_byte *p = rows[y];
10876
10877 for (x = 0; x < width; ++x)
10878 {
10879 unsigned r, g, b;
10880
10881 r = *p++;
10882 g = *p++;
10883 b = *p++;
10884 #if 0 /* TODO: Color tables. */
10885 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10886 #else
10887 XPutPixel (ximg, x, y, PALETTERGB (r, g, b));
10888 #endif
10889 /* An alpha channel, aka mask channel, associates variable
10890 transparency with an image. Where other image formats
10891 support binary transparency---fully transparent or fully
10892 opaque---PNG allows up to 254 levels of partial transparency.
10893 The PNG library implements partial transparency by combining
10894 the image with a specified background color.
10895
10896 I'm not sure how to handle this here nicely: because the
10897 background on which the image is displayed may change, for
10898 real alpha channel support, it would be necessary to create
10899 a new image for each possible background.
10900
10901 What I'm doing now is that a mask is created if we have
10902 boolean transparency information. Otherwise I'm using
10903 the frame's background color to combine the image with. */
10904
10905 if (channels == 4)
10906 {
10907 if (mask_img)
10908 XPutPixel (mask_img, x, y, *p > 0);
10909 ++p;
10910 }
10911 }
10912 }
10913
10914 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
10915 /* Set IMG's background color from the PNG image, unless the user
10916 overrode it. */
10917 {
10918 png_color_16 *bg;
10919 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
10920 {
10921 #if 0 /* TODO: Color tables. */
10922 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
10923 #else
10924 img->background = PALETTERGB (bg->red / 256, bg->green / 256,
10925 bg->blue / 256);
10926 #endif
10927 img->background_valid = 1;
10928 }
10929 }
10930
10931 #if 0 /* TODO: Color tables. */
10932 /* Remember colors allocated for this image. */
10933 img->colors = colors_in_color_table (&img->ncolors);
10934 free_color_table ();
10935 #endif
10936
10937 /* Clean up. */
10938 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10939 xfree (rows);
10940 xfree (pixels);
10941
10942 img->width = width;
10943 img->height = height;
10944
10945 /* Maybe fill in the background field while we have ximg handy. */
10946 IMAGE_BACKGROUND (img, f, ximg);
10947
10948 /* Put the image into the pixmap, then free the X image and its buffer. */
10949 x_put_x_image (f, ximg, img->pixmap, width, height);
10950 x_destroy_x_image (ximg);
10951
10952 /* Same for the mask. */
10953 if (mask_img)
10954 {
10955 /* Fill in the background_transparent field while we have the mask
10956 handy. */
10957 image_background_transparent (img, f, mask_img);
10958
10959 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10960 x_destroy_x_image (mask_img);
10961 }
10962
10963 UNGCPRO;
10964 return 1;
10965 }
10966
10967 #endif /* HAVE_PNG != 0 */
10968
10969
10970 \f
10971 /***********************************************************************
10972 JPEG
10973 ***********************************************************************/
10974
10975 #if HAVE_JPEG
10976
10977 /* Work around a warning about HAVE_STDLIB_H being redefined in
10978 jconfig.h. */
10979 #ifdef HAVE_STDLIB_H
10980 #define HAVE_STDLIB_H_1
10981 #undef HAVE_STDLIB_H
10982 #endif /* HAVE_STLIB_H */
10983
10984 #include <jpeglib.h>
10985 #include <jerror.h>
10986 #include <setjmp.h>
10987
10988 #ifdef HAVE_STLIB_H_1
10989 #define HAVE_STDLIB_H 1
10990 #endif
10991
10992 static int jpeg_image_p P_ ((Lisp_Object object));
10993 static int jpeg_load P_ ((struct frame *f, struct image *img));
10994
10995 /* The symbol `jpeg' identifying images of this type. */
10996
10997 Lisp_Object Qjpeg;
10998
10999 /* Indices of image specification fields in gs_format, below. */
11000
11001 enum jpeg_keyword_index
11002 {
11003 JPEG_TYPE,
11004 JPEG_DATA,
11005 JPEG_FILE,
11006 JPEG_ASCENT,
11007 JPEG_MARGIN,
11008 JPEG_RELIEF,
11009 JPEG_ALGORITHM,
11010 JPEG_HEURISTIC_MASK,
11011 JPEG_MASK,
11012 JPEG_BACKGROUND,
11013 JPEG_LAST
11014 };
11015
11016 /* Vector of image_keyword structures describing the format
11017 of valid user-defined image specifications. */
11018
11019 static struct image_keyword jpeg_format[JPEG_LAST] =
11020 {
11021 {":type", IMAGE_SYMBOL_VALUE, 1},
11022 {":data", IMAGE_STRING_VALUE, 0},
11023 {":file", IMAGE_STRING_VALUE, 0},
11024 {":ascent", IMAGE_ASCENT_VALUE, 0},
11025 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11026 {":relief", IMAGE_INTEGER_VALUE, 0},
11027 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11028 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11029 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11030 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11031 };
11032
11033 /* Structure describing the image type `jpeg'. */
11034
11035 static struct image_type jpeg_type =
11036 {
11037 &Qjpeg,
11038 jpeg_image_p,
11039 jpeg_load,
11040 x_clear_image,
11041 NULL
11042 };
11043
11044
11045 /* JPEG library details. */
11046 DEF_IMGLIB_FN (jpeg_CreateDecompress);
11047 DEF_IMGLIB_FN (jpeg_start_decompress);
11048 DEF_IMGLIB_FN (jpeg_finish_decompress);
11049 DEF_IMGLIB_FN (jpeg_destroy_decompress);
11050 DEF_IMGLIB_FN (jpeg_read_header);
11051 DEF_IMGLIB_FN (jpeg_read_scanlines);
11052 DEF_IMGLIB_FN (jpeg_stdio_src);
11053 DEF_IMGLIB_FN (jpeg_std_error);
11054 DEF_IMGLIB_FN (jpeg_resync_to_restart);
11055
11056 static int
11057 init_jpeg_functions (library)
11058 HMODULE library;
11059 {
11060 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
11061 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
11062 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
11063 LOAD_IMGLIB_FN (library, jpeg_read_header);
11064 LOAD_IMGLIB_FN (library, jpeg_stdio_src);
11065 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
11066 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
11067 LOAD_IMGLIB_FN (library, jpeg_std_error);
11068 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
11069 return 1;
11070 }
11071
11072 /* Wrapper since we can't directly assign the function pointer
11073 to another function pointer that was declared more completely easily. */
11074 static boolean
11075 jpeg_resync_to_restart_wrapper(cinfo, desired)
11076 j_decompress_ptr cinfo;
11077 int desired;
11078 {
11079 return fn_jpeg_resync_to_restart (cinfo, desired);
11080 }
11081
11082
11083 /* Return non-zero if OBJECT is a valid JPEG image specification. */
11084
11085 static int
11086 jpeg_image_p (object)
11087 Lisp_Object object;
11088 {
11089 struct image_keyword fmt[JPEG_LAST];
11090
11091 bcopy (jpeg_format, fmt, sizeof fmt);
11092
11093 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
11094 return 0;
11095
11096 /* Must specify either the :data or :file keyword. */
11097 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
11098 }
11099
11100
11101 struct my_jpeg_error_mgr
11102 {
11103 struct jpeg_error_mgr pub;
11104 jmp_buf setjmp_buffer;
11105 };
11106
11107
11108 static void
11109 my_error_exit (cinfo)
11110 j_common_ptr cinfo;
11111 {
11112 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
11113 longjmp (mgr->setjmp_buffer, 1);
11114 }
11115
11116
11117 /* Init source method for JPEG data source manager. Called by
11118 jpeg_read_header() before any data is actually read. See
11119 libjpeg.doc from the JPEG lib distribution. */
11120
11121 static void
11122 our_init_source (cinfo)
11123 j_decompress_ptr cinfo;
11124 {
11125 }
11126
11127
11128 /* Fill input buffer method for JPEG data source manager. Called
11129 whenever more data is needed. We read the whole image in one step,
11130 so this only adds a fake end of input marker at the end. */
11131
11132 static boolean
11133 our_fill_input_buffer (cinfo)
11134 j_decompress_ptr cinfo;
11135 {
11136 /* Insert a fake EOI marker. */
11137 struct jpeg_source_mgr *src = cinfo->src;
11138 static JOCTET buffer[2];
11139
11140 buffer[0] = (JOCTET) 0xFF;
11141 buffer[1] = (JOCTET) JPEG_EOI;
11142
11143 src->next_input_byte = buffer;
11144 src->bytes_in_buffer = 2;
11145 return TRUE;
11146 }
11147
11148
11149 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
11150 is the JPEG data source manager. */
11151
11152 static void
11153 our_skip_input_data (cinfo, num_bytes)
11154 j_decompress_ptr cinfo;
11155 long num_bytes;
11156 {
11157 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
11158
11159 if (src)
11160 {
11161 if (num_bytes > src->bytes_in_buffer)
11162 ERREXIT (cinfo, JERR_INPUT_EOF);
11163
11164 src->bytes_in_buffer -= num_bytes;
11165 src->next_input_byte += num_bytes;
11166 }
11167 }
11168
11169
11170 /* Method to terminate data source. Called by
11171 jpeg_finish_decompress() after all data has been processed. */
11172
11173 static void
11174 our_term_source (cinfo)
11175 j_decompress_ptr cinfo;
11176 {
11177 }
11178
11179
11180 /* Set up the JPEG lib for reading an image from DATA which contains
11181 LEN bytes. CINFO is the decompression info structure created for
11182 reading the image. */
11183
11184 static void
11185 jpeg_memory_src (cinfo, data, len)
11186 j_decompress_ptr cinfo;
11187 JOCTET *data;
11188 unsigned int len;
11189 {
11190 struct jpeg_source_mgr *src;
11191
11192 if (cinfo->src == NULL)
11193 {
11194 /* First time for this JPEG object? */
11195 cinfo->src = (struct jpeg_source_mgr *)
11196 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
11197 sizeof (struct jpeg_source_mgr));
11198 src = (struct jpeg_source_mgr *) cinfo->src;
11199 src->next_input_byte = data;
11200 }
11201
11202 src = (struct jpeg_source_mgr *) cinfo->src;
11203 src->init_source = our_init_source;
11204 src->fill_input_buffer = our_fill_input_buffer;
11205 src->skip_input_data = our_skip_input_data;
11206 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
11207 src->term_source = our_term_source;
11208 src->bytes_in_buffer = len;
11209 src->next_input_byte = data;
11210 }
11211
11212
11213 /* Load image IMG for use on frame F. Patterned after example.c
11214 from the JPEG lib. */
11215
11216 static int
11217 jpeg_load (f, img)
11218 struct frame *f;
11219 struct image *img;
11220 {
11221 struct jpeg_decompress_struct cinfo;
11222 struct my_jpeg_error_mgr mgr;
11223 Lisp_Object file, specified_file;
11224 Lisp_Object specified_data;
11225 FILE * volatile fp = NULL;
11226 JSAMPARRAY buffer;
11227 int row_stride, x, y;
11228 XImage *ximg = NULL;
11229 int rc;
11230 unsigned long *colors;
11231 int width, height;
11232 struct gcpro gcpro1;
11233
11234 /* Open the JPEG file. */
11235 specified_file = image_spec_value (img->spec, QCfile, NULL);
11236 specified_data = image_spec_value (img->spec, QCdata, NULL);
11237 file = Qnil;
11238 GCPRO1 (file);
11239
11240 if (NILP (specified_data))
11241 {
11242 file = x_find_image_file (specified_file);
11243 if (!STRINGP (file))
11244 {
11245 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11246 UNGCPRO;
11247 return 0;
11248 }
11249
11250 fp = fopen (SDATA (file), "rb");
11251 if (fp == NULL)
11252 {
11253 image_error ("Cannot open `%s'", file, Qnil);
11254 UNGCPRO;
11255 return 0;
11256 }
11257 }
11258
11259 /* Customize libjpeg's error handling to call my_error_exit when an
11260 error is detected. This function will perform a longjmp. */
11261 cinfo.err = fn_jpeg_std_error (&mgr.pub);
11262 mgr.pub.error_exit = my_error_exit;
11263
11264 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
11265 {
11266 if (rc == 1)
11267 {
11268 /* Called from my_error_exit. Display a JPEG error. */
11269 char buffer[JMSG_LENGTH_MAX];
11270 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
11271 image_error ("Error reading JPEG image `%s': %s", img->spec,
11272 build_string (buffer));
11273 }
11274
11275 /* Close the input file and destroy the JPEG object. */
11276 if (fp)
11277 fclose ((FILE *) fp);
11278 fn_jpeg_destroy_decompress (&cinfo);
11279
11280 /* If we already have an XImage, free that. */
11281 x_destroy_x_image (ximg);
11282
11283 /* Free pixmap and colors. */
11284 x_clear_image (f, img);
11285
11286 UNGCPRO;
11287 return 0;
11288 }
11289
11290 /* Create the JPEG decompression object. Let it read from fp.
11291 Read the JPEG image header. */
11292 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
11293
11294 if (NILP (specified_data))
11295 fn_jpeg_stdio_src (&cinfo, (FILE *) fp);
11296 else
11297 jpeg_memory_src (&cinfo, SDATA (specified_data),
11298 SBYTES (specified_data));
11299
11300 fn_jpeg_read_header (&cinfo, TRUE);
11301
11302 /* Customize decompression so that color quantization will be used.
11303 Start decompression. */
11304 cinfo.quantize_colors = TRUE;
11305 fn_jpeg_start_decompress (&cinfo);
11306 width = img->width = cinfo.output_width;
11307 height = img->height = cinfo.output_height;
11308
11309 /* Create X image and pixmap. */
11310 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11311 longjmp (mgr.setjmp_buffer, 2);
11312
11313 /* Allocate colors. When color quantization is used,
11314 cinfo.actual_number_of_colors has been set with the number of
11315 colors generated, and cinfo.colormap is a two-dimensional array
11316 of color indices in the range 0..cinfo.actual_number_of_colors.
11317 No more than 255 colors will be generated. */
11318 {
11319 int i, ir, ig, ib;
11320
11321 if (cinfo.out_color_components > 2)
11322 ir = 0, ig = 1, ib = 2;
11323 else if (cinfo.out_color_components > 1)
11324 ir = 0, ig = 1, ib = 0;
11325 else
11326 ir = 0, ig = 0, ib = 0;
11327
11328 #if 0 /* TODO: Color tables. */
11329 /* Use the color table mechanism because it handles colors that
11330 cannot be allocated nicely. Such colors will be replaced with
11331 a default color, and we don't have to care about which colors
11332 can be freed safely, and which can't. */
11333 init_color_table ();
11334 #endif
11335 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
11336 * sizeof *colors);
11337
11338 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
11339 {
11340 int r = cinfo.colormap[ir][i];
11341 int g = cinfo.colormap[ig][i];
11342 int b = cinfo.colormap[ib][i];
11343 #if 0 /* TODO: Color tables. */
11344 colors[i] = lookup_rgb_color (f, r, g, b);
11345 #else
11346 colors[i] = PALETTERGB (r, g, b);
11347 #endif
11348 }
11349
11350 #if 0 /* TODO: Color tables. */
11351 /* Remember those colors actually allocated. */
11352 img->colors = colors_in_color_table (&img->ncolors);
11353 free_color_table ();
11354 #endif
11355 }
11356
11357 /* Read pixels. */
11358 row_stride = width * cinfo.output_components;
11359 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
11360 row_stride, 1);
11361 for (y = 0; y < height; ++y)
11362 {
11363 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
11364 for (x = 0; x < cinfo.output_width; ++x)
11365 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
11366 }
11367
11368 /* Clean up. */
11369 fn_jpeg_finish_decompress (&cinfo);
11370 fn_jpeg_destroy_decompress (&cinfo);
11371 if (fp)
11372 fclose ((FILE *) fp);
11373
11374 /* Maybe fill in the background field while we have ximg handy. */
11375 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11376 IMAGE_BACKGROUND (img, f, ximg);
11377
11378 /* Put the image into the pixmap. */
11379 x_put_x_image (f, ximg, img->pixmap, width, height);
11380 x_destroy_x_image (ximg);
11381 UNGCPRO;
11382 return 1;
11383 }
11384
11385 #endif /* HAVE_JPEG */
11386
11387
11388 \f
11389 /***********************************************************************
11390 TIFF
11391 ***********************************************************************/
11392
11393 #if HAVE_TIFF
11394
11395 #include <tiffio.h>
11396
11397 static int tiff_image_p P_ ((Lisp_Object object));
11398 static int tiff_load P_ ((struct frame *f, struct image *img));
11399
11400 /* The symbol `tiff' identifying images of this type. */
11401
11402 Lisp_Object Qtiff;
11403
11404 /* Indices of image specification fields in tiff_format, below. */
11405
11406 enum tiff_keyword_index
11407 {
11408 TIFF_TYPE,
11409 TIFF_DATA,
11410 TIFF_FILE,
11411 TIFF_ASCENT,
11412 TIFF_MARGIN,
11413 TIFF_RELIEF,
11414 TIFF_ALGORITHM,
11415 TIFF_HEURISTIC_MASK,
11416 TIFF_MASK,
11417 TIFF_BACKGROUND,
11418 TIFF_LAST
11419 };
11420
11421 /* Vector of image_keyword structures describing the format
11422 of valid user-defined image specifications. */
11423
11424 static struct image_keyword tiff_format[TIFF_LAST] =
11425 {
11426 {":type", IMAGE_SYMBOL_VALUE, 1},
11427 {":data", IMAGE_STRING_VALUE, 0},
11428 {":file", IMAGE_STRING_VALUE, 0},
11429 {":ascent", IMAGE_ASCENT_VALUE, 0},
11430 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11431 {":relief", IMAGE_INTEGER_VALUE, 0},
11432 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11433 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11434 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11435 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11436 };
11437
11438 /* Structure describing the image type `tiff'. */
11439
11440 static struct image_type tiff_type =
11441 {
11442 &Qtiff,
11443 tiff_image_p,
11444 tiff_load,
11445 x_clear_image,
11446 NULL
11447 };
11448
11449 /* TIFF library details. */
11450 DEF_IMGLIB_FN (TIFFSetErrorHandler);
11451 DEF_IMGLIB_FN (TIFFSetWarningHandler);
11452 DEF_IMGLIB_FN (TIFFOpen);
11453 DEF_IMGLIB_FN (TIFFClientOpen);
11454 DEF_IMGLIB_FN (TIFFGetField);
11455 DEF_IMGLIB_FN (TIFFReadRGBAImage);
11456 DEF_IMGLIB_FN (TIFFClose);
11457
11458 static int
11459 init_tiff_functions (library)
11460 HMODULE library;
11461 {
11462 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
11463 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
11464 LOAD_IMGLIB_FN (library, TIFFOpen);
11465 LOAD_IMGLIB_FN (library, TIFFClientOpen);
11466 LOAD_IMGLIB_FN (library, TIFFGetField);
11467 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
11468 LOAD_IMGLIB_FN (library, TIFFClose);
11469 return 1;
11470 }
11471
11472 /* Return non-zero if OBJECT is a valid TIFF image specification. */
11473
11474 static int
11475 tiff_image_p (object)
11476 Lisp_Object object;
11477 {
11478 struct image_keyword fmt[TIFF_LAST];
11479 bcopy (tiff_format, fmt, sizeof fmt);
11480
11481 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
11482 return 0;
11483
11484 /* Must specify either the :data or :file keyword. */
11485 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
11486 }
11487
11488
11489 /* Reading from a memory buffer for TIFF images Based on the PNG
11490 memory source, but we have to provide a lot of extra functions.
11491 Blah.
11492
11493 We really only need to implement read and seek, but I am not
11494 convinced that the TIFF library is smart enough not to destroy
11495 itself if we only hand it the function pointers we need to
11496 override. */
11497
11498 typedef struct
11499 {
11500 unsigned char *bytes;
11501 size_t len;
11502 int index;
11503 }
11504 tiff_memory_source;
11505
11506 static size_t
11507 tiff_read_from_memory (data, buf, size)
11508 thandle_t data;
11509 tdata_t buf;
11510 tsize_t size;
11511 {
11512 tiff_memory_source *src = (tiff_memory_source *) data;
11513
11514 if (size > src->len - src->index)
11515 return (size_t) -1;
11516 bcopy (src->bytes + src->index, buf, size);
11517 src->index += size;
11518 return size;
11519 }
11520
11521 static size_t
11522 tiff_write_from_memory (data, buf, size)
11523 thandle_t data;
11524 tdata_t buf;
11525 tsize_t size;
11526 {
11527 return (size_t) -1;
11528 }
11529
11530 static toff_t
11531 tiff_seek_in_memory (data, off, whence)
11532 thandle_t data;
11533 toff_t off;
11534 int whence;
11535 {
11536 tiff_memory_source *src = (tiff_memory_source *) data;
11537 int idx;
11538
11539 switch (whence)
11540 {
11541 case SEEK_SET: /* Go from beginning of source. */
11542 idx = off;
11543 break;
11544
11545 case SEEK_END: /* Go from end of source. */
11546 idx = src->len + off;
11547 break;
11548
11549 case SEEK_CUR: /* Go from current position. */
11550 idx = src->index + off;
11551 break;
11552
11553 default: /* Invalid `whence'. */
11554 return -1;
11555 }
11556
11557 if (idx > src->len || idx < 0)
11558 return -1;
11559
11560 src->index = idx;
11561 return src->index;
11562 }
11563
11564 static int
11565 tiff_close_memory (data)
11566 thandle_t data;
11567 {
11568 /* NOOP */
11569 return 0;
11570 }
11571
11572 static int
11573 tiff_mmap_memory (data, pbase, psize)
11574 thandle_t data;
11575 tdata_t *pbase;
11576 toff_t *psize;
11577 {
11578 /* It is already _IN_ memory. */
11579 return 0;
11580 }
11581
11582 static void
11583 tiff_unmap_memory (data, base, size)
11584 thandle_t data;
11585 tdata_t base;
11586 toff_t size;
11587 {
11588 /* We don't need to do this. */
11589 }
11590
11591 static toff_t
11592 tiff_size_of_memory (data)
11593 thandle_t data;
11594 {
11595 return ((tiff_memory_source *) data)->len;
11596 }
11597
11598
11599 static void
11600 tiff_error_handler (title, format, ap)
11601 const char *title, *format;
11602 va_list ap;
11603 {
11604 char buf[512];
11605 int len;
11606
11607 len = sprintf (buf, "TIFF error: %s ", title);
11608 vsprintf (buf + len, format, ap);
11609 add_to_log (buf, Qnil, Qnil);
11610 }
11611
11612
11613 static void
11614 tiff_warning_handler (title, format, ap)
11615 const char *title, *format;
11616 va_list ap;
11617 {
11618 char buf[512];
11619 int len;
11620
11621 len = sprintf (buf, "TIFF warning: %s ", title);
11622 vsprintf (buf + len, format, ap);
11623 add_to_log (buf, Qnil, Qnil);
11624 }
11625
11626
11627 /* Load TIFF image IMG for use on frame F. Value is non-zero if
11628 successful. */
11629
11630 static int
11631 tiff_load (f, img)
11632 struct frame *f;
11633 struct image *img;
11634 {
11635 Lisp_Object file, specified_file;
11636 Lisp_Object specified_data;
11637 TIFF *tiff;
11638 int width, height, x, y;
11639 uint32 *buf;
11640 int rc;
11641 XImage *ximg;
11642 struct gcpro gcpro1;
11643 tiff_memory_source memsrc;
11644
11645 specified_file = image_spec_value (img->spec, QCfile, NULL);
11646 specified_data = image_spec_value (img->spec, QCdata, NULL);
11647 file = Qnil;
11648 GCPRO1 (file);
11649
11650 fn_TIFFSetErrorHandler (tiff_error_handler);
11651 fn_TIFFSetWarningHandler (tiff_warning_handler);
11652
11653 if (NILP (specified_data))
11654 {
11655 /* Read from a file */
11656 file = x_find_image_file (specified_file);
11657 if (!STRINGP (file))
11658 {
11659 image_error ("Cannot find image file `%s'", file, Qnil);
11660 UNGCPRO;
11661 return 0;
11662 }
11663
11664 /* Try to open the image file. */
11665 tiff = fn_TIFFOpen (SDATA (file), "r");
11666 if (tiff == NULL)
11667 {
11668 image_error ("Cannot open `%s'", file, Qnil);
11669 UNGCPRO;
11670 return 0;
11671 }
11672 }
11673 else
11674 {
11675 /* Memory source! */
11676 memsrc.bytes = SDATA (specified_data);
11677 memsrc.len = SBYTES (specified_data);
11678 memsrc.index = 0;
11679
11680 tiff = fn_TIFFClientOpen ("memory_source", "r", &memsrc,
11681 (TIFFReadWriteProc) tiff_read_from_memory,
11682 (TIFFReadWriteProc) tiff_write_from_memory,
11683 tiff_seek_in_memory,
11684 tiff_close_memory,
11685 tiff_size_of_memory,
11686 tiff_mmap_memory,
11687 tiff_unmap_memory);
11688
11689 if (!tiff)
11690 {
11691 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
11692 UNGCPRO;
11693 return 0;
11694 }
11695 }
11696
11697 /* Get width and height of the image, and allocate a raster buffer
11698 of width x height 32-bit values. */
11699 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
11700 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
11701 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
11702
11703 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
11704 fn_TIFFClose (tiff);
11705 if (!rc)
11706 {
11707 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
11708 xfree (buf);
11709 UNGCPRO;
11710 return 0;
11711 }
11712
11713 /* Create the X image and pixmap. */
11714 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11715 {
11716 xfree (buf);
11717 UNGCPRO;
11718 return 0;
11719 }
11720
11721 #if 0 /* TODO: Color tables. */
11722 /* Initialize the color table. */
11723 init_color_table ();
11724 #endif
11725
11726 /* Process the pixel raster. Origin is in the lower-left corner. */
11727 for (y = 0; y < height; ++y)
11728 {
11729 uint32 *row = buf + y * width;
11730
11731 for (x = 0; x < width; ++x)
11732 {
11733 uint32 abgr = row[x];
11734 int r = TIFFGetR (abgr);
11735 int g = TIFFGetG (abgr);
11736 int b = TIFFGetB (abgr);
11737 #if 0 /* TODO: Color tables. */
11738 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
11739 #else
11740 XPutPixel (ximg, x, height - 1 - y, PALETTERGB (r, g, b));
11741 #endif
11742 }
11743 }
11744
11745 #if 0 /* TODO: Color tables. */
11746 /* Remember the colors allocated for the image. Free the color table. */
11747 img->colors = colors_in_color_table (&img->ncolors);
11748 free_color_table ();
11749 #endif
11750
11751 img->width = width;
11752 img->height = height;
11753
11754 /* Maybe fill in the background field while we have ximg handy. */
11755 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11756 IMAGE_BACKGROUND (img, f, ximg);
11757
11758 /* Put the image into the pixmap, then free the X image and its buffer. */
11759 x_put_x_image (f, ximg, img->pixmap, width, height);
11760 x_destroy_x_image (ximg);
11761 xfree (buf);
11762
11763 UNGCPRO;
11764 return 1;
11765 }
11766
11767 #endif /* HAVE_TIFF != 0 */
11768
11769
11770 \f
11771 /***********************************************************************
11772 GIF
11773 ***********************************************************************/
11774
11775 #if HAVE_GIF
11776
11777 #define DrawText gif_DrawText
11778 #include <gif_lib.h>
11779 #undef DrawText
11780
11781 static int gif_image_p P_ ((Lisp_Object object));
11782 static int gif_load P_ ((struct frame *f, struct image *img));
11783
11784 /* The symbol `gif' identifying images of this type. */
11785
11786 Lisp_Object Qgif;
11787
11788 /* Indices of image specification fields in gif_format, below. */
11789
11790 enum gif_keyword_index
11791 {
11792 GIF_TYPE,
11793 GIF_DATA,
11794 GIF_FILE,
11795 GIF_ASCENT,
11796 GIF_MARGIN,
11797 GIF_RELIEF,
11798 GIF_ALGORITHM,
11799 GIF_HEURISTIC_MASK,
11800 GIF_MASK,
11801 GIF_IMAGE,
11802 GIF_BACKGROUND,
11803 GIF_LAST
11804 };
11805
11806 /* Vector of image_keyword structures describing the format
11807 of valid user-defined image specifications. */
11808
11809 static struct image_keyword gif_format[GIF_LAST] =
11810 {
11811 {":type", IMAGE_SYMBOL_VALUE, 1},
11812 {":data", IMAGE_STRING_VALUE, 0},
11813 {":file", IMAGE_STRING_VALUE, 0},
11814 {":ascent", IMAGE_ASCENT_VALUE, 0},
11815 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11816 {":relief", IMAGE_INTEGER_VALUE, 0},
11817 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11818 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11819 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11820 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11821 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11822 };
11823
11824 /* Structure describing the image type `gif'. */
11825
11826 static struct image_type gif_type =
11827 {
11828 &Qgif,
11829 gif_image_p,
11830 gif_load,
11831 x_clear_image,
11832 NULL
11833 };
11834
11835
11836 /* GIF library details. */
11837 DEF_IMGLIB_FN (DGifCloseFile);
11838 DEF_IMGLIB_FN (DGifSlurp);
11839 DEF_IMGLIB_FN (DGifOpen);
11840 DEF_IMGLIB_FN (DGifOpenFileName);
11841
11842 static int
11843 init_gif_functions (library)
11844 HMODULE library;
11845 {
11846 LOAD_IMGLIB_FN (library, DGifCloseFile);
11847 LOAD_IMGLIB_FN (library, DGifSlurp);
11848 LOAD_IMGLIB_FN (library, DGifOpen);
11849 LOAD_IMGLIB_FN (library, DGifOpenFileName);
11850 return 1;
11851 }
11852
11853
11854 /* Return non-zero if OBJECT is a valid GIF image specification. */
11855
11856 static int
11857 gif_image_p (object)
11858 Lisp_Object object;
11859 {
11860 struct image_keyword fmt[GIF_LAST];
11861 bcopy (gif_format, fmt, sizeof fmt);
11862
11863 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
11864 return 0;
11865
11866 /* Must specify either the :data or :file keyword. */
11867 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11868 }
11869
11870 /* Reading a GIF image from memory
11871 Based on the PNG memory stuff to a certain extent. */
11872
11873 typedef struct
11874 {
11875 unsigned char *bytes;
11876 size_t len;
11877 int index;
11878 }
11879 gif_memory_source;
11880
11881 /* Make the current memory source available to gif_read_from_memory.
11882 It's done this way because not all versions of libungif support
11883 a UserData field in the GifFileType structure. */
11884 static gif_memory_source *current_gif_memory_src;
11885
11886 static int
11887 gif_read_from_memory (file, buf, len)
11888 GifFileType *file;
11889 GifByteType *buf;
11890 int len;
11891 {
11892 gif_memory_source *src = current_gif_memory_src;
11893
11894 if (len > src->len - src->index)
11895 return -1;
11896
11897 bcopy (src->bytes + src->index, buf, len);
11898 src->index += len;
11899 return len;
11900 }
11901
11902
11903 /* Load GIF image IMG for use on frame F. Value is non-zero if
11904 successful. */
11905
11906 static int
11907 gif_load (f, img)
11908 struct frame *f;
11909 struct image *img;
11910 {
11911 Lisp_Object file, specified_file;
11912 Lisp_Object specified_data;
11913 int rc, width, height, x, y, i;
11914 XImage *ximg;
11915 ColorMapObject *gif_color_map;
11916 unsigned long pixel_colors[256];
11917 GifFileType *gif;
11918 struct gcpro gcpro1;
11919 Lisp_Object image;
11920 int ino, image_left, image_top, image_width, image_height;
11921 gif_memory_source memsrc;
11922 unsigned char *raster;
11923
11924 specified_file = image_spec_value (img->spec, QCfile, NULL);
11925 specified_data = image_spec_value (img->spec, QCdata, NULL);
11926 file = Qnil;
11927 GCPRO1 (file);
11928
11929 if (NILP (specified_data))
11930 {
11931 file = x_find_image_file (specified_file);
11932 if (!STRINGP (file))
11933 {
11934 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11935 UNGCPRO;
11936 return 0;
11937 }
11938
11939 /* Open the GIF file. */
11940 gif = fn_DGifOpenFileName (SDATA (file));
11941 if (gif == NULL)
11942 {
11943 image_error ("Cannot open `%s'", file, Qnil);
11944 UNGCPRO;
11945 return 0;
11946 }
11947 }
11948 else
11949 {
11950 /* Read from memory! */
11951 current_gif_memory_src = &memsrc;
11952 memsrc.bytes = SDATA (specified_data);
11953 memsrc.len = SBYTES (specified_data);
11954 memsrc.index = 0;
11955
11956 gif = fn_DGifOpen(&memsrc, gif_read_from_memory);
11957 if (!gif)
11958 {
11959 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11960 UNGCPRO;
11961 return 0;
11962 }
11963 }
11964
11965 /* Read entire contents. */
11966 rc = fn_DGifSlurp (gif);
11967 if (rc == GIF_ERROR)
11968 {
11969 image_error ("Error reading `%s'", img->spec, Qnil);
11970 fn_DGifCloseFile (gif);
11971 UNGCPRO;
11972 return 0;
11973 }
11974
11975 image = image_spec_value (img->spec, QCindex, NULL);
11976 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11977 if (ino >= gif->ImageCount)
11978 {
11979 image_error ("Invalid image number `%s' in image `%s'",
11980 image, img->spec);
11981 fn_DGifCloseFile (gif);
11982 UNGCPRO;
11983 return 0;
11984 }
11985
11986 width = img->width = max (gif->SWidth, gif->Image.Left + gif->Image.Width);
11987 height = img->height = max (gif->SHeight, gif->Image.Top + gif->Image.Height);
11988
11989 /* Create the X image and pixmap. */
11990 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11991 {
11992 fn_DGifCloseFile (gif);
11993 UNGCPRO;
11994 return 0;
11995 }
11996
11997 /* Allocate colors. */
11998 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11999 if (!gif_color_map)
12000 gif_color_map = gif->SColorMap;
12001 #if 0 /* TODO: Color tables */
12002 init_color_table ();
12003 #endif
12004 bzero (pixel_colors, sizeof pixel_colors);
12005
12006 for (i = 0; i < gif_color_map->ColorCount; ++i)
12007 {
12008 int r = gif_color_map->Colors[i].Red;
12009 int g = gif_color_map->Colors[i].Green;
12010 int b = gif_color_map->Colors[i].Blue;
12011 #if 0 /* TODO: Color tables */
12012 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
12013 #else
12014 pixel_colors[i] = PALETTERGB (r, g, b);
12015 #endif
12016 }
12017
12018 #if 0 /* TODO: Color tables */
12019 img->colors = colors_in_color_table (&img->ncolors);
12020 free_color_table ();
12021 #endif
12022
12023 /* Clear the part of the screen image that are not covered by
12024 the image from the GIF file. Full animated GIF support
12025 requires more than can be done here (see the gif89 spec,
12026 disposal methods). Let's simply assume that the part
12027 not covered by a sub-image is in the frame's background color. */
12028 image_top = gif->SavedImages[ino].ImageDesc.Top;
12029 image_left = gif->SavedImages[ino].ImageDesc.Left;
12030 image_width = gif->SavedImages[ino].ImageDesc.Width;
12031 image_height = gif->SavedImages[ino].ImageDesc.Height;
12032
12033 for (y = 0; y < image_top; ++y)
12034 for (x = 0; x < width; ++x)
12035 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12036
12037 for (y = image_top + image_height; y < height; ++y)
12038 for (x = 0; x < width; ++x)
12039 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12040
12041 for (y = image_top; y < image_top + image_height; ++y)
12042 {
12043 for (x = 0; x < image_left; ++x)
12044 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12045 for (x = image_left + image_width; x < width; ++x)
12046 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12047 }
12048
12049 /* Read the GIF image into the X image. We use a local variable
12050 `raster' here because RasterBits below is a char *, and invites
12051 problems with bytes >= 0x80. */
12052 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
12053
12054 if (gif->SavedImages[ino].ImageDesc.Interlace)
12055 {
12056 static int interlace_start[] = {0, 4, 2, 1};
12057 static int interlace_increment[] = {8, 8, 4, 2};
12058 int pass;
12059 int row = interlace_start[0];
12060
12061 pass = 0;
12062
12063 for (y = 0; y < image_height; y++)
12064 {
12065 if (row >= image_height)
12066 {
12067 row = interlace_start[++pass];
12068 while (row >= image_height)
12069 row = interlace_start[++pass];
12070 }
12071
12072 for (x = 0; x < image_width; x++)
12073 {
12074 int i = raster[(y * image_width) + x];
12075 XPutPixel (ximg, x + image_left, row + image_top,
12076 pixel_colors[i]);
12077 }
12078
12079 row += interlace_increment[pass];
12080 }
12081 }
12082 else
12083 {
12084 for (y = 0; y < image_height; ++y)
12085 for (x = 0; x < image_width; ++x)
12086 {
12087 int i = raster[y* image_width + x];
12088 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
12089 }
12090 }
12091
12092 fn_DGifCloseFile (gif);
12093
12094 /* Maybe fill in the background field while we have ximg handy. */
12095 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12096 IMAGE_BACKGROUND (img, f, ximg);
12097
12098 /* Put the image into the pixmap, then free the X image and its buffer. */
12099 x_put_x_image (f, ximg, img->pixmap, width, height);
12100 x_destroy_x_image (ximg);
12101
12102 UNGCPRO;
12103 return 1;
12104 }
12105
12106 #endif /* HAVE_GIF != 0 */
12107
12108
12109 \f
12110 /***********************************************************************
12111 Ghostscript
12112 ***********************************************************************/
12113
12114 Lisp_Object Qpostscript;
12115
12116 /* Keyword symbols. */
12117
12118 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12119
12120 #ifdef HAVE_GHOSTSCRIPT
12121 static int gs_image_p P_ ((Lisp_Object object));
12122 static int gs_load P_ ((struct frame *f, struct image *img));
12123 static void gs_clear_image P_ ((struct frame *f, struct image *img));
12124
12125 /* The symbol `postscript' identifying images of this type. */
12126
12127 /* Keyword symbols. */
12128
12129 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12130
12131 /* Indices of image specification fields in gs_format, below. */
12132
12133 enum gs_keyword_index
12134 {
12135 GS_TYPE,
12136 GS_PT_WIDTH,
12137 GS_PT_HEIGHT,
12138 GS_FILE,
12139 GS_LOADER,
12140 GS_BOUNDING_BOX,
12141 GS_ASCENT,
12142 GS_MARGIN,
12143 GS_RELIEF,
12144 GS_ALGORITHM,
12145 GS_HEURISTIC_MASK,
12146 GS_MASK,
12147 GS_BACKGROUND,
12148 GS_LAST
12149 };
12150
12151 /* Vector of image_keyword structures describing the format
12152 of valid user-defined image specifications. */
12153
12154 static struct image_keyword gs_format[GS_LAST] =
12155 {
12156 {":type", IMAGE_SYMBOL_VALUE, 1},
12157 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12158 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12159 {":file", IMAGE_STRING_VALUE, 1},
12160 {":loader", IMAGE_FUNCTION_VALUE, 0},
12161 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
12162 {":ascent", IMAGE_ASCENT_VALUE, 0},
12163 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12164 {":relief", IMAGE_INTEGER_VALUE, 0},
12165 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12166 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12167 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12168 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12169 };
12170
12171 /* Structure describing the image type `ghostscript'. */
12172
12173 static struct image_type gs_type =
12174 {
12175 &Qpostscript,
12176 gs_image_p,
12177 gs_load,
12178 gs_clear_image,
12179 NULL
12180 };
12181
12182
12183 /* Free X resources of Ghostscript image IMG which is used on frame F. */
12184
12185 static void
12186 gs_clear_image (f, img)
12187 struct frame *f;
12188 struct image *img;
12189 {
12190 /* IMG->data.ptr_val may contain a recorded colormap. */
12191 xfree (img->data.ptr_val);
12192 x_clear_image (f, img);
12193 }
12194
12195
12196 /* Return non-zero if OBJECT is a valid Ghostscript image
12197 specification. */
12198
12199 static int
12200 gs_image_p (object)
12201 Lisp_Object object;
12202 {
12203 struct image_keyword fmt[GS_LAST];
12204 Lisp_Object tem;
12205 int i;
12206
12207 bcopy (gs_format, fmt, sizeof fmt);
12208
12209 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
12210 return 0;
12211
12212 /* Bounding box must be a list or vector containing 4 integers. */
12213 tem = fmt[GS_BOUNDING_BOX].value;
12214 if (CONSP (tem))
12215 {
12216 for (i = 0; i < 4; ++i, tem = XCDR (tem))
12217 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
12218 return 0;
12219 if (!NILP (tem))
12220 return 0;
12221 }
12222 else if (VECTORP (tem))
12223 {
12224 if (XVECTOR (tem)->size != 4)
12225 return 0;
12226 for (i = 0; i < 4; ++i)
12227 if (!INTEGERP (XVECTOR (tem)->contents[i]))
12228 return 0;
12229 }
12230 else
12231 return 0;
12232
12233 return 1;
12234 }
12235
12236
12237 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
12238 if successful. */
12239
12240 static int
12241 gs_load (f, img)
12242 struct frame *f;
12243 struct image *img;
12244 {
12245 char buffer[100];
12246 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
12247 struct gcpro gcpro1, gcpro2;
12248 Lisp_Object frame;
12249 double in_width, in_height;
12250 Lisp_Object pixel_colors = Qnil;
12251
12252 /* Compute pixel size of pixmap needed from the given size in the
12253 image specification. Sizes in the specification are in pt. 1 pt
12254 = 1/72 in, xdpi and ydpi are stored in the frame's X display
12255 info. */
12256 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
12257 in_width = XFASTINT (pt_width) / 72.0;
12258 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
12259 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
12260 in_height = XFASTINT (pt_height) / 72.0;
12261 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
12262
12263 /* Create the pixmap. */
12264 BLOCK_INPUT;
12265 xassert (img->pixmap == 0);
12266 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12267 img->width, img->height,
12268 one_w32_display_info.n_cbits);
12269 UNBLOCK_INPUT;
12270
12271 if (!img->pixmap)
12272 {
12273 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
12274 return 0;
12275 }
12276
12277 /* Call the loader to fill the pixmap. It returns a process object
12278 if successful. We do not record_unwind_protect here because
12279 other places in redisplay like calling window scroll functions
12280 don't either. Let the Lisp loader use `unwind-protect' instead. */
12281 GCPRO2 (window_and_pixmap_id, pixel_colors);
12282
12283 sprintf (buffer, "%lu %lu",
12284 (unsigned long) FRAME_W32_WINDOW (f),
12285 (unsigned long) img->pixmap);
12286 window_and_pixmap_id = build_string (buffer);
12287
12288 sprintf (buffer, "%lu %lu",
12289 FRAME_FOREGROUND_PIXEL (f),
12290 FRAME_BACKGROUND_PIXEL (f));
12291 pixel_colors = build_string (buffer);
12292
12293 XSETFRAME (frame, f);
12294 loader = image_spec_value (img->spec, QCloader, NULL);
12295 if (NILP (loader))
12296 loader = intern ("gs-load-image");
12297
12298 img->data.lisp_val = call6 (loader, frame, img->spec,
12299 make_number (img->width),
12300 make_number (img->height),
12301 window_and_pixmap_id,
12302 pixel_colors);
12303 UNGCPRO;
12304 return PROCESSP (img->data.lisp_val);
12305 }
12306
12307
12308 /* Kill the Ghostscript process that was started to fill PIXMAP on
12309 frame F. Called from XTread_socket when receiving an event
12310 telling Emacs that Ghostscript has finished drawing. */
12311
12312 void
12313 x_kill_gs_process (pixmap, f)
12314 Pixmap pixmap;
12315 struct frame *f;
12316 {
12317 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
12318 int class, i;
12319 struct image *img;
12320
12321 /* Find the image containing PIXMAP. */
12322 for (i = 0; i < c->used; ++i)
12323 if (c->images[i]->pixmap == pixmap)
12324 break;
12325
12326 /* Should someone in between have cleared the image cache, for
12327 instance, give up. */
12328 if (i == c->used)
12329 return;
12330
12331 /* Kill the GS process. We should have found PIXMAP in the image
12332 cache and its image should contain a process object. */
12333 img = c->images[i];
12334 xassert (PROCESSP (img->data.lisp_val));
12335 Fkill_process (img->data.lisp_val, Qnil);
12336 img->data.lisp_val = Qnil;
12337
12338 /* On displays with a mutable colormap, figure out the colors
12339 allocated for the image by looking at the pixels of an XImage for
12340 img->pixmap. */
12341 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
12342 if (class != StaticColor && class != StaticGray && class != TrueColor)
12343 {
12344 XImage *ximg;
12345
12346 BLOCK_INPUT;
12347
12348 /* Try to get an XImage for img->pixmep. */
12349 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
12350 0, 0, img->width, img->height, ~0, ZPixmap);
12351 if (ximg)
12352 {
12353 int x, y;
12354
12355 /* Initialize the color table. */
12356 init_color_table ();
12357
12358 /* For each pixel of the image, look its color up in the
12359 color table. After having done so, the color table will
12360 contain an entry for each color used by the image. */
12361 for (y = 0; y < img->height; ++y)
12362 for (x = 0; x < img->width; ++x)
12363 {
12364 unsigned long pixel = XGetPixel (ximg, x, y);
12365 lookup_pixel_color (f, pixel);
12366 }
12367
12368 /* Record colors in the image. Free color table and XImage. */
12369 img->colors = colors_in_color_table (&img->ncolors);
12370 free_color_table ();
12371 XDestroyImage (ximg);
12372
12373 #if 0 /* This doesn't seem to be the case. If we free the colors
12374 here, we get a BadAccess later in x_clear_image when
12375 freeing the colors. */
12376 /* We have allocated colors once, but Ghostscript has also
12377 allocated colors on behalf of us. So, to get the
12378 reference counts right, free them once. */
12379 if (img->ncolors)
12380 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
12381 img->colors, img->ncolors, 0);
12382 #endif
12383 }
12384 else
12385 image_error ("Cannot get X image of `%s'; colors will not be freed",
12386 img->spec, Qnil);
12387
12388 UNBLOCK_INPUT;
12389 }
12390
12391 /* Now that we have the pixmap, compute mask and transform the
12392 image if requested. */
12393 BLOCK_INPUT;
12394 postprocess_image (f, img);
12395 UNBLOCK_INPUT;
12396 }
12397
12398 #endif /* HAVE_GHOSTSCRIPT */
12399
12400 \f
12401 /***********************************************************************
12402 Window properties
12403 ***********************************************************************/
12404
12405 DEFUN ("x-change-window-property", Fx_change_window_property,
12406 Sx_change_window_property, 2, 3, 0,
12407 doc: /* Change window property PROP to VALUE on the X window of FRAME.
12408 PROP and VALUE must be strings. FRAME nil or omitted means use the
12409 selected frame. Value is VALUE. */)
12410 (prop, value, frame)
12411 Lisp_Object frame, prop, value;
12412 {
12413 #if 0 /* TODO : port window properties to W32 */
12414 struct frame *f = check_x_frame (frame);
12415 Atom prop_atom;
12416
12417 CHECK_STRING (prop);
12418 CHECK_STRING (value);
12419
12420 BLOCK_INPUT;
12421 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
12422 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12423 prop_atom, XA_STRING, 8, PropModeReplace,
12424 SDATA (value), SCHARS (value));
12425
12426 /* Make sure the property is set when we return. */
12427 XFlush (FRAME_W32_DISPLAY (f));
12428 UNBLOCK_INPUT;
12429
12430 #endif /* TODO */
12431
12432 return value;
12433 }
12434
12435
12436 DEFUN ("x-delete-window-property", Fx_delete_window_property,
12437 Sx_delete_window_property, 1, 2, 0,
12438 doc: /* Remove window property PROP from X window of FRAME.
12439 FRAME nil or omitted means use the selected frame. Value is PROP. */)
12440 (prop, frame)
12441 Lisp_Object prop, frame;
12442 {
12443 #if 0 /* TODO : port window properties to W32 */
12444
12445 struct frame *f = check_x_frame (frame);
12446 Atom prop_atom;
12447
12448 CHECK_STRING (prop);
12449 BLOCK_INPUT;
12450 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
12451 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
12452
12453 /* Make sure the property is removed when we return. */
12454 XFlush (FRAME_W32_DISPLAY (f));
12455 UNBLOCK_INPUT;
12456 #endif /* TODO */
12457
12458 return prop;
12459 }
12460
12461
12462 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
12463 1, 2, 0,
12464 doc: /* Value is the value of window property PROP on FRAME.
12465 If FRAME is nil or omitted, use the selected frame. Value is nil
12466 if FRAME hasn't a property with name PROP or if PROP has no string
12467 value. */)
12468 (prop, frame)
12469 Lisp_Object prop, frame;
12470 {
12471 #if 0 /* TODO : port window properties to W32 */
12472
12473 struct frame *f = check_x_frame (frame);
12474 Atom prop_atom;
12475 int rc;
12476 Lisp_Object prop_value = Qnil;
12477 char *tmp_data = NULL;
12478 Atom actual_type;
12479 int actual_format;
12480 unsigned long actual_size, bytes_remaining;
12481
12482 CHECK_STRING (prop);
12483 BLOCK_INPUT;
12484 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
12485 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12486 prop_atom, 0, 0, False, XA_STRING,
12487 &actual_type, &actual_format, &actual_size,
12488 &bytes_remaining, (unsigned char **) &tmp_data);
12489 if (rc == Success)
12490 {
12491 int size = bytes_remaining;
12492
12493 XFree (tmp_data);
12494 tmp_data = NULL;
12495
12496 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12497 prop_atom, 0, bytes_remaining,
12498 False, XA_STRING,
12499 &actual_type, &actual_format,
12500 &actual_size, &bytes_remaining,
12501 (unsigned char **) &tmp_data);
12502 if (rc == Success)
12503 prop_value = make_string (tmp_data, size);
12504
12505 XFree (tmp_data);
12506 }
12507
12508 UNBLOCK_INPUT;
12509
12510 return prop_value;
12511
12512 #endif /* TODO */
12513 return Qnil;
12514 }
12515
12516
12517 \f
12518 /***********************************************************************
12519 Busy cursor
12520 ***********************************************************************/
12521
12522 /* If non-null, an asynchronous timer that, when it expires, displays
12523 an hourglass cursor on all frames. */
12524
12525 static struct atimer *hourglass_atimer;
12526
12527 /* Non-zero means an hourglass cursor is currently shown. */
12528
12529 static int hourglass_shown_p;
12530
12531 /* Number of seconds to wait before displaying an hourglass cursor. */
12532
12533 static Lisp_Object Vhourglass_delay;
12534
12535 /* Default number of seconds to wait before displaying an hourglass
12536 cursor. */
12537
12538 #define DEFAULT_HOURGLASS_DELAY 1
12539
12540 /* Function prototypes. */
12541
12542 static void show_hourglass P_ ((struct atimer *));
12543 static void hide_hourglass P_ ((void));
12544
12545
12546 /* Cancel a currently active hourglass timer, and start a new one. */
12547
12548 void
12549 start_hourglass ()
12550 {
12551 #if 0 /* TODO: cursor shape changes. */
12552 EMACS_TIME delay;
12553 int secs, usecs = 0;
12554
12555 cancel_hourglass ();
12556
12557 if (INTEGERP (Vhourglass_delay)
12558 && XINT (Vhourglass_delay) > 0)
12559 secs = XFASTINT (Vhourglass_delay);
12560 else if (FLOATP (Vhourglass_delay)
12561 && XFLOAT_DATA (Vhourglass_delay) > 0)
12562 {
12563 Lisp_Object tem;
12564 tem = Ftruncate (Vhourglass_delay, Qnil);
12565 secs = XFASTINT (tem);
12566 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
12567 }
12568 else
12569 secs = DEFAULT_HOURGLASS_DELAY;
12570
12571 EMACS_SET_SECS_USECS (delay, secs, usecs);
12572 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
12573 show_hourglass, NULL);
12574 #endif
12575 }
12576
12577
12578 /* Cancel the hourglass cursor timer if active, hide an hourglass
12579 cursor if shown. */
12580
12581 void
12582 cancel_hourglass ()
12583 {
12584 if (hourglass_atimer)
12585 {
12586 cancel_atimer (hourglass_atimer);
12587 hourglass_atimer = NULL;
12588 }
12589
12590 if (hourglass_shown_p)
12591 hide_hourglass ();
12592 }
12593
12594
12595 /* Timer function of hourglass_atimer. TIMER is equal to
12596 hourglass_atimer.
12597
12598 Display an hourglass cursor on all frames by mapping the frames'
12599 hourglass_window. Set the hourglass_p flag in the frames'
12600 output_data.x structure to indicate that an hourglass cursor is
12601 shown on the frames. */
12602
12603 static void
12604 show_hourglass (timer)
12605 struct atimer *timer;
12606 {
12607 #if 0 /* TODO: cursor shape changes. */
12608 /* The timer implementation will cancel this timer automatically
12609 after this function has run. Set hourglass_atimer to null
12610 so that we know the timer doesn't have to be canceled. */
12611 hourglass_atimer = NULL;
12612
12613 if (!hourglass_shown_p)
12614 {
12615 Lisp_Object rest, frame;
12616
12617 BLOCK_INPUT;
12618
12619 FOR_EACH_FRAME (rest, frame)
12620 if (FRAME_W32_P (XFRAME (frame)))
12621 {
12622 struct frame *f = XFRAME (frame);
12623
12624 f->output_data.w32->hourglass_p = 1;
12625
12626 if (!f->output_data.w32->hourglass_window)
12627 {
12628 unsigned long mask = CWCursor;
12629 XSetWindowAttributes attrs;
12630
12631 attrs.cursor = f->output_data.w32->hourglass_cursor;
12632
12633 f->output_data.w32->hourglass_window
12634 = XCreateWindow (FRAME_X_DISPLAY (f),
12635 FRAME_OUTER_WINDOW (f),
12636 0, 0, 32000, 32000, 0, 0,
12637 InputOnly,
12638 CopyFromParent,
12639 mask, &attrs);
12640 }
12641
12642 XMapRaised (FRAME_X_DISPLAY (f),
12643 f->output_data.w32->hourglass_window);
12644 XFlush (FRAME_X_DISPLAY (f));
12645 }
12646
12647 hourglass_shown_p = 1;
12648 UNBLOCK_INPUT;
12649 }
12650 #endif
12651 }
12652
12653
12654 /* Hide the hourglass cursor on all frames, if it is currently shown. */
12655
12656 static void
12657 hide_hourglass ()
12658 {
12659 #if 0 /* TODO: cursor shape changes. */
12660 if (hourglass_shown_p)
12661 {
12662 Lisp_Object rest, frame;
12663
12664 BLOCK_INPUT;
12665 FOR_EACH_FRAME (rest, frame)
12666 {
12667 struct frame *f = XFRAME (frame);
12668
12669 if (FRAME_W32_P (f)
12670 /* Watch out for newly created frames. */
12671 && f->output_data.x->hourglass_window)
12672 {
12673 XUnmapWindow (FRAME_X_DISPLAY (f),
12674 f->output_data.x->hourglass_window);
12675 /* Sync here because XTread_socket looks at the
12676 hourglass_p flag that is reset to zero below. */
12677 XSync (FRAME_X_DISPLAY (f), False);
12678 f->output_data.x->hourglass_p = 0;
12679 }
12680 }
12681
12682 hourglass_shown_p = 0;
12683 UNBLOCK_INPUT;
12684 }
12685 #endif
12686 }
12687
12688
12689 \f
12690 /***********************************************************************
12691 Tool tips
12692 ***********************************************************************/
12693
12694 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
12695 Lisp_Object, Lisp_Object));
12696 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
12697 Lisp_Object, int, int, int *, int *));
12698
12699 /* The frame of a currently visible tooltip. */
12700
12701 Lisp_Object tip_frame;
12702
12703 /* If non-nil, a timer started that hides the last tooltip when it
12704 fires. */
12705
12706 Lisp_Object tip_timer;
12707 Window tip_window;
12708
12709 /* If non-nil, a vector of 3 elements containing the last args
12710 with which x-show-tip was called. See there. */
12711
12712 Lisp_Object last_show_tip_args;
12713
12714 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
12715
12716 Lisp_Object Vx_max_tooltip_size;
12717
12718
12719 static Lisp_Object
12720 unwind_create_tip_frame (frame)
12721 Lisp_Object frame;
12722 {
12723 Lisp_Object deleted;
12724
12725 deleted = unwind_create_frame (frame);
12726 if (EQ (deleted, Qt))
12727 {
12728 tip_window = NULL;
12729 tip_frame = Qnil;
12730 }
12731
12732 return deleted;
12733 }
12734
12735
12736 /* Create a frame for a tooltip on the display described by DPYINFO.
12737 PARMS is a list of frame parameters. TEXT is the string to
12738 display in the tip frame. Value is the frame.
12739
12740 Note that functions called here, esp. x_default_parameter can
12741 signal errors, for instance when a specified color name is
12742 undefined. We have to make sure that we're in a consistent state
12743 when this happens. */
12744
12745 static Lisp_Object
12746 x_create_tip_frame (dpyinfo, parms, text)
12747 struct w32_display_info *dpyinfo;
12748 Lisp_Object parms, text;
12749 {
12750 struct frame *f;
12751 Lisp_Object frame, tem;
12752 Lisp_Object name;
12753 long window_prompting = 0;
12754 int width, height;
12755 int count = SPECPDL_INDEX ();
12756 struct gcpro gcpro1, gcpro2, gcpro3;
12757 struct kboard *kb;
12758 int face_change_count_before = face_change_count;
12759 Lisp_Object buffer;
12760 struct buffer *old_buffer;
12761
12762 check_w32 ();
12763
12764 /* Use this general default value to start with until we know if
12765 this frame has a specified name. */
12766 Vx_resource_name = Vinvocation_name;
12767
12768 #ifdef MULTI_KBOARD
12769 kb = dpyinfo->kboard;
12770 #else
12771 kb = &the_only_kboard;
12772 #endif
12773
12774 /* Get the name of the frame to use for resource lookup. */
12775 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
12776 if (!STRINGP (name)
12777 && !EQ (name, Qunbound)
12778 && !NILP (name))
12779 error ("Invalid frame name--not a string or nil");
12780 Vx_resource_name = name;
12781
12782 frame = Qnil;
12783 GCPRO3 (parms, name, frame);
12784 /* Make a frame without minibuffer nor mode-line. */
12785 f = make_frame (0);
12786 f->wants_modeline = 0;
12787 XSETFRAME (frame, f);
12788
12789 buffer = Fget_buffer_create (build_string (" *tip*"));
12790 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer, Qnil);
12791 old_buffer = current_buffer;
12792 set_buffer_internal_1 (XBUFFER (buffer));
12793 current_buffer->truncate_lines = Qnil;
12794 Ferase_buffer ();
12795 Finsert (1, &text);
12796 set_buffer_internal_1 (old_buffer);
12797
12798 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
12799 record_unwind_protect (unwind_create_tip_frame, frame);
12800
12801 /* By setting the output method, we're essentially saying that
12802 the frame is live, as per FRAME_LIVE_P. If we get a signal
12803 from this point on, x_destroy_window might screw up reference
12804 counts etc. */
12805 f->output_method = output_w32;
12806 f->output_data.w32 =
12807 (struct w32_output *) xmalloc (sizeof (struct w32_output));
12808 bzero (f->output_data.w32, sizeof (struct w32_output));
12809
12810 FRAME_FONTSET (f) = -1;
12811 f->icon_name = Qnil;
12812
12813 #if 0 /* GLYPH_DEBUG TODO: image support. */
12814 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
12815 dpyinfo_refcount = dpyinfo->reference_count;
12816 #endif /* GLYPH_DEBUG */
12817 #ifdef MULTI_KBOARD
12818 FRAME_KBOARD (f) = kb;
12819 #endif
12820 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12821 f->output_data.w32->explicit_parent = 0;
12822
12823 /* Set the name; the functions to which we pass f expect the name to
12824 be set. */
12825 if (EQ (name, Qunbound) || NILP (name))
12826 {
12827 f->name = build_string (dpyinfo->w32_id_name);
12828 f->explicit_name = 0;
12829 }
12830 else
12831 {
12832 f->name = name;
12833 f->explicit_name = 1;
12834 /* use the frame's title when getting resources for this frame. */
12835 specbind (Qx_resource_name, name);
12836 }
12837
12838 /* Extract the window parameters from the supplied values
12839 that are needed to determine window geometry. */
12840 {
12841 Lisp_Object font;
12842
12843 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12844
12845 BLOCK_INPUT;
12846 /* First, try whatever font the caller has specified. */
12847 if (STRINGP (font))
12848 {
12849 tem = Fquery_fontset (font, Qnil);
12850 if (STRINGP (tem))
12851 font = x_new_fontset (f, SDATA (tem));
12852 else
12853 font = x_new_font (f, SDATA (font));
12854 }
12855
12856 /* Try out a font which we hope has bold and italic variations. */
12857 if (!STRINGP (font))
12858 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
12859 if (! STRINGP (font))
12860 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
12861 /* If those didn't work, look for something which will at least work. */
12862 if (! STRINGP (font))
12863 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
12864 UNBLOCK_INPUT;
12865 if (! STRINGP (font))
12866 font = build_string ("Fixedsys");
12867
12868 x_default_parameter (f, parms, Qfont, font,
12869 "font", "Font", RES_TYPE_STRING);
12870 }
12871
12872 x_default_parameter (f, parms, Qborder_width, make_number (2),
12873 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
12874 /* This defaults to 2 in order to match xterm. We recognize either
12875 internalBorderWidth or internalBorder (which is what xterm calls
12876 it). */
12877 if (NILP (Fassq (Qinternal_border_width, parms)))
12878 {
12879 Lisp_Object value;
12880
12881 value = w32_get_arg (parms, Qinternal_border_width,
12882 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12883 if (! EQ (value, Qunbound))
12884 parms = Fcons (Fcons (Qinternal_border_width, value),
12885 parms);
12886 }
12887 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
12888 "internalBorderWidth", "internalBorderWidth",
12889 RES_TYPE_NUMBER);
12890
12891 /* Also do the stuff which must be set before the window exists. */
12892 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12893 "foreground", "Foreground", RES_TYPE_STRING);
12894 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12895 "background", "Background", RES_TYPE_STRING);
12896 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12897 "pointerColor", "Foreground", RES_TYPE_STRING);
12898 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12899 "cursorColor", "Foreground", RES_TYPE_STRING);
12900 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12901 "borderColor", "BorderColor", RES_TYPE_STRING);
12902
12903 /* Init faces before x_default_parameter is called for scroll-bar
12904 parameters because that function calls x_set_scroll_bar_width,
12905 which calls change_frame_size, which calls Fset_window_buffer,
12906 which runs hooks, which call Fvertical_motion. At the end, we
12907 end up in init_iterator with a null face cache, which should not
12908 happen. */
12909 init_frame_faces (f);
12910
12911 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
12912 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12913
12914 window_prompting = x_figure_window_size (f, parms, 0);
12915
12916 /* No fringes on tip frame. */
12917 f->fringe_cols = 0;
12918 f->left_fringe_width = 0;
12919 f->right_fringe_width = 0;
12920
12921 BLOCK_INPUT;
12922 my_create_tip_window (f);
12923 UNBLOCK_INPUT;
12924
12925 x_make_gc (f);
12926
12927 x_default_parameter (f, parms, Qauto_raise, Qnil,
12928 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12929 x_default_parameter (f, parms, Qauto_lower, Qnil,
12930 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12931 x_default_parameter (f, parms, Qcursor_type, Qbox,
12932 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12933
12934 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
12935 Change will not be effected unless different from the current
12936 FRAME_LINES (f). */
12937 width = FRAME_COLS (f);
12938 height = FRAME_LINES (f);
12939 FRAME_LINES (f) = 0;
12940 SET_FRAME_COLS (f, 0);
12941 change_frame_size (f, height, width, 1, 0, 0);
12942
12943 /* Add `tooltip' frame parameter's default value. */
12944 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
12945 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
12946 Qnil));
12947
12948 /* Set up faces after all frame parameters are known. This call
12949 also merges in face attributes specified for new frames.
12950
12951 Frame parameters may be changed if .Xdefaults contains
12952 specifications for the default font. For example, if there is an
12953 `Emacs.default.attributeBackground: pink', the `background-color'
12954 attribute of the frame get's set, which let's the internal border
12955 of the tooltip frame appear in pink. Prevent this. */
12956 {
12957 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
12958
12959 /* Set tip_frame here, so that */
12960 tip_frame = frame;
12961 call1 (Qface_set_after_frame_default, frame);
12962
12963 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
12964 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
12965 Qnil));
12966 }
12967
12968 f->no_split = 1;
12969
12970 UNGCPRO;
12971
12972 /* It is now ok to make the frame official even if we get an error
12973 below. And the frame needs to be on Vframe_list or making it
12974 visible won't work. */
12975 Vframe_list = Fcons (frame, Vframe_list);
12976
12977 /* Now that the frame is official, it counts as a reference to
12978 its display. */
12979 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
12980
12981 /* Setting attributes of faces of the tooltip frame from resources
12982 and similar will increment face_change_count, which leads to the
12983 clearing of all current matrices. Since this isn't necessary
12984 here, avoid it by resetting face_change_count to the value it
12985 had before we created the tip frame. */
12986 face_change_count = face_change_count_before;
12987
12988 /* Discard the unwind_protect. */
12989 return unbind_to (count, frame);
12990 }
12991
12992
12993 /* Compute where to display tip frame F. PARMS is the list of frame
12994 parameters for F. DX and DY are specified offsets from the current
12995 location of the mouse. WIDTH and HEIGHT are the width and height
12996 of the tooltip. Return coordinates relative to the root window of
12997 the display in *ROOT_X, and *ROOT_Y. */
12998
12999 static void
13000 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
13001 struct frame *f;
13002 Lisp_Object parms, dx, dy;
13003 int width, height;
13004 int *root_x, *root_y;
13005 {
13006 Lisp_Object left, top;
13007
13008 /* User-specified position? */
13009 left = Fcdr (Fassq (Qleft, parms));
13010 top = Fcdr (Fassq (Qtop, parms));
13011
13012 /* Move the tooltip window where the mouse pointer is. Resize and
13013 show it. */
13014 if (!INTEGERP (left) || !INTEGERP (top))
13015 {
13016 POINT pt;
13017
13018 BLOCK_INPUT;
13019 GetCursorPos (&pt);
13020 *root_x = pt.x;
13021 *root_y = pt.y;
13022 UNBLOCK_INPUT;
13023 }
13024
13025 if (INTEGERP (top))
13026 *root_y = XINT (top);
13027 else if (*root_y + XINT (dy) - height < 0)
13028 *root_y -= XINT (dy);
13029 else
13030 {
13031 *root_y -= height;
13032 *root_y += XINT (dy);
13033 }
13034
13035 if (INTEGERP (left))
13036 *root_x = XINT (left);
13037 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
13038 /* It fits to the right of the pointer. */
13039 *root_x += XINT (dx);
13040 else if (width + XINT (dx) <= *root_x)
13041 /* It fits to the left of the pointer. */
13042 *root_x -= width + XINT (dx);
13043 else
13044 /* Put it left justified on the screen -- it ought to fit that way. */
13045 *root_x = 0;
13046 }
13047
13048
13049 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
13050 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
13051 A tooltip window is a small window displaying a string.
13052
13053 FRAME nil or omitted means use the selected frame.
13054
13055 PARMS is an optional list of frame parameters which can be
13056 used to change the tooltip's appearance.
13057
13058 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
13059 means use the default timeout of 5 seconds.
13060
13061 If the list of frame parameters PARAMS contains a `left' parameter,
13062 the tooltip is displayed at that x-position. Otherwise it is
13063 displayed at the mouse position, with offset DX added (default is 5 if
13064 DX isn't specified). Likewise for the y-position; if a `top' frame
13065 parameter is specified, it determines the y-position of the tooltip
13066 window, otherwise it is displayed at the mouse position, with offset
13067 DY added (default is -10).
13068
13069 A tooltip's maximum size is specified by `x-max-tooltip-size'.
13070 Text larger than the specified size is clipped. */)
13071 (string, frame, parms, timeout, dx, dy)
13072 Lisp_Object string, frame, parms, timeout, dx, dy;
13073 {
13074 struct frame *f;
13075 struct window *w;
13076 int root_x, root_y;
13077 struct buffer *old_buffer;
13078 struct text_pos pos;
13079 int i, width, height;
13080 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
13081 int old_windows_or_buffers_changed = windows_or_buffers_changed;
13082 int count = SPECPDL_INDEX ();
13083
13084 specbind (Qinhibit_redisplay, Qt);
13085
13086 GCPRO4 (string, parms, frame, timeout);
13087
13088 CHECK_STRING (string);
13089 f = check_x_frame (frame);
13090 if (NILP (timeout))
13091 timeout = make_number (5);
13092 else
13093 CHECK_NATNUM (timeout);
13094
13095 if (NILP (dx))
13096 dx = make_number (5);
13097 else
13098 CHECK_NUMBER (dx);
13099
13100 if (NILP (dy))
13101 dy = make_number (-10);
13102 else
13103 CHECK_NUMBER (dy);
13104
13105 if (NILP (last_show_tip_args))
13106 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
13107
13108 if (!NILP (tip_frame))
13109 {
13110 Lisp_Object last_string = AREF (last_show_tip_args, 0);
13111 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
13112 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
13113
13114 if (EQ (frame, last_frame)
13115 && !NILP (Fequal (last_string, string))
13116 && !NILP (Fequal (last_parms, parms)))
13117 {
13118 struct frame *f = XFRAME (tip_frame);
13119
13120 /* Only DX and DY have changed. */
13121 if (!NILP (tip_timer))
13122 {
13123 Lisp_Object timer = tip_timer;
13124 tip_timer = Qnil;
13125 call1 (Qcancel_timer, timer);
13126 }
13127
13128 BLOCK_INPUT;
13129 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
13130 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
13131
13132 /* Put tooltip in topmost group and in position. */
13133 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13134 root_x, root_y, 0, 0,
13135 SWP_NOSIZE | SWP_NOACTIVATE);
13136
13137 /* Ensure tooltip is on top of other topmost windows (eg menus). */
13138 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
13139 0, 0, 0, 0,
13140 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
13141
13142 UNBLOCK_INPUT;
13143 goto start_timer;
13144 }
13145 }
13146
13147 /* Hide a previous tip, if any. */
13148 Fx_hide_tip ();
13149
13150 ASET (last_show_tip_args, 0, string);
13151 ASET (last_show_tip_args, 1, frame);
13152 ASET (last_show_tip_args, 2, parms);
13153
13154 /* Add default values to frame parameters. */
13155 if (NILP (Fassq (Qname, parms)))
13156 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
13157 if (NILP (Fassq (Qinternal_border_width, parms)))
13158 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
13159 if (NILP (Fassq (Qborder_width, parms)))
13160 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
13161 if (NILP (Fassq (Qborder_color, parms)))
13162 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
13163 if (NILP (Fassq (Qbackground_color, parms)))
13164 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
13165 parms);
13166
13167 /* Block input until the tip has been fully drawn, to avoid crashes
13168 when drawing tips in menus. */
13169 BLOCK_INPUT;
13170
13171 /* Create a frame for the tooltip, and record it in the global
13172 variable tip_frame. */
13173 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
13174 f = XFRAME (frame);
13175
13176 /* Set up the frame's root window. */
13177 w = XWINDOW (FRAME_ROOT_WINDOW (f));
13178 w->left_col = w->top_line = make_number (0);
13179
13180 if (CONSP (Vx_max_tooltip_size)
13181 && INTEGERP (XCAR (Vx_max_tooltip_size))
13182 && XINT (XCAR (Vx_max_tooltip_size)) > 0
13183 && INTEGERP (XCDR (Vx_max_tooltip_size))
13184 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
13185 {
13186 w->total_cols = XCAR (Vx_max_tooltip_size);
13187 w->total_lines = XCDR (Vx_max_tooltip_size);
13188 }
13189 else
13190 {
13191 w->total_cols = make_number (80);
13192 w->total_lines = make_number (40);
13193 }
13194
13195 FRAME_TOTAL_COLS (f) = XINT (w->total_cols);
13196 adjust_glyphs (f);
13197 w->pseudo_window_p = 1;
13198
13199 /* Display the tooltip text in a temporary buffer. */
13200 old_buffer = current_buffer;
13201 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
13202 current_buffer->truncate_lines = Qnil;
13203 clear_glyph_matrix (w->desired_matrix);
13204 clear_glyph_matrix (w->current_matrix);
13205 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
13206 try_window (FRAME_ROOT_WINDOW (f), pos);
13207
13208 /* Compute width and height of the tooltip. */
13209 width = height = 0;
13210 for (i = 0; i < w->desired_matrix->nrows; ++i)
13211 {
13212 struct glyph_row *row = &w->desired_matrix->rows[i];
13213 struct glyph *last;
13214 int row_width;
13215
13216 /* Stop at the first empty row at the end. */
13217 if (!row->enabled_p || !row->displays_text_p)
13218 break;
13219
13220 /* Let the row go over the full width of the frame. */
13221 row->full_width_p = 1;
13222
13223 #ifdef TODO /* Investigate why some fonts need more width than is
13224 calculated for some tooltips. */
13225 /* There's a glyph at the end of rows that is use to place
13226 the cursor there. Don't include the width of this glyph. */
13227 if (row->used[TEXT_AREA])
13228 {
13229 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
13230 row_width = row->pixel_width - last->pixel_width;
13231 }
13232 else
13233 #endif
13234 row_width = row->pixel_width;
13235
13236 /* TODO: find why tips do not draw along baseline as instructed. */
13237 height += row->height;
13238 width = max (width, row_width);
13239 }
13240
13241 /* Add the frame's internal border to the width and height the X
13242 window should have. */
13243 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
13244 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
13245
13246 /* Move the tooltip window where the mouse pointer is. Resize and
13247 show it. */
13248 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
13249
13250 {
13251 /* Adjust Window size to take border into account. */
13252 RECT rect;
13253 rect.left = rect.top = 0;
13254 rect.right = width;
13255 rect.bottom = height;
13256 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
13257 FRAME_EXTERNAL_MENU_BAR (f));
13258
13259 /* Position and size tooltip, and put it in the topmost group. */
13260 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13261 root_x, root_y, rect.right - rect.left,
13262 rect.bottom - rect.top, SWP_NOACTIVATE);
13263
13264 /* Ensure tooltip is on top of other topmost windows (eg menus). */
13265 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
13266 0, 0, 0, 0,
13267 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
13268
13269 /* Let redisplay know that we have made the frame visible already. */
13270 f->async_visible = 1;
13271
13272 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
13273 }
13274
13275 /* Draw into the window. */
13276 w->must_be_updated_p = 1;
13277 update_single_window (w, 1);
13278
13279 UNBLOCK_INPUT;
13280
13281 /* Restore original current buffer. */
13282 set_buffer_internal_1 (old_buffer);
13283 windows_or_buffers_changed = old_windows_or_buffers_changed;
13284
13285 start_timer:
13286 /* Let the tip disappear after timeout seconds. */
13287 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
13288 intern ("x-hide-tip"));
13289
13290 UNGCPRO;
13291 return unbind_to (count, Qnil);
13292 }
13293
13294
13295 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
13296 doc: /* Hide the current tooltip window, if there is any.
13297 Value is t if tooltip was open, nil otherwise. */)
13298 ()
13299 {
13300 int count;
13301 Lisp_Object deleted, frame, timer;
13302 struct gcpro gcpro1, gcpro2;
13303
13304 /* Return quickly if nothing to do. */
13305 if (NILP (tip_timer) && NILP (tip_frame))
13306 return Qnil;
13307
13308 frame = tip_frame;
13309 timer = tip_timer;
13310 GCPRO2 (frame, timer);
13311 tip_frame = tip_timer = deleted = Qnil;
13312
13313 count = SPECPDL_INDEX ();
13314 specbind (Qinhibit_redisplay, Qt);
13315 specbind (Qinhibit_quit, Qt);
13316
13317 if (!NILP (timer))
13318 call1 (Qcancel_timer, timer);
13319
13320 if (FRAMEP (frame))
13321 {
13322 Fdelete_frame (frame, Qnil);
13323 deleted = Qt;
13324 }
13325
13326 UNGCPRO;
13327 return unbind_to (count, deleted);
13328 }
13329
13330
13331 \f
13332 /***********************************************************************
13333 File selection dialog
13334 ***********************************************************************/
13335 extern Lisp_Object Qfile_name_history;
13336
13337 /* Callback for altering the behaviour of the Open File dialog.
13338 Makes the Filename text field contain "Current Directory" and be
13339 read-only when "Directories" is selected in the filter. This
13340 allows us to work around the fact that the standard Open File
13341 dialog does not support directories. */
13342 UINT CALLBACK
13343 file_dialog_callback (hwnd, msg, wParam, lParam)
13344 HWND hwnd;
13345 UINT msg;
13346 WPARAM wParam;
13347 LPARAM lParam;
13348 {
13349 if (msg == WM_NOTIFY)
13350 {
13351 OFNOTIFY * notify = (OFNOTIFY *)lParam;
13352 /* Detect when the Filter dropdown is changed. */
13353 if (notify->hdr.code == CDN_TYPECHANGE)
13354 {
13355 HWND dialog = GetParent (hwnd);
13356 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
13357
13358 /* Directories is in index 2. */
13359 if (notify->lpOFN->nFilterIndex == 2)
13360 {
13361 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
13362 "Current Directory");
13363 EnableWindow (edit_control, FALSE);
13364 }
13365 else
13366 {
13367 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
13368 "");
13369 EnableWindow (edit_control, TRUE);
13370 }
13371 }
13372 }
13373 return 0;
13374 }
13375
13376 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
13377 doc: /* Read file name, prompting with PROMPT in directory DIR.
13378 Use a file selection dialog.
13379 Select DEFAULT-FILENAME in the dialog's file selection box, if
13380 specified. Ensure that file exists if MUSTMATCH is non-nil. */)
13381 (prompt, dir, default_filename, mustmatch)
13382 Lisp_Object prompt, dir, default_filename, mustmatch;
13383 {
13384 struct frame *f = SELECTED_FRAME ();
13385 Lisp_Object file = Qnil;
13386 int count = SPECPDL_INDEX ();
13387 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
13388 char filename[MAX_PATH + 1];
13389 char init_dir[MAX_PATH + 1];
13390
13391 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
13392 CHECK_STRING (prompt);
13393 CHECK_STRING (dir);
13394
13395 /* Create the dialog with PROMPT as title, using DIR as initial
13396 directory and using "*" as pattern. */
13397 dir = Fexpand_file_name (dir, Qnil);
13398 strncpy (init_dir, SDATA (dir), MAX_PATH);
13399 init_dir[MAX_PATH] = '\0';
13400 unixtodos_filename (init_dir);
13401
13402 if (STRINGP (default_filename))
13403 {
13404 char *file_name_only;
13405 char *full_path_name = SDATA (default_filename);
13406
13407 unixtodos_filename (full_path_name);
13408
13409 file_name_only = strrchr (full_path_name, '\\');
13410 if (!file_name_only)
13411 file_name_only = full_path_name;
13412 else
13413 {
13414 file_name_only++;
13415 }
13416
13417 strncpy (filename, file_name_only, MAX_PATH);
13418 filename[MAX_PATH] = '\0';
13419 }
13420 else
13421 filename[0] = '\0';
13422
13423 {
13424 OPENFILENAME file_details;
13425
13426 /* Prevent redisplay. */
13427 specbind (Qinhibit_redisplay, Qt);
13428 BLOCK_INPUT;
13429
13430 bzero (&file_details, sizeof (file_details));
13431 file_details.lStructSize = sizeof (file_details);
13432 file_details.hwndOwner = FRAME_W32_WINDOW (f);
13433 /* Undocumented Bug in Common File Dialog:
13434 If a filter is not specified, shell links are not resolved. */
13435 file_details.lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
13436 file_details.lpstrFile = filename;
13437 file_details.nMaxFile = sizeof (filename);
13438 file_details.lpstrInitialDir = init_dir;
13439 file_details.lpstrTitle = SDATA (prompt);
13440 file_details.Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
13441 | OFN_EXPLORER | OFN_ENABLEHOOK);
13442 if (!NILP (mustmatch))
13443 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
13444
13445 file_details.lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
13446
13447 if (GetOpenFileName (&file_details))
13448 {
13449 dostounix_filename (filename);
13450 if (file_details.nFilterIndex == 2)
13451 {
13452 /* "Folder Only" selected - strip dummy file name. */
13453 char * last = strrchr (filename, '/');
13454 *last = '\0';
13455 }
13456
13457 file = DECODE_FILE(build_string (filename));
13458 }
13459 /* User cancelled the dialog without making a selection. */
13460 else if (!CommDlgExtendedError ())
13461 file = Qnil;
13462 /* An error occurred, fallback on reading from the mini-buffer. */
13463 else
13464 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
13465 dir, mustmatch, dir, Qfile_name_history,
13466 default_filename, Qnil);
13467
13468 UNBLOCK_INPUT;
13469 file = unbind_to (count, file);
13470 }
13471
13472 UNGCPRO;
13473
13474 /* Make "Cancel" equivalent to C-g. */
13475 if (NILP (file))
13476 Fsignal (Qquit, Qnil);
13477
13478 return unbind_to (count, file);
13479 }
13480
13481
13482 \f
13483 /***********************************************************************
13484 w32 specialized functions
13485 ***********************************************************************/
13486
13487 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
13488 doc: /* Select a font using the W32 font dialog.
13489 Returns an X font string corresponding to the selection. */)
13490 (frame, include_proportional)
13491 Lisp_Object frame, include_proportional;
13492 {
13493 FRAME_PTR f = check_x_frame (frame);
13494 CHOOSEFONT cf;
13495 LOGFONT lf;
13496 TEXTMETRIC tm;
13497 HDC hdc;
13498 HANDLE oldobj;
13499 char buf[100];
13500
13501 bzero (&cf, sizeof (cf));
13502 bzero (&lf, sizeof (lf));
13503
13504 cf.lStructSize = sizeof (cf);
13505 cf.hwndOwner = FRAME_W32_WINDOW (f);
13506 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
13507
13508 /* Unless include_proportional is non-nil, limit the selection to
13509 monospaced fonts. */
13510 if (NILP (include_proportional))
13511 cf.Flags |= CF_FIXEDPITCHONLY;
13512
13513 cf.lpLogFont = &lf;
13514
13515 /* Initialize as much of the font details as we can from the current
13516 default font. */
13517 hdc = GetDC (FRAME_W32_WINDOW (f));
13518 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
13519 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
13520 if (GetTextMetrics (hdc, &tm))
13521 {
13522 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
13523 lf.lfWeight = tm.tmWeight;
13524 lf.lfItalic = tm.tmItalic;
13525 lf.lfUnderline = tm.tmUnderlined;
13526 lf.lfStrikeOut = tm.tmStruckOut;
13527 lf.lfCharSet = tm.tmCharSet;
13528 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
13529 }
13530 SelectObject (hdc, oldobj);
13531 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
13532
13533 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
13534 return Qnil;
13535
13536 return build_string (buf);
13537 }
13538
13539 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
13540 Sw32_send_sys_command, 1, 2, 0,
13541 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
13542 Some useful values for command are #xf030 to maximise frame (#xf020
13543 to minimize), #xf120 to restore frame to original size, and #xf100
13544 to activate the menubar for keyboard access. #xf140 activates the
13545 screen saver if defined.
13546
13547 If optional parameter FRAME is not specified, use selected frame. */)
13548 (command, frame)
13549 Lisp_Object command, frame;
13550 {
13551 FRAME_PTR f = check_x_frame (frame);
13552
13553 CHECK_NUMBER (command);
13554
13555 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
13556
13557 return Qnil;
13558 }
13559
13560 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
13561 doc: /* Get Windows to perform OPERATION on DOCUMENT.
13562 This is a wrapper around the ShellExecute system function, which
13563 invokes the application registered to handle OPERATION for DOCUMENT.
13564 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
13565 nil for the default action), and DOCUMENT is typically the name of a
13566 document file or URL, but can also be a program executable to run or
13567 a directory to open in the Windows Explorer.
13568
13569 If DOCUMENT is a program executable, PARAMETERS can be a string
13570 containing command line parameters, but otherwise should be nil.
13571
13572 SHOW-FLAG can be used to control whether the invoked application is hidden
13573 or minimized. If SHOW-FLAG is nil, the application is displayed normally,
13574 otherwise it is an integer representing a ShowWindow flag:
13575
13576 0 - start hidden
13577 1 - start normally
13578 3 - start maximized
13579 6 - start minimized */)
13580 (operation, document, parameters, show_flag)
13581 Lisp_Object operation, document, parameters, show_flag;
13582 {
13583 Lisp_Object current_dir;
13584
13585 CHECK_STRING (document);
13586
13587 /* Encode filename and current directory. */
13588 current_dir = ENCODE_FILE (current_buffer->directory);
13589 document = ENCODE_FILE (document);
13590 if ((int) ShellExecute (NULL,
13591 (STRINGP (operation) ?
13592 SDATA (operation) : NULL),
13593 SDATA (document),
13594 (STRINGP (parameters) ?
13595 SDATA (parameters) : NULL),
13596 SDATA (current_dir),
13597 (INTEGERP (show_flag) ?
13598 XINT (show_flag) : SW_SHOWDEFAULT))
13599 > 32)
13600 return Qt;
13601 error ("ShellExecute failed: %s", w32_strerror (0));
13602 }
13603
13604 /* Lookup virtual keycode from string representing the name of a
13605 non-ascii keystroke into the corresponding virtual key, using
13606 lispy_function_keys. */
13607 static int
13608 lookup_vk_code (char *key)
13609 {
13610 int i;
13611
13612 for (i = 0; i < 256; i++)
13613 if (lispy_function_keys[i] != 0
13614 && strcmp (lispy_function_keys[i], key) == 0)
13615 return i;
13616
13617 return -1;
13618 }
13619
13620 /* Convert a one-element vector style key sequence to a hot key
13621 definition. */
13622 static int
13623 w32_parse_hot_key (key)
13624 Lisp_Object key;
13625 {
13626 /* Copied from Fdefine_key and store_in_keymap. */
13627 register Lisp_Object c;
13628 int vk_code;
13629 int lisp_modifiers;
13630 int w32_modifiers;
13631 struct gcpro gcpro1;
13632
13633 CHECK_VECTOR (key);
13634
13635 if (XFASTINT (Flength (key)) != 1)
13636 return Qnil;
13637
13638 GCPRO1 (key);
13639
13640 c = Faref (key, make_number (0));
13641
13642 if (CONSP (c) && lucid_event_type_list_p (c))
13643 c = Fevent_convert_list (c);
13644
13645 UNGCPRO;
13646
13647 if (! INTEGERP (c) && ! SYMBOLP (c))
13648 error ("Key definition is invalid");
13649
13650 /* Work out the base key and the modifiers. */
13651 if (SYMBOLP (c))
13652 {
13653 c = parse_modifiers (c);
13654 lisp_modifiers = Fcar (Fcdr (c));
13655 c = Fcar (c);
13656 if (!SYMBOLP (c))
13657 abort ();
13658 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
13659 }
13660 else if (INTEGERP (c))
13661 {
13662 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
13663 /* Many ascii characters are their own virtual key code. */
13664 vk_code = XINT (c) & CHARACTERBITS;
13665 }
13666
13667 if (vk_code < 0 || vk_code > 255)
13668 return Qnil;
13669
13670 if ((lisp_modifiers & meta_modifier) != 0
13671 && !NILP (Vw32_alt_is_meta))
13672 lisp_modifiers |= alt_modifier;
13673
13674 /* Supply defs missing from mingw32. */
13675 #ifndef MOD_ALT
13676 #define MOD_ALT 0x0001
13677 #define MOD_CONTROL 0x0002
13678 #define MOD_SHIFT 0x0004
13679 #define MOD_WIN 0x0008
13680 #endif
13681
13682 /* Convert lisp modifiers to Windows hot-key form. */
13683 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
13684 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
13685 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
13686 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
13687
13688 return HOTKEY (vk_code, w32_modifiers);
13689 }
13690
13691 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
13692 Sw32_register_hot_key, 1, 1, 0,
13693 doc: /* Register KEY as a hot-key combination.
13694 Certain key combinations like Alt-Tab are reserved for system use on
13695 Windows, and therefore are normally intercepted by the system. However,
13696 most of these key combinations can be received by registering them as
13697 hot-keys, overriding their special meaning.
13698
13699 KEY must be a one element key definition in vector form that would be
13700 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
13701 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
13702 is always interpreted as the Windows modifier keys.
13703
13704 The return value is the hotkey-id if registered, otherwise nil. */)
13705 (key)
13706 Lisp_Object key;
13707 {
13708 key = w32_parse_hot_key (key);
13709
13710 if (NILP (Fmemq (key, w32_grabbed_keys)))
13711 {
13712 /* Reuse an empty slot if possible. */
13713 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
13714
13715 /* Safe to add new key to list, even if we have focus. */
13716 if (NILP (item))
13717 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
13718 else
13719 XSETCAR (item, key);
13720
13721 /* Notify input thread about new hot-key definition, so that it
13722 takes effect without needing to switch focus. */
13723 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
13724 (WPARAM) key, 0);
13725 }
13726
13727 return key;
13728 }
13729
13730 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
13731 Sw32_unregister_hot_key, 1, 1, 0,
13732 doc: /* Unregister HOTKEY as a hot-key combination. */)
13733 (key)
13734 Lisp_Object key;
13735 {
13736 Lisp_Object item;
13737
13738 if (!INTEGERP (key))
13739 key = w32_parse_hot_key (key);
13740
13741 item = Fmemq (key, w32_grabbed_keys);
13742
13743 if (!NILP (item))
13744 {
13745 /* Notify input thread about hot-key definition being removed, so
13746 that it takes effect without needing focus switch. */
13747 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
13748 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
13749 {
13750 MSG msg;
13751 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13752 }
13753 return Qt;
13754 }
13755 return Qnil;
13756 }
13757
13758 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
13759 Sw32_registered_hot_keys, 0, 0, 0,
13760 doc: /* Return list of registered hot-key IDs. */)
13761 ()
13762 {
13763 return Fcopy_sequence (w32_grabbed_keys);
13764 }
13765
13766 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
13767 Sw32_reconstruct_hot_key, 1, 1, 0,
13768 doc: /* Convert hot-key ID to a lisp key combination. */)
13769 (hotkeyid)
13770 Lisp_Object hotkeyid;
13771 {
13772 int vk_code, w32_modifiers;
13773 Lisp_Object key;
13774
13775 CHECK_NUMBER (hotkeyid);
13776
13777 vk_code = HOTKEY_VK_CODE (hotkeyid);
13778 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
13779
13780 if (lispy_function_keys[vk_code])
13781 key = intern (lispy_function_keys[vk_code]);
13782 else
13783 key = make_number (vk_code);
13784
13785 key = Fcons (key, Qnil);
13786 if (w32_modifiers & MOD_SHIFT)
13787 key = Fcons (Qshift, key);
13788 if (w32_modifiers & MOD_CONTROL)
13789 key = Fcons (Qctrl, key);
13790 if (w32_modifiers & MOD_ALT)
13791 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
13792 if (w32_modifiers & MOD_WIN)
13793 key = Fcons (Qhyper, key);
13794
13795 return key;
13796 }
13797
13798 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
13799 Sw32_toggle_lock_key, 1, 2, 0,
13800 doc: /* Toggle the state of the lock key KEY.
13801 KEY can be `capslock', `kp-numlock', or `scroll'.
13802 If the optional parameter NEW-STATE is a number, then the state of KEY
13803 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
13804 (key, new_state)
13805 Lisp_Object key, new_state;
13806 {
13807 int vk_code;
13808
13809 if (EQ (key, intern ("capslock")))
13810 vk_code = VK_CAPITAL;
13811 else if (EQ (key, intern ("kp-numlock")))
13812 vk_code = VK_NUMLOCK;
13813 else if (EQ (key, intern ("scroll")))
13814 vk_code = VK_SCROLL;
13815 else
13816 return Qnil;
13817
13818 if (!dwWindowsThreadId)
13819 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
13820
13821 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
13822 (WPARAM) vk_code, (LPARAM) new_state))
13823 {
13824 MSG msg;
13825 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13826 return make_number (msg.wParam);
13827 }
13828 return Qnil;
13829 }
13830 \f
13831 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
13832 doc: /* Return storage information about the file system FILENAME is on.
13833 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
13834 storage of the file system, FREE is the free storage, and AVAIL is the
13835 storage available to a non-superuser. All 3 numbers are in bytes.
13836 If the underlying system call fails, value is nil. */)
13837 (filename)
13838 Lisp_Object filename;
13839 {
13840 Lisp_Object encoded, value;
13841
13842 CHECK_STRING (filename);
13843 filename = Fexpand_file_name (filename, Qnil);
13844 encoded = ENCODE_FILE (filename);
13845
13846 value = Qnil;
13847
13848 /* Determining the required information on Windows turns out, sadly,
13849 to be more involved than one would hope. The original Win32 api
13850 call for this will return bogus information on some systems, but we
13851 must dynamically probe for the replacement api, since that was
13852 added rather late on. */
13853 {
13854 HMODULE hKernel = GetModuleHandle ("kernel32");
13855 BOOL (*pfn_GetDiskFreeSpaceEx)
13856 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
13857 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
13858
13859 /* On Windows, we may need to specify the root directory of the
13860 volume holding FILENAME. */
13861 char rootname[MAX_PATH];
13862 char *name = SDATA (encoded);
13863
13864 /* find the root name of the volume if given */
13865 if (isalpha (name[0]) && name[1] == ':')
13866 {
13867 rootname[0] = name[0];
13868 rootname[1] = name[1];
13869 rootname[2] = '\\';
13870 rootname[3] = 0;
13871 }
13872 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
13873 {
13874 char *str = rootname;
13875 int slashes = 4;
13876 do
13877 {
13878 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
13879 break;
13880 *str++ = *name++;
13881 }
13882 while ( *name );
13883
13884 *str++ = '\\';
13885 *str = 0;
13886 }
13887
13888 if (pfn_GetDiskFreeSpaceEx)
13889 {
13890 /* Unsigned large integers cannot be cast to double, so
13891 use signed ones instead. */
13892 LARGE_INTEGER availbytes;
13893 LARGE_INTEGER freebytes;
13894 LARGE_INTEGER totalbytes;
13895
13896 if (pfn_GetDiskFreeSpaceEx(rootname,
13897 (ULARGE_INTEGER *)&availbytes,
13898 (ULARGE_INTEGER *)&totalbytes,
13899 (ULARGE_INTEGER *)&freebytes))
13900 value = list3 (make_float ((double) totalbytes.QuadPart),
13901 make_float ((double) freebytes.QuadPart),
13902 make_float ((double) availbytes.QuadPart));
13903 }
13904 else
13905 {
13906 DWORD sectors_per_cluster;
13907 DWORD bytes_per_sector;
13908 DWORD free_clusters;
13909 DWORD total_clusters;
13910
13911 if (GetDiskFreeSpace(rootname,
13912 &sectors_per_cluster,
13913 &bytes_per_sector,
13914 &free_clusters,
13915 &total_clusters))
13916 value = list3 (make_float ((double) total_clusters
13917 * sectors_per_cluster * bytes_per_sector),
13918 make_float ((double) free_clusters
13919 * sectors_per_cluster * bytes_per_sector),
13920 make_float ((double) free_clusters
13921 * sectors_per_cluster * bytes_per_sector));
13922 }
13923 }
13924
13925 return value;
13926 }
13927 \f
13928 /***********************************************************************
13929 Initialization
13930 ***********************************************************************/
13931
13932 /* Keep this list in the same order as frame_parms in frame.c.
13933 Use 0 for unsupported frame parameters. */
13934
13935 frame_parm_handler w32_frame_parm_handlers[] =
13936 {
13937 x_set_autoraise,
13938 x_set_autolower,
13939 x_set_background_color,
13940 x_set_border_color,
13941 x_set_border_width,
13942 x_set_cursor_color,
13943 x_set_cursor_type,
13944 x_set_font,
13945 x_set_foreground_color,
13946 x_set_icon_name,
13947 x_set_icon_type,
13948 x_set_internal_border_width,
13949 x_set_menu_bar_lines,
13950 x_set_mouse_color,
13951 x_explicitly_set_name,
13952 x_set_scroll_bar_width,
13953 x_set_title,
13954 x_set_unsplittable,
13955 x_set_vertical_scroll_bars,
13956 x_set_visibility,
13957 x_set_tool_bar_lines,
13958 0, /* x_set_scroll_bar_foreground, */
13959 0, /* x_set_scroll_bar_background, */
13960 x_set_screen_gamma,
13961 x_set_line_spacing,
13962 x_set_fringe_width,
13963 x_set_fringe_width,
13964 0, /* x_set_wait_for_wm, */
13965 x_set_fullscreen,
13966 };
13967
13968 void
13969 syms_of_w32fns ()
13970 {
13971 globals_of_w32fns ();
13972 /* This is zero if not using MS-Windows. */
13973 w32_in_use = 0;
13974 track_mouse_window = NULL;
13975
13976 w32_visible_system_caret_hwnd = NULL;
13977
13978 Qnone = intern ("none");
13979 staticpro (&Qnone);
13980 Qsuppress_icon = intern ("suppress-icon");
13981 staticpro (&Qsuppress_icon);
13982 Qundefined_color = intern ("undefined-color");
13983 staticpro (&Qundefined_color);
13984 Qcenter = intern ("center");
13985 staticpro (&Qcenter);
13986 Qcancel_timer = intern ("cancel-timer");
13987 staticpro (&Qcancel_timer);
13988
13989 Qhyper = intern ("hyper");
13990 staticpro (&Qhyper);
13991 Qsuper = intern ("super");
13992 staticpro (&Qsuper);
13993 Qmeta = intern ("meta");
13994 staticpro (&Qmeta);
13995 Qalt = intern ("alt");
13996 staticpro (&Qalt);
13997 Qctrl = intern ("ctrl");
13998 staticpro (&Qctrl);
13999 Qcontrol = intern ("control");
14000 staticpro (&Qcontrol);
14001 Qshift = intern ("shift");
14002 staticpro (&Qshift);
14003 /* This is the end of symbol initialization. */
14004
14005 /* Text property `display' should be nonsticky by default. */
14006 Vtext_property_default_nonsticky
14007 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
14008
14009
14010 Qlaplace = intern ("laplace");
14011 staticpro (&Qlaplace);
14012 Qemboss = intern ("emboss");
14013 staticpro (&Qemboss);
14014 Qedge_detection = intern ("edge-detection");
14015 staticpro (&Qedge_detection);
14016 Qheuristic = intern ("heuristic");
14017 staticpro (&Qheuristic);
14018 QCmatrix = intern (":matrix");
14019 staticpro (&QCmatrix);
14020 QCcolor_adjustment = intern (":color-adjustment");
14021 staticpro (&QCcolor_adjustment);
14022 QCmask = intern (":mask");
14023 staticpro (&QCmask);
14024
14025 Fput (Qundefined_color, Qerror_conditions,
14026 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
14027 Fput (Qundefined_color, Qerror_message,
14028 build_string ("Undefined color"));
14029
14030 staticpro (&w32_grabbed_keys);
14031 w32_grabbed_keys = Qnil;
14032
14033 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
14034 doc: /* An array of color name mappings for windows. */);
14035 Vw32_color_map = Qnil;
14036
14037 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
14038 doc: /* Non-nil if alt key presses are passed on to Windows.
14039 When non-nil, for example, alt pressed and released and then space will
14040 open the System menu. When nil, Emacs silently swallows alt key events. */);
14041 Vw32_pass_alt_to_system = Qnil;
14042
14043 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
14044 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
14045 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
14046 Vw32_alt_is_meta = Qt;
14047
14048 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
14049 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
14050 XSETINT (Vw32_quit_key, 0);
14051
14052 DEFVAR_LISP ("w32-pass-lwindow-to-system",
14053 &Vw32_pass_lwindow_to_system,
14054 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
14055 When non-nil, the Start menu is opened by tapping the key. */);
14056 Vw32_pass_lwindow_to_system = Qt;
14057
14058 DEFVAR_LISP ("w32-pass-rwindow-to-system",
14059 &Vw32_pass_rwindow_to_system,
14060 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
14061 When non-nil, the Start menu is opened by tapping the key. */);
14062 Vw32_pass_rwindow_to_system = Qt;
14063
14064 DEFVAR_INT ("w32-phantom-key-code",
14065 &Vw32_phantom_key_code,
14066 doc: /* Virtual key code used to generate \"phantom\" key presses.
14067 Value is a number between 0 and 255.
14068
14069 Phantom key presses are generated in order to stop the system from
14070 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
14071 `w32-pass-rwindow-to-system' is nil. */);
14072 /* Although 255 is technically not a valid key code, it works and
14073 means that this hack won't interfere with any real key code. */
14074 Vw32_phantom_key_code = 255;
14075
14076 DEFVAR_LISP ("w32-enable-num-lock",
14077 &Vw32_enable_num_lock,
14078 doc: /* Non-nil if Num Lock should act normally.
14079 Set to nil to see Num Lock as the key `kp-numlock'. */);
14080 Vw32_enable_num_lock = Qt;
14081
14082 DEFVAR_LISP ("w32-enable-caps-lock",
14083 &Vw32_enable_caps_lock,
14084 doc: /* Non-nil if Caps Lock should act normally.
14085 Set to nil to see Caps Lock as the key `capslock'. */);
14086 Vw32_enable_caps_lock = Qt;
14087
14088 DEFVAR_LISP ("w32-scroll-lock-modifier",
14089 &Vw32_scroll_lock_modifier,
14090 doc: /* Modifier to use for the Scroll Lock on state.
14091 The value can be hyper, super, meta, alt, control or shift for the
14092 respective modifier, or nil to see Scroll Lock as the key `scroll'.
14093 Any other value will cause the key to be ignored. */);
14094 Vw32_scroll_lock_modifier = Qt;
14095
14096 DEFVAR_LISP ("w32-lwindow-modifier",
14097 &Vw32_lwindow_modifier,
14098 doc: /* Modifier to use for the left \"Windows\" key.
14099 The value can be hyper, super, meta, alt, control or shift for the
14100 respective modifier, or nil to appear as the key `lwindow'.
14101 Any other value will cause the key to be ignored. */);
14102 Vw32_lwindow_modifier = Qnil;
14103
14104 DEFVAR_LISP ("w32-rwindow-modifier",
14105 &Vw32_rwindow_modifier,
14106 doc: /* Modifier to use for the right \"Windows\" key.
14107 The value can be hyper, super, meta, alt, control or shift for the
14108 respective modifier, or nil to appear as the key `rwindow'.
14109 Any other value will cause the key to be ignored. */);
14110 Vw32_rwindow_modifier = Qnil;
14111
14112 DEFVAR_LISP ("w32-apps-modifier",
14113 &Vw32_apps_modifier,
14114 doc: /* Modifier to use for the \"Apps\" key.
14115 The value can be hyper, super, meta, alt, control or shift for the
14116 respective modifier, or nil to appear as the key `apps'.
14117 Any other value will cause the key to be ignored. */);
14118 Vw32_apps_modifier = Qnil;
14119
14120 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
14121 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
14122 w32_enable_synthesized_fonts = 0;
14123
14124 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
14125 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
14126 Vw32_enable_palette = Qt;
14127
14128 DEFVAR_INT ("w32-mouse-button-tolerance",
14129 &Vw32_mouse_button_tolerance,
14130 doc: /* Analogue of double click interval for faking middle mouse events.
14131 The value is the minimum time in milliseconds that must elapse between
14132 left/right button down events before they are considered distinct events.
14133 If both mouse buttons are depressed within this interval, a middle mouse
14134 button down event is generated instead. */);
14135 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
14136
14137 DEFVAR_INT ("w32-mouse-move-interval",
14138 &Vw32_mouse_move_interval,
14139 doc: /* Minimum interval between mouse move events.
14140 The value is the minimum time in milliseconds that must elapse between
14141 successive mouse move (or scroll bar drag) events before they are
14142 reported as lisp events. */);
14143 XSETINT (Vw32_mouse_move_interval, 0);
14144
14145 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
14146 &w32_pass_extra_mouse_buttons_to_system,
14147 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
14148 Recent versions of Windows support mice with up to five buttons.
14149 Since most applications don't support these extra buttons, most mouse
14150 drivers will allow you to map them to functions at the system level.
14151 If this variable is non-nil, Emacs will pass them on, allowing the
14152 system to handle them. */);
14153 w32_pass_extra_mouse_buttons_to_system = 0;
14154
14155 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
14156 doc: /* List of directories to search for window system bitmap files. */);
14157 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
14158
14159 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
14160 doc: /* The shape of the pointer when over text.
14161 Changing the value does not affect existing frames
14162 unless you set the mouse color. */);
14163 Vx_pointer_shape = Qnil;
14164
14165 Vx_nontext_pointer_shape = Qnil;
14166
14167 Vx_mode_pointer_shape = Qnil;
14168
14169 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
14170 doc: /* The shape of the pointer when Emacs is busy.
14171 This variable takes effect when you create a new frame
14172 or when you set the mouse color. */);
14173 Vx_hourglass_pointer_shape = Qnil;
14174
14175 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
14176 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
14177 display_hourglass_p = 1;
14178
14179 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
14180 doc: /* *Seconds to wait before displaying an hourglass pointer.
14181 Value must be an integer or float. */);
14182 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
14183
14184 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
14185 &Vx_sensitive_text_pointer_shape,
14186 doc: /* The shape of the pointer when over mouse-sensitive text.
14187 This variable takes effect when you create a new frame
14188 or when you set the mouse color. */);
14189 Vx_sensitive_text_pointer_shape = Qnil;
14190
14191 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
14192 &Vx_window_horizontal_drag_shape,
14193 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
14194 This variable takes effect when you create a new frame
14195 or when you set the mouse color. */);
14196 Vx_window_horizontal_drag_shape = Qnil;
14197
14198 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
14199 doc: /* A string indicating the foreground color of the cursor box. */);
14200 Vx_cursor_fore_pixel = Qnil;
14201
14202 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
14203 doc: /* Maximum size for tooltips.
14204 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
14205 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
14206
14207 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
14208 doc: /* Non-nil if no window manager is in use.
14209 Emacs doesn't try to figure this out; this is always nil
14210 unless you set it to something else. */);
14211 /* We don't have any way to find this out, so set it to nil
14212 and maybe the user would like to set it to t. */
14213 Vx_no_window_manager = Qnil;
14214
14215 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
14216 &Vx_pixel_size_width_font_regexp,
14217 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
14218
14219 Since Emacs gets width of a font matching with this regexp from
14220 PIXEL_SIZE field of the name, font finding mechanism gets faster for
14221 such a font. This is especially effective for such large fonts as
14222 Chinese, Japanese, and Korean. */);
14223 Vx_pixel_size_width_font_regexp = Qnil;
14224
14225 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
14226 doc: /* Time after which cached images are removed from the cache.
14227 When an image has not been displayed this many seconds, remove it
14228 from the image cache. Value must be an integer or nil with nil
14229 meaning don't clear the cache. */);
14230 Vimage_cache_eviction_delay = make_number (30 * 60);
14231
14232 DEFVAR_LISP ("w32-bdf-filename-alist",
14233 &Vw32_bdf_filename_alist,
14234 doc: /* List of bdf fonts and their corresponding filenames. */);
14235 Vw32_bdf_filename_alist = Qnil;
14236
14237 DEFVAR_BOOL ("w32-strict-fontnames",
14238 &w32_strict_fontnames,
14239 doc: /* Non-nil means only use fonts that are exact matches for those requested.
14240 Default is nil, which allows old fontnames that are not XLFD compliant,
14241 and allows third-party CJK display to work by specifying false charset
14242 fields to trick Emacs into translating to Big5, SJIS etc.
14243 Setting this to t will prevent wrong fonts being selected when
14244 fontsets are automatically created. */);
14245 w32_strict_fontnames = 0;
14246
14247 DEFVAR_BOOL ("w32-strict-painting",
14248 &w32_strict_painting,
14249 doc: /* Non-nil means use strict rules for repainting frames.
14250 Set this to nil to get the old behaviour for repainting; this should
14251 only be necessary if the default setting causes problems. */);
14252 w32_strict_painting = 1;
14253
14254 DEFVAR_LISP ("w32-charset-info-alist",
14255 &Vw32_charset_info_alist,
14256 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
14257 Each entry should be of the form:
14258
14259 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
14260
14261 where CHARSET_NAME is a string used in font names to identify the charset,
14262 WINDOWS_CHARSET is a symbol that can be one of:
14263 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
14264 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
14265 w32-charset-chinesebig5,
14266 w32-charset-johab, w32-charset-hebrew,
14267 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
14268 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
14269 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
14270 w32-charset-unicode,
14271 or w32-charset-oem.
14272 CODEPAGE should be an integer specifying the codepage that should be used
14273 to display the character set, t to do no translation and output as Unicode,
14274 or nil to do no translation and output as 8 bit (or multibyte on far-east
14275 versions of Windows) characters. */);
14276 Vw32_charset_info_alist = Qnil;
14277
14278 staticpro (&Qw32_charset_ansi);
14279 Qw32_charset_ansi = intern ("w32-charset-ansi");
14280 staticpro (&Qw32_charset_symbol);
14281 Qw32_charset_symbol = intern ("w32-charset-symbol");
14282 staticpro (&Qw32_charset_shiftjis);
14283 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
14284 staticpro (&Qw32_charset_hangeul);
14285 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
14286 staticpro (&Qw32_charset_chinesebig5);
14287 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
14288 staticpro (&Qw32_charset_gb2312);
14289 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
14290 staticpro (&Qw32_charset_oem);
14291 Qw32_charset_oem = intern ("w32-charset-oem");
14292
14293 #ifdef JOHAB_CHARSET
14294 {
14295 static int w32_extra_charsets_defined = 1;
14296 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
14297 doc: /* Internal variable. */);
14298
14299 staticpro (&Qw32_charset_johab);
14300 Qw32_charset_johab = intern ("w32-charset-johab");
14301 staticpro (&Qw32_charset_easteurope);
14302 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
14303 staticpro (&Qw32_charset_turkish);
14304 Qw32_charset_turkish = intern ("w32-charset-turkish");
14305 staticpro (&Qw32_charset_baltic);
14306 Qw32_charset_baltic = intern ("w32-charset-baltic");
14307 staticpro (&Qw32_charset_russian);
14308 Qw32_charset_russian = intern ("w32-charset-russian");
14309 staticpro (&Qw32_charset_arabic);
14310 Qw32_charset_arabic = intern ("w32-charset-arabic");
14311 staticpro (&Qw32_charset_greek);
14312 Qw32_charset_greek = intern ("w32-charset-greek");
14313 staticpro (&Qw32_charset_hebrew);
14314 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
14315 staticpro (&Qw32_charset_vietnamese);
14316 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
14317 staticpro (&Qw32_charset_thai);
14318 Qw32_charset_thai = intern ("w32-charset-thai");
14319 staticpro (&Qw32_charset_mac);
14320 Qw32_charset_mac = intern ("w32-charset-mac");
14321 }
14322 #endif
14323
14324 #ifdef UNICODE_CHARSET
14325 {
14326 static int w32_unicode_charset_defined = 1;
14327 DEFVAR_BOOL ("w32-unicode-charset-defined",
14328 &w32_unicode_charset_defined,
14329 doc: /* Internal variable. */);
14330
14331 staticpro (&Qw32_charset_unicode);
14332 Qw32_charset_unicode = intern ("w32-charset-unicode");
14333 #endif
14334
14335 #if 0 /* TODO: Port to W32 */
14336 defsubr (&Sx_change_window_property);
14337 defsubr (&Sx_delete_window_property);
14338 defsubr (&Sx_window_property);
14339 #endif
14340 defsubr (&Sxw_display_color_p);
14341 defsubr (&Sx_display_grayscale_p);
14342 defsubr (&Sxw_color_defined_p);
14343 defsubr (&Sxw_color_values);
14344 defsubr (&Sx_server_max_request_size);
14345 defsubr (&Sx_server_vendor);
14346 defsubr (&Sx_server_version);
14347 defsubr (&Sx_display_pixel_width);
14348 defsubr (&Sx_display_pixel_height);
14349 defsubr (&Sx_display_mm_width);
14350 defsubr (&Sx_display_mm_height);
14351 defsubr (&Sx_display_screens);
14352 defsubr (&Sx_display_planes);
14353 defsubr (&Sx_display_color_cells);
14354 defsubr (&Sx_display_visual_class);
14355 defsubr (&Sx_display_backing_store);
14356 defsubr (&Sx_display_save_under);
14357 defsubr (&Sx_create_frame);
14358 defsubr (&Sx_open_connection);
14359 defsubr (&Sx_close_connection);
14360 defsubr (&Sx_display_list);
14361 defsubr (&Sx_synchronize);
14362
14363 /* W32 specific functions */
14364
14365 defsubr (&Sw32_focus_frame);
14366 defsubr (&Sw32_select_font);
14367 defsubr (&Sw32_define_rgb_color);
14368 defsubr (&Sw32_default_color_map);
14369 defsubr (&Sw32_load_color_file);
14370 defsubr (&Sw32_send_sys_command);
14371 defsubr (&Sw32_shell_execute);
14372 defsubr (&Sw32_register_hot_key);
14373 defsubr (&Sw32_unregister_hot_key);
14374 defsubr (&Sw32_registered_hot_keys);
14375 defsubr (&Sw32_reconstruct_hot_key);
14376 defsubr (&Sw32_toggle_lock_key);
14377 defsubr (&Sw32_find_bdf_fonts);
14378
14379 defsubr (&Sfile_system_info);
14380
14381 /* Setting callback functions for fontset handler. */
14382 get_font_info_func = w32_get_font_info;
14383
14384 #if 0 /* This function pointer doesn't seem to be used anywhere.
14385 And the pointer assigned has the wrong type, anyway. */
14386 list_fonts_func = w32_list_fonts;
14387 #endif
14388
14389 load_font_func = w32_load_font;
14390 find_ccl_program_func = w32_find_ccl_program;
14391 query_font_func = w32_query_font;
14392 set_frame_fontset_func = x_set_font;
14393 check_window_system_func = check_w32;
14394
14395 /* Images. */
14396 Qxbm = intern ("xbm");
14397 staticpro (&Qxbm);
14398 QCconversion = intern (":conversion");
14399 staticpro (&QCconversion);
14400 QCheuristic_mask = intern (":heuristic-mask");
14401 staticpro (&QCheuristic_mask);
14402 QCcolor_symbols = intern (":color-symbols");
14403 staticpro (&QCcolor_symbols);
14404 QCascent = intern (":ascent");
14405 staticpro (&QCascent);
14406 QCmargin = intern (":margin");
14407 staticpro (&QCmargin);
14408 QCrelief = intern (":relief");
14409 staticpro (&QCrelief);
14410 Qpostscript = intern ("postscript");
14411 staticpro (&Qpostscript);
14412 QCloader = intern (":loader");
14413 staticpro (&QCloader);
14414 QCbounding_box = intern (":bounding-box");
14415 staticpro (&QCbounding_box);
14416 QCpt_width = intern (":pt-width");
14417 staticpro (&QCpt_width);
14418 QCpt_height = intern (":pt-height");
14419 staticpro (&QCpt_height);
14420 QCindex = intern (":index");
14421 staticpro (&QCindex);
14422 Qpbm = intern ("pbm");
14423 staticpro (&Qpbm);
14424
14425 #if HAVE_XPM
14426 Qxpm = intern ("xpm");
14427 staticpro (&Qxpm);
14428 #endif
14429
14430 #if HAVE_JPEG
14431 Qjpeg = intern ("jpeg");
14432 staticpro (&Qjpeg);
14433 #endif
14434
14435 #if HAVE_TIFF
14436 Qtiff = intern ("tiff");
14437 staticpro (&Qtiff);
14438 #endif
14439
14440 #if HAVE_GIF
14441 Qgif = intern ("gif");
14442 staticpro (&Qgif);
14443 #endif
14444
14445 #if HAVE_PNG
14446 Qpng = intern ("png");
14447 staticpro (&Qpng);
14448 #endif
14449
14450 defsubr (&Sclear_image_cache);
14451 defsubr (&Simage_size);
14452 defsubr (&Simage_mask_p);
14453
14454 hourglass_atimer = NULL;
14455 hourglass_shown_p = 0;
14456 defsubr (&Sx_show_tip);
14457 defsubr (&Sx_hide_tip);
14458 tip_timer = Qnil;
14459 staticpro (&tip_timer);
14460 tip_frame = Qnil;
14461 staticpro (&tip_frame);
14462
14463 last_show_tip_args = Qnil;
14464 staticpro (&last_show_tip_args);
14465
14466 defsubr (&Sx_file_dialog);
14467 }
14468
14469
14470 /*
14471 globals_of_w32fns is used to initialize those global variables that
14472 must always be initialized on startup even when the global variable
14473 initialized is non zero (see the function main in emacs.c).
14474 globals_of_w32fns is called from syms_of_w32fns when the global
14475 variable initialized is 0 and directly from main when initialized
14476 is non zero.
14477 */
14478 void globals_of_w32fns ()
14479 {
14480 HMODULE user32_lib = GetModuleHandle ("user32.dll");
14481 /*
14482 TrackMouseEvent not available in all versions of Windows, so must load
14483 it dynamically. Do it once, here, instead of every time it is used.
14484 */
14485 track_mouse_event_fn = (TrackMouseEvent_Proc)
14486 GetProcAddress (user32_lib, "TrackMouseEvent");
14487 /* ditto for GetClipboardSequenceNumber. */
14488 clipboard_sequence_fn = (ClipboardSequence_Proc)
14489 GetProcAddress (user32_lib, "GetClipboardSequenceNumber");
14490 }
14491
14492 /* Initialize image types. Based on which libraries are available. */
14493 static void
14494 init_external_image_libraries ()
14495 {
14496 HINSTANCE library;
14497
14498 #if HAVE_XPM
14499 if ((library = LoadLibrary ("libXpm.dll")))
14500 {
14501 if (init_xpm_functions (library))
14502 define_image_type (&xpm_type);
14503 }
14504
14505 #endif
14506
14507 #if HAVE_JPEG
14508 /* Try loading jpeg library under probable names. */
14509 if ((library = LoadLibrary ("libjpeg.dll"))
14510 || (library = LoadLibrary ("jpeg-62.dll"))
14511 || (library = LoadLibrary ("jpeg.dll")))
14512 {
14513 if (init_jpeg_functions (library))
14514 define_image_type (&jpeg_type);
14515 }
14516 #endif
14517
14518 #if HAVE_TIFF
14519 if (library = LoadLibrary ("libtiff.dll"))
14520 {
14521 if (init_tiff_functions (library))
14522 define_image_type (&tiff_type);
14523 }
14524 #endif
14525
14526 #if HAVE_GIF
14527 if (library = LoadLibrary ("libungif.dll"))
14528 {
14529 if (init_gif_functions (library))
14530 define_image_type (&gif_type);
14531 }
14532 #endif
14533
14534 #if HAVE_PNG
14535 /* Ensure zlib is loaded. Try debug version first. */
14536 if (!LoadLibrary ("zlibd.dll"))
14537 LoadLibrary ("zlib.dll");
14538
14539 /* Try loading libpng under probable names. */
14540 if ((library = LoadLibrary ("libpng13d.dll"))
14541 || (library = LoadLibrary ("libpng13.dll"))
14542 || (library = LoadLibrary ("libpng12d.dll"))
14543 || (library = LoadLibrary ("libpng12.dll"))
14544 || (library = LoadLibrary ("libpng.dll")))
14545 {
14546 if (init_png_functions (library))
14547 define_image_type (&png_type);
14548 }
14549 #endif
14550 }
14551
14552 void
14553 init_xfns ()
14554 {
14555 image_types = NULL;
14556 Vimage_types = Qnil;
14557
14558 define_image_type (&pbm_type);
14559 define_image_type (&xbm_type);
14560
14561 #if 0 /* TODO : Ghostscript support for W32 */
14562 define_image_type (&gs_type);
14563 #endif
14564
14565 /* Image types that rely on external libraries are loaded dynamically
14566 if the library is available. */
14567 init_external_image_libraries ();
14568 }
14569
14570 #undef abort
14571
14572 void
14573 w32_abort()
14574 {
14575 int button;
14576 button = MessageBox (NULL,
14577 "A fatal error has occurred!\n\n"
14578 "Select Abort to exit, Retry to debug, Ignore to continue",
14579 "Emacs Abort Dialog",
14580 MB_ICONEXCLAMATION | MB_TASKMODAL
14581 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
14582 switch (button)
14583 {
14584 case IDRETRY:
14585 DebugBreak ();
14586 break;
14587 case IDIGNORE:
14588 break;
14589 case IDABORT:
14590 default:
14591 abort ();
14592 break;
14593 }
14594 }
14595
14596 /* For convenience when debugging. */
14597 int
14598 w32_last_error()
14599 {
14600 return GetLastError ();
14601 }
14602
14603 /* arch-tag: 707589ab-b9be-4638-8cdd-74629cc9b446
14604 (do not change this comment) */