(ido-make-file-list, ido-make-dir-list): Don't move
[bpt/emacs.git] / src / w32fns.c
... / ...
CommitLineData
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
5This file is part of GNU Emacs.
6
7GNU Emacs is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 2, or (at your option)
10any later version.
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GNU Emacs; see the file COPYING. If not, write to
19the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20Boston, 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
58void syms_of_w32fns ();
59void globals_of_w32fns ();
60
61extern void free_frame_menubar ();
62extern void x_compute_fringe_widths P_ ((struct frame *, int));
63extern double atof ();
64extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
65extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
66extern void w32_free_menu_strings P_ ((HWND));
67
68extern int quit_char;
69
70extern 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
76int gray_bitmap_width = gray_width;
77int gray_bitmap_height = gray_height;
78unsigned char *gray_bitmap_bits = gray_bits;
79
80/* The colormap for converting color names to RGB values */
81Lisp_Object Vw32_color_map;
82
83/* Non nil if alt key presses are passed on to Windows. */
84Lisp_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. */
88Lisp_Object Vw32_alt_is_meta;
89
90/* If non-zero, the windows virtual key code for an alternative quit key. */
91Lisp_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). */
95Lisp_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). */
99Lisp_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. */
103Lisp_Object Vw32_phantom_key_code;
104
105/* Modifier associated with the left "Windows" key, or nil to act as a
106 normal key. */
107Lisp_Object Vw32_lwindow_modifier;
108
109/* Modifier associated with the right "Windows" key, or nil to act as a
110 normal key. */
111Lisp_Object Vw32_rwindow_modifier;
112
113/* Modifier associated with the "Apps" key, or nil to act as a normal
114 key. */
115Lisp_Object Vw32_apps_modifier;
116
117/* Value is nil if Num Lock acts as a function key. */
118Lisp_Object Vw32_enable_num_lock;
119
120/* Value is nil if Caps Lock acts as a function key. */
121Lisp_Object Vw32_enable_caps_lock;
122
123/* Modifier associated with Scroll Lock, or nil to act as a normal key. */
124Lisp_Object Vw32_scroll_lock_modifier;
125
126/* Switch to control whether we inhibit requests for synthesized bold
127 and italic versions of fonts. */
128int w32_enable_synthesized_fonts;
129
130/* Enable palette management. */
131Lisp_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. */
135Lisp_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. */
139Lisp_Object Vw32_mouse_move_interval;
140
141/* Flag to indicate if XBUTTON events should be passed on to Windows. */
142int w32_pass_extra_mouse_buttons_to_system;
143
144/* The name we're using in resource queries. */
145Lisp_Object Vx_resource_name;
146
147/* Non nil if no window manager is in use. */
148Lisp_Object Vx_no_window_manager;
149
150/* Non-zero means we're allowed to display a hourglass pointer. */
151
152int display_hourglass_p;
153
154/* The background and shape of the mouse pointer, and shape when not
155 over text or in the modeline. */
156
157Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
158Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
159
160/* The shape when over mouse-sensitive text. */
161
162Lisp_Object Vx_sensitive_text_pointer_shape;
163
164/* Color of chars displayed in cursor box. */
165
166Lisp_Object Vx_cursor_fore_pixel;
167
168/* Nonzero if using Windows. */
169
170static int w32_in_use;
171
172/* Search path for bitmap files. */
173
174Lisp_Object Vx_bitmap_file_path;
175
176/* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
177
178Lisp_Object Vx_pixel_size_width_font_regexp;
179
180/* Alist of bdf fonts and the files that define them. */
181Lisp_Object Vw32_bdf_filename_alist;
182
183/* A flag to control whether fonts are matched strictly or not. */
184int w32_strict_fontnames;
185
186/* A flag to control whether we should only repaint if GetUpdateRect
187 indicates there is an update region. */
188int w32_strict_painting;
189
190/* Associative list linking character set strings to Windows codepages. */
191Lisp_Object Vw32_charset_info_alist;
192
193/* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
194#ifndef VIETNAMESE_CHARSET
195#define VIETNAMESE_CHARSET 163
196#endif
197
198Lisp_Object Qauto_raise;
199Lisp_Object Qauto_lower;
200Lisp_Object Qborder_color;
201Lisp_Object Qborder_width;
202extern Lisp_Object Qbox;
203Lisp_Object Qcursor_color;
204Lisp_Object Qcursor_type;
205Lisp_Object Qgeometry;
206Lisp_Object Qicon_left;
207Lisp_Object Qicon_top;
208Lisp_Object Qicon_type;
209Lisp_Object Qicon_name;
210Lisp_Object Qinternal_border_width;
211Lisp_Object Qleft;
212Lisp_Object Qright;
213Lisp_Object Qmouse_color;
214Lisp_Object Qnone;
215Lisp_Object Qparent_id;
216Lisp_Object Qscroll_bar_width;
217Lisp_Object Qsuppress_icon;
218Lisp_Object Qundefined_color;
219Lisp_Object Qvertical_scroll_bars;
220Lisp_Object Qvisibility;
221Lisp_Object Qwindow_id;
222Lisp_Object Qx_frame_parameter;
223Lisp_Object Qx_resource_name;
224Lisp_Object Quser_position;
225Lisp_Object Quser_size;
226Lisp_Object Qscreen_gamma;
227Lisp_Object Qline_spacing;
228Lisp_Object Qcenter;
229Lisp_Object Qcancel_timer;
230Lisp_Object Qhyper;
231Lisp_Object Qsuper;
232Lisp_Object Qmeta;
233Lisp_Object Qalt;
234Lisp_Object Qctrl;
235Lisp_Object Qcontrol;
236Lisp_Object Qshift;
237
238Lisp_Object Qw32_charset_ansi;
239Lisp_Object Qw32_charset_default;
240Lisp_Object Qw32_charset_symbol;
241Lisp_Object Qw32_charset_shiftjis;
242Lisp_Object Qw32_charset_hangeul;
243Lisp_Object Qw32_charset_gb2312;
244Lisp_Object Qw32_charset_chinesebig5;
245Lisp_Object Qw32_charset_oem;
246
247#ifndef JOHAB_CHARSET
248#define JOHAB_CHARSET 130
249#endif
250#ifdef JOHAB_CHARSET
251Lisp_Object Qw32_charset_easteurope;
252Lisp_Object Qw32_charset_turkish;
253Lisp_Object Qw32_charset_baltic;
254Lisp_Object Qw32_charset_russian;
255Lisp_Object Qw32_charset_arabic;
256Lisp_Object Qw32_charset_greek;
257Lisp_Object Qw32_charset_hebrew;
258Lisp_Object Qw32_charset_vietnamese;
259Lisp_Object Qw32_charset_thai;
260Lisp_Object Qw32_charset_johab;
261Lisp_Object Qw32_charset_mac;
262#endif
263
264#ifdef UNICODE_CHARSET
265Lisp_Object Qw32_charset_unicode;
266#endif
267
268Lisp_Object Qfullscreen;
269Lisp_Object Qfullwidth;
270Lisp_Object Qfullheight;
271Lisp_Object Qfullboth;
272
273extern Lisp_Object Qtop;
274extern Lisp_Object Qdisplay;
275
276/* State variables for emulating a three button mouse. */
277#define LMOUSE 1
278#define MMOUSE 2
279#define RMOUSE 4
280
281static int button_state = 0;
282static W32Msg saved_mouse_button_msg;
283static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
284static W32Msg saved_mouse_move_msg;
285static unsigned mouse_move_timer = 0;
286
287/* Window that is tracking the mouse. */
288static HWND track_mouse_window;
289
290typedef BOOL (WINAPI * TrackMouseEvent_Proc) (
291 IN OUT LPTRACKMOUSEEVENT lpEventTrack
292 );
293
294TrackMouseEvent_Proc track_mouse_event_fn=NULL;
295
296/* W95 mousewheel handler */
297unsigned int msh_mousewheel = 0;
298
299/* Timers */
300#define MOUSE_BUTTON_ID 1
301#define MOUSE_MOVE_ID 2
302#define MENU_FREE_ID 3
303/* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
304 is received. */
305#define MENU_FREE_DELAY 1000
306static unsigned menu_free_timer = 0;
307
308/* The below are defined in frame.c. */
309
310extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
311extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
312extern Lisp_Object Qtool_bar_lines;
313
314extern Lisp_Object Vwindow_system_version;
315
316Lisp_Object Qface_set_after_frame_default;
317
318#ifdef GLYPH_DEBUG
319int image_cache_refcount, dpyinfo_refcount;
320#endif
321
322
323/* From w32term.c. */
324extern Lisp_Object Vw32_num_mouse_buttons;
325extern Lisp_Object Vw32_recognize_altgr;
326
327extern HWND w32_system_caret_hwnd;
328
329extern int w32_system_caret_height;
330extern int w32_system_caret_x;
331extern int w32_system_caret_y;
332extern int w32_use_visible_system_caret;
333
334static HWND w32_visible_system_caret_hwnd;
335
336\f
337/* Error if we are not connected to MS-Windows. */
338void
339check_w32 ()
340{
341 if (! w32_in_use)
342 error ("MS-Windows not in use or not initialized");
343}
344
345/* Nonzero if we can use mouse menus.
346 You should not call this unless HAVE_MENUS is defined. */
347
348int
349have_menus_p ()
350{
351 return w32_in_use;
352}
353
354/* Extract a frame as a FRAME_PTR, defaulting to the selected frame
355 and checking validity for W32. */
356
357FRAME_PTR
358check_x_frame (frame)
359 Lisp_Object frame;
360{
361 FRAME_PTR f;
362
363 if (NILP (frame))
364 frame = selected_frame;
365 CHECK_LIVE_FRAME (frame);
366 f = XFRAME (frame);
367 if (! FRAME_W32_P (f))
368 error ("non-w32 frame used");
369 return f;
370}
371
372/* Let the user specify a display with a frame.
373 nil stands for the selected frame--or, if that is not a w32 frame,
374 the first display on the list. */
375
376static struct w32_display_info *
377check_x_display_info (frame)
378 Lisp_Object frame;
379{
380 if (NILP (frame))
381 {
382 struct frame *sf = XFRAME (selected_frame);
383
384 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
385 return FRAME_W32_DISPLAY_INFO (sf);
386 else
387 return &one_w32_display_info;
388 }
389 else if (STRINGP (frame))
390 return x_display_info_for_name (frame);
391 else
392 {
393 FRAME_PTR f;
394
395 CHECK_LIVE_FRAME (frame);
396 f = XFRAME (frame);
397 if (! FRAME_W32_P (f))
398 error ("non-w32 frame used");
399 return FRAME_W32_DISPLAY_INFO (f);
400 }
401}
402\f
403/* Return the Emacs frame-object corresponding to an w32 window.
404 It could be the frame's main window or an icon window. */
405
406/* This function can be called during GC, so use GC_xxx type test macros. */
407
408struct frame *
409x_window_to_frame (dpyinfo, wdesc)
410 struct w32_display_info *dpyinfo;
411 HWND wdesc;
412{
413 Lisp_Object tail, frame;
414 struct frame *f;
415
416 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
417 {
418 frame = XCAR (tail);
419 if (!GC_FRAMEP (frame))
420 continue;
421 f = XFRAME (frame);
422 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
423 continue;
424 if (f->output_data.w32->hourglass_window == wdesc)
425 return f;
426
427 if (FRAME_W32_WINDOW (f) == wdesc)
428 return f;
429 }
430 return 0;
431}
432
433\f
434
435/* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
436 id, which is just an int that this section returns. Bitmaps are
437 reference counted so they can be shared among frames.
438
439 Bitmap indices are guaranteed to be > 0, so a negative number can
440 be used to indicate no bitmap.
441
442 If you use x_create_bitmap_from_data, then you must keep track of
443 the bitmaps yourself. That is, creating a bitmap from the same
444 data more than once will not be caught. */
445
446
447/* Functions to access the contents of a bitmap, given an id. */
448
449int
450x_bitmap_height (f, id)
451 FRAME_PTR f;
452 int id;
453{
454 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
455}
456
457int
458x_bitmap_width (f, id)
459 FRAME_PTR f;
460 int id;
461{
462 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
463}
464
465int
466x_bitmap_pixmap (f, id)
467 FRAME_PTR f;
468 int id;
469{
470 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
471}
472
473
474/* Allocate a new bitmap record. Returns index of new record. */
475
476static int
477x_allocate_bitmap_record (f)
478 FRAME_PTR f;
479{
480 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
481 int i;
482
483 if (dpyinfo->bitmaps == NULL)
484 {
485 dpyinfo->bitmaps_size = 10;
486 dpyinfo->bitmaps
487 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
488 dpyinfo->bitmaps_last = 1;
489 return 1;
490 }
491
492 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
493 return ++dpyinfo->bitmaps_last;
494
495 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
496 if (dpyinfo->bitmaps[i].refcount == 0)
497 return i + 1;
498
499 dpyinfo->bitmaps_size *= 2;
500 dpyinfo->bitmaps
501 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
502 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
503 return ++dpyinfo->bitmaps_last;
504}
505
506/* Add one reference to the reference count of the bitmap with id ID. */
507
508void
509x_reference_bitmap (f, id)
510 FRAME_PTR f;
511 int id;
512{
513 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
514}
515
516/* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
517
518int
519x_create_bitmap_from_data (f, bits, width, height)
520 struct frame *f;
521 char *bits;
522 unsigned int width, height;
523{
524 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
525 Pixmap bitmap;
526 int id;
527
528 bitmap = CreateBitmap (width, height,
529 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
530 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
531 bits);
532
533 if (! bitmap)
534 return -1;
535
536 id = x_allocate_bitmap_record (f);
537 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
538 dpyinfo->bitmaps[id - 1].file = NULL;
539 dpyinfo->bitmaps[id - 1].hinst = NULL;
540 dpyinfo->bitmaps[id - 1].refcount = 1;
541 dpyinfo->bitmaps[id - 1].depth = 1;
542 dpyinfo->bitmaps[id - 1].height = height;
543 dpyinfo->bitmaps[id - 1].width = width;
544
545 return id;
546}
547
548/* Create bitmap from file FILE for frame F. */
549
550int
551x_create_bitmap_from_file (f, file)
552 struct frame *f;
553 Lisp_Object file;
554{
555 return -1;
556#if 0 /* TODO : bitmap support */
557 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
558 unsigned int width, height;
559 HBITMAP bitmap;
560 int xhot, yhot, result, id;
561 Lisp_Object found;
562 int fd;
563 char *filename;
564 HINSTANCE hinst;
565
566 /* Look for an existing bitmap with the same name. */
567 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
568 {
569 if (dpyinfo->bitmaps[id].refcount
570 && dpyinfo->bitmaps[id].file
571 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
572 {
573 ++dpyinfo->bitmaps[id].refcount;
574 return id + 1;
575 }
576 }
577
578 /* Search bitmap-file-path for the file, if appropriate. */
579 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
580 if (fd < 0)
581 return -1;
582 emacs_close (fd);
583
584 filename = (char *) SDATA (found);
585
586 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
587
588 if (hinst == NULL)
589 return -1;
590
591
592 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
593 filename, &width, &height, &bitmap, &xhot, &yhot);
594 if (result != BitmapSuccess)
595 return -1;
596
597 id = x_allocate_bitmap_record (f);
598 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
599 dpyinfo->bitmaps[id - 1].refcount = 1;
600 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SCHARS (file) + 1);
601 dpyinfo->bitmaps[id - 1].depth = 1;
602 dpyinfo->bitmaps[id - 1].height = height;
603 dpyinfo->bitmaps[id - 1].width = width;
604 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
605
606 return id;
607#endif /* TODO */
608}
609
610/* Remove reference to bitmap with id number ID. */
611
612void
613x_destroy_bitmap (f, id)
614 FRAME_PTR f;
615 int id;
616{
617 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
618
619 if (id > 0)
620 {
621 --dpyinfo->bitmaps[id - 1].refcount;
622 if (dpyinfo->bitmaps[id - 1].refcount == 0)
623 {
624 BLOCK_INPUT;
625 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
626 if (dpyinfo->bitmaps[id - 1].file)
627 {
628 xfree (dpyinfo->bitmaps[id - 1].file);
629 dpyinfo->bitmaps[id - 1].file = NULL;
630 }
631 UNBLOCK_INPUT;
632 }
633 }
634}
635
636/* Free all the bitmaps for the display specified by DPYINFO. */
637
638static void
639x_destroy_all_bitmaps (dpyinfo)
640 struct w32_display_info *dpyinfo;
641{
642 int i;
643 for (i = 0; i < dpyinfo->bitmaps_last; i++)
644 if (dpyinfo->bitmaps[i].refcount > 0)
645 {
646 DeleteObject (dpyinfo->bitmaps[i].pixmap);
647 if (dpyinfo->bitmaps[i].file)
648 xfree (dpyinfo->bitmaps[i].file);
649 }
650 dpyinfo->bitmaps_last = 0;
651}
652\f
653/* Connect the frame-parameter names for W32 frames
654 to the ways of passing the parameter values to the window system.
655
656 The name of a parameter, as a Lisp symbol,
657 has an `x-frame-parameter' property which is an integer in Lisp
658 but can be interpreted as an `enum x_frame_parm' in C. */
659
660enum x_frame_parm
661{
662 X_PARM_FOREGROUND_COLOR,
663 X_PARM_BACKGROUND_COLOR,
664 X_PARM_MOUSE_COLOR,
665 X_PARM_CURSOR_COLOR,
666 X_PARM_BORDER_COLOR,
667 X_PARM_ICON_TYPE,
668 X_PARM_FONT,
669 X_PARM_BORDER_WIDTH,
670 X_PARM_INTERNAL_BORDER_WIDTH,
671 X_PARM_NAME,
672 X_PARM_AUTORAISE,
673 X_PARM_AUTOLOWER,
674 X_PARM_VERT_SCROLL_BAR,
675 X_PARM_VISIBILITY,
676 X_PARM_MENU_BAR_LINES
677};
678
679
680struct x_frame_parm_table
681{
682 char *name;
683 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
684};
685
686BOOL my_show_window P_ ((struct frame *, HWND, int));
687void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
688static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
689static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
690static void x_change_window_heights P_ ((Lisp_Object, int));
691/* TODO: Native Input Method support; see x_create_im. */
692void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
693static void x_set_line_spacing P_ ((struct frame *, Lisp_Object, Lisp_Object));
694static void x_set_fullscreen P_ ((struct frame *, Lisp_Object, Lisp_Object));
695void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
696void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
697void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
698void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
699void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
700void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
701void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
702void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
703static void x_set_fringe_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
704void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
705void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
706 Lisp_Object));
707void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
708void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
709void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
710void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
711 Lisp_Object));
712void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
713void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
714void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
715void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
716void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
717void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
718static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
719static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
720 Lisp_Object));
721
722static struct x_frame_parm_table x_frame_parms[] =
723{
724 {"auto-raise", x_set_autoraise},
725 {"auto-lower", x_set_autolower},
726 {"background-color", x_set_background_color},
727 {"border-color", x_set_border_color},
728 {"border-width", x_set_border_width},
729 {"cursor-color", x_set_cursor_color},
730 {"cursor-type", x_set_cursor_type},
731 {"font", x_set_font},
732 {"foreground-color", x_set_foreground_color},
733 {"icon-name", x_set_icon_name},
734 {"icon-type", x_set_icon_type},
735 {"internal-border-width", x_set_internal_border_width},
736 {"menu-bar-lines", x_set_menu_bar_lines},
737 {"mouse-color", x_set_mouse_color},
738 {"name", x_explicitly_set_name},
739 {"scroll-bar-width", x_set_scroll_bar_width},
740 {"title", x_set_title},
741 {"unsplittable", x_set_unsplittable},
742 {"vertical-scroll-bars", x_set_vertical_scroll_bars},
743 {"visibility", x_set_visibility},
744 {"tool-bar-lines", x_set_tool_bar_lines},
745 {"screen-gamma", x_set_screen_gamma},
746 {"line-spacing", x_set_line_spacing},
747 {"left-fringe", x_set_fringe_width},
748 {"right-fringe", x_set_fringe_width},
749 {"fullscreen", x_set_fullscreen},
750};
751
752/* Attach the `x-frame-parameter' properties to
753 the Lisp symbol names of parameters relevant to W32. */
754
755void
756init_x_parm_symbols ()
757{
758 int i;
759
760 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
761 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
762 make_number (i));
763}
764\f
765/* Really try to move where we want to be in case of fullscreen. Some WMs
766 moves the window where we tell them. Some (mwm, twm) moves the outer
767 window manager window there instead.
768 Try to compensate for those WM here. */
769static void
770x_fullscreen_move (f, new_top, new_left)
771 struct frame *f;
772 int new_top;
773 int new_left;
774{
775 if (new_top != f->output_data.w32->top_pos
776 || new_left != f->output_data.w32->left_pos)
777 {
778 int move_x = new_left;
779 int move_y = new_top;
780
781 f->output_data.w32->want_fullscreen |= FULLSCREEN_MOVE_WAIT;
782 x_set_offset (f, move_x, move_y, 1);
783 }
784}
785
786/* Change the parameters of frame F as specified by ALIST.
787 If a parameter is not specially recognized, do nothing;
788 otherwise call the `x_set_...' function for that parameter. */
789
790void
791x_set_frame_parameters (f, alist)
792 FRAME_PTR f;
793 Lisp_Object alist;
794{
795 Lisp_Object tail;
796
797 /* If both of these parameters are present, it's more efficient to
798 set them both at once. So we wait until we've looked at the
799 entire list before we set them. */
800 int width, height;
801
802 /* Same here. */
803 Lisp_Object left, top;
804
805 /* Same with these. */
806 Lisp_Object icon_left, icon_top;
807
808 /* Record in these vectors all the parms specified. */
809 Lisp_Object *parms;
810 Lisp_Object *values;
811 int i, p;
812 int left_no_change = 0, top_no_change = 0;
813 int icon_left_no_change = 0, icon_top_no_change = 0;
814 int fullscreen_is_being_set = 0;
815
816 struct gcpro gcpro1, gcpro2;
817
818 i = 0;
819 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
820 i++;
821
822 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
823 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
824
825 /* Extract parm names and values into those vectors. */
826
827 i = 0;
828 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
829 {
830 Lisp_Object elt;
831
832 elt = Fcar (tail);
833 parms[i] = Fcar (elt);
834 values[i] = Fcdr (elt);
835 i++;
836 }
837 /* TAIL and ALIST are not used again below here. */
838 alist = tail = Qnil;
839
840 GCPRO2 (*parms, *values);
841 gcpro1.nvars = i;
842 gcpro2.nvars = i;
843
844 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
845 because their values appear in VALUES and strings are not valid. */
846 top = left = Qunbound;
847 icon_left = icon_top = Qunbound;
848
849 /* Provide default values for HEIGHT and WIDTH. */
850 if (FRAME_NEW_WIDTH (f))
851 width = FRAME_NEW_WIDTH (f);
852 else
853 width = FRAME_WIDTH (f);
854
855 if (FRAME_NEW_HEIGHT (f))
856 height = FRAME_NEW_HEIGHT (f);
857 else
858 height = FRAME_HEIGHT (f);
859
860 /* Process foreground_color and background_color before anything else.
861 They are independent of other properties, but other properties (e.g.,
862 cursor_color) are dependent upon them. */
863 /* Process default font as well, since fringe widths depends on it. */
864 for (p = 0; p < i; p++)
865 {
866 Lisp_Object prop, val;
867
868 prop = parms[p];
869 val = values[p];
870 if (EQ (prop, Qforeground_color)
871 || EQ (prop, Qbackground_color)
872 || EQ (prop, Qfont)
873 || EQ (prop, Qfullscreen))
874 {
875 register Lisp_Object param_index, old_value;
876
877 old_value = get_frame_param (f, prop);
878 fullscreen_is_being_set |= EQ (prop, Qfullscreen);
879
880 if (NILP (Fequal (val, old_value)))
881 {
882 store_frame_param (f, prop, val);
883
884 param_index = Fget (prop, Qx_frame_parameter);
885 if (NATNUMP (param_index)
886 && (XFASTINT (param_index)
887 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
888 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
889 }
890 }
891 }
892
893 /* Now process them in reverse of specified order. */
894 for (i--; i >= 0; i--)
895 {
896 Lisp_Object prop, val;
897
898 prop = parms[i];
899 val = values[i];
900
901 if (EQ (prop, Qwidth) && NUMBERP (val))
902 width = XFASTINT (val);
903 else if (EQ (prop, Qheight) && NUMBERP (val))
904 height = XFASTINT (val);
905 else if (EQ (prop, Qtop))
906 top = val;
907 else if (EQ (prop, Qleft))
908 left = val;
909 else if (EQ (prop, Qicon_top))
910 icon_top = val;
911 else if (EQ (prop, Qicon_left))
912 icon_left = val;
913 else if (EQ (prop, Qforeground_color)
914 || EQ (prop, Qbackground_color)
915 || EQ (prop, Qfont)
916 || EQ (prop, Qfullscreen))
917 /* Processed above. */
918 continue;
919 else
920 {
921 register Lisp_Object param_index, old_value;
922
923 old_value = get_frame_param (f, prop);
924
925 store_frame_param (f, prop, val);
926
927 param_index = Fget (prop, Qx_frame_parameter);
928 if (NATNUMP (param_index)
929 && (XFASTINT (param_index)
930 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
931 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
932 }
933 }
934
935 /* Don't die if just one of these was set. */
936 if (EQ (left, Qunbound))
937 {
938 left_no_change = 1;
939 if (f->output_data.w32->left_pos < 0)
940 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
941 else
942 XSETINT (left, f->output_data.w32->left_pos);
943 }
944 if (EQ (top, Qunbound))
945 {
946 top_no_change = 1;
947 if (f->output_data.w32->top_pos < 0)
948 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
949 else
950 XSETINT (top, f->output_data.w32->top_pos);
951 }
952
953 /* If one of the icon positions was not set, preserve or default it. */
954 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
955 {
956 icon_left_no_change = 1;
957 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
958 if (NILP (icon_left))
959 XSETINT (icon_left, 0);
960 }
961 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
962 {
963 icon_top_no_change = 1;
964 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
965 if (NILP (icon_top))
966 XSETINT (icon_top, 0);
967 }
968
969 if (FRAME_VISIBLE_P (f) && fullscreen_is_being_set)
970 {
971 /* If the frame is visible already and the fullscreen parameter is
972 being set, it is too late to set WM manager hints to specify
973 size and position.
974 Here we first get the width, height and position that applies to
975 fullscreen. We then move the frame to the appropriate
976 position. Resize of the frame is taken care of in the code after
977 this if-statement. */
978 int new_left, new_top;
979
980 x_fullscreen_adjust (f, &width, &height, &new_top, &new_left);
981 x_fullscreen_move (f, new_top, new_left);
982 }
983
984 /* Don't set these parameters unless they've been explicitly
985 specified. The window might be mapped or resized while we're in
986 this function, and we don't want to override that unless the lisp
987 code has asked for it.
988
989 Don't set these parameters unless they actually differ from the
990 window's current parameters; the window may not actually exist
991 yet. */
992 {
993 Lisp_Object frame;
994
995 check_frame_size (f, &height, &width);
996
997 XSETFRAME (frame, f);
998
999 if (width != FRAME_WIDTH (f)
1000 || height != FRAME_HEIGHT (f)
1001 || FRAME_NEW_HEIGHT (f) || FRAME_NEW_WIDTH (f))
1002 Fset_frame_size (frame, make_number (width), make_number (height));
1003
1004 if ((!NILP (left) || !NILP (top))
1005 && ! (left_no_change && top_no_change)
1006 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
1007 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
1008 {
1009 int leftpos = 0;
1010 int toppos = 0;
1011
1012 /* Record the signs. */
1013 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
1014 if (EQ (left, Qminus))
1015 f->output_data.w32->size_hint_flags |= XNegative;
1016 else if (INTEGERP (left))
1017 {
1018 leftpos = XINT (left);
1019 if (leftpos < 0)
1020 f->output_data.w32->size_hint_flags |= XNegative;
1021 }
1022 else if (CONSP (left) && EQ (XCAR (left), Qminus)
1023 && CONSP (XCDR (left))
1024 && INTEGERP (XCAR (XCDR (left))))
1025 {
1026 leftpos = - XINT (XCAR (XCDR (left)));
1027 f->output_data.w32->size_hint_flags |= XNegative;
1028 }
1029 else if (CONSP (left) && EQ (XCAR (left), Qplus)
1030 && CONSP (XCDR (left))
1031 && INTEGERP (XCAR (XCDR (left))))
1032 {
1033 leftpos = XINT (XCAR (XCDR (left)));
1034 }
1035
1036 if (EQ (top, Qminus))
1037 f->output_data.w32->size_hint_flags |= YNegative;
1038 else if (INTEGERP (top))
1039 {
1040 toppos = XINT (top);
1041 if (toppos < 0)
1042 f->output_data.w32->size_hint_flags |= YNegative;
1043 }
1044 else if (CONSP (top) && EQ (XCAR (top), Qminus)
1045 && CONSP (XCDR (top))
1046 && INTEGERP (XCAR (XCDR (top))))
1047 {
1048 toppos = - XINT (XCAR (XCDR (top)));
1049 f->output_data.w32->size_hint_flags |= YNegative;
1050 }
1051 else if (CONSP (top) && EQ (XCAR (top), Qplus)
1052 && CONSP (XCDR (top))
1053 && INTEGERP (XCAR (XCDR (top))))
1054 {
1055 toppos = XINT (XCAR (XCDR (top)));
1056 }
1057
1058
1059 /* Store the numeric value of the position. */
1060 f->output_data.w32->top_pos = toppos;
1061 f->output_data.w32->left_pos = leftpos;
1062
1063 f->output_data.w32->win_gravity = NorthWestGravity;
1064
1065 /* Actually set that position, and convert to absolute. */
1066 x_set_offset (f, leftpos, toppos, -1);
1067 }
1068
1069 if ((!NILP (icon_left) || !NILP (icon_top))
1070 && ! (icon_left_no_change && icon_top_no_change))
1071 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
1072 }
1073
1074 UNGCPRO;
1075}
1076
1077/* Store the screen positions of frame F into XPTR and YPTR.
1078 These are the positions of the containing window manager window,
1079 not Emacs's own window. */
1080
1081void
1082x_real_positions (f, xptr, yptr)
1083 FRAME_PTR f;
1084 int *xptr, *yptr;
1085{
1086 POINT pt;
1087 RECT rect;
1088
1089 GetClientRect(FRAME_W32_WINDOW(f), &rect);
1090 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
1091
1092 pt.x = rect.left;
1093 pt.y = rect.top;
1094
1095 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
1096
1097 /* Remember x_pixels_diff and y_pixels_diff. */
1098 f->output_data.w32->x_pixels_diff = pt.x - rect.left;
1099 f->output_data.w32->y_pixels_diff = pt.y - rect.top;
1100
1101 *xptr = pt.x;
1102 *yptr = pt.y;
1103}
1104
1105/* Insert a description of internally-recorded parameters of frame X
1106 into the parameter alist *ALISTPTR that is to be given to the user.
1107 Only parameters that are specific to W32
1108 and whose values are not correctly recorded in the frame's
1109 param_alist need to be considered here. */
1110
1111void
1112x_report_frame_params (f, alistptr)
1113 struct frame *f;
1114 Lisp_Object *alistptr;
1115{
1116 char buf[16];
1117 Lisp_Object tem;
1118
1119 /* Represent negative positions (off the top or left screen edge)
1120 in a way that Fmodify_frame_parameters will understand correctly. */
1121 XSETINT (tem, f->output_data.w32->left_pos);
1122 if (f->output_data.w32->left_pos >= 0)
1123 store_in_alist (alistptr, Qleft, tem);
1124 else
1125 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1126
1127 XSETINT (tem, f->output_data.w32->top_pos);
1128 if (f->output_data.w32->top_pos >= 0)
1129 store_in_alist (alistptr, Qtop, tem);
1130 else
1131 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1132
1133 store_in_alist (alistptr, Qborder_width,
1134 make_number (f->output_data.w32->border_width));
1135 store_in_alist (alistptr, Qinternal_border_width,
1136 make_number (f->output_data.w32->internal_border_width));
1137 store_in_alist (alistptr, Qleft_fringe,
1138 make_number (f->output_data.w32->left_fringe_width));
1139 store_in_alist (alistptr, Qright_fringe,
1140 make_number (f->output_data.w32->right_fringe_width));
1141 store_in_alist (alistptr, Qscroll_bar_width,
1142 make_number (FRAME_HAS_VERTICAL_SCROLL_BARS (f)
1143 ? FRAME_SCROLL_BAR_PIXEL_WIDTH(f)
1144 : 0));
1145 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1146 store_in_alist (alistptr, Qwindow_id,
1147 build_string (buf));
1148 store_in_alist (alistptr, Qicon_name, f->icon_name);
1149 FRAME_SAMPLE_VISIBILITY (f);
1150 store_in_alist (alistptr, Qvisibility,
1151 (FRAME_VISIBLE_P (f) ? Qt
1152 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1153 store_in_alist (alistptr, Qdisplay,
1154 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1155}
1156\f
1157
1158DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
1159 Sw32_define_rgb_color, 4, 4, 0,
1160 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
1161This adds or updates a named color to w32-color-map, making it
1162available for use. The original entry's RGB ref is returned, or nil
1163if the entry is new. */)
1164 (red, green, blue, name)
1165 Lisp_Object red, green, blue, name;
1166{
1167 Lisp_Object rgb;
1168 Lisp_Object oldrgb = Qnil;
1169 Lisp_Object entry;
1170
1171 CHECK_NUMBER (red);
1172 CHECK_NUMBER (green);
1173 CHECK_NUMBER (blue);
1174 CHECK_STRING (name);
1175
1176 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1177
1178 BLOCK_INPUT;
1179
1180 /* replace existing entry in w32-color-map or add new entry. */
1181 entry = Fassoc (name, Vw32_color_map);
1182 if (NILP (entry))
1183 {
1184 entry = Fcons (name, rgb);
1185 Vw32_color_map = Fcons (entry, Vw32_color_map);
1186 }
1187 else
1188 {
1189 oldrgb = Fcdr (entry);
1190 Fsetcdr (entry, rgb);
1191 }
1192
1193 UNBLOCK_INPUT;
1194
1195 return (oldrgb);
1196}
1197
1198DEFUN ("w32-load-color-file", Fw32_load_color_file,
1199 Sw32_load_color_file, 1, 1, 0,
1200 doc: /* Create an alist of color entries from an external file.
1201Assign this value to w32-color-map to replace the existing color map.
1202
1203The file should define one named RGB color per line like so:
1204 R G B name
1205where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
1206 (filename)
1207 Lisp_Object filename;
1208{
1209 FILE *fp;
1210 Lisp_Object cmap = Qnil;
1211 Lisp_Object abspath;
1212
1213 CHECK_STRING (filename);
1214 abspath = Fexpand_file_name (filename, Qnil);
1215
1216 fp = fopen (SDATA (filename), "rt");
1217 if (fp)
1218 {
1219 char buf[512];
1220 int red, green, blue;
1221 int num;
1222
1223 BLOCK_INPUT;
1224
1225 while (fgets (buf, sizeof (buf), fp) != NULL) {
1226 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1227 {
1228 char *name = buf + num;
1229 num = strlen (name) - 1;
1230 if (name[num] == '\n')
1231 name[num] = 0;
1232 cmap = Fcons (Fcons (build_string (name),
1233 make_number (RGB (red, green, blue))),
1234 cmap);
1235 }
1236 }
1237 fclose (fp);
1238
1239 UNBLOCK_INPUT;
1240 }
1241
1242 return cmap;
1243}
1244
1245/* The default colors for the w32 color map */
1246typedef struct colormap_t
1247{
1248 char *name;
1249 COLORREF colorref;
1250} colormap_t;
1251
1252colormap_t w32_color_map[] =
1253{
1254 {"snow" , PALETTERGB (255,250,250)},
1255 {"ghost white" , PALETTERGB (248,248,255)},
1256 {"GhostWhite" , PALETTERGB (248,248,255)},
1257 {"white smoke" , PALETTERGB (245,245,245)},
1258 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1259 {"gainsboro" , PALETTERGB (220,220,220)},
1260 {"floral white" , PALETTERGB (255,250,240)},
1261 {"FloralWhite" , PALETTERGB (255,250,240)},
1262 {"old lace" , PALETTERGB (253,245,230)},
1263 {"OldLace" , PALETTERGB (253,245,230)},
1264 {"linen" , PALETTERGB (250,240,230)},
1265 {"antique white" , PALETTERGB (250,235,215)},
1266 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1267 {"papaya whip" , PALETTERGB (255,239,213)},
1268 {"PapayaWhip" , PALETTERGB (255,239,213)},
1269 {"blanched almond" , PALETTERGB (255,235,205)},
1270 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1271 {"bisque" , PALETTERGB (255,228,196)},
1272 {"peach puff" , PALETTERGB (255,218,185)},
1273 {"PeachPuff" , PALETTERGB (255,218,185)},
1274 {"navajo white" , PALETTERGB (255,222,173)},
1275 {"NavajoWhite" , PALETTERGB (255,222,173)},
1276 {"moccasin" , PALETTERGB (255,228,181)},
1277 {"cornsilk" , PALETTERGB (255,248,220)},
1278 {"ivory" , PALETTERGB (255,255,240)},
1279 {"lemon chiffon" , PALETTERGB (255,250,205)},
1280 {"LemonChiffon" , PALETTERGB (255,250,205)},
1281 {"seashell" , PALETTERGB (255,245,238)},
1282 {"honeydew" , PALETTERGB (240,255,240)},
1283 {"mint cream" , PALETTERGB (245,255,250)},
1284 {"MintCream" , PALETTERGB (245,255,250)},
1285 {"azure" , PALETTERGB (240,255,255)},
1286 {"alice blue" , PALETTERGB (240,248,255)},
1287 {"AliceBlue" , PALETTERGB (240,248,255)},
1288 {"lavender" , PALETTERGB (230,230,250)},
1289 {"lavender blush" , PALETTERGB (255,240,245)},
1290 {"LavenderBlush" , PALETTERGB (255,240,245)},
1291 {"misty rose" , PALETTERGB (255,228,225)},
1292 {"MistyRose" , PALETTERGB (255,228,225)},
1293 {"white" , PALETTERGB (255,255,255)},
1294 {"black" , PALETTERGB ( 0, 0, 0)},
1295 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1296 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1297 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1298 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1299 {"dim gray" , PALETTERGB (105,105,105)},
1300 {"DimGray" , PALETTERGB (105,105,105)},
1301 {"dim grey" , PALETTERGB (105,105,105)},
1302 {"DimGrey" , PALETTERGB (105,105,105)},
1303 {"slate gray" , PALETTERGB (112,128,144)},
1304 {"SlateGray" , PALETTERGB (112,128,144)},
1305 {"slate grey" , PALETTERGB (112,128,144)},
1306 {"SlateGrey" , PALETTERGB (112,128,144)},
1307 {"light slate gray" , PALETTERGB (119,136,153)},
1308 {"LightSlateGray" , PALETTERGB (119,136,153)},
1309 {"light slate grey" , PALETTERGB (119,136,153)},
1310 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1311 {"gray" , PALETTERGB (190,190,190)},
1312 {"grey" , PALETTERGB (190,190,190)},
1313 {"light grey" , PALETTERGB (211,211,211)},
1314 {"LightGrey" , PALETTERGB (211,211,211)},
1315 {"light gray" , PALETTERGB (211,211,211)},
1316 {"LightGray" , PALETTERGB (211,211,211)},
1317 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1318 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1319 {"navy" , PALETTERGB ( 0, 0,128)},
1320 {"navy blue" , PALETTERGB ( 0, 0,128)},
1321 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1322 {"cornflower blue" , PALETTERGB (100,149,237)},
1323 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1324 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1325 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1326 {"slate blue" , PALETTERGB (106, 90,205)},
1327 {"SlateBlue" , PALETTERGB (106, 90,205)},
1328 {"medium slate blue" , PALETTERGB (123,104,238)},
1329 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1330 {"light slate blue" , PALETTERGB (132,112,255)},
1331 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1332 {"medium blue" , PALETTERGB ( 0, 0,205)},
1333 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1334 {"royal blue" , PALETTERGB ( 65,105,225)},
1335 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1336 {"blue" , PALETTERGB ( 0, 0,255)},
1337 {"dodger blue" , PALETTERGB ( 30,144,255)},
1338 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1339 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1340 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1341 {"sky blue" , PALETTERGB (135,206,235)},
1342 {"SkyBlue" , PALETTERGB (135,206,235)},
1343 {"light sky blue" , PALETTERGB (135,206,250)},
1344 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1345 {"steel blue" , PALETTERGB ( 70,130,180)},
1346 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1347 {"light steel blue" , PALETTERGB (176,196,222)},
1348 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1349 {"light blue" , PALETTERGB (173,216,230)},
1350 {"LightBlue" , PALETTERGB (173,216,230)},
1351 {"powder blue" , PALETTERGB (176,224,230)},
1352 {"PowderBlue" , PALETTERGB (176,224,230)},
1353 {"pale turquoise" , PALETTERGB (175,238,238)},
1354 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1355 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1356 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1357 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1358 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1359 {"turquoise" , PALETTERGB ( 64,224,208)},
1360 {"cyan" , PALETTERGB ( 0,255,255)},
1361 {"light cyan" , PALETTERGB (224,255,255)},
1362 {"LightCyan" , PALETTERGB (224,255,255)},
1363 {"cadet blue" , PALETTERGB ( 95,158,160)},
1364 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1365 {"medium aquamarine" , PALETTERGB (102,205,170)},
1366 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1367 {"aquamarine" , PALETTERGB (127,255,212)},
1368 {"dark green" , PALETTERGB ( 0,100, 0)},
1369 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1370 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1371 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1372 {"dark sea green" , PALETTERGB (143,188,143)},
1373 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1374 {"sea green" , PALETTERGB ( 46,139, 87)},
1375 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1376 {"medium sea green" , PALETTERGB ( 60,179,113)},
1377 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1378 {"light sea green" , PALETTERGB ( 32,178,170)},
1379 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1380 {"pale green" , PALETTERGB (152,251,152)},
1381 {"PaleGreen" , PALETTERGB (152,251,152)},
1382 {"spring green" , PALETTERGB ( 0,255,127)},
1383 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1384 {"lawn green" , PALETTERGB (124,252, 0)},
1385 {"LawnGreen" , PALETTERGB (124,252, 0)},
1386 {"green" , PALETTERGB ( 0,255, 0)},
1387 {"chartreuse" , PALETTERGB (127,255, 0)},
1388 {"medium spring green" , PALETTERGB ( 0,250,154)},
1389 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1390 {"green yellow" , PALETTERGB (173,255, 47)},
1391 {"GreenYellow" , PALETTERGB (173,255, 47)},
1392 {"lime green" , PALETTERGB ( 50,205, 50)},
1393 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1394 {"yellow green" , PALETTERGB (154,205, 50)},
1395 {"YellowGreen" , PALETTERGB (154,205, 50)},
1396 {"forest green" , PALETTERGB ( 34,139, 34)},
1397 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1398 {"olive drab" , PALETTERGB (107,142, 35)},
1399 {"OliveDrab" , PALETTERGB (107,142, 35)},
1400 {"dark khaki" , PALETTERGB (189,183,107)},
1401 {"DarkKhaki" , PALETTERGB (189,183,107)},
1402 {"khaki" , PALETTERGB (240,230,140)},
1403 {"pale goldenrod" , PALETTERGB (238,232,170)},
1404 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1405 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1406 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1407 {"light yellow" , PALETTERGB (255,255,224)},
1408 {"LightYellow" , PALETTERGB (255,255,224)},
1409 {"yellow" , PALETTERGB (255,255, 0)},
1410 {"gold" , PALETTERGB (255,215, 0)},
1411 {"light goldenrod" , PALETTERGB (238,221,130)},
1412 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1413 {"goldenrod" , PALETTERGB (218,165, 32)},
1414 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1415 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1416 {"rosy brown" , PALETTERGB (188,143,143)},
1417 {"RosyBrown" , PALETTERGB (188,143,143)},
1418 {"indian red" , PALETTERGB (205, 92, 92)},
1419 {"IndianRed" , PALETTERGB (205, 92, 92)},
1420 {"saddle brown" , PALETTERGB (139, 69, 19)},
1421 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1422 {"sienna" , PALETTERGB (160, 82, 45)},
1423 {"peru" , PALETTERGB (205,133, 63)},
1424 {"burlywood" , PALETTERGB (222,184,135)},
1425 {"beige" , PALETTERGB (245,245,220)},
1426 {"wheat" , PALETTERGB (245,222,179)},
1427 {"sandy brown" , PALETTERGB (244,164, 96)},
1428 {"SandyBrown" , PALETTERGB (244,164, 96)},
1429 {"tan" , PALETTERGB (210,180,140)},
1430 {"chocolate" , PALETTERGB (210,105, 30)},
1431 {"firebrick" , PALETTERGB (178,34, 34)},
1432 {"brown" , PALETTERGB (165,42, 42)},
1433 {"dark salmon" , PALETTERGB (233,150,122)},
1434 {"DarkSalmon" , PALETTERGB (233,150,122)},
1435 {"salmon" , PALETTERGB (250,128,114)},
1436 {"light salmon" , PALETTERGB (255,160,122)},
1437 {"LightSalmon" , PALETTERGB (255,160,122)},
1438 {"orange" , PALETTERGB (255,165, 0)},
1439 {"dark orange" , PALETTERGB (255,140, 0)},
1440 {"DarkOrange" , PALETTERGB (255,140, 0)},
1441 {"coral" , PALETTERGB (255,127, 80)},
1442 {"light coral" , PALETTERGB (240,128,128)},
1443 {"LightCoral" , PALETTERGB (240,128,128)},
1444 {"tomato" , PALETTERGB (255, 99, 71)},
1445 {"orange red" , PALETTERGB (255, 69, 0)},
1446 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1447 {"red" , PALETTERGB (255, 0, 0)},
1448 {"hot pink" , PALETTERGB (255,105,180)},
1449 {"HotPink" , PALETTERGB (255,105,180)},
1450 {"deep pink" , PALETTERGB (255, 20,147)},
1451 {"DeepPink" , PALETTERGB (255, 20,147)},
1452 {"pink" , PALETTERGB (255,192,203)},
1453 {"light pink" , PALETTERGB (255,182,193)},
1454 {"LightPink" , PALETTERGB (255,182,193)},
1455 {"pale violet red" , PALETTERGB (219,112,147)},
1456 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1457 {"maroon" , PALETTERGB (176, 48, 96)},
1458 {"medium violet red" , PALETTERGB (199, 21,133)},
1459 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1460 {"violet red" , PALETTERGB (208, 32,144)},
1461 {"VioletRed" , PALETTERGB (208, 32,144)},
1462 {"magenta" , PALETTERGB (255, 0,255)},
1463 {"violet" , PALETTERGB (238,130,238)},
1464 {"plum" , PALETTERGB (221,160,221)},
1465 {"orchid" , PALETTERGB (218,112,214)},
1466 {"medium orchid" , PALETTERGB (186, 85,211)},
1467 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1468 {"dark orchid" , PALETTERGB (153, 50,204)},
1469 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1470 {"dark violet" , PALETTERGB (148, 0,211)},
1471 {"DarkViolet" , PALETTERGB (148, 0,211)},
1472 {"blue violet" , PALETTERGB (138, 43,226)},
1473 {"BlueViolet" , PALETTERGB (138, 43,226)},
1474 {"purple" , PALETTERGB (160, 32,240)},
1475 {"medium purple" , PALETTERGB (147,112,219)},
1476 {"MediumPurple" , PALETTERGB (147,112,219)},
1477 {"thistle" , PALETTERGB (216,191,216)},
1478 {"gray0" , PALETTERGB ( 0, 0, 0)},
1479 {"grey0" , PALETTERGB ( 0, 0, 0)},
1480 {"dark grey" , PALETTERGB (169,169,169)},
1481 {"DarkGrey" , PALETTERGB (169,169,169)},
1482 {"dark gray" , PALETTERGB (169,169,169)},
1483 {"DarkGray" , PALETTERGB (169,169,169)},
1484 {"dark blue" , PALETTERGB ( 0, 0,139)},
1485 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1486 {"dark cyan" , PALETTERGB ( 0,139,139)},
1487 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1488 {"dark magenta" , PALETTERGB (139, 0,139)},
1489 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1490 {"dark red" , PALETTERGB (139, 0, 0)},
1491 {"DarkRed" , PALETTERGB (139, 0, 0)},
1492 {"light green" , PALETTERGB (144,238,144)},
1493 {"LightGreen" , PALETTERGB (144,238,144)},
1494};
1495
1496DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1497 0, 0, 0, doc: /* Return the default color map. */)
1498 ()
1499{
1500 int i;
1501 colormap_t *pc = w32_color_map;
1502 Lisp_Object cmap;
1503
1504 BLOCK_INPUT;
1505
1506 cmap = Qnil;
1507
1508 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1509 pc++, i++)
1510 cmap = Fcons (Fcons (build_string (pc->name),
1511 make_number (pc->colorref)),
1512 cmap);
1513
1514 UNBLOCK_INPUT;
1515
1516 return (cmap);
1517}
1518
1519Lisp_Object
1520w32_to_x_color (rgb)
1521 Lisp_Object rgb;
1522{
1523 Lisp_Object color;
1524
1525 CHECK_NUMBER (rgb);
1526
1527 BLOCK_INPUT;
1528
1529 color = Frassq (rgb, Vw32_color_map);
1530
1531 UNBLOCK_INPUT;
1532
1533 if (!NILP (color))
1534 return (Fcar (color));
1535 else
1536 return Qnil;
1537}
1538
1539COLORREF
1540w32_color_map_lookup (colorname)
1541 char *colorname;
1542{
1543 Lisp_Object tail, ret = Qnil;
1544
1545 BLOCK_INPUT;
1546
1547 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1548 {
1549 register Lisp_Object elt, tem;
1550
1551 elt = Fcar (tail);
1552 if (!CONSP (elt)) continue;
1553
1554 tem = Fcar (elt);
1555
1556 if (lstrcmpi (SDATA (tem), colorname) == 0)
1557 {
1558 ret = XUINT (Fcdr (elt));
1559 break;
1560 }
1561
1562 QUIT;
1563 }
1564
1565
1566 UNBLOCK_INPUT;
1567
1568 return ret;
1569}
1570
1571COLORREF
1572x_to_w32_color (colorname)
1573 char * colorname;
1574{
1575 register Lisp_Object ret = Qnil;
1576
1577 BLOCK_INPUT;
1578
1579 if (colorname[0] == '#')
1580 {
1581 /* Could be an old-style RGB Device specification. */
1582 char *color;
1583 int size;
1584 color = colorname + 1;
1585
1586 size = strlen(color);
1587 if (size == 3 || size == 6 || size == 9 || size == 12)
1588 {
1589 UINT colorval;
1590 int i, pos;
1591 pos = 0;
1592 size /= 3;
1593 colorval = 0;
1594
1595 for (i = 0; i < 3; i++)
1596 {
1597 char *end;
1598 char t;
1599 unsigned long value;
1600
1601 /* The check for 'x' in the following conditional takes into
1602 account the fact that strtol allows a "0x" in front of
1603 our numbers, and we don't. */
1604 if (!isxdigit(color[0]) || color[1] == 'x')
1605 break;
1606 t = color[size];
1607 color[size] = '\0';
1608 value = strtoul(color, &end, 16);
1609 color[size] = t;
1610 if (errno == ERANGE || end - color != size)
1611 break;
1612 switch (size)
1613 {
1614 case 1:
1615 value = value * 0x10;
1616 break;
1617 case 2:
1618 break;
1619 case 3:
1620 value /= 0x10;
1621 break;
1622 case 4:
1623 value /= 0x100;
1624 break;
1625 }
1626 colorval |= (value << pos);
1627 pos += 0x8;
1628 if (i == 2)
1629 {
1630 UNBLOCK_INPUT;
1631 return (colorval);
1632 }
1633 color = end;
1634 }
1635 }
1636 }
1637 else if (strnicmp(colorname, "rgb:", 4) == 0)
1638 {
1639 char *color;
1640 UINT colorval;
1641 int i, pos;
1642 pos = 0;
1643
1644 colorval = 0;
1645 color = colorname + 4;
1646 for (i = 0; i < 3; i++)
1647 {
1648 char *end;
1649 unsigned long value;
1650
1651 /* The check for 'x' in the following conditional takes into
1652 account the fact that strtol allows a "0x" in front of
1653 our numbers, and we don't. */
1654 if (!isxdigit(color[0]) || color[1] == 'x')
1655 break;
1656 value = strtoul(color, &end, 16);
1657 if (errno == ERANGE)
1658 break;
1659 switch (end - color)
1660 {
1661 case 1:
1662 value = value * 0x10 + value;
1663 break;
1664 case 2:
1665 break;
1666 case 3:
1667 value /= 0x10;
1668 break;
1669 case 4:
1670 value /= 0x100;
1671 break;
1672 default:
1673 value = ULONG_MAX;
1674 }
1675 if (value == ULONG_MAX)
1676 break;
1677 colorval |= (value << pos);
1678 pos += 0x8;
1679 if (i == 2)
1680 {
1681 if (*end != '\0')
1682 break;
1683 UNBLOCK_INPUT;
1684 return (colorval);
1685 }
1686 if (*end != '/')
1687 break;
1688 color = end + 1;
1689 }
1690 }
1691 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1692 {
1693 /* This is an RGB Intensity specification. */
1694 char *color;
1695 UINT colorval;
1696 int i, pos;
1697 pos = 0;
1698
1699 colorval = 0;
1700 color = colorname + 5;
1701 for (i = 0; i < 3; i++)
1702 {
1703 char *end;
1704 double value;
1705 UINT val;
1706
1707 value = strtod(color, &end);
1708 if (errno == ERANGE)
1709 break;
1710 if (value < 0.0 || value > 1.0)
1711 break;
1712 val = (UINT)(0x100 * value);
1713 /* We used 0x100 instead of 0xFF to give a continuous
1714 range between 0.0 and 1.0 inclusive. The next statement
1715 fixes the 1.0 case. */
1716 if (val == 0x100)
1717 val = 0xFF;
1718 colorval |= (val << pos);
1719 pos += 0x8;
1720 if (i == 2)
1721 {
1722 if (*end != '\0')
1723 break;
1724 UNBLOCK_INPUT;
1725 return (colorval);
1726 }
1727 if (*end != '/')
1728 break;
1729 color = end + 1;
1730 }
1731 }
1732 /* I am not going to attempt to handle any of the CIE color schemes
1733 or TekHVC, since I don't know the algorithms for conversion to
1734 RGB. */
1735
1736 /* If we fail to lookup the color name in w32_color_map, then check the
1737 colorname to see if it can be crudely approximated: If the X color
1738 ends in a number (e.g., "darkseagreen2"), strip the number and
1739 return the result of looking up the base color name. */
1740 ret = w32_color_map_lookup (colorname);
1741 if (NILP (ret))
1742 {
1743 int len = strlen (colorname);
1744
1745 if (isdigit (colorname[len - 1]))
1746 {
1747 char *ptr, *approx = alloca (len + 1);
1748
1749 strcpy (approx, colorname);
1750 ptr = &approx[len - 1];
1751 while (ptr > approx && isdigit (*ptr))
1752 *ptr-- = '\0';
1753
1754 ret = w32_color_map_lookup (approx);
1755 }
1756 }
1757
1758 UNBLOCK_INPUT;
1759 return ret;
1760}
1761
1762
1763void
1764w32_regenerate_palette (FRAME_PTR f)
1765{
1766 struct w32_palette_entry * list;
1767 LOGPALETTE * log_palette;
1768 HPALETTE new_palette;
1769 int i;
1770
1771 /* don't bother trying to create palette if not supported */
1772 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1773 return;
1774
1775 log_palette = (LOGPALETTE *)
1776 alloca (sizeof (LOGPALETTE) +
1777 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1778 log_palette->palVersion = 0x300;
1779 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1780
1781 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1782 for (i = 0;
1783 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1784 i++, list = list->next)
1785 log_palette->palPalEntry[i] = list->entry;
1786
1787 new_palette = CreatePalette (log_palette);
1788
1789 enter_crit ();
1790
1791 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1792 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1793 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1794
1795 /* Realize display palette and garbage all frames. */
1796 release_frame_dc (f, get_frame_dc (f));
1797
1798 leave_crit ();
1799}
1800
1801#define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1802#define SET_W32_COLOR(pe, color) \
1803 do \
1804 { \
1805 pe.peRed = GetRValue (color); \
1806 pe.peGreen = GetGValue (color); \
1807 pe.peBlue = GetBValue (color); \
1808 pe.peFlags = 0; \
1809 } while (0)
1810
1811#if 0
1812/* Keep these around in case we ever want to track color usage. */
1813void
1814w32_map_color (FRAME_PTR f, COLORREF color)
1815{
1816 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1817
1818 if (NILP (Vw32_enable_palette))
1819 return;
1820
1821 /* check if color is already mapped */
1822 while (list)
1823 {
1824 if (W32_COLOR (list->entry) == color)
1825 {
1826 ++list->refcount;
1827 return;
1828 }
1829 list = list->next;
1830 }
1831
1832 /* not already mapped, so add to list and recreate Windows palette */
1833 list = (struct w32_palette_entry *)
1834 xmalloc (sizeof (struct w32_palette_entry));
1835 SET_W32_COLOR (list->entry, color);
1836 list->refcount = 1;
1837 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1838 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1839 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1840
1841 /* set flag that palette must be regenerated */
1842 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1843}
1844
1845void
1846w32_unmap_color (FRAME_PTR f, COLORREF color)
1847{
1848 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1849 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1850
1851 if (NILP (Vw32_enable_palette))
1852 return;
1853
1854 /* check if color is already mapped */
1855 while (list)
1856 {
1857 if (W32_COLOR (list->entry) == color)
1858 {
1859 if (--list->refcount == 0)
1860 {
1861 *prev = list->next;
1862 xfree (list);
1863 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1864 break;
1865 }
1866 else
1867 return;
1868 }
1869 prev = &list->next;
1870 list = list->next;
1871 }
1872
1873 /* set flag that palette must be regenerated */
1874 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1875}
1876#endif
1877
1878
1879/* Gamma-correct COLOR on frame F. */
1880
1881void
1882gamma_correct (f, color)
1883 struct frame *f;
1884 COLORREF *color;
1885{
1886 if (f->gamma)
1887 {
1888 *color = PALETTERGB (
1889 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1890 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1891 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1892 }
1893}
1894
1895
1896/* Decide if color named COLOR is valid for the display associated with
1897 the selected frame; if so, return the rgb values in COLOR_DEF.
1898 If ALLOC is nonzero, allocate a new colormap cell. */
1899
1900int
1901w32_defined_color (f, color, color_def, alloc)
1902 FRAME_PTR f;
1903 char *color;
1904 XColor *color_def;
1905 int alloc;
1906{
1907 register Lisp_Object tem;
1908 COLORREF w32_color_ref;
1909
1910 tem = x_to_w32_color (color);
1911
1912 if (!NILP (tem))
1913 {
1914 if (f)
1915 {
1916 /* Apply gamma correction. */
1917 w32_color_ref = XUINT (tem);
1918 gamma_correct (f, &w32_color_ref);
1919 XSETINT (tem, w32_color_ref);
1920 }
1921
1922 /* Map this color to the palette if it is enabled. */
1923 if (!NILP (Vw32_enable_palette))
1924 {
1925 struct w32_palette_entry * entry =
1926 one_w32_display_info.color_list;
1927 struct w32_palette_entry ** prev =
1928 &one_w32_display_info.color_list;
1929
1930 /* check if color is already mapped */
1931 while (entry)
1932 {
1933 if (W32_COLOR (entry->entry) == XUINT (tem))
1934 break;
1935 prev = &entry->next;
1936 entry = entry->next;
1937 }
1938
1939 if (entry == NULL && alloc)
1940 {
1941 /* not already mapped, so add to list */
1942 entry = (struct w32_palette_entry *)
1943 xmalloc (sizeof (struct w32_palette_entry));
1944 SET_W32_COLOR (entry->entry, XUINT (tem));
1945 entry->next = NULL;
1946 *prev = entry;
1947 one_w32_display_info.num_colors++;
1948
1949 /* set flag that palette must be regenerated */
1950 one_w32_display_info.regen_palette = TRUE;
1951 }
1952 }
1953 /* Ensure COLORREF value is snapped to nearest color in (default)
1954 palette by simulating the PALETTERGB macro. This works whether
1955 or not the display device has a palette. */
1956 w32_color_ref = XUINT (tem) | 0x2000000;
1957
1958 color_def->pixel = w32_color_ref;
1959 color_def->red = GetRValue (w32_color_ref) * 256;
1960 color_def->green = GetGValue (w32_color_ref) * 256;
1961 color_def->blue = GetBValue (w32_color_ref) * 256;
1962
1963 return 1;
1964 }
1965 else
1966 {
1967 return 0;
1968 }
1969}
1970
1971/* Given a string ARG naming a color, compute a pixel value from it
1972 suitable for screen F.
1973 If F is not a color screen, return DEF (default) regardless of what
1974 ARG says. */
1975
1976int
1977x_decode_color (f, arg, def)
1978 FRAME_PTR f;
1979 Lisp_Object arg;
1980 int def;
1981{
1982 XColor cdef;
1983
1984 CHECK_STRING (arg);
1985
1986 if (strcmp (SDATA (arg), "black") == 0)
1987 return BLACK_PIX_DEFAULT (f);
1988 else if (strcmp (SDATA (arg), "white") == 0)
1989 return WHITE_PIX_DEFAULT (f);
1990
1991 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1992 return def;
1993
1994 /* w32_defined_color is responsible for coping with failures
1995 by looking for a near-miss. */
1996 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1997 return cdef.pixel;
1998
1999 /* defined_color failed; return an ultimate default. */
2000 return def;
2001}
2002\f
2003/* Change the `line-spacing' frame parameter of frame F. OLD_VALUE is
2004 the previous value of that parameter, NEW_VALUE is the new value. */
2005
2006static void
2007x_set_line_spacing (f, new_value, old_value)
2008 struct frame *f;
2009 Lisp_Object new_value, old_value;
2010{
2011 if (NILP (new_value))
2012 f->extra_line_spacing = 0;
2013 else if (NATNUMP (new_value))
2014 f->extra_line_spacing = XFASTINT (new_value);
2015 else
2016 Fsignal (Qerror, Fcons (build_string ("Invalid line-spacing"),
2017 Fcons (new_value, Qnil)));
2018 if (FRAME_VISIBLE_P (f))
2019 redraw_frame (f);
2020}
2021
2022
2023/* Change the `fullscreen' frame parameter of frame F. OLD_VALUE is
2024 the previous value of that parameter, NEW_VALUE is the new value. */
2025
2026static void
2027x_set_fullscreen (f, new_value, old_value)
2028 struct frame *f;
2029 Lisp_Object new_value, old_value;
2030{
2031 if (NILP (new_value))
2032 f->output_data.w32->want_fullscreen = FULLSCREEN_NONE;
2033 else if (EQ (new_value, Qfullboth))
2034 f->output_data.w32->want_fullscreen = FULLSCREEN_BOTH;
2035 else if (EQ (new_value, Qfullwidth))
2036 f->output_data.w32->want_fullscreen = FULLSCREEN_WIDTH;
2037 else if (EQ (new_value, Qfullheight))
2038 f->output_data.w32->want_fullscreen = FULLSCREEN_HEIGHT;
2039}
2040
2041
2042/* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
2043 the previous value of that parameter, NEW_VALUE is the new value. */
2044
2045static void
2046x_set_screen_gamma (f, new_value, old_value)
2047 struct frame *f;
2048 Lisp_Object new_value, old_value;
2049{
2050 if (NILP (new_value))
2051 f->gamma = 0;
2052 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
2053 /* The value 0.4545 is the normal viewing gamma. */
2054 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
2055 else
2056 Fsignal (Qerror, Fcons (build_string ("Invalid screen-gamma"),
2057 Fcons (new_value, Qnil)));
2058
2059 clear_face_cache (0);
2060}
2061
2062
2063/* Functions called only from `x_set_frame_param'
2064 to set individual parameters.
2065
2066 If FRAME_W32_WINDOW (f) is 0,
2067 the frame is being created and its window does not exist yet.
2068 In that case, just record the parameter's new value
2069 in the standard place; do not attempt to change the window. */
2070
2071void
2072x_set_foreground_color (f, arg, oldval)
2073 struct frame *f;
2074 Lisp_Object arg, oldval;
2075{
2076 struct w32_output *x = f->output_data.w32;
2077 PIX_TYPE fg, old_fg;
2078
2079 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2080 old_fg = FRAME_FOREGROUND_PIXEL (f);
2081 FRAME_FOREGROUND_PIXEL (f) = fg;
2082
2083 if (FRAME_W32_WINDOW (f) != 0)
2084 {
2085 if (x->cursor_pixel == old_fg)
2086 x->cursor_pixel = fg;
2087
2088 update_face_from_frame_parameter (f, Qforeground_color, arg);
2089 if (FRAME_VISIBLE_P (f))
2090 redraw_frame (f);
2091 }
2092}
2093
2094void
2095x_set_background_color (f, arg, oldval)
2096 struct frame *f;
2097 Lisp_Object arg, oldval;
2098{
2099 FRAME_BACKGROUND_PIXEL (f)
2100 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
2101
2102 if (FRAME_W32_WINDOW (f) != 0)
2103 {
2104 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
2105 FRAME_BACKGROUND_PIXEL (f));
2106
2107 update_face_from_frame_parameter (f, Qbackground_color, arg);
2108
2109 if (FRAME_VISIBLE_P (f))
2110 redraw_frame (f);
2111 }
2112}
2113
2114void
2115x_set_mouse_color (f, arg, oldval)
2116 struct frame *f;
2117 Lisp_Object arg, oldval;
2118{
2119 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
2120 int count;
2121 int mask_color;
2122
2123 if (!EQ (Qnil, arg))
2124 f->output_data.w32->mouse_pixel
2125 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2126 mask_color = FRAME_BACKGROUND_PIXEL (f);
2127
2128 /* Don't let pointers be invisible. */
2129 if (mask_color == f->output_data.w32->mouse_pixel
2130 && mask_color == FRAME_BACKGROUND_PIXEL (f))
2131 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
2132
2133#if 0 /* TODO : cursor changes */
2134 BLOCK_INPUT;
2135
2136 /* It's not okay to crash if the user selects a screwy cursor. */
2137 count = x_catch_errors (FRAME_W32_DISPLAY (f));
2138
2139 if (!EQ (Qnil, Vx_pointer_shape))
2140 {
2141 CHECK_NUMBER (Vx_pointer_shape);
2142 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
2143 }
2144 else
2145 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2146 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
2147
2148 if (!EQ (Qnil, Vx_nontext_pointer_shape))
2149 {
2150 CHECK_NUMBER (Vx_nontext_pointer_shape);
2151 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2152 XINT (Vx_nontext_pointer_shape));
2153 }
2154 else
2155 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
2156 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2157
2158 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
2159 {
2160 CHECK_NUMBER (Vx_hourglass_pointer_shape);
2161 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2162 XINT (Vx_hourglass_pointer_shape));
2163 }
2164 else
2165 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
2166 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
2167
2168 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
2169 if (!EQ (Qnil, Vx_mode_pointer_shape))
2170 {
2171 CHECK_NUMBER (Vx_mode_pointer_shape);
2172 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2173 XINT (Vx_mode_pointer_shape));
2174 }
2175 else
2176 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2177 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2178
2179 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2180 {
2181 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
2182 cross_cursor
2183 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2184 XINT (Vx_sensitive_text_pointer_shape));
2185 }
2186 else
2187 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2188
2189 if (!NILP (Vx_window_horizontal_drag_shape))
2190 {
2191 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
2192 horizontal_drag_cursor
2193 = XCreateFontCursor (FRAME_X_DISPLAY (f),
2194 XINT (Vx_window_horizontal_drag_shape));
2195 }
2196 else
2197 horizontal_drag_cursor
2198 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
2199
2200 /* Check and report errors with the above calls. */
2201 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2202 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2203
2204 {
2205 XColor fore_color, back_color;
2206
2207 fore_color.pixel = f->output_data.w32->mouse_pixel;
2208 back_color.pixel = mask_color;
2209 XQueryColor (FRAME_W32_DISPLAY (f),
2210 DefaultColormap (FRAME_W32_DISPLAY (f),
2211 DefaultScreen (FRAME_W32_DISPLAY (f))),
2212 &fore_color);
2213 XQueryColor (FRAME_W32_DISPLAY (f),
2214 DefaultColormap (FRAME_W32_DISPLAY (f),
2215 DefaultScreen (FRAME_W32_DISPLAY (f))),
2216 &back_color);
2217 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2218 &fore_color, &back_color);
2219 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2220 &fore_color, &back_color);
2221 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2222 &fore_color, &back_color);
2223 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2224 &fore_color, &back_color);
2225 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
2226 &fore_color, &back_color);
2227 }
2228
2229 if (FRAME_W32_WINDOW (f) != 0)
2230 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2231
2232 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2233 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2234 f->output_data.w32->text_cursor = cursor;
2235
2236 if (nontext_cursor != f->output_data.w32->nontext_cursor
2237 && f->output_data.w32->nontext_cursor != 0)
2238 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2239 f->output_data.w32->nontext_cursor = nontext_cursor;
2240
2241 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
2242 && f->output_data.w32->hourglass_cursor != 0)
2243 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
2244 f->output_data.w32->hourglass_cursor = hourglass_cursor;
2245
2246 if (mode_cursor != f->output_data.w32->modeline_cursor
2247 && f->output_data.w32->modeline_cursor != 0)
2248 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2249 f->output_data.w32->modeline_cursor = mode_cursor;
2250
2251 if (cross_cursor != f->output_data.w32->cross_cursor
2252 && f->output_data.w32->cross_cursor != 0)
2253 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2254 f->output_data.w32->cross_cursor = cross_cursor;
2255
2256 XFlush (FRAME_W32_DISPLAY (f));
2257 UNBLOCK_INPUT;
2258
2259 update_face_from_frame_parameter (f, Qmouse_color, arg);
2260#endif /* TODO */
2261}
2262
2263/* Defined in w32term.c. */
2264void x_update_cursor (struct frame *f, int on_p);
2265
2266void
2267x_set_cursor_color (f, arg, oldval)
2268 struct frame *f;
2269 Lisp_Object arg, oldval;
2270{
2271 unsigned long fore_pixel, pixel;
2272
2273 if (!NILP (Vx_cursor_fore_pixel))
2274 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2275 WHITE_PIX_DEFAULT (f));
2276 else
2277 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2278
2279 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2280
2281 /* Make sure that the cursor color differs from the background color. */
2282 if (pixel == FRAME_BACKGROUND_PIXEL (f))
2283 {
2284 pixel = f->output_data.w32->mouse_pixel;
2285 if (pixel == fore_pixel)
2286 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2287 }
2288
2289 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
2290 f->output_data.w32->cursor_pixel = pixel;
2291
2292 if (FRAME_W32_WINDOW (f) != 0)
2293 {
2294 BLOCK_INPUT;
2295 /* Update frame's cursor_gc. */
2296 f->output_data.w32->cursor_gc->foreground = fore_pixel;
2297 f->output_data.w32->cursor_gc->background = pixel;
2298
2299 UNBLOCK_INPUT;
2300
2301 if (FRAME_VISIBLE_P (f))
2302 {
2303 x_update_cursor (f, 0);
2304 x_update_cursor (f, 1);
2305 }
2306 }
2307
2308 update_face_from_frame_parameter (f, Qcursor_color, arg);
2309}
2310
2311/* Set the border-color of frame F to pixel value PIX.
2312 Note that this does not fully take effect if done before
2313 F has a window. */
2314void
2315x_set_border_pixel (f, pix)
2316 struct frame *f;
2317 int pix;
2318{
2319 f->output_data.w32->border_pixel = pix;
2320
2321 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2322 {
2323 if (FRAME_VISIBLE_P (f))
2324 redraw_frame (f);
2325 }
2326}
2327
2328/* Set the border-color of frame F to value described by ARG.
2329 ARG can be a string naming a color.
2330 The border-color is used for the border that is drawn by the server.
2331 Note that this does not fully take effect if done before
2332 F has a window; it must be redone when the window is created. */
2333
2334void
2335x_set_border_color (f, arg, oldval)
2336 struct frame *f;
2337 Lisp_Object arg, oldval;
2338{
2339 int pix;
2340
2341 CHECK_STRING (arg);
2342 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2343 x_set_border_pixel (f, pix);
2344 update_face_from_frame_parameter (f, Qborder_color, arg);
2345}
2346
2347
2348void
2349x_set_cursor_type (f, arg, oldval)
2350 FRAME_PTR f;
2351 Lisp_Object arg, oldval;
2352{
2353 set_frame_cursor_types (f, arg);
2354
2355 /* Make sure the cursor gets redrawn. This is overkill, but how
2356 often do people change cursor types? */
2357 update_mode_lines++;
2358}
2359\f
2360void
2361x_set_icon_type (f, arg, oldval)
2362 struct frame *f;
2363 Lisp_Object arg, oldval;
2364{
2365 int result;
2366
2367 if (NILP (arg) && NILP (oldval))
2368 return;
2369
2370 if (STRINGP (arg) && STRINGP (oldval)
2371 && EQ (Fstring_equal (oldval, arg), Qt))
2372 return;
2373
2374 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2375 return;
2376
2377 BLOCK_INPUT;
2378
2379 result = x_bitmap_icon (f, arg);
2380 if (result)
2381 {
2382 UNBLOCK_INPUT;
2383 error ("No icon window available");
2384 }
2385
2386 UNBLOCK_INPUT;
2387}
2388
2389/* Return non-nil if frame F wants a bitmap icon. */
2390
2391Lisp_Object
2392x_icon_type (f)
2393 FRAME_PTR f;
2394{
2395 Lisp_Object tem;
2396
2397 tem = assq_no_quit (Qicon_type, f->param_alist);
2398 if (CONSP (tem))
2399 return XCDR (tem);
2400 else
2401 return Qnil;
2402}
2403
2404void
2405x_set_icon_name (f, arg, oldval)
2406 struct frame *f;
2407 Lisp_Object arg, oldval;
2408{
2409 if (STRINGP (arg))
2410 {
2411 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2412 return;
2413 }
2414 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2415 return;
2416
2417 f->icon_name = arg;
2418
2419#if 0
2420 if (f->output_data.w32->icon_bitmap != 0)
2421 return;
2422
2423 BLOCK_INPUT;
2424
2425 result = x_text_icon (f,
2426 (char *) SDATA ((!NILP (f->icon_name)
2427 ? f->icon_name
2428 : !NILP (f->title)
2429 ? f->title
2430 : f->name)));
2431
2432 if (result)
2433 {
2434 UNBLOCK_INPUT;
2435 error ("No icon window available");
2436 }
2437
2438 /* If the window was unmapped (and its icon was mapped),
2439 the new icon is not mapped, so map the window in its stead. */
2440 if (FRAME_VISIBLE_P (f))
2441 {
2442#ifdef USE_X_TOOLKIT
2443 XtPopup (f->output_data.w32->widget, XtGrabNone);
2444#endif
2445 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2446 }
2447
2448 XFlush (FRAME_W32_DISPLAY (f));
2449 UNBLOCK_INPUT;
2450#endif
2451}
2452
2453extern Lisp_Object x_new_font ();
2454extern Lisp_Object x_new_fontset();
2455
2456void
2457x_set_font (f, arg, oldval)
2458 struct frame *f;
2459 Lisp_Object arg, oldval;
2460{
2461 Lisp_Object result;
2462 Lisp_Object fontset_name;
2463 Lisp_Object frame;
2464 int old_fontset = FRAME_FONTSET(f);
2465
2466 CHECK_STRING (arg);
2467
2468 fontset_name = Fquery_fontset (arg, Qnil);
2469
2470 BLOCK_INPUT;
2471 result = (STRINGP (fontset_name)
2472 ? x_new_fontset (f, SDATA (fontset_name))
2473 : x_new_font (f, SDATA (arg)));
2474 UNBLOCK_INPUT;
2475
2476 if (EQ (result, Qnil))
2477 error ("Font `%s' is not defined", SDATA (arg));
2478 else if (EQ (result, Qt))
2479 error ("The characters of the given font have varying widths");
2480 else if (STRINGP (result))
2481 {
2482 if (STRINGP (fontset_name))
2483 {
2484 /* Fontset names are built from ASCII font names, so the
2485 names may be equal despite there was a change. */
2486 if (old_fontset == FRAME_FONTSET (f))
2487 return;
2488 }
2489 else if (!NILP (Fequal (result, oldval)))
2490 return;
2491
2492 store_frame_param (f, Qfont, result);
2493 recompute_basic_faces (f);
2494 }
2495 else
2496 abort ();
2497
2498 do_pending_window_change (0);
2499
2500 /* Don't call `face-set-after-frame-default' when faces haven't been
2501 initialized yet. This is the case when called from
2502 Fx_create_frame. In that case, the X widget or window doesn't
2503 exist either, and we can end up in x_report_frame_params with a
2504 null widget which gives a segfault. */
2505 if (FRAME_FACE_CACHE (f))
2506 {
2507 XSETFRAME (frame, f);
2508 call1 (Qface_set_after_frame_default, frame);
2509 }
2510}
2511
2512static void
2513x_set_fringe_width (f, new_value, old_value)
2514 struct frame *f;
2515 Lisp_Object new_value, old_value;
2516{
2517 x_compute_fringe_widths (f, 1);
2518}
2519
2520void
2521x_set_border_width (f, arg, oldval)
2522 struct frame *f;
2523 Lisp_Object arg, oldval;
2524{
2525 CHECK_NUMBER (arg);
2526
2527 if (XINT (arg) == f->output_data.w32->border_width)
2528 return;
2529
2530 if (FRAME_W32_WINDOW (f) != 0)
2531 error ("Cannot change the border width of a window");
2532
2533 f->output_data.w32->border_width = XINT (arg);
2534}
2535
2536void
2537x_set_internal_border_width (f, arg, oldval)
2538 struct frame *f;
2539 Lisp_Object arg, oldval;
2540{
2541 int old = f->output_data.w32->internal_border_width;
2542
2543 CHECK_NUMBER (arg);
2544 f->output_data.w32->internal_border_width = XINT (arg);
2545 if (f->output_data.w32->internal_border_width < 0)
2546 f->output_data.w32->internal_border_width = 0;
2547
2548 if (f->output_data.w32->internal_border_width == old)
2549 return;
2550
2551 if (FRAME_W32_WINDOW (f) != 0)
2552 {
2553 x_set_window_size (f, 0, f->width, f->height);
2554 SET_FRAME_GARBAGED (f);
2555 do_pending_window_change (0);
2556 }
2557 else
2558 SET_FRAME_GARBAGED (f);
2559}
2560
2561void
2562x_set_visibility (f, value, oldval)
2563 struct frame *f;
2564 Lisp_Object value, oldval;
2565{
2566 Lisp_Object frame;
2567 XSETFRAME (frame, f);
2568
2569 if (NILP (value))
2570 Fmake_frame_invisible (frame, Qt);
2571 else if (EQ (value, Qicon))
2572 Ficonify_frame (frame);
2573 else
2574 Fmake_frame_visible (frame);
2575}
2576
2577\f
2578/* Change window heights in windows rooted in WINDOW by N lines. */
2579
2580static void
2581x_change_window_heights (window, n)
2582 Lisp_Object window;
2583 int n;
2584{
2585 struct window *w = XWINDOW (window);
2586
2587 XSETFASTINT (w->top, XFASTINT (w->top) + n);
2588 XSETFASTINT (w->height, XFASTINT (w->height) - n);
2589
2590 if (INTEGERP (w->orig_top))
2591 XSETFASTINT (w->orig_top, XFASTINT (w->orig_top) + n);
2592 if (INTEGERP (w->orig_height))
2593 XSETFASTINT (w->orig_height, XFASTINT (w->orig_height) - n);
2594
2595 /* Handle just the top child in a vertical split. */
2596 if (!NILP (w->vchild))
2597 x_change_window_heights (w->vchild, n);
2598
2599 /* Adjust all children in a horizontal split. */
2600 for (window = w->hchild; !NILP (window); window = w->next)
2601 {
2602 w = XWINDOW (window);
2603 x_change_window_heights (window, n);
2604 }
2605}
2606
2607void
2608x_set_menu_bar_lines (f, value, oldval)
2609 struct frame *f;
2610 Lisp_Object value, oldval;
2611{
2612 int nlines;
2613 int olines = FRAME_MENU_BAR_LINES (f);
2614
2615 /* Right now, menu bars don't work properly in minibuf-only frames;
2616 most of the commands try to apply themselves to the minibuffer
2617 frame itself, and get an error because you can't switch buffers
2618 in or split the minibuffer window. */
2619 if (FRAME_MINIBUF_ONLY_P (f))
2620 return;
2621
2622 if (INTEGERP (value))
2623 nlines = XINT (value);
2624 else
2625 nlines = 0;
2626
2627 FRAME_MENU_BAR_LINES (f) = 0;
2628 if (nlines)
2629 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2630 else
2631 {
2632 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2633 free_frame_menubar (f);
2634 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2635
2636 /* Adjust the frame size so that the client (text) dimensions
2637 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2638 set correctly. */
2639 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2640 do_pending_window_change (0);
2641 }
2642 adjust_glyphs (f);
2643}
2644
2645
2646/* Set the number of lines used for the tool bar of frame F to VALUE.
2647 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2648 is the old number of tool bar lines. This function changes the
2649 height of all windows on frame F to match the new tool bar height.
2650 The frame's height doesn't change. */
2651
2652void
2653x_set_tool_bar_lines (f, value, oldval)
2654 struct frame *f;
2655 Lisp_Object value, oldval;
2656{
2657 int delta, nlines, root_height;
2658 Lisp_Object root_window;
2659
2660 /* Treat tool bars like menu bars. */
2661 if (FRAME_MINIBUF_ONLY_P (f))
2662 return;
2663
2664 /* Use VALUE only if an integer >= 0. */
2665 if (INTEGERP (value) && XINT (value) >= 0)
2666 nlines = XFASTINT (value);
2667 else
2668 nlines = 0;
2669
2670 /* Make sure we redisplay all windows in this frame. */
2671 ++windows_or_buffers_changed;
2672
2673 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2674
2675 /* Don't resize the tool-bar to more than we have room for. */
2676 root_window = FRAME_ROOT_WINDOW (f);
2677 root_height = XINT (XWINDOW (root_window)->height);
2678 if (root_height - delta < 1)
2679 {
2680 delta = root_height - 1;
2681 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2682 }
2683
2684 FRAME_TOOL_BAR_LINES (f) = nlines;
2685 x_change_window_heights (root_window, delta);
2686 adjust_glyphs (f);
2687
2688 /* We also have to make sure that the internal border at the top of
2689 the frame, below the menu bar or tool bar, is redrawn when the
2690 tool bar disappears. This is so because the internal border is
2691 below the tool bar if one is displayed, but is below the menu bar
2692 if there isn't a tool bar. The tool bar draws into the area
2693 below the menu bar. */
2694 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2695 {
2696 updating_frame = f;
2697 clear_frame ();
2698 clear_current_matrices (f);
2699 updating_frame = NULL;
2700 }
2701
2702 /* If the tool bar gets smaller, the internal border below it
2703 has to be cleared. It was formerly part of the display
2704 of the larger tool bar, and updating windows won't clear it. */
2705 if (delta < 0)
2706 {
2707 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
2708 int width = PIXEL_WIDTH (f);
2709 int y = nlines * CANON_Y_UNIT (f);
2710
2711 BLOCK_INPUT;
2712 {
2713 HDC hdc = get_frame_dc (f);
2714 w32_clear_area (f, hdc, 0, y, width, height);
2715 release_frame_dc (f, hdc);
2716 }
2717 UNBLOCK_INPUT;
2718
2719 if (WINDOWP (f->tool_bar_window))
2720 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
2721 }
2722}
2723
2724
2725/* Change the name of frame F to NAME. If NAME is nil, set F's name to
2726 w32_id_name.
2727
2728 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2729 name; if NAME is a string, set F's name to NAME and set
2730 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2731
2732 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2733 suggesting a new name, which lisp code should override; if
2734 F->explicit_name is set, ignore the new name; otherwise, set it. */
2735
2736void
2737x_set_name (f, name, explicit)
2738 struct frame *f;
2739 Lisp_Object name;
2740 int explicit;
2741{
2742 /* Make sure that requests from lisp code override requests from
2743 Emacs redisplay code. */
2744 if (explicit)
2745 {
2746 /* If we're switching from explicit to implicit, we had better
2747 update the mode lines and thereby update the title. */
2748 if (f->explicit_name && NILP (name))
2749 update_mode_lines = 1;
2750
2751 f->explicit_name = ! NILP (name);
2752 }
2753 else if (f->explicit_name)
2754 return;
2755
2756 /* If NAME is nil, set the name to the w32_id_name. */
2757 if (NILP (name))
2758 {
2759 /* Check for no change needed in this very common case
2760 before we do any consing. */
2761 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2762 SDATA (f->name)))
2763 return;
2764 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2765 }
2766 else
2767 CHECK_STRING (name);
2768
2769 /* Don't change the name if it's already NAME. */
2770 if (! NILP (Fstring_equal (name, f->name)))
2771 return;
2772
2773 f->name = name;
2774
2775 /* For setting the frame title, the title parameter should override
2776 the name parameter. */
2777 if (! NILP (f->title))
2778 name = f->title;
2779
2780 if (FRAME_W32_WINDOW (f))
2781 {
2782 if (STRING_MULTIBYTE (name))
2783 name = ENCODE_SYSTEM (name);
2784
2785 BLOCK_INPUT;
2786 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2787 UNBLOCK_INPUT;
2788 }
2789}
2790
2791/* This function should be called when the user's lisp code has
2792 specified a name for the frame; the name will override any set by the
2793 redisplay code. */
2794void
2795x_explicitly_set_name (f, arg, oldval)
2796 FRAME_PTR f;
2797 Lisp_Object arg, oldval;
2798{
2799 x_set_name (f, arg, 1);
2800}
2801
2802/* This function should be called by Emacs redisplay code to set the
2803 name; names set this way will never override names set by the user's
2804 lisp code. */
2805void
2806x_implicitly_set_name (f, arg, oldval)
2807 FRAME_PTR f;
2808 Lisp_Object arg, oldval;
2809{
2810 x_set_name (f, arg, 0);
2811}
2812\f
2813/* Change the title of frame F to NAME.
2814 If NAME is nil, use the frame name as the title.
2815
2816 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2817 name; if NAME is a string, set F's name to NAME and set
2818 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2819
2820 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2821 suggesting a new name, which lisp code should override; if
2822 F->explicit_name is set, ignore the new name; otherwise, set it. */
2823
2824void
2825x_set_title (f, name, old_name)
2826 struct frame *f;
2827 Lisp_Object name, old_name;
2828{
2829 /* Don't change the title if it's already NAME. */
2830 if (EQ (name, f->title))
2831 return;
2832
2833 update_mode_lines = 1;
2834
2835 f->title = name;
2836
2837 if (NILP (name))
2838 name = f->name;
2839
2840 if (FRAME_W32_WINDOW (f))
2841 {
2842 if (STRING_MULTIBYTE (name))
2843 name = ENCODE_SYSTEM (name);
2844
2845 BLOCK_INPUT;
2846 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
2847 UNBLOCK_INPUT;
2848 }
2849}
2850\f
2851void
2852x_set_autoraise (f, arg, oldval)
2853 struct frame *f;
2854 Lisp_Object arg, oldval;
2855{
2856 f->auto_raise = !EQ (Qnil, arg);
2857}
2858
2859void
2860x_set_autolower (f, arg, oldval)
2861 struct frame *f;
2862 Lisp_Object arg, oldval;
2863{
2864 f->auto_lower = !EQ (Qnil, arg);
2865}
2866
2867void
2868x_set_unsplittable (f, arg, oldval)
2869 struct frame *f;
2870 Lisp_Object arg, oldval;
2871{
2872 f->no_split = !NILP (arg);
2873}
2874
2875void
2876x_set_vertical_scroll_bars (f, arg, oldval)
2877 struct frame *f;
2878 Lisp_Object arg, oldval;
2879{
2880 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2881 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2882 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2883 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2884 {
2885 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2886 vertical_scroll_bar_none :
2887 /* Put scroll bars on the right by default, as is conventional
2888 on MS-Windows. */
2889 EQ (Qleft, arg)
2890 ? vertical_scroll_bar_left
2891 : vertical_scroll_bar_right;
2892
2893 /* We set this parameter before creating the window for the
2894 frame, so we can get the geometry right from the start.
2895 However, if the window hasn't been created yet, we shouldn't
2896 call x_set_window_size. */
2897 if (FRAME_W32_WINDOW (f))
2898 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2899 do_pending_window_change (0);
2900 }
2901}
2902
2903void
2904x_set_scroll_bar_width (f, arg, oldval)
2905 struct frame *f;
2906 Lisp_Object arg, oldval;
2907{
2908 int wid = FONT_WIDTH (f->output_data.w32->font);
2909
2910 if (NILP (arg))
2911 {
2912 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2913 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2914 wid - 1) / wid;
2915 if (FRAME_W32_WINDOW (f))
2916 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2917 do_pending_window_change (0);
2918 }
2919 else if (INTEGERP (arg) && XINT (arg) > 0
2920 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2921 {
2922 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2923 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2924 + wid-1) / wid;
2925 if (FRAME_W32_WINDOW (f))
2926 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2927 do_pending_window_change (0);
2928 }
2929 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2930 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2931 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2932}
2933\f
2934/* Subroutines of creating a frame. */
2935
2936/* Make sure that Vx_resource_name is set to a reasonable value.
2937 Fix it up, or set it to `emacs' if it is too hopeless. */
2938
2939static void
2940validate_x_resource_name ()
2941{
2942 int len = 0;
2943 /* Number of valid characters in the resource name. */
2944 int good_count = 0;
2945 /* Number of invalid characters in the resource name. */
2946 int bad_count = 0;
2947 Lisp_Object new;
2948 int i;
2949
2950 if (STRINGP (Vx_resource_name))
2951 {
2952 unsigned char *p = SDATA (Vx_resource_name);
2953 int i;
2954
2955 len = SBYTES (Vx_resource_name);
2956
2957 /* Only letters, digits, - and _ are valid in resource names.
2958 Count the valid characters and count the invalid ones. */
2959 for (i = 0; i < len; i++)
2960 {
2961 int c = p[i];
2962 if (! ((c >= 'a' && c <= 'z')
2963 || (c >= 'A' && c <= 'Z')
2964 || (c >= '0' && c <= '9')
2965 || c == '-' || c == '_'))
2966 bad_count++;
2967 else
2968 good_count++;
2969 }
2970 }
2971 else
2972 /* Not a string => completely invalid. */
2973 bad_count = 5, good_count = 0;
2974
2975 /* If name is valid already, return. */
2976 if (bad_count == 0)
2977 return;
2978
2979 /* If name is entirely invalid, or nearly so, use `emacs'. */
2980 if (good_count == 0
2981 || (good_count == 1 && bad_count > 0))
2982 {
2983 Vx_resource_name = build_string ("emacs");
2984 return;
2985 }
2986
2987 /* Name is partly valid. Copy it and replace the invalid characters
2988 with underscores. */
2989
2990 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2991
2992 for (i = 0; i < len; i++)
2993 {
2994 int c = SREF (new, i);
2995 if (! ((c >= 'a' && c <= 'z')
2996 || (c >= 'A' && c <= 'Z')
2997 || (c >= '0' && c <= '9')
2998 || c == '-' || c == '_'))
2999 SSET (new, i, '_');
3000 }
3001}
3002
3003
3004extern char *x_get_string_resource ();
3005
3006DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
3007 doc: /* Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.
3008This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the
3009class, where INSTANCE is the name under which Emacs was invoked, or
3010the name specified by the `-name' or `-rn' command-line arguments.
3011
3012The optional arguments COMPONENT and SUBCLASS add to the key and the
3013class, respectively. You must specify both of them or neither.
3014If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'
3015and the class is `Emacs.CLASS.SUBCLASS'. */)
3016 (attribute, class, component, subclass)
3017 Lisp_Object attribute, class, component, subclass;
3018{
3019 register char *value;
3020 char *name_key;
3021 char *class_key;
3022
3023 CHECK_STRING (attribute);
3024 CHECK_STRING (class);
3025
3026 if (!NILP (component))
3027 CHECK_STRING (component);
3028 if (!NILP (subclass))
3029 CHECK_STRING (subclass);
3030 if (NILP (component) != NILP (subclass))
3031 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
3032
3033 validate_x_resource_name ();
3034
3035 /* Allocate space for the components, the dots which separate them,
3036 and the final '\0'. Make them big enough for the worst case. */
3037 name_key = (char *) alloca (SBYTES (Vx_resource_name)
3038 + (STRINGP (component)
3039 ? SBYTES (component) : 0)
3040 + SBYTES (attribute)
3041 + 3);
3042
3043 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3044 + SBYTES (class)
3045 + (STRINGP (subclass)
3046 ? SBYTES (subclass) : 0)
3047 + 3);
3048
3049 /* Start with emacs.FRAMENAME for the name (the specific one)
3050 and with `Emacs' for the class key (the general one). */
3051 strcpy (name_key, SDATA (Vx_resource_name));
3052 strcpy (class_key, EMACS_CLASS);
3053
3054 strcat (class_key, ".");
3055 strcat (class_key, SDATA (class));
3056
3057 if (!NILP (component))
3058 {
3059 strcat (class_key, ".");
3060 strcat (class_key, SDATA (subclass));
3061
3062 strcat (name_key, ".");
3063 strcat (name_key, SDATA (component));
3064 }
3065
3066 strcat (name_key, ".");
3067 strcat (name_key, SDATA (attribute));
3068
3069 value = x_get_string_resource (Qnil,
3070 name_key, class_key);
3071
3072 if (value != (char *) 0)
3073 return build_string (value);
3074 else
3075 return Qnil;
3076}
3077
3078/* Used when C code wants a resource value. */
3079
3080char *
3081x_get_resource_string (attribute, class)
3082 char *attribute, *class;
3083{
3084 char *name_key;
3085 char *class_key;
3086 struct frame *sf = SELECTED_FRAME ();
3087
3088 /* Allocate space for the components, the dots which separate them,
3089 and the final '\0'. */
3090 name_key = (char *) alloca (SBYTES (Vinvocation_name)
3091 + strlen (attribute) + 2);
3092 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
3093 + strlen (class) + 2);
3094
3095 sprintf (name_key, "%s.%s",
3096 SDATA (Vinvocation_name),
3097 attribute);
3098 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
3099
3100 return x_get_string_resource (sf, name_key, class_key);
3101}
3102
3103/* Types we might convert a resource string into. */
3104enum resource_types
3105{
3106 RES_TYPE_NUMBER,
3107 RES_TYPE_FLOAT,
3108 RES_TYPE_BOOLEAN,
3109 RES_TYPE_STRING,
3110 RES_TYPE_SYMBOL
3111};
3112
3113/* Return the value of parameter PARAM.
3114
3115 First search ALIST, then Vdefault_frame_alist, then the X defaults
3116 database, using ATTRIBUTE as the attribute name and CLASS as its class.
3117
3118 Convert the resource to the type specified by desired_type.
3119
3120 If no default is specified, return Qunbound. If you call
3121 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
3122 and don't let it get stored in any Lisp-visible variables! */
3123
3124static Lisp_Object
3125w32_get_arg (alist, param, attribute, class, type)
3126 Lisp_Object alist, param;
3127 char *attribute;
3128 char *class;
3129 enum resource_types type;
3130{
3131 register Lisp_Object tem;
3132
3133 tem = Fassq (param, alist);
3134 if (EQ (tem, Qnil))
3135 tem = Fassq (param, Vdefault_frame_alist);
3136 if (EQ (tem, Qnil))
3137 {
3138
3139 if (attribute)
3140 {
3141 tem = Fx_get_resource (build_string (attribute),
3142 build_string (class),
3143 Qnil, Qnil);
3144
3145 if (NILP (tem))
3146 return Qunbound;
3147
3148 switch (type)
3149 {
3150 case RES_TYPE_NUMBER:
3151 return make_number (atoi (SDATA (tem)));
3152
3153 case RES_TYPE_FLOAT:
3154 return make_float (atof (SDATA (tem)));
3155
3156 case RES_TYPE_BOOLEAN:
3157 tem = Fdowncase (tem);
3158 if (!strcmp (SDATA (tem), "on")
3159 || !strcmp (SDATA (tem), "true"))
3160 return Qt;
3161 else
3162 return Qnil;
3163
3164 case RES_TYPE_STRING:
3165 return tem;
3166
3167 case RES_TYPE_SYMBOL:
3168 /* As a special case, we map the values `true' and `on'
3169 to Qt, and `false' and `off' to Qnil. */
3170 {
3171 Lisp_Object lower;
3172 lower = Fdowncase (tem);
3173 if (!strcmp (SDATA (lower), "on")
3174 || !strcmp (SDATA (lower), "true"))
3175 return Qt;
3176 else if (!strcmp (SDATA (lower), "off")
3177 || !strcmp (SDATA (lower), "false"))
3178 return Qnil;
3179 else
3180 return Fintern (tem, Qnil);
3181 }
3182
3183 default:
3184 abort ();
3185 }
3186 }
3187 else
3188 return Qunbound;
3189 }
3190 return Fcdr (tem);
3191}
3192
3193/* Record in frame F the specified or default value according to ALIST
3194 of the parameter named PROP (a Lisp symbol).
3195 If no value is specified for PROP, look for an X default for XPROP
3196 on the frame named NAME.
3197 If that is not found either, use the value DEFLT. */
3198
3199static Lisp_Object
3200x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
3201 struct frame *f;
3202 Lisp_Object alist;
3203 Lisp_Object prop;
3204 Lisp_Object deflt;
3205 char *xprop;
3206 char *xclass;
3207 enum resource_types type;
3208{
3209 Lisp_Object tem;
3210
3211 tem = w32_get_arg (alist, prop, xprop, xclass, type);
3212 if (EQ (tem, Qunbound))
3213 tem = deflt;
3214 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
3215 return tem;
3216}
3217\f
3218DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
3219 doc: /* Parse an X-style geometry string STRING.
3220Returns an alist of the form ((top . TOP), (left . LEFT) ... ).
3221The properties returned may include `top', `left', `height', and `width'.
3222The value of `left' or `top' may be an integer,
3223or a list (+ N) meaning N pixels relative to top/left corner,
3224or a list (- N) meaning -N pixels relative to bottom/right corner. */)
3225 (string)
3226 Lisp_Object string;
3227{
3228 int geometry, x, y;
3229 unsigned int width, height;
3230 Lisp_Object result;
3231
3232 CHECK_STRING (string);
3233
3234 geometry = XParseGeometry ((char *) SDATA (string),
3235 &x, &y, &width, &height);
3236
3237 result = Qnil;
3238 if (geometry & XValue)
3239 {
3240 Lisp_Object element;
3241
3242 if (x >= 0 && (geometry & XNegative))
3243 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
3244 else if (x < 0 && ! (geometry & XNegative))
3245 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
3246 else
3247 element = Fcons (Qleft, make_number (x));
3248 result = Fcons (element, result);
3249 }
3250
3251 if (geometry & YValue)
3252 {
3253 Lisp_Object element;
3254
3255 if (y >= 0 && (geometry & YNegative))
3256 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
3257 else if (y < 0 && ! (geometry & YNegative))
3258 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
3259 else
3260 element = Fcons (Qtop, make_number (y));
3261 result = Fcons (element, result);
3262 }
3263
3264 if (geometry & WidthValue)
3265 result = Fcons (Fcons (Qwidth, make_number (width)), result);
3266 if (geometry & HeightValue)
3267 result = Fcons (Fcons (Qheight, make_number (height)), result);
3268
3269 return result;
3270}
3271
3272/* Calculate the desired size and position of this window,
3273 and return the flags saying which aspects were specified.
3274
3275 This function does not make the coordinates positive. */
3276
3277#define DEFAULT_ROWS 40
3278#define DEFAULT_COLS 80
3279
3280static int
3281x_figure_window_size (f, parms)
3282 struct frame *f;
3283 Lisp_Object parms;
3284{
3285 register Lisp_Object tem0, tem1, tem2;
3286 long window_prompting = 0;
3287
3288 /* Default values if we fall through.
3289 Actually, if that happens we should get
3290 window manager prompting. */
3291 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3292 f->height = DEFAULT_ROWS;
3293 /* Window managers expect that if program-specified
3294 positions are not (0,0), they're intentional, not defaults. */
3295 f->output_data.w32->top_pos = 0;
3296 f->output_data.w32->left_pos = 0;
3297
3298 /* Ensure that old new_width and new_height will not override the
3299 values set here. */
3300 FRAME_NEW_WIDTH (f) = 0;
3301 FRAME_NEW_HEIGHT (f) = 0;
3302
3303 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3304 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3305 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3306 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3307 {
3308 if (!EQ (tem0, Qunbound))
3309 {
3310 CHECK_NUMBER (tem0);
3311 f->height = XINT (tem0);
3312 }
3313 if (!EQ (tem1, Qunbound))
3314 {
3315 CHECK_NUMBER (tem1);
3316 SET_FRAME_WIDTH (f, XINT (tem1));
3317 }
3318 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3319 window_prompting |= USSize;
3320 else
3321 window_prompting |= PSize;
3322 }
3323
3324 f->output_data.w32->vertical_scroll_bar_extra
3325 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3326 ? 0
3327 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3328 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3329 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3330
3331 x_compute_fringe_widths (f, 0);
3332
3333 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3334 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3335
3336 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3337 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3338 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3339 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3340 {
3341 if (EQ (tem0, Qminus))
3342 {
3343 f->output_data.w32->top_pos = 0;
3344 window_prompting |= YNegative;
3345 }
3346 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3347 && CONSP (XCDR (tem0))
3348 && INTEGERP (XCAR (XCDR (tem0))))
3349 {
3350 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3351 window_prompting |= YNegative;
3352 }
3353 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3354 && CONSP (XCDR (tem0))
3355 && INTEGERP (XCAR (XCDR (tem0))))
3356 {
3357 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3358 }
3359 else if (EQ (tem0, Qunbound))
3360 f->output_data.w32->top_pos = 0;
3361 else
3362 {
3363 CHECK_NUMBER (tem0);
3364 f->output_data.w32->top_pos = XINT (tem0);
3365 if (f->output_data.w32->top_pos < 0)
3366 window_prompting |= YNegative;
3367 }
3368
3369 if (EQ (tem1, Qminus))
3370 {
3371 f->output_data.w32->left_pos = 0;
3372 window_prompting |= XNegative;
3373 }
3374 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3375 && CONSP (XCDR (tem1))
3376 && INTEGERP (XCAR (XCDR (tem1))))
3377 {
3378 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3379 window_prompting |= XNegative;
3380 }
3381 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3382 && CONSP (XCDR (tem1))
3383 && INTEGERP (XCAR (XCDR (tem1))))
3384 {
3385 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3386 }
3387 else if (EQ (tem1, Qunbound))
3388 f->output_data.w32->left_pos = 0;
3389 else
3390 {
3391 CHECK_NUMBER (tem1);
3392 f->output_data.w32->left_pos = XINT (tem1);
3393 if (f->output_data.w32->left_pos < 0)
3394 window_prompting |= XNegative;
3395 }
3396
3397 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3398 window_prompting |= USPosition;
3399 else
3400 window_prompting |= PPosition;
3401 }
3402
3403 if (f->output_data.w32->want_fullscreen != FULLSCREEN_NONE)
3404 {
3405 int left, top;
3406 int width, height;
3407
3408 /* It takes both for some WM:s to place it where we want */
3409 window_prompting = USPosition | PPosition;
3410 x_fullscreen_adjust (f, &width, &height, &top, &left);
3411 f->width = width;
3412 f->height = height;
3413 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3414 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3415 f->output_data.w32->left_pos = left;
3416 f->output_data.w32->top_pos = top;
3417 }
3418
3419 return window_prompting;
3420}
3421
3422\f
3423
3424extern LRESULT CALLBACK w32_wnd_proc ();
3425
3426BOOL
3427w32_init_class (hinst)
3428 HINSTANCE hinst;
3429{
3430 WNDCLASS wc;
3431
3432 wc.style = CS_HREDRAW | CS_VREDRAW;
3433 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3434 wc.cbClsExtra = 0;
3435 wc.cbWndExtra = WND_EXTRA_BYTES;
3436 wc.hInstance = hinst;
3437 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3438 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3439 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3440 wc.lpszMenuName = NULL;
3441 wc.lpszClassName = EMACS_CLASS;
3442
3443 return (RegisterClass (&wc));
3444}
3445
3446HWND
3447w32_createscrollbar (f, bar)
3448 struct frame *f;
3449 struct scroll_bar * bar;
3450{
3451 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3452 /* Position and size of scroll bar. */
3453 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3454 XINT(bar->top),
3455 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3456 XINT(bar->height),
3457 FRAME_W32_WINDOW (f),
3458 NULL,
3459 hinst,
3460 NULL));
3461}
3462
3463void
3464w32_createwindow (f)
3465 struct frame *f;
3466{
3467 HWND hwnd;
3468 RECT rect;
3469
3470 rect.left = rect.top = 0;
3471 rect.right = PIXEL_WIDTH (f);
3472 rect.bottom = PIXEL_HEIGHT (f);
3473
3474 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3475 FRAME_EXTERNAL_MENU_BAR (f));
3476
3477 /* Do first time app init */
3478
3479 if (!hprevinst)
3480 {
3481 w32_init_class (hinst);
3482 }
3483
3484 FRAME_W32_WINDOW (f) = hwnd
3485 = CreateWindow (EMACS_CLASS,
3486 f->namebuf,
3487 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3488 f->output_data.w32->left_pos,
3489 f->output_data.w32->top_pos,
3490 rect.right - rect.left,
3491 rect.bottom - rect.top,
3492 NULL,
3493 NULL,
3494 hinst,
3495 NULL);
3496
3497 if (hwnd)
3498 {
3499 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3500 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3501 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3502 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3503 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3504
3505 /* Enable drag-n-drop. */
3506 DragAcceptFiles (hwnd, TRUE);
3507
3508 /* Do this to discard the default setting specified by our parent. */
3509 ShowWindow (hwnd, SW_HIDE);
3510 }
3511}
3512
3513void
3514my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3515 W32Msg * wmsg;
3516 HWND hwnd;
3517 UINT msg;
3518 WPARAM wParam;
3519 LPARAM lParam;
3520{
3521 wmsg->msg.hwnd = hwnd;
3522 wmsg->msg.message = msg;
3523 wmsg->msg.wParam = wParam;
3524 wmsg->msg.lParam = lParam;
3525 wmsg->msg.time = GetMessageTime ();
3526
3527 post_msg (wmsg);
3528}
3529
3530/* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3531 between left and right keys as advertised. We test for this
3532 support dynamically, and set a flag when the support is absent. If
3533 absent, we keep track of the left and right control and alt keys
3534 ourselves. This is particularly necessary on keyboards that rely
3535 upon the AltGr key, which is represented as having the left control
3536 and right alt keys pressed. For these keyboards, we need to know
3537 when the left alt key has been pressed in addition to the AltGr key
3538 so that we can properly support M-AltGr-key sequences (such as M-@
3539 on Swedish keyboards). */
3540
3541#define EMACS_LCONTROL 0
3542#define EMACS_RCONTROL 1
3543#define EMACS_LMENU 2
3544#define EMACS_RMENU 3
3545
3546static int modifiers[4];
3547static int modifiers_recorded;
3548static int modifier_key_support_tested;
3549
3550static void
3551test_modifier_support (unsigned int wparam)
3552{
3553 unsigned int l, r;
3554
3555 if (wparam != VK_CONTROL && wparam != VK_MENU)
3556 return;
3557 if (wparam == VK_CONTROL)
3558 {
3559 l = VK_LCONTROL;
3560 r = VK_RCONTROL;
3561 }
3562 else
3563 {
3564 l = VK_LMENU;
3565 r = VK_RMENU;
3566 }
3567 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3568 modifiers_recorded = 1;
3569 else
3570 modifiers_recorded = 0;
3571 modifier_key_support_tested = 1;
3572}
3573
3574static void
3575record_keydown (unsigned int wparam, unsigned int lparam)
3576{
3577 int i;
3578
3579 if (!modifier_key_support_tested)
3580 test_modifier_support (wparam);
3581
3582 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3583 return;
3584
3585 if (wparam == VK_CONTROL)
3586 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3587 else
3588 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3589
3590 modifiers[i] = 1;
3591}
3592
3593static void
3594record_keyup (unsigned int wparam, unsigned int lparam)
3595{
3596 int i;
3597
3598 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3599 return;
3600
3601 if (wparam == VK_CONTROL)
3602 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3603 else
3604 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3605
3606 modifiers[i] = 0;
3607}
3608
3609/* Emacs can lose focus while a modifier key has been pressed. When
3610 it regains focus, be conservative and clear all modifiers since
3611 we cannot reconstruct the left and right modifier state. */
3612static void
3613reset_modifiers ()
3614{
3615 SHORT ctrl, alt;
3616
3617 if (GetFocus () == NULL)
3618 /* Emacs doesn't have keyboard focus. Do nothing. */
3619 return;
3620
3621 ctrl = GetAsyncKeyState (VK_CONTROL);
3622 alt = GetAsyncKeyState (VK_MENU);
3623
3624 if (!(ctrl & 0x08000))
3625 /* Clear any recorded control modifier state. */
3626 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3627
3628 if (!(alt & 0x08000))
3629 /* Clear any recorded alt modifier state. */
3630 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3631
3632 /* Update the state of all modifier keys, because modifiers used in
3633 hot-key combinations can get stuck on if Emacs loses focus as a
3634 result of a hot-key being pressed. */
3635 {
3636 BYTE keystate[256];
3637
3638#define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3639
3640 GetKeyboardState (keystate);
3641 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3642 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3643 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3644 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3645 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3646 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3647 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3648 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3649 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3650 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3651 SetKeyboardState (keystate);
3652 }
3653}
3654
3655/* Synchronize modifier state with what is reported with the current
3656 keystroke. Even if we cannot distinguish between left and right
3657 modifier keys, we know that, if no modifiers are set, then neither
3658 the left or right modifier should be set. */
3659static void
3660sync_modifiers ()
3661{
3662 if (!modifiers_recorded)
3663 return;
3664
3665 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3666 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3667
3668 if (!(GetKeyState (VK_MENU) & 0x8000))
3669 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3670}
3671
3672static int
3673modifier_set (int vkey)
3674{
3675 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3676 return (GetKeyState (vkey) & 0x1);
3677 if (!modifiers_recorded)
3678 return (GetKeyState (vkey) & 0x8000);
3679
3680 switch (vkey)
3681 {
3682 case VK_LCONTROL:
3683 return modifiers[EMACS_LCONTROL];
3684 case VK_RCONTROL:
3685 return modifiers[EMACS_RCONTROL];
3686 case VK_LMENU:
3687 return modifiers[EMACS_LMENU];
3688 case VK_RMENU:
3689 return modifiers[EMACS_RMENU];
3690 }
3691 return (GetKeyState (vkey) & 0x8000);
3692}
3693
3694/* Convert between the modifier bits W32 uses and the modifier bits
3695 Emacs uses. */
3696
3697unsigned int
3698w32_key_to_modifier (int key)
3699{
3700 Lisp_Object key_mapping;
3701
3702 switch (key)
3703 {
3704 case VK_LWIN:
3705 key_mapping = Vw32_lwindow_modifier;
3706 break;
3707 case VK_RWIN:
3708 key_mapping = Vw32_rwindow_modifier;
3709 break;
3710 case VK_APPS:
3711 key_mapping = Vw32_apps_modifier;
3712 break;
3713 case VK_SCROLL:
3714 key_mapping = Vw32_scroll_lock_modifier;
3715 break;
3716 default:
3717 key_mapping = Qnil;
3718 }
3719
3720 /* NB. This code runs in the input thread, asychronously to the lisp
3721 thread, so we must be careful to ensure access to lisp data is
3722 thread-safe. The following code is safe because the modifier
3723 variable values are updated atomically from lisp and symbols are
3724 not relocated by GC. Also, we don't have to worry about seeing GC
3725 markbits here. */
3726 if (EQ (key_mapping, Qhyper))
3727 return hyper_modifier;
3728 if (EQ (key_mapping, Qsuper))
3729 return super_modifier;
3730 if (EQ (key_mapping, Qmeta))
3731 return meta_modifier;
3732 if (EQ (key_mapping, Qalt))
3733 return alt_modifier;
3734 if (EQ (key_mapping, Qctrl))
3735 return ctrl_modifier;
3736 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3737 return ctrl_modifier;
3738 if (EQ (key_mapping, Qshift))
3739 return shift_modifier;
3740
3741 /* Don't generate any modifier if not explicitly requested. */
3742 return 0;
3743}
3744
3745unsigned int
3746w32_get_modifiers ()
3747{
3748 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3749 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3750 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3751 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3752 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3753 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3754 (modifier_set (VK_MENU) ?
3755 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3756}
3757
3758/* We map the VK_* modifiers into console modifier constants
3759 so that we can use the same routines to handle both console
3760 and window input. */
3761
3762static int
3763construct_console_modifiers ()
3764{
3765 int mods;
3766
3767 mods = 0;
3768 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3769 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3770 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3771 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3772 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3773 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3774 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3775 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3776 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3777 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3778 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3779
3780 return mods;
3781}
3782
3783static int
3784w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3785{
3786 int mods;
3787
3788 /* Convert to emacs modifiers. */
3789 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3790
3791 return mods;
3792}
3793
3794unsigned int
3795map_keypad_keys (unsigned int virt_key, unsigned int extended)
3796{
3797 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3798 return virt_key;
3799
3800 if (virt_key == VK_RETURN)
3801 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3802
3803 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3804 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3805
3806 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3807 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3808
3809 if (virt_key == VK_CLEAR)
3810 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3811
3812 return virt_key;
3813}
3814
3815/* List of special key combinations which w32 would normally capture,
3816 but emacs should grab instead. Not directly visible to lisp, to
3817 simplify synchronization. Each item is an integer encoding a virtual
3818 key code and modifier combination to capture. */
3819Lisp_Object w32_grabbed_keys;
3820
3821#define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3822#define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3823#define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3824#define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3825
3826/* Register hot-keys for reserved key combinations when Emacs has
3827 keyboard focus, since this is the only way Emacs can receive key
3828 combinations like Alt-Tab which are used by the system. */
3829
3830static void
3831register_hot_keys (hwnd)
3832 HWND hwnd;
3833{
3834 Lisp_Object keylist;
3835
3836 /* Use GC_CONSP, since we are called asynchronously. */
3837 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3838 {
3839 Lisp_Object key = XCAR (keylist);
3840
3841 /* Deleted entries get set to nil. */
3842 if (!INTEGERP (key))
3843 continue;
3844
3845 RegisterHotKey (hwnd, HOTKEY_ID (key),
3846 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3847 }
3848}
3849
3850static void
3851unregister_hot_keys (hwnd)
3852 HWND hwnd;
3853{
3854 Lisp_Object keylist;
3855
3856 /* Use GC_CONSP, since we are called asynchronously. */
3857 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3858 {
3859 Lisp_Object key = XCAR (keylist);
3860
3861 if (!INTEGERP (key))
3862 continue;
3863
3864 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3865 }
3866}
3867
3868/* Main message dispatch loop. */
3869
3870static void
3871w32_msg_pump (deferred_msg * msg_buf)
3872{
3873 MSG msg;
3874 int result;
3875 HWND focus_window;
3876
3877 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3878
3879 while (GetMessage (&msg, NULL, 0, 0))
3880 {
3881 if (msg.hwnd == NULL)
3882 {
3883 switch (msg.message)
3884 {
3885 case WM_NULL:
3886 /* Produced by complete_deferred_msg; just ignore. */
3887 break;
3888 case WM_EMACS_CREATEWINDOW:
3889 w32_createwindow ((struct frame *) msg.wParam);
3890 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3891 abort ();
3892 break;
3893 case WM_EMACS_SETLOCALE:
3894 SetThreadLocale (msg.wParam);
3895 /* Reply is not expected. */
3896 break;
3897 case WM_EMACS_SETKEYBOARDLAYOUT:
3898 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3899 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3900 result, 0))
3901 abort ();
3902 break;
3903 case WM_EMACS_REGISTER_HOT_KEY:
3904 focus_window = GetFocus ();
3905 if (focus_window != NULL)
3906 RegisterHotKey (focus_window,
3907 HOTKEY_ID (msg.wParam),
3908 HOTKEY_MODIFIERS (msg.wParam),
3909 HOTKEY_VK_CODE (msg.wParam));
3910 /* Reply is not expected. */
3911 break;
3912 case WM_EMACS_UNREGISTER_HOT_KEY:
3913 focus_window = GetFocus ();
3914 if (focus_window != NULL)
3915 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3916 /* Mark item as erased. NB: this code must be
3917 thread-safe. The next line is okay because the cons
3918 cell is never made into garbage and is not relocated by
3919 GC. */
3920 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
3921 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3922 abort ();
3923 break;
3924 case WM_EMACS_TOGGLE_LOCK_KEY:
3925 {
3926 int vk_code = (int) msg.wParam;
3927 int cur_state = (GetKeyState (vk_code) & 1);
3928 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3929
3930 /* NB: This code must be thread-safe. It is safe to
3931 call NILP because symbols are not relocated by GC,
3932 and pointer here is not touched by GC (so the markbit
3933 can't be set). Numbers are safe because they are
3934 immediate values. */
3935 if (NILP (new_state)
3936 || (NUMBERP (new_state)
3937 && ((XUINT (new_state)) & 1) != cur_state))
3938 {
3939 one_w32_display_info.faked_key = vk_code;
3940
3941 keybd_event ((BYTE) vk_code,
3942 (BYTE) MapVirtualKey (vk_code, 0),
3943 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3944 keybd_event ((BYTE) vk_code,
3945 (BYTE) MapVirtualKey (vk_code, 0),
3946 KEYEVENTF_EXTENDEDKEY | 0, 0);
3947 keybd_event ((BYTE) vk_code,
3948 (BYTE) MapVirtualKey (vk_code, 0),
3949 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3950 cur_state = !cur_state;
3951 }
3952 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3953 cur_state, 0))
3954 abort ();
3955 }
3956 break;
3957 default:
3958 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3959 }
3960 }
3961 else
3962 {
3963 DispatchMessage (&msg);
3964 }
3965
3966 /* Exit nested loop when our deferred message has completed. */
3967 if (msg_buf->completed)
3968 break;
3969 }
3970}
3971
3972deferred_msg * deferred_msg_head;
3973
3974static deferred_msg *
3975find_deferred_msg (HWND hwnd, UINT msg)
3976{
3977 deferred_msg * item;
3978
3979 /* Don't actually need synchronization for read access, since
3980 modification of single pointer is always atomic. */
3981 /* enter_crit (); */
3982
3983 for (item = deferred_msg_head; item != NULL; item = item->next)
3984 if (item->w32msg.msg.hwnd == hwnd
3985 && item->w32msg.msg.message == msg)
3986 break;
3987
3988 /* leave_crit (); */
3989
3990 return item;
3991}
3992
3993static LRESULT
3994send_deferred_msg (deferred_msg * msg_buf,
3995 HWND hwnd,
3996 UINT msg,
3997 WPARAM wParam,
3998 LPARAM lParam)
3999{
4000 /* Only input thread can send deferred messages. */
4001 if (GetCurrentThreadId () != dwWindowsThreadId)
4002 abort ();
4003
4004 /* It is an error to send a message that is already deferred. */
4005 if (find_deferred_msg (hwnd, msg) != NULL)
4006 abort ();
4007
4008 /* Enforced synchronization is not needed because this is the only
4009 function that alters deferred_msg_head, and the following critical
4010 section is guaranteed to only be serially reentered (since only the
4011 input thread can call us). */
4012
4013 /* enter_crit (); */
4014
4015 msg_buf->completed = 0;
4016 msg_buf->next = deferred_msg_head;
4017 deferred_msg_head = msg_buf;
4018 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
4019
4020 /* leave_crit (); */
4021
4022 /* Start a new nested message loop to process other messages until
4023 this one is completed. */
4024 w32_msg_pump (msg_buf);
4025
4026 deferred_msg_head = msg_buf->next;
4027
4028 return msg_buf->result;
4029}
4030
4031void
4032complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
4033{
4034 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
4035
4036 if (msg_buf == NULL)
4037 /* Message may have been cancelled, so don't abort(). */
4038 return;
4039
4040 msg_buf->result = result;
4041 msg_buf->completed = 1;
4042
4043 /* Ensure input thread is woken so it notices the completion. */
4044 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4045}
4046
4047void
4048cancel_all_deferred_msgs ()
4049{
4050 deferred_msg * item;
4051
4052 /* Don't actually need synchronization for read access, since
4053 modification of single pointer is always atomic. */
4054 /* enter_crit (); */
4055
4056 for (item = deferred_msg_head; item != NULL; item = item->next)
4057 {
4058 item->result = 0;
4059 item->completed = 1;
4060 }
4061
4062 /* leave_crit (); */
4063
4064 /* Ensure input thread is woken so it notices the completion. */
4065 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
4066}
4067
4068DWORD
4069w32_msg_worker (dw)
4070 DWORD dw;
4071{
4072 MSG msg;
4073 deferred_msg dummy_buf;
4074
4075 /* Ensure our message queue is created */
4076
4077 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
4078
4079 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
4080 abort ();
4081
4082 memset (&dummy_buf, 0, sizeof (dummy_buf));
4083 dummy_buf.w32msg.msg.hwnd = NULL;
4084 dummy_buf.w32msg.msg.message = WM_NULL;
4085
4086 /* This is the inital message loop which should only exit when the
4087 application quits. */
4088 w32_msg_pump (&dummy_buf);
4089
4090 return 0;
4091}
4092
4093static void
4094post_character_message (hwnd, msg, wParam, lParam, modifiers)
4095 HWND hwnd;
4096 UINT msg;
4097 WPARAM wParam;
4098 LPARAM lParam;
4099 DWORD modifiers;
4100
4101{
4102 W32Msg wmsg;
4103
4104 wmsg.dwModifiers = modifiers;
4105
4106 /* Detect quit_char and set quit-flag directly. Note that we
4107 still need to post a message to ensure the main thread will be
4108 woken up if blocked in sys_select(), but we do NOT want to post
4109 the quit_char message itself (because it will usually be as if
4110 the user had typed quit_char twice). Instead, we post a dummy
4111 message that has no particular effect. */
4112 {
4113 int c = wParam;
4114 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
4115 c = make_ctrl_char (c) & 0377;
4116 if (c == quit_char
4117 || (wmsg.dwModifiers == 0 &&
4118 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
4119 {
4120 Vquit_flag = Qt;
4121
4122 /* The choice of message is somewhat arbitrary, as long as
4123 the main thread handler just ignores it. */
4124 msg = WM_NULL;
4125
4126 /* Interrupt any blocking system calls. */
4127 signal_quit ();
4128
4129 /* As a safety precaution, forcibly complete any deferred
4130 messages. This is a kludge, but I don't see any particularly
4131 clean way to handle the situation where a deferred message is
4132 "dropped" in the lisp thread, and will thus never be
4133 completed, eg. by the user trying to activate the menubar
4134 when the lisp thread is busy, and then typing C-g when the
4135 menubar doesn't open promptly (with the result that the
4136 menubar never responds at all because the deferred
4137 WM_INITMENU message is never completed). Another problem
4138 situation is when the lisp thread calls SendMessage (to send
4139 a window manager command) when a message has been deferred;
4140 the lisp thread gets blocked indefinitely waiting for the
4141 deferred message to be completed, which itself is waiting for
4142 the lisp thread to respond.
4143
4144 Note that we don't want to block the input thread waiting for
4145 a reponse from the lisp thread (although that would at least
4146 solve the deadlock problem above), because we want to be able
4147 to receive C-g to interrupt the lisp thread. */
4148 cancel_all_deferred_msgs ();
4149 }
4150 }
4151
4152 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4153}
4154
4155/* Main window procedure */
4156
4157LRESULT CALLBACK
4158w32_wnd_proc (hwnd, msg, wParam, lParam)
4159 HWND hwnd;
4160 UINT msg;
4161 WPARAM wParam;
4162 LPARAM lParam;
4163{
4164 struct frame *f;
4165 struct w32_display_info *dpyinfo = &one_w32_display_info;
4166 W32Msg wmsg;
4167 int windows_translate;
4168 int key;
4169
4170 /* Note that it is okay to call x_window_to_frame, even though we are
4171 not running in the main lisp thread, because frame deletion
4172 requires the lisp thread to synchronize with this thread. Thus, if
4173 a frame struct is returned, it can be used without concern that the
4174 lisp thread might make it disappear while we are using it.
4175
4176 NB. Walking the frame list in this thread is safe (as long as
4177 writes of Lisp_Object slots are atomic, which they are on Windows).
4178 Although delete-frame can destructively modify the frame list while
4179 we are walking it, a garbage collection cannot occur until after
4180 delete-frame has synchronized with this thread.
4181
4182 It is also safe to use functions that make GDI calls, such as
4183 w32_clear_rect, because these functions must obtain a DC handle
4184 from the frame struct using get_frame_dc which is thread-aware. */
4185
4186 switch (msg)
4187 {
4188 case WM_ERASEBKGND:
4189 f = x_window_to_frame (dpyinfo, hwnd);
4190 if (f)
4191 {
4192 HDC hdc = get_frame_dc (f);
4193 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4194 w32_clear_rect (f, hdc, &wmsg.rect);
4195 release_frame_dc (f, hdc);
4196
4197#if defined (W32_DEBUG_DISPLAY)
4198 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
4199 f,
4200 wmsg.rect.left, wmsg.rect.top,
4201 wmsg.rect.right, wmsg.rect.bottom));
4202#endif /* W32_DEBUG_DISPLAY */
4203 }
4204 return 1;
4205 case WM_PALETTECHANGED:
4206 /* ignore our own changes */
4207 if ((HWND)wParam != hwnd)
4208 {
4209 f = x_window_to_frame (dpyinfo, hwnd);
4210 if (f)
4211 /* get_frame_dc will realize our palette and force all
4212 frames to be redrawn if needed. */
4213 release_frame_dc (f, get_frame_dc (f));
4214 }
4215 return 0;
4216 case WM_PAINT:
4217 {
4218 PAINTSTRUCT paintStruct;
4219 RECT update_rect;
4220 bzero (&update_rect, sizeof (update_rect));
4221
4222 f = x_window_to_frame (dpyinfo, hwnd);
4223 if (f == 0)
4224 {
4225 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
4226 return 0;
4227 }
4228
4229 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4230 fails. Apparently this can happen under some
4231 circumstances. */
4232 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
4233 {
4234 enter_crit ();
4235 BeginPaint (hwnd, &paintStruct);
4236
4237 /* The rectangles returned by GetUpdateRect and BeginPaint
4238 do not always match. Play it safe by assuming both areas
4239 are invalid. */
4240 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
4241
4242#if defined (W32_DEBUG_DISPLAY)
4243 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
4244 f,
4245 wmsg.rect.left, wmsg.rect.top,
4246 wmsg.rect.right, wmsg.rect.bottom));
4247 DebPrint ((" [update region is %d,%d-%d,%d]\n",
4248 update_rect.left, update_rect.top,
4249 update_rect.right, update_rect.bottom));
4250#endif
4251 EndPaint (hwnd, &paintStruct);
4252 leave_crit ();
4253
4254 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4255
4256 return 0;
4257 }
4258
4259 /* If GetUpdateRect returns 0 (meaning there is no update
4260 region), assume the whole window needs to be repainted. */
4261 GetClientRect(hwnd, &wmsg.rect);
4262 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4263 return 0;
4264 }
4265
4266 case WM_INPUTLANGCHANGE:
4267 /* Inform lisp thread of keyboard layout changes. */
4268 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4269
4270 /* Clear dead keys in the keyboard state; for simplicity only
4271 preserve modifier key states. */
4272 {
4273 int i;
4274 BYTE keystate[256];
4275
4276 GetKeyboardState (keystate);
4277 for (i = 0; i < 256; i++)
4278 if (1
4279 && i != VK_SHIFT
4280 && i != VK_LSHIFT
4281 && i != VK_RSHIFT
4282 && i != VK_CAPITAL
4283 && i != VK_NUMLOCK
4284 && i != VK_SCROLL
4285 && i != VK_CONTROL
4286 && i != VK_LCONTROL
4287 && i != VK_RCONTROL
4288 && i != VK_MENU
4289 && i != VK_LMENU
4290 && i != VK_RMENU
4291 && i != VK_LWIN
4292 && i != VK_RWIN)
4293 keystate[i] = 0;
4294 SetKeyboardState (keystate);
4295 }
4296 goto dflt;
4297
4298 case WM_HOTKEY:
4299 /* Synchronize hot keys with normal input. */
4300 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4301 return (0);
4302
4303 case WM_KEYUP:
4304 case WM_SYSKEYUP:
4305 record_keyup (wParam, lParam);
4306 goto dflt;
4307
4308 case WM_KEYDOWN:
4309 case WM_SYSKEYDOWN:
4310 /* Ignore keystrokes we fake ourself; see below. */
4311 if (dpyinfo->faked_key == wParam)
4312 {
4313 dpyinfo->faked_key = 0;
4314 /* Make sure TranslateMessage sees them though (as long as
4315 they don't produce WM_CHAR messages). This ensures that
4316 indicator lights are toggled promptly on Windows 9x, for
4317 example. */
4318 if (lispy_function_keys[wParam] != 0)
4319 {
4320 windows_translate = 1;
4321 goto translate;
4322 }
4323 return 0;
4324 }
4325
4326 /* Synchronize modifiers with current keystroke. */
4327 sync_modifiers ();
4328 record_keydown (wParam, lParam);
4329 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4330
4331 windows_translate = 0;
4332
4333 switch (wParam)
4334 {
4335 case VK_LWIN:
4336 if (NILP (Vw32_pass_lwindow_to_system))
4337 {
4338 /* Prevent system from acting on keyup (which opens the
4339 Start menu if no other key was pressed) by simulating a
4340 press of Space which we will ignore. */
4341 if (GetAsyncKeyState (wParam) & 1)
4342 {
4343 if (NUMBERP (Vw32_phantom_key_code))
4344 key = XUINT (Vw32_phantom_key_code) & 255;
4345 else
4346 key = VK_SPACE;
4347 dpyinfo->faked_key = key;
4348 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4349 }
4350 }
4351 if (!NILP (Vw32_lwindow_modifier))
4352 return 0;
4353 break;
4354 case VK_RWIN:
4355 if (NILP (Vw32_pass_rwindow_to_system))
4356 {
4357 if (GetAsyncKeyState (wParam) & 1)
4358 {
4359 if (NUMBERP (Vw32_phantom_key_code))
4360 key = XUINT (Vw32_phantom_key_code) & 255;
4361 else
4362 key = VK_SPACE;
4363 dpyinfo->faked_key = key;
4364 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4365 }
4366 }
4367 if (!NILP (Vw32_rwindow_modifier))
4368 return 0;
4369 break;
4370 case VK_APPS:
4371 if (!NILP (Vw32_apps_modifier))
4372 return 0;
4373 break;
4374 case VK_MENU:
4375 if (NILP (Vw32_pass_alt_to_system))
4376 /* Prevent DefWindowProc from activating the menu bar if an
4377 Alt key is pressed and released by itself. */
4378 return 0;
4379 windows_translate = 1;
4380 break;
4381 case VK_CAPITAL:
4382 /* Decide whether to treat as modifier or function key. */
4383 if (NILP (Vw32_enable_caps_lock))
4384 goto disable_lock_key;
4385 windows_translate = 1;
4386 break;
4387 case VK_NUMLOCK:
4388 /* Decide whether to treat as modifier or function key. */
4389 if (NILP (Vw32_enable_num_lock))
4390 goto disable_lock_key;
4391 windows_translate = 1;
4392 break;
4393 case VK_SCROLL:
4394 /* Decide whether to treat as modifier or function key. */
4395 if (NILP (Vw32_scroll_lock_modifier))
4396 goto disable_lock_key;
4397 windows_translate = 1;
4398 break;
4399 disable_lock_key:
4400 /* Ensure the appropriate lock key state (and indicator light)
4401 remains in the same state. We do this by faking another
4402 press of the relevant key. Apparently, this really is the
4403 only way to toggle the state of the indicator lights. */
4404 dpyinfo->faked_key = wParam;
4405 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4406 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4407 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4408 KEYEVENTF_EXTENDEDKEY | 0, 0);
4409 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4410 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4411 /* Ensure indicator lights are updated promptly on Windows 9x
4412 (TranslateMessage apparently does this), after forwarding
4413 input event. */
4414 post_character_message (hwnd, msg, wParam, lParam,
4415 w32_get_key_modifiers (wParam, lParam));
4416 windows_translate = 1;
4417 break;
4418 case VK_CONTROL:
4419 case VK_SHIFT:
4420 case VK_PROCESSKEY: /* Generated by IME. */
4421 windows_translate = 1;
4422 break;
4423 case VK_CANCEL:
4424 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4425 which is confusing for purposes of key binding; convert
4426 VK_CANCEL events into VK_PAUSE events. */
4427 wParam = VK_PAUSE;
4428 break;
4429 case VK_PAUSE:
4430 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4431 for purposes of key binding; convert these back into
4432 VK_NUMLOCK events, at least when we want to see NumLock key
4433 presses. (Note that there is never any possibility that
4434 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4435 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4436 wParam = VK_NUMLOCK;
4437 break;
4438 default:
4439 /* If not defined as a function key, change it to a WM_CHAR message. */
4440 if (lispy_function_keys[wParam] == 0)
4441 {
4442 DWORD modifiers = construct_console_modifiers ();
4443
4444 if (!NILP (Vw32_recognize_altgr)
4445 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4446 {
4447 /* Always let TranslateMessage handle AltGr key chords;
4448 for some reason, ToAscii doesn't always process AltGr
4449 chords correctly. */
4450 windows_translate = 1;
4451 }
4452 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4453 {
4454 /* Handle key chords including any modifiers other
4455 than shift directly, in order to preserve as much
4456 modifier information as possible. */
4457 if ('A' <= wParam && wParam <= 'Z')
4458 {
4459 /* Don't translate modified alphabetic keystrokes,
4460 so the user doesn't need to constantly switch
4461 layout to type control or meta keystrokes when
4462 the normal layout translates alphabetic
4463 characters to non-ascii characters. */
4464 if (!modifier_set (VK_SHIFT))
4465 wParam += ('a' - 'A');
4466 msg = WM_CHAR;
4467 }
4468 else
4469 {
4470 /* Try to handle other keystrokes by determining the
4471 base character (ie. translating the base key plus
4472 shift modifier). */
4473 int add;
4474 int isdead = 0;
4475 KEY_EVENT_RECORD key;
4476
4477 key.bKeyDown = TRUE;
4478 key.wRepeatCount = 1;
4479 key.wVirtualKeyCode = wParam;
4480 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4481 key.uChar.AsciiChar = 0;
4482 key.dwControlKeyState = modifiers;
4483
4484 add = w32_kbd_patch_key (&key);
4485 /* 0 means an unrecognised keycode, negative means
4486 dead key. Ignore both. */
4487 while (--add >= 0)
4488 {
4489 /* Forward asciified character sequence. */
4490 post_character_message
4491 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4492 w32_get_key_modifiers (wParam, lParam));
4493 w32_kbd_patch_key (&key);
4494 }
4495 return 0;
4496 }
4497 }
4498 else
4499 {
4500 /* Let TranslateMessage handle everything else. */
4501 windows_translate = 1;
4502 }
4503 }
4504 }
4505
4506 translate:
4507 if (windows_translate)
4508 {
4509 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4510
4511 windows_msg.time = GetMessageTime ();
4512 TranslateMessage (&windows_msg);
4513 goto dflt;
4514 }
4515
4516 /* Fall through */
4517
4518 case WM_SYSCHAR:
4519 case WM_CHAR:
4520 post_character_message (hwnd, msg, wParam, lParam,
4521 w32_get_key_modifiers (wParam, lParam));
4522 break;
4523
4524 /* Simulate middle mouse button events when left and right buttons
4525 are used together, but only if user has two button mouse. */
4526 case WM_LBUTTONDOWN:
4527 case WM_RBUTTONDOWN:
4528 if (XINT (Vw32_num_mouse_buttons) > 2)
4529 goto handle_plain_button;
4530
4531 {
4532 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4533 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4534
4535 if (button_state & this)
4536 return 0;
4537
4538 if (button_state == 0)
4539 SetCapture (hwnd);
4540
4541 button_state |= this;
4542
4543 if (button_state & other)
4544 {
4545 if (mouse_button_timer)
4546 {
4547 KillTimer (hwnd, mouse_button_timer);
4548 mouse_button_timer = 0;
4549
4550 /* Generate middle mouse event instead. */
4551 msg = WM_MBUTTONDOWN;
4552 button_state |= MMOUSE;
4553 }
4554 else if (button_state & MMOUSE)
4555 {
4556 /* Ignore button event if we've already generated a
4557 middle mouse down event. This happens if the
4558 user releases and press one of the two buttons
4559 after we've faked a middle mouse event. */
4560 return 0;
4561 }
4562 else
4563 {
4564 /* Flush out saved message. */
4565 post_msg (&saved_mouse_button_msg);
4566 }
4567 wmsg.dwModifiers = w32_get_modifiers ();
4568 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4569
4570 /* Clear message buffer. */
4571 saved_mouse_button_msg.msg.hwnd = 0;
4572 }
4573 else
4574 {
4575 /* Hold onto message for now. */
4576 mouse_button_timer =
4577 SetTimer (hwnd, MOUSE_BUTTON_ID,
4578 XINT (Vw32_mouse_button_tolerance), NULL);
4579 saved_mouse_button_msg.msg.hwnd = hwnd;
4580 saved_mouse_button_msg.msg.message = msg;
4581 saved_mouse_button_msg.msg.wParam = wParam;
4582 saved_mouse_button_msg.msg.lParam = lParam;
4583 saved_mouse_button_msg.msg.time = GetMessageTime ();
4584 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4585 }
4586 }
4587 return 0;
4588
4589 case WM_LBUTTONUP:
4590 case WM_RBUTTONUP:
4591 if (XINT (Vw32_num_mouse_buttons) > 2)
4592 goto handle_plain_button;
4593
4594 {
4595 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4596 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4597
4598 if ((button_state & this) == 0)
4599 return 0;
4600
4601 button_state &= ~this;
4602
4603 if (button_state & MMOUSE)
4604 {
4605 /* Only generate event when second button is released. */
4606 if ((button_state & other) == 0)
4607 {
4608 msg = WM_MBUTTONUP;
4609 button_state &= ~MMOUSE;
4610
4611 if (button_state) abort ();
4612 }
4613 else
4614 return 0;
4615 }
4616 else
4617 {
4618 /* Flush out saved message if necessary. */
4619 if (saved_mouse_button_msg.msg.hwnd)
4620 {
4621 post_msg (&saved_mouse_button_msg);
4622 }
4623 }
4624 wmsg.dwModifiers = w32_get_modifiers ();
4625 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4626
4627 /* Always clear message buffer and cancel timer. */
4628 saved_mouse_button_msg.msg.hwnd = 0;
4629 KillTimer (hwnd, mouse_button_timer);
4630 mouse_button_timer = 0;
4631
4632 if (button_state == 0)
4633 ReleaseCapture ();
4634 }
4635 return 0;
4636
4637 case WM_XBUTTONDOWN:
4638 case WM_XBUTTONUP:
4639 if (w32_pass_extra_mouse_buttons_to_system)
4640 goto dflt;
4641 /* else fall through and process them. */
4642 case WM_MBUTTONDOWN:
4643 case WM_MBUTTONUP:
4644 handle_plain_button:
4645 {
4646 BOOL up;
4647 int button;
4648
4649 if (parse_button (msg, HIWORD (wParam), &button, &up))
4650 {
4651 if (up) ReleaseCapture ();
4652 else SetCapture (hwnd);
4653 button = (button == 0) ? LMOUSE :
4654 ((button == 1) ? MMOUSE : RMOUSE);
4655 if (up)
4656 button_state &= ~button;
4657 else
4658 button_state |= button;
4659 }
4660 }
4661
4662 wmsg.dwModifiers = w32_get_modifiers ();
4663 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4664
4665 /* Need to return true for XBUTTON messages, false for others,
4666 to indicate that we processed the message. */
4667 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4668
4669 case WM_MOUSEMOVE:
4670 /* If the mouse has just moved into the frame, start tracking
4671 it, so we will be notified when it leaves the frame. Mouse
4672 tracking only works under W98 and NT4 and later. On earlier
4673 versions, there is no way of telling when the mouse leaves the
4674 frame, so we just have to put up with help-echo and mouse
4675 highlighting remaining while the frame is not active. */
4676 if (track_mouse_event_fn && !track_mouse_window)
4677 {
4678 TRACKMOUSEEVENT tme;
4679 tme.cbSize = sizeof (tme);
4680 tme.dwFlags = TME_LEAVE;
4681 tme.hwndTrack = hwnd;
4682
4683 track_mouse_event_fn (&tme);
4684 track_mouse_window = hwnd;
4685 }
4686 case WM_VSCROLL:
4687 if (XINT (Vw32_mouse_move_interval) <= 0
4688 || (msg == WM_MOUSEMOVE && button_state == 0))
4689 {
4690 wmsg.dwModifiers = w32_get_modifiers ();
4691 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4692 return 0;
4693 }
4694
4695 /* Hang onto mouse move and scroll messages for a bit, to avoid
4696 sending such events to Emacs faster than it can process them.
4697 If we get more events before the timer from the first message
4698 expires, we just replace the first message. */
4699
4700 if (saved_mouse_move_msg.msg.hwnd == 0)
4701 mouse_move_timer =
4702 SetTimer (hwnd, MOUSE_MOVE_ID,
4703 XINT (Vw32_mouse_move_interval), NULL);
4704
4705 /* Hold onto message for now. */
4706 saved_mouse_move_msg.msg.hwnd = hwnd;
4707 saved_mouse_move_msg.msg.message = msg;
4708 saved_mouse_move_msg.msg.wParam = wParam;
4709 saved_mouse_move_msg.msg.lParam = lParam;
4710 saved_mouse_move_msg.msg.time = GetMessageTime ();
4711 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4712
4713 return 0;
4714
4715 case WM_MOUSEWHEEL:
4716 wmsg.dwModifiers = w32_get_modifiers ();
4717 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4718 return 0;
4719
4720 case WM_DROPFILES:
4721 wmsg.dwModifiers = w32_get_modifiers ();
4722 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4723 return 0;
4724
4725 case WM_TIMER:
4726 /* Flush out saved messages if necessary. */
4727 if (wParam == mouse_button_timer)
4728 {
4729 if (saved_mouse_button_msg.msg.hwnd)
4730 {
4731 post_msg (&saved_mouse_button_msg);
4732 saved_mouse_button_msg.msg.hwnd = 0;
4733 }
4734 KillTimer (hwnd, mouse_button_timer);
4735 mouse_button_timer = 0;
4736 }
4737 else if (wParam == mouse_move_timer)
4738 {
4739 if (saved_mouse_move_msg.msg.hwnd)
4740 {
4741 post_msg (&saved_mouse_move_msg);
4742 saved_mouse_move_msg.msg.hwnd = 0;
4743 }
4744 KillTimer (hwnd, mouse_move_timer);
4745 mouse_move_timer = 0;
4746 }
4747 else if (wParam == menu_free_timer)
4748 {
4749 KillTimer (hwnd, menu_free_timer);
4750 menu_free_timer = 0;
4751 f = x_window_to_frame (dpyinfo, hwnd);
4752 if (!f->output_data.w32->menu_command_in_progress)
4753 {
4754 /* Free memory used by owner-drawn and help-echo strings. */
4755 w32_free_menu_strings (hwnd);
4756 f->output_data.w32->menubar_active = 0;
4757 }
4758 }
4759 return 0;
4760
4761 case WM_NCACTIVATE:
4762 /* Windows doesn't send us focus messages when putting up and
4763 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4764 The only indication we get that something happened is receiving
4765 this message afterwards. So this is a good time to reset our
4766 keyboard modifiers' state. */
4767 reset_modifiers ();
4768 goto dflt;
4769
4770 case WM_INITMENU:
4771 button_state = 0;
4772 ReleaseCapture ();
4773 /* We must ensure menu bar is fully constructed and up to date
4774 before allowing user interaction with it. To achieve this
4775 we send this message to the lisp thread and wait for a
4776 reply (whose value is not actually needed) to indicate that
4777 the menu bar is now ready for use, so we can now return.
4778
4779 To remain responsive in the meantime, we enter a nested message
4780 loop that can process all other messages.
4781
4782 However, we skip all this if the message results from calling
4783 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4784 thread a message because it is blocked on us at this point. We
4785 set menubar_active before calling TrackPopupMenu to indicate
4786 this (there is no possibility of confusion with real menubar
4787 being active). */
4788
4789 f = x_window_to_frame (dpyinfo, hwnd);
4790 if (f
4791 && (f->output_data.w32->menubar_active
4792 /* We can receive this message even in the absence of a
4793 menubar (ie. when the system menu is activated) - in this
4794 case we do NOT want to forward the message, otherwise it
4795 will cause the menubar to suddenly appear when the user
4796 had requested it to be turned off! */
4797 || f->output_data.w32->menubar_widget == NULL))
4798 return 0;
4799
4800 {
4801 deferred_msg msg_buf;
4802
4803 /* Detect if message has already been deferred; in this case
4804 we cannot return any sensible value to ignore this. */
4805 if (find_deferred_msg (hwnd, msg) != NULL)
4806 abort ();
4807
4808 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4809 }
4810
4811 case WM_EXITMENULOOP:
4812 f = x_window_to_frame (dpyinfo, hwnd);
4813
4814 /* If a menu command is not already in progress, check again
4815 after a short delay, since Windows often (always?) sends the
4816 WM_EXITMENULOOP before the corresponding WM_COMMAND message. */
4817 if (f && !f->output_data.w32->menu_command_in_progress)
4818 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4819 goto dflt;
4820
4821 case WM_MENUSELECT:
4822 /* Direct handling of help_echo in menus. Should be safe now
4823 that we generate the help_echo by placing a help event in the
4824 keyboard buffer. */
4825 {
4826 HMENU menu = (HMENU) lParam;
4827 UINT menu_item = (UINT) LOWORD (wParam);
4828 UINT flags = (UINT) HIWORD (wParam);
4829
4830 w32_menu_display_help (hwnd, menu, menu_item, flags);
4831 }
4832 return 0;
4833
4834 case WM_MEASUREITEM:
4835 f = x_window_to_frame (dpyinfo, hwnd);
4836 if (f)
4837 {
4838 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4839
4840 if (pMis->CtlType == ODT_MENU)
4841 {
4842 /* Work out dimensions for popup menu titles. */
4843 char * title = (char *) pMis->itemData;
4844 HDC hdc = GetDC (hwnd);
4845 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4846 LOGFONT menu_logfont;
4847 HFONT old_font;
4848 SIZE size;
4849
4850 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4851 menu_logfont.lfWeight = FW_BOLD;
4852 menu_font = CreateFontIndirect (&menu_logfont);
4853 old_font = SelectObject (hdc, menu_font);
4854
4855 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4856 if (title)
4857 {
4858 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4859 pMis->itemWidth = size.cx;
4860 if (pMis->itemHeight < size.cy)
4861 pMis->itemHeight = size.cy;
4862 }
4863 else
4864 pMis->itemWidth = 0;
4865
4866 SelectObject (hdc, old_font);
4867 DeleteObject (menu_font);
4868 ReleaseDC (hwnd, hdc);
4869 return TRUE;
4870 }
4871 }
4872 return 0;
4873
4874 case WM_DRAWITEM:
4875 f = x_window_to_frame (dpyinfo, hwnd);
4876 if (f)
4877 {
4878 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4879
4880 if (pDis->CtlType == ODT_MENU)
4881 {
4882 /* Draw popup menu title. */
4883 char * title = (char *) pDis->itemData;
4884 if (title)
4885 {
4886 HDC hdc = pDis->hDC;
4887 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4888 LOGFONT menu_logfont;
4889 HFONT old_font;
4890
4891 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4892 menu_logfont.lfWeight = FW_BOLD;
4893 menu_font = CreateFontIndirect (&menu_logfont);
4894 old_font = SelectObject (hdc, menu_font);
4895
4896 /* Always draw title as if not selected. */
4897 ExtTextOut (hdc,
4898 pDis->rcItem.left
4899 + GetSystemMetrics (SM_CXMENUCHECK),
4900 pDis->rcItem.top,
4901 ETO_OPAQUE, &pDis->rcItem,
4902 title, strlen (title), NULL);
4903
4904 SelectObject (hdc, old_font);
4905 DeleteObject (menu_font);
4906 }
4907 return TRUE;
4908 }
4909 }
4910 return 0;
4911
4912#if 0
4913 /* Still not right - can't distinguish between clicks in the
4914 client area of the frame from clicks forwarded from the scroll
4915 bars - may have to hook WM_NCHITTEST to remember the mouse
4916 position and then check if it is in the client area ourselves. */
4917 case WM_MOUSEACTIVATE:
4918 /* Discard the mouse click that activates a frame, allowing the
4919 user to click anywhere without changing point (or worse!).
4920 Don't eat mouse clicks on scrollbars though!! */
4921 if (LOWORD (lParam) == HTCLIENT )
4922 return MA_ACTIVATEANDEAT;
4923 goto dflt;
4924#endif
4925
4926 case WM_MOUSELEAVE:
4927 /* No longer tracking mouse. */
4928 track_mouse_window = NULL;
4929
4930 case WM_ACTIVATEAPP:
4931 case WM_ACTIVATE:
4932 case WM_WINDOWPOSCHANGED:
4933 case WM_SHOWWINDOW:
4934 /* Inform lisp thread that a frame might have just been obscured
4935 or exposed, so should recheck visibility of all frames. */
4936 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4937 goto dflt;
4938
4939 case WM_SETFOCUS:
4940 dpyinfo->faked_key = 0;
4941 reset_modifiers ();
4942 register_hot_keys (hwnd);
4943 goto command;
4944 case WM_KILLFOCUS:
4945 unregister_hot_keys (hwnd);
4946 button_state = 0;
4947 ReleaseCapture ();
4948 /* Relinquish the system caret. */
4949 if (w32_system_caret_hwnd)
4950 {
4951 w32_visible_system_caret_hwnd = NULL;
4952 w32_system_caret_hwnd = NULL;
4953 DestroyCaret ();
4954 }
4955 goto command;
4956 case WM_COMMAND:
4957 f = x_window_to_frame (dpyinfo, hwnd);
4958 if (f && HIWORD (wParam) == 0)
4959 {
4960 f->output_data.w32->menu_command_in_progress = 1;
4961 if (menu_free_timer)
4962 {
4963 KillTimer (hwnd, menu_free_timer);
4964 menu_free_timer = 0;
4965 }
4966 }
4967 case WM_MOVE:
4968 case WM_SIZE:
4969 command:
4970 wmsg.dwModifiers = w32_get_modifiers ();
4971 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4972 goto dflt;
4973
4974 case WM_CLOSE:
4975 wmsg.dwModifiers = w32_get_modifiers ();
4976 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4977 return 0;
4978
4979 case WM_WINDOWPOSCHANGING:
4980 /* Don't restrict the sizing of tip frames. */
4981 if (hwnd == tip_window)
4982 return 0;
4983 {
4984 WINDOWPLACEMENT wp;
4985 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4986
4987 wp.length = sizeof (WINDOWPLACEMENT);
4988 GetWindowPlacement (hwnd, &wp);
4989
4990 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4991 {
4992 RECT rect;
4993 int wdiff;
4994 int hdiff;
4995 DWORD font_width;
4996 DWORD line_height;
4997 DWORD internal_border;
4998 DWORD scrollbar_extra;
4999 RECT wr;
5000
5001 wp.length = sizeof(wp);
5002 GetWindowRect (hwnd, &wr);
5003
5004 enter_crit ();
5005
5006 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
5007 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
5008 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
5009 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
5010
5011 leave_crit ();
5012
5013 memset (&rect, 0, sizeof (rect));
5014 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
5015 GetMenu (hwnd) != NULL);
5016
5017 /* Force width and height of client area to be exact
5018 multiples of the character cell dimensions. */
5019 wdiff = (lppos->cx - (rect.right - rect.left)
5020 - 2 * internal_border - scrollbar_extra)
5021 % font_width;
5022 hdiff = (lppos->cy - (rect.bottom - rect.top)
5023 - 2 * internal_border)
5024 % line_height;
5025
5026 if (wdiff || hdiff)
5027 {
5028 /* For right/bottom sizing we can just fix the sizes.
5029 However for top/left sizing we will need to fix the X
5030 and Y positions as well. */
5031
5032 lppos->cx -= wdiff;
5033 lppos->cy -= hdiff;
5034
5035 if (wp.showCmd != SW_SHOWMAXIMIZED
5036 && (lppos->flags & SWP_NOMOVE) == 0)
5037 {
5038 if (lppos->x != wr.left || lppos->y != wr.top)
5039 {
5040 lppos->x += wdiff;
5041 lppos->y += hdiff;
5042 }
5043 else
5044 {
5045 lppos->flags |= SWP_NOMOVE;
5046 }
5047 }
5048
5049 return 0;
5050 }
5051 }
5052 }
5053
5054 goto dflt;
5055
5056 case WM_GETMINMAXINFO:
5057 /* Hack to correct bug that allows Emacs frames to be resized
5058 below the Minimum Tracking Size. */
5059 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
5060 /* Hack to allow resizing the Emacs frame above the screen size.
5061 Note that Windows 9x limits coordinates to 16-bits. */
5062 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
5063 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
5064 return 0;
5065
5066 case WM_EMACS_CREATESCROLLBAR:
5067 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
5068 (struct scroll_bar *) lParam);
5069
5070 case WM_EMACS_SHOWWINDOW:
5071 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
5072
5073 case WM_EMACS_SETFOREGROUND:
5074 {
5075 HWND foreground_window;
5076 DWORD foreground_thread, retval;
5077
5078 /* On NT 5.0, and apparently Windows 98, it is necessary to
5079 attach to the thread that currently has focus in order to
5080 pull the focus away from it. */
5081 foreground_window = GetForegroundWindow ();
5082 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
5083 if (!foreground_window
5084 || foreground_thread == GetCurrentThreadId ()
5085 || !AttachThreadInput (GetCurrentThreadId (),
5086 foreground_thread, TRUE))
5087 foreground_thread = 0;
5088
5089 retval = SetForegroundWindow ((HWND) wParam);
5090
5091 /* Detach from the previous foreground thread. */
5092 if (foreground_thread)
5093 AttachThreadInput (GetCurrentThreadId (),
5094 foreground_thread, FALSE);
5095
5096 return retval;
5097 }
5098
5099 case WM_EMACS_SETWINDOWPOS:
5100 {
5101 WINDOWPOS * pos = (WINDOWPOS *) wParam;
5102 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5103 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
5104 }
5105
5106 case WM_EMACS_DESTROYWINDOW:
5107 DragAcceptFiles ((HWND) wParam, FALSE);
5108 return DestroyWindow ((HWND) wParam);
5109
5110 case WM_EMACS_HIDE_CARET:
5111 return HideCaret (hwnd);
5112
5113 case WM_EMACS_SHOW_CARET:
5114 return ShowCaret (hwnd);
5115
5116 case WM_EMACS_DESTROY_CARET:
5117 w32_system_caret_hwnd = NULL;
5118 w32_visible_system_caret_hwnd = NULL;
5119 return DestroyCaret ();
5120
5121 case WM_EMACS_TRACK_CARET:
5122 /* If there is currently no system caret, create one. */
5123 if (w32_system_caret_hwnd == NULL)
5124 {
5125 /* Use the default caret width, and avoid changing it
5126 unneccesarily, as it confuses screen reader software. */
5127 w32_system_caret_hwnd = hwnd;
5128 CreateCaret (hwnd, NULL, 0,
5129 w32_system_caret_height);
5130 }
5131
5132 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
5133 return 0;
5134 /* Ensure visible caret gets turned on when requested. */
5135 else if (w32_use_visible_system_caret
5136 && w32_visible_system_caret_hwnd != hwnd)
5137 {
5138 w32_visible_system_caret_hwnd = hwnd;
5139 return ShowCaret (hwnd);
5140 }
5141 /* Ensure visible caret gets turned off when requested. */
5142 else if (!w32_use_visible_system_caret
5143 && w32_visible_system_caret_hwnd)
5144 {
5145 w32_visible_system_caret_hwnd = NULL;
5146 return HideCaret (hwnd);
5147 }
5148 else
5149 return 1;
5150
5151 case WM_EMACS_TRACKPOPUPMENU:
5152 {
5153 UINT flags;
5154 POINT *pos;
5155 int retval;
5156 pos = (POINT *)lParam;
5157 flags = TPM_CENTERALIGN;
5158 if (button_state & LMOUSE)
5159 flags |= TPM_LEFTBUTTON;
5160 else if (button_state & RMOUSE)
5161 flags |= TPM_RIGHTBUTTON;
5162
5163 /* Remember we did a SetCapture on the initial mouse down event,
5164 so for safety, we make sure the capture is cancelled now. */
5165 ReleaseCapture ();
5166 button_state = 0;
5167
5168 /* Use menubar_active to indicate that WM_INITMENU is from
5169 TrackPopupMenu below, and should be ignored. */
5170 f = x_window_to_frame (dpyinfo, hwnd);
5171 if (f)
5172 f->output_data.w32->menubar_active = 1;
5173
5174 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
5175 0, hwnd, NULL))
5176 {
5177 MSG amsg;
5178 /* Eat any mouse messages during popupmenu */
5179 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
5180 PM_REMOVE));
5181 /* Get the menu selection, if any */
5182 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
5183 {
5184 retval = LOWORD (amsg.wParam);
5185 }
5186 else
5187 {
5188 retval = 0;
5189 }
5190 }
5191 else
5192 {
5193 retval = -1;
5194 }
5195
5196 return retval;
5197 }
5198
5199 default:
5200 /* Check for messages registered at runtime. */
5201 if (msg == msh_mousewheel)
5202 {
5203 wmsg.dwModifiers = w32_get_modifiers ();
5204 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5205 return 0;
5206 }
5207
5208 dflt:
5209 return DefWindowProc (hwnd, msg, wParam, lParam);
5210 }
5211
5212
5213 /* The most common default return code for handled messages is 0. */
5214 return 0;
5215}
5216
5217void
5218my_create_window (f)
5219 struct frame * f;
5220{
5221 MSG msg;
5222
5223 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
5224 abort ();
5225 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5226}
5227
5228
5229/* Create a tooltip window. Unlike my_create_window, we do not do this
5230 indirectly via the Window thread, as we do not need to process Window
5231 messages for the tooltip. Creating tooltips indirectly also creates
5232 deadlocks when tooltips are created for menu items. */
5233void
5234my_create_tip_window (f)
5235 struct frame *f;
5236{
5237 RECT rect;
5238
5239 rect.left = rect.top = 0;
5240 rect.right = PIXEL_WIDTH (f);
5241 rect.bottom = PIXEL_HEIGHT (f);
5242
5243 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
5244 FRAME_EXTERNAL_MENU_BAR (f));
5245
5246 tip_window = FRAME_W32_WINDOW (f)
5247 = CreateWindow (EMACS_CLASS,
5248 f->namebuf,
5249 f->output_data.w32->dwStyle,
5250 f->output_data.w32->left_pos,
5251 f->output_data.w32->top_pos,
5252 rect.right - rect.left,
5253 rect.bottom - rect.top,
5254 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5255 NULL,
5256 hinst,
5257 NULL);
5258
5259 if (tip_window)
5260 {
5261 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
5262 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
5263 SetWindowLong (tip_window, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
5264 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5265
5266 /* Tip frames have no scrollbars. */
5267 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
5268
5269 /* Do this to discard the default setting specified by our parent. */
5270 ShowWindow (tip_window, SW_HIDE);
5271 }
5272}
5273
5274
5275/* Create and set up the w32 window for frame F. */
5276
5277static void
5278w32_window (f, window_prompting, minibuffer_only)
5279 struct frame *f;
5280 long window_prompting;
5281 int minibuffer_only;
5282{
5283 BLOCK_INPUT;
5284
5285 /* Use the resource name as the top-level window name
5286 for looking up resources. Make a non-Lisp copy
5287 for the window manager, so GC relocation won't bother it.
5288
5289 Elsewhere we specify the window name for the window manager. */
5290
5291 {
5292 char *str = (char *) SDATA (Vx_resource_name);
5293 f->namebuf = (char *) xmalloc (strlen (str) + 1);
5294 strcpy (f->namebuf, str);
5295 }
5296
5297 my_create_window (f);
5298
5299 validate_x_resource_name ();
5300
5301 /* x_set_name normally ignores requests to set the name if the
5302 requested name is the same as the current name. This is the one
5303 place where that assumption isn't correct; f->name is set, but
5304 the server hasn't been told. */
5305 {
5306 Lisp_Object name;
5307 int explicit = f->explicit_name;
5308
5309 f->explicit_name = 0;
5310 name = f->name;
5311 f->name = Qnil;
5312 x_set_name (f, name, explicit);
5313 }
5314
5315 UNBLOCK_INPUT;
5316
5317 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5318 initialize_frame_menubar (f);
5319
5320 if (FRAME_W32_WINDOW (f) == 0)
5321 error ("Unable to create window");
5322}
5323
5324/* Handle the icon stuff for this window. Perhaps later we might
5325 want an x_set_icon_position which can be called interactively as
5326 well. */
5327
5328static void
5329x_icon (f, parms)
5330 struct frame *f;
5331 Lisp_Object parms;
5332{
5333 Lisp_Object icon_x, icon_y;
5334
5335 /* Set the position of the icon. Note that Windows 95 groups all
5336 icons in the tray. */
5337 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5338 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5339 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5340 {
5341 CHECK_NUMBER (icon_x);
5342 CHECK_NUMBER (icon_y);
5343 }
5344 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5345 error ("Both left and top icon corners of icon must be specified");
5346
5347 BLOCK_INPUT;
5348
5349 if (! EQ (icon_x, Qunbound))
5350 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
5351
5352#if 0 /* TODO */
5353 /* Start up iconic or window? */
5354 x_wm_set_window_state
5355 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5356 ? IconicState
5357 : NormalState));
5358
5359 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
5360 ? f->icon_name
5361 : f->name)));
5362#endif
5363
5364 UNBLOCK_INPUT;
5365}
5366
5367
5368static void
5369x_make_gc (f)
5370 struct frame *f;
5371{
5372 XGCValues gc_values;
5373
5374 BLOCK_INPUT;
5375
5376 /* Create the GC's of this frame.
5377 Note that many default values are used. */
5378
5379 /* Normal video */
5380 gc_values.font = f->output_data.w32->font;
5381
5382 /* Cursor has cursor-color background, background-color foreground. */
5383 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5384 gc_values.background = f->output_data.w32->cursor_pixel;
5385 f->output_data.w32->cursor_gc
5386 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5387 (GCFont | GCForeground | GCBackground),
5388 &gc_values);
5389
5390 /* Reliefs. */
5391 f->output_data.w32->white_relief.gc = 0;
5392 f->output_data.w32->black_relief.gc = 0;
5393
5394 UNBLOCK_INPUT;
5395}
5396
5397
5398/* Handler for signals raised during x_create_frame and
5399 x_create_top_frame. FRAME is the frame which is partially
5400 constructed. */
5401
5402static Lisp_Object
5403unwind_create_frame (frame)
5404 Lisp_Object frame;
5405{
5406 struct frame *f = XFRAME (frame);
5407
5408 /* If frame is ``official'', nothing to do. */
5409 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
5410 {
5411#ifdef GLYPH_DEBUG
5412 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5413#endif
5414
5415 x_free_frame_resources (f);
5416
5417 /* Check that reference counts are indeed correct. */
5418 xassert (dpyinfo->reference_count == dpyinfo_refcount);
5419 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
5420
5421 return Qt;
5422 }
5423
5424 return Qnil;
5425}
5426
5427
5428DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5429 1, 1, 0,
5430 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5431Returns an Emacs frame object.
5432ALIST is an alist of frame parameters.
5433If the parameters specify that the frame should not have a minibuffer,
5434and do not specify a specific minibuffer window to use,
5435then `default-minibuffer-frame' must be a frame whose minibuffer can
5436be shared by the new frame.
5437
5438This function is an internal primitive--use `make-frame' instead. */)
5439 (parms)
5440 Lisp_Object parms;
5441{
5442 struct frame *f;
5443 Lisp_Object frame, tem;
5444 Lisp_Object name;
5445 int minibuffer_only = 0;
5446 long window_prompting = 0;
5447 int width, height;
5448 int count = SPECPDL_INDEX ();
5449 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5450 Lisp_Object display;
5451 struct w32_display_info *dpyinfo = NULL;
5452 Lisp_Object parent;
5453 struct kboard *kb;
5454
5455 check_w32 ();
5456
5457 /* Use this general default value to start with
5458 until we know if this frame has a specified name. */
5459 Vx_resource_name = Vinvocation_name;
5460
5461 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
5462 if (EQ (display, Qunbound))
5463 display = Qnil;
5464 dpyinfo = check_x_display_info (display);
5465#ifdef MULTI_KBOARD
5466 kb = dpyinfo->kboard;
5467#else
5468 kb = &the_only_kboard;
5469#endif
5470
5471 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
5472 if (!STRINGP (name)
5473 && ! EQ (name, Qunbound)
5474 && ! NILP (name))
5475 error ("Invalid frame name--not a string or nil");
5476
5477 if (STRINGP (name))
5478 Vx_resource_name = name;
5479
5480 /* See if parent window is specified. */
5481 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5482 if (EQ (parent, Qunbound))
5483 parent = Qnil;
5484 if (! NILP (parent))
5485 CHECK_NUMBER (parent);
5486
5487 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5488 /* No need to protect DISPLAY because that's not used after passing
5489 it to make_frame_without_minibuffer. */
5490 frame = Qnil;
5491 GCPRO4 (parms, parent, name, frame);
5492 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
5493 RES_TYPE_SYMBOL);
5494 if (EQ (tem, Qnone) || NILP (tem))
5495 f = make_frame_without_minibuffer (Qnil, kb, display);
5496 else if (EQ (tem, Qonly))
5497 {
5498 f = make_minibuffer_frame ();
5499 minibuffer_only = 1;
5500 }
5501 else if (WINDOWP (tem))
5502 f = make_frame_without_minibuffer (tem, kb, display);
5503 else
5504 f = make_frame (1);
5505
5506 XSETFRAME (frame, f);
5507
5508 /* Note that Windows does support scroll bars. */
5509 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
5510 /* By default, make scrollbars the system standard width. */
5511 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
5512
5513 f->output_method = output_w32;
5514 f->output_data.w32 =
5515 (struct w32_output *) xmalloc (sizeof (struct w32_output));
5516 bzero (f->output_data.w32, sizeof (struct w32_output));
5517 FRAME_FONTSET (f) = -1;
5518 record_unwind_protect (unwind_create_frame, frame);
5519
5520 f->icon_name
5521 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5522 if (! STRINGP (f->icon_name))
5523 f->icon_name = Qnil;
5524
5525/* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5526#ifdef MULTI_KBOARD
5527 FRAME_KBOARD (f) = kb;
5528#endif
5529
5530 /* Specify the parent under which to make this window. */
5531
5532 if (!NILP (parent))
5533 {
5534 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
5535 f->output_data.w32->explicit_parent = 1;
5536 }
5537 else
5538 {
5539 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5540 f->output_data.w32->explicit_parent = 0;
5541 }
5542
5543 /* Set the name; the functions to which we pass f expect the name to
5544 be set. */
5545 if (EQ (name, Qunbound) || NILP (name))
5546 {
5547 f->name = build_string (dpyinfo->w32_id_name);
5548 f->explicit_name = 0;
5549 }
5550 else
5551 {
5552 f->name = name;
5553 f->explicit_name = 1;
5554 /* use the frame's title when getting resources for this frame. */
5555 specbind (Qx_resource_name, name);
5556 }
5557
5558 /* Extract the window parameters from the supplied values
5559 that are needed to determine window geometry. */
5560 {
5561 Lisp_Object font;
5562
5563 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5564
5565 BLOCK_INPUT;
5566 /* First, try whatever font the caller has specified. */
5567 if (STRINGP (font))
5568 {
5569 tem = Fquery_fontset (font, Qnil);
5570 if (STRINGP (tem))
5571 font = x_new_fontset (f, SDATA (tem));
5572 else
5573 font = x_new_font (f, SDATA (font));
5574 }
5575 /* Try out a font which we hope has bold and italic variations. */
5576 if (!STRINGP (font))
5577 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
5578 if (! STRINGP (font))
5579 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5580 /* If those didn't work, look for something which will at least work. */
5581 if (! STRINGP (font))
5582 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5583 UNBLOCK_INPUT;
5584 if (! STRINGP (font))
5585 font = build_string ("Fixedsys");
5586
5587 x_default_parameter (f, parms, Qfont, font,
5588 "font", "Font", RES_TYPE_STRING);
5589 }
5590
5591 x_default_parameter (f, parms, Qborder_width, make_number (2),
5592 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5593 /* This defaults to 2 in order to match xterm. We recognize either
5594 internalBorderWidth or internalBorder (which is what xterm calls
5595 it). */
5596 if (NILP (Fassq (Qinternal_border_width, parms)))
5597 {
5598 Lisp_Object value;
5599
5600 value = w32_get_arg (parms, Qinternal_border_width,
5601 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5602 if (! EQ (value, Qunbound))
5603 parms = Fcons (Fcons (Qinternal_border_width, value),
5604 parms);
5605 }
5606 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5607 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5608 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5609 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
5610 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5611
5612 /* Also do the stuff which must be set before the window exists. */
5613 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5614 "foreground", "Foreground", RES_TYPE_STRING);
5615 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5616 "background", "Background", RES_TYPE_STRING);
5617 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5618 "pointerColor", "Foreground", RES_TYPE_STRING);
5619 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5620 "cursorColor", "Foreground", RES_TYPE_STRING);
5621 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5622 "borderColor", "BorderColor", RES_TYPE_STRING);
5623 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5624 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5625 x_default_parameter (f, parms, Qline_spacing, Qnil,
5626 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5627 x_default_parameter (f, parms, Qleft_fringe, Qnil,
5628 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5629 x_default_parameter (f, parms, Qright_fringe, Qnil,
5630 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5631
5632
5633 /* Init faces before x_default_parameter is called for scroll-bar
5634 parameters because that function calls x_set_scroll_bar_width,
5635 which calls change_frame_size, which calls Fset_window_buffer,
5636 which runs hooks, which call Fvertical_motion. At the end, we
5637 end up in init_iterator with a null face cache, which should not
5638 happen. */
5639 init_frame_faces (f);
5640
5641 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5642 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5643 x_default_parameter (f, parms, Qtool_bar_lines, make_number (1),
5644 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5645
5646 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5647 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5648 x_default_parameter (f, parms, Qtitle, Qnil,
5649 "title", "Title", RES_TYPE_STRING);
5650 x_default_parameter (f, parms, Qfullscreen, Qnil,
5651 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5652
5653 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5654 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5655
5656 /* Add the tool-bar height to the initial frame height so that the
5657 user gets a text display area of the size he specified with -g or
5658 via .Xdefaults. Later changes of the tool-bar height don't
5659 change the frame size. This is done so that users can create
5660 tall Emacs frames without having to guess how tall the tool-bar
5661 will get. */
5662 if (FRAME_TOOL_BAR_LINES (f))
5663 {
5664 int margin, relief, bar_height;
5665
5666 relief = (tool_bar_button_relief >= 0
5667 ? tool_bar_button_relief
5668 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
5669
5670 if (INTEGERP (Vtool_bar_button_margin)
5671 && XINT (Vtool_bar_button_margin) > 0)
5672 margin = XFASTINT (Vtool_bar_button_margin);
5673 else if (CONSP (Vtool_bar_button_margin)
5674 && INTEGERP (XCDR (Vtool_bar_button_margin))
5675 && XINT (XCDR (Vtool_bar_button_margin)) > 0)
5676 margin = XFASTINT (XCDR (Vtool_bar_button_margin));
5677 else
5678 margin = 0;
5679
5680 bar_height = DEFAULT_TOOL_BAR_IMAGE_HEIGHT + 2 * margin + 2 * relief;
5681 f->height += (bar_height + CANON_Y_UNIT (f) - 1) / CANON_Y_UNIT (f);
5682 }
5683
5684 window_prompting = x_figure_window_size (f, parms);
5685
5686 if (window_prompting & XNegative)
5687 {
5688 if (window_prompting & YNegative)
5689 f->output_data.w32->win_gravity = SouthEastGravity;
5690 else
5691 f->output_data.w32->win_gravity = NorthEastGravity;
5692 }
5693 else
5694 {
5695 if (window_prompting & YNegative)
5696 f->output_data.w32->win_gravity = SouthWestGravity;
5697 else
5698 f->output_data.w32->win_gravity = NorthWestGravity;
5699 }
5700
5701 f->output_data.w32->size_hint_flags = window_prompting;
5702
5703 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5704 f->no_split = minibuffer_only || EQ (tem, Qt);
5705
5706 w32_window (f, window_prompting, minibuffer_only);
5707 x_icon (f, parms);
5708
5709 x_make_gc (f);
5710
5711 /* Now consider the frame official. */
5712 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5713 Vframe_list = Fcons (frame, Vframe_list);
5714
5715 /* We need to do this after creating the window, so that the
5716 icon-creation functions can say whose icon they're describing. */
5717 x_default_parameter (f, parms, Qicon_type, Qnil,
5718 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5719
5720 x_default_parameter (f, parms, Qauto_raise, Qnil,
5721 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5722 x_default_parameter (f, parms, Qauto_lower, Qnil,
5723 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5724 x_default_parameter (f, parms, Qcursor_type, Qbox,
5725 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5726 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5727 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5728
5729 /* Dimensions, especially f->height, must be done via change_frame_size.
5730 Change will not be effected unless different from the current
5731 f->height. */
5732 width = f->width;
5733 height = f->height;
5734
5735 f->height = 0;
5736 SET_FRAME_WIDTH (f, 0);
5737 change_frame_size (f, height, width, 1, 0, 0);
5738
5739 /* Tell the server what size and position, etc, we want, and how
5740 badly we want them. This should be done after we have the menu
5741 bar so that its size can be taken into account. */
5742 BLOCK_INPUT;
5743 x_wm_set_size_hint (f, window_prompting, 0);
5744 UNBLOCK_INPUT;
5745
5746 /* Avoid a bug that causes the new frame to never become visible if
5747 an echo area message is displayed during the following call1. */
5748 specbind(Qredisplay_dont_pause, Qt);
5749
5750 /* Set up faces after all frame parameters are known. This call
5751 also merges in face attributes specified for new frames. If we
5752 don't do this, the `menu' face for instance won't have the right
5753 colors, and the menu bar won't appear in the specified colors for
5754 new frames. */
5755 call1 (Qface_set_after_frame_default, frame);
5756
5757 /* Make the window appear on the frame and enable display, unless
5758 the caller says not to. However, with explicit parent, Emacs
5759 cannot control visibility, so don't try. */
5760 if (! f->output_data.w32->explicit_parent)
5761 {
5762 Lisp_Object visibility;
5763
5764 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5765 if (EQ (visibility, Qunbound))
5766 visibility = Qt;
5767
5768 if (EQ (visibility, Qicon))
5769 x_iconify_frame (f);
5770 else if (! NILP (visibility))
5771 x_make_frame_visible (f);
5772 else
5773 /* Must have been Qnil. */
5774 ;
5775 }
5776 UNGCPRO;
5777
5778 /* Make sure windows on this frame appear in calls to next-window
5779 and similar functions. */
5780 Vwindow_list = Qnil;
5781
5782 return unbind_to (count, frame);
5783}
5784
5785/* FRAME is used only to get a handle on the X display. We don't pass the
5786 display info directly because we're called from frame.c, which doesn't
5787 know about that structure. */
5788Lisp_Object
5789x_get_focus_frame (frame)
5790 struct frame *frame;
5791{
5792 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5793 Lisp_Object xfocus;
5794 if (! dpyinfo->w32_focus_frame)
5795 return Qnil;
5796
5797 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5798 return xfocus;
5799}
5800
5801DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5802 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
5803 (frame)
5804 Lisp_Object frame;
5805{
5806 x_focus_on_frame (check_x_frame (frame));
5807 return Qnil;
5808}
5809
5810\f
5811/* Return the charset portion of a font name. */
5812char * xlfd_charset_of_font (char * fontname)
5813{
5814 char *charset, *encoding;
5815
5816 encoding = strrchr(fontname, '-');
5817 if (!encoding || encoding == fontname)
5818 return NULL;
5819
5820 for (charset = encoding - 1; charset >= fontname; charset--)
5821 if (*charset == '-')
5822 break;
5823
5824 if (charset == fontname || strcmp(charset, "-*-*") == 0)
5825 return NULL;
5826
5827 return charset + 1;
5828}
5829
5830struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5831 int size, char* filename);
5832static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
5833static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
5834 char * charset);
5835static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
5836
5837static struct font_info *
5838w32_load_system_font (f,fontname,size)
5839 struct frame *f;
5840 char * fontname;
5841 int size;
5842{
5843 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5844 Lisp_Object font_names;
5845
5846 /* Get a list of all the fonts that match this name. Once we
5847 have a list of matching fonts, we compare them against the fonts
5848 we already have loaded by comparing names. */
5849 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5850
5851 if (!NILP (font_names))
5852 {
5853 Lisp_Object tail;
5854 int i;
5855
5856 /* First check if any are already loaded, as that is cheaper
5857 than loading another one. */
5858 for (i = 0; i < dpyinfo->n_fonts; i++)
5859 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5860 if (dpyinfo->font_table[i].name
5861 && (!strcmp (dpyinfo->font_table[i].name,
5862 SDATA (XCAR (tail)))
5863 || !strcmp (dpyinfo->font_table[i].full_name,
5864 SDATA (XCAR (tail)))))
5865 return (dpyinfo->font_table + i);
5866
5867 fontname = (char *) SDATA (XCAR (font_names));
5868 }
5869 else if (w32_strict_fontnames)
5870 {
5871 /* If EnumFontFamiliesEx was available, we got a full list of
5872 fonts back so stop now to avoid the possibility of loading a
5873 random font. If we had to fall back to EnumFontFamilies, the
5874 list is incomplete, so continue whether the font we want was
5875 listed or not. */
5876 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5877 FARPROC enum_font_families_ex
5878 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5879 if (enum_font_families_ex)
5880 return NULL;
5881 }
5882
5883 /* Load the font and add it to the table. */
5884 {
5885 char *full_name, *encoding, *charset;
5886 XFontStruct *font;
5887 struct font_info *fontp;
5888 LOGFONT lf;
5889 BOOL ok;
5890 int codepage;
5891 int i;
5892
5893 if (!fontname || !x_to_w32_font (fontname, &lf))
5894 return (NULL);
5895
5896 if (!*lf.lfFaceName)
5897 /* If no name was specified for the font, we get a random font
5898 from CreateFontIndirect - this is not particularly
5899 desirable, especially since CreateFontIndirect does not
5900 fill out the missing name in lf, so we never know what we
5901 ended up with. */
5902 return NULL;
5903
5904 lf.lfQuality = DEFAULT_QUALITY;
5905
5906 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5907 bzero (font, sizeof (*font));
5908
5909 /* Set bdf to NULL to indicate that this is a Windows font. */
5910 font->bdf = NULL;
5911
5912 BLOCK_INPUT;
5913
5914 font->hfont = CreateFontIndirect (&lf);
5915
5916 if (font->hfont == NULL)
5917 {
5918 ok = FALSE;
5919 }
5920 else
5921 {
5922 HDC hdc;
5923 HANDLE oldobj;
5924
5925 codepage = w32_codepage_for_font (fontname);
5926
5927 hdc = GetDC (dpyinfo->root_window);
5928 oldobj = SelectObject (hdc, font->hfont);
5929
5930 ok = GetTextMetrics (hdc, &font->tm);
5931 if (codepage == CP_UNICODE)
5932 font->double_byte_p = 1;
5933 else
5934 {
5935 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
5936 don't report themselves as double byte fonts, when
5937 patently they are. So instead of trusting
5938 GetFontLanguageInfo, we check the properties of the
5939 codepage directly, since that is ultimately what we are
5940 working from anyway. */
5941 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
5942 CPINFO cpi = {0};
5943 GetCPInfo (codepage, &cpi);
5944 font->double_byte_p = cpi.MaxCharSize > 1;
5945 }
5946
5947 SelectObject (hdc, oldobj);
5948 ReleaseDC (dpyinfo->root_window, hdc);
5949 /* Fill out details in lf according to the font that was
5950 actually loaded. */
5951 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5952 lf.lfWidth = font->tm.tmAveCharWidth;
5953 lf.lfWeight = font->tm.tmWeight;
5954 lf.lfItalic = font->tm.tmItalic;
5955 lf.lfCharSet = font->tm.tmCharSet;
5956 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5957 ? VARIABLE_PITCH : FIXED_PITCH);
5958 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5959 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5960
5961 w32_cache_char_metrics (font);
5962 }
5963
5964 UNBLOCK_INPUT;
5965
5966 if (!ok)
5967 {
5968 w32_unload_font (dpyinfo, font);
5969 return (NULL);
5970 }
5971
5972 /* Find a free slot in the font table. */
5973 for (i = 0; i < dpyinfo->n_fonts; ++i)
5974 if (dpyinfo->font_table[i].name == NULL)
5975 break;
5976
5977 /* If no free slot found, maybe enlarge the font table. */
5978 if (i == dpyinfo->n_fonts
5979 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5980 {
5981 int sz;
5982 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5983 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5984 dpyinfo->font_table
5985 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5986 }
5987
5988 fontp = dpyinfo->font_table + i;
5989 if (i == dpyinfo->n_fonts)
5990 ++dpyinfo->n_fonts;
5991
5992 /* Now fill in the slots of *FONTP. */
5993 BLOCK_INPUT;
5994 fontp->font = font;
5995 fontp->font_idx = i;
5996 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5997 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5998
5999 charset = xlfd_charset_of_font (fontname);
6000
6001 /* Cache the W32 codepage for a font. This makes w32_encode_char
6002 (called for every glyph during redisplay) much faster. */
6003 fontp->codepage = codepage;
6004
6005 /* Work out the font's full name. */
6006 full_name = (char *)xmalloc (100);
6007 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
6008 fontp->full_name = full_name;
6009 else
6010 {
6011 /* If all else fails - just use the name we used to load it. */
6012 xfree (full_name);
6013 fontp->full_name = fontp->name;
6014 }
6015
6016 fontp->size = FONT_WIDTH (font);
6017 fontp->height = FONT_HEIGHT (font);
6018
6019 /* The slot `encoding' specifies how to map a character
6020 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
6021 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
6022 (0:0x20..0x7F, 1:0xA0..0xFF,
6023 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
6024 2:0xA020..0xFF7F). For the moment, we don't know which charset
6025 uses this font. So, we set information in fontp->encoding[1]
6026 which is never used by any charset. If mapping can't be
6027 decided, set FONT_ENCODING_NOT_DECIDED. */
6028
6029 /* SJIS fonts need to be set to type 4, all others seem to work as
6030 type FONT_ENCODING_NOT_DECIDED. */
6031 encoding = strrchr (fontp->name, '-');
6032 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
6033 fontp->encoding[1] = 4;
6034 else
6035 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
6036
6037 /* The following three values are set to 0 under W32, which is
6038 what they get set to if XGetFontProperty fails under X. */
6039 fontp->baseline_offset = 0;
6040 fontp->relative_compose = 0;
6041 fontp->default_ascent = 0;
6042
6043 /* Set global flag fonts_changed_p to non-zero if the font loaded
6044 has a character with a smaller width than any other character
6045 before, or if the font loaded has a smaller height than any
6046 other font loaded before. If this happens, it will make a
6047 glyph matrix reallocation necessary. */
6048 fonts_changed_p |= x_compute_min_glyph_bounds (f);
6049 UNBLOCK_INPUT;
6050 return fontp;
6051 }
6052}
6053
6054/* Load font named FONTNAME of size SIZE for frame F, and return a
6055 pointer to the structure font_info while allocating it dynamically.
6056 If loading fails, return NULL. */
6057struct font_info *
6058w32_load_font (f,fontname,size)
6059struct frame *f;
6060char * fontname;
6061int size;
6062{
6063 Lisp_Object bdf_fonts;
6064 struct font_info *retval = NULL;
6065
6066 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
6067
6068 while (!retval && CONSP (bdf_fonts))
6069 {
6070 char *bdf_name, *bdf_file;
6071 Lisp_Object bdf_pair;
6072
6073 bdf_name = SDATA (XCAR (bdf_fonts));
6074 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
6075 bdf_file = SDATA (XCDR (bdf_pair));
6076
6077 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
6078
6079 bdf_fonts = XCDR (bdf_fonts);
6080 }
6081
6082 if (retval)
6083 return retval;
6084
6085 return w32_load_system_font(f, fontname, size);
6086}
6087
6088
6089void
6090w32_unload_font (dpyinfo, font)
6091 struct w32_display_info *dpyinfo;
6092 XFontStruct * font;
6093{
6094 if (font)
6095 {
6096 if (font->per_char) xfree (font->per_char);
6097 if (font->bdf) w32_free_bdf_font (font->bdf);
6098
6099 if (font->hfont) DeleteObject(font->hfont);
6100 xfree (font);
6101 }
6102}
6103
6104/* The font conversion stuff between x and w32 */
6105
6106/* X font string is as follows (from faces.el)
6107 * (let ((- "[-?]")
6108 * (foundry "[^-]+")
6109 * (family "[^-]+")
6110 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
6111 * (weight\? "\\([^-]*\\)") ; 1
6112 * (slant "\\([ior]\\)") ; 2
6113 * (slant\? "\\([^-]?\\)") ; 2
6114 * (swidth "\\([^-]*\\)") ; 3
6115 * (adstyle "[^-]*") ; 4
6116 * (pixelsize "[0-9]+")
6117 * (pointsize "[0-9][0-9]+")
6118 * (resx "[0-9][0-9]+")
6119 * (resy "[0-9][0-9]+")
6120 * (spacing "[cmp?*]")
6121 * (avgwidth "[0-9]+")
6122 * (registry "[^-]+")
6123 * (encoding "[^-]+")
6124 * )
6125 */
6126
6127static LONG
6128x_to_w32_weight (lpw)
6129 char * lpw;
6130{
6131 if (!lpw) return (FW_DONTCARE);
6132
6133 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
6134 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
6135 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
6136 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
6137 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
6138 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
6139 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
6140 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
6141 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
6142 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
6143 else
6144 return FW_DONTCARE;
6145}
6146
6147
6148static char *
6149w32_to_x_weight (fnweight)
6150 int fnweight;
6151{
6152 if (fnweight >= FW_HEAVY) return "heavy";
6153 if (fnweight >= FW_EXTRABOLD) return "extrabold";
6154 if (fnweight >= FW_BOLD) return "bold";
6155 if (fnweight >= FW_SEMIBOLD) return "demibold";
6156 if (fnweight >= FW_MEDIUM) return "medium";
6157 if (fnweight >= FW_NORMAL) return "normal";
6158 if (fnweight >= FW_LIGHT) return "light";
6159 if (fnweight >= FW_EXTRALIGHT) return "extralight";
6160 if (fnweight >= FW_THIN) return "thin";
6161 else
6162 return "*";
6163}
6164
6165static LONG
6166x_to_w32_charset (lpcs)
6167 char * lpcs;
6168{
6169 Lisp_Object this_entry, w32_charset;
6170 char *charset;
6171 int len = strlen (lpcs);
6172
6173 /* Support "*-#nnn" format for unknown charsets. */
6174 if (strncmp (lpcs, "*-#", 3) == 0)
6175 return atoi (lpcs + 3);
6176
6177 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
6178 charset = alloca (len + 1);
6179 strcpy (charset, lpcs);
6180 lpcs = strchr (charset, '*');
6181 if (lpcs)
6182 *lpcs = 0;
6183
6184 /* Look through w32-charset-info-alist for the character set.
6185 Format of each entry is
6186 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6187 */
6188 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6189
6190 if (NILP(this_entry))
6191 {
6192 /* At startup, we want iso8859-1 fonts to come up properly. */
6193 if (stricmp(charset, "iso8859-1") == 0)
6194 return ANSI_CHARSET;
6195 else
6196 return DEFAULT_CHARSET;
6197 }
6198
6199 w32_charset = Fcar (Fcdr (this_entry));
6200
6201 /* Translate Lisp symbol to number. */
6202 if (w32_charset == Qw32_charset_ansi)
6203 return ANSI_CHARSET;
6204 if (w32_charset == Qw32_charset_symbol)
6205 return SYMBOL_CHARSET;
6206 if (w32_charset == Qw32_charset_shiftjis)
6207 return SHIFTJIS_CHARSET;
6208 if (w32_charset == Qw32_charset_hangeul)
6209 return HANGEUL_CHARSET;
6210 if (w32_charset == Qw32_charset_chinesebig5)
6211 return CHINESEBIG5_CHARSET;
6212 if (w32_charset == Qw32_charset_gb2312)
6213 return GB2312_CHARSET;
6214 if (w32_charset == Qw32_charset_oem)
6215 return OEM_CHARSET;
6216#ifdef JOHAB_CHARSET
6217 if (w32_charset == Qw32_charset_johab)
6218 return JOHAB_CHARSET;
6219 if (w32_charset == Qw32_charset_easteurope)
6220 return EASTEUROPE_CHARSET;
6221 if (w32_charset == Qw32_charset_turkish)
6222 return TURKISH_CHARSET;
6223 if (w32_charset == Qw32_charset_baltic)
6224 return BALTIC_CHARSET;
6225 if (w32_charset == Qw32_charset_russian)
6226 return RUSSIAN_CHARSET;
6227 if (w32_charset == Qw32_charset_arabic)
6228 return ARABIC_CHARSET;
6229 if (w32_charset == Qw32_charset_greek)
6230 return GREEK_CHARSET;
6231 if (w32_charset == Qw32_charset_hebrew)
6232 return HEBREW_CHARSET;
6233 if (w32_charset == Qw32_charset_vietnamese)
6234 return VIETNAMESE_CHARSET;
6235 if (w32_charset == Qw32_charset_thai)
6236 return THAI_CHARSET;
6237 if (w32_charset == Qw32_charset_mac)
6238 return MAC_CHARSET;
6239#endif /* JOHAB_CHARSET */
6240#ifdef UNICODE_CHARSET
6241 if (w32_charset == Qw32_charset_unicode)
6242 return UNICODE_CHARSET;
6243#endif
6244
6245 return DEFAULT_CHARSET;
6246}
6247
6248
6249static char *
6250w32_to_x_charset (fncharset)
6251 int fncharset;
6252{
6253 static char buf[32];
6254 Lisp_Object charset_type;
6255
6256 switch (fncharset)
6257 {
6258 case ANSI_CHARSET:
6259 /* Handle startup case of w32-charset-info-alist not
6260 being set up yet. */
6261 if (NILP(Vw32_charset_info_alist))
6262 return "iso8859-1";
6263 charset_type = Qw32_charset_ansi;
6264 break;
6265 case DEFAULT_CHARSET:
6266 charset_type = Qw32_charset_default;
6267 break;
6268 case SYMBOL_CHARSET:
6269 charset_type = Qw32_charset_symbol;
6270 break;
6271 case SHIFTJIS_CHARSET:
6272 charset_type = Qw32_charset_shiftjis;
6273 break;
6274 case HANGEUL_CHARSET:
6275 charset_type = Qw32_charset_hangeul;
6276 break;
6277 case GB2312_CHARSET:
6278 charset_type = Qw32_charset_gb2312;
6279 break;
6280 case CHINESEBIG5_CHARSET:
6281 charset_type = Qw32_charset_chinesebig5;
6282 break;
6283 case OEM_CHARSET:
6284 charset_type = Qw32_charset_oem;
6285 break;
6286
6287 /* More recent versions of Windows (95 and NT4.0) define more
6288 character sets. */
6289#ifdef EASTEUROPE_CHARSET
6290 case EASTEUROPE_CHARSET:
6291 charset_type = Qw32_charset_easteurope;
6292 break;
6293 case TURKISH_CHARSET:
6294 charset_type = Qw32_charset_turkish;
6295 break;
6296 case BALTIC_CHARSET:
6297 charset_type = Qw32_charset_baltic;
6298 break;
6299 case RUSSIAN_CHARSET:
6300 charset_type = Qw32_charset_russian;
6301 break;
6302 case ARABIC_CHARSET:
6303 charset_type = Qw32_charset_arabic;
6304 break;
6305 case GREEK_CHARSET:
6306 charset_type = Qw32_charset_greek;
6307 break;
6308 case HEBREW_CHARSET:
6309 charset_type = Qw32_charset_hebrew;
6310 break;
6311 case VIETNAMESE_CHARSET:
6312 charset_type = Qw32_charset_vietnamese;
6313 break;
6314 case THAI_CHARSET:
6315 charset_type = Qw32_charset_thai;
6316 break;
6317 case MAC_CHARSET:
6318 charset_type = Qw32_charset_mac;
6319 break;
6320 case JOHAB_CHARSET:
6321 charset_type = Qw32_charset_johab;
6322 break;
6323#endif
6324
6325#ifdef UNICODE_CHARSET
6326 case UNICODE_CHARSET:
6327 charset_type = Qw32_charset_unicode;
6328 break;
6329#endif
6330 default:
6331 /* Encode numerical value of unknown charset. */
6332 sprintf (buf, "*-#%u", fncharset);
6333 return buf;
6334 }
6335
6336 {
6337 Lisp_Object rest;
6338 char * best_match = NULL;
6339
6340 /* Look through w32-charset-info-alist for the character set.
6341 Prefer ISO codepages, and prefer lower numbers in the ISO
6342 range. Only return charsets for codepages which are installed.
6343
6344 Format of each entry is
6345 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6346 */
6347 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6348 {
6349 char * x_charset;
6350 Lisp_Object w32_charset;
6351 Lisp_Object codepage;
6352
6353 Lisp_Object this_entry = XCAR (rest);
6354
6355 /* Skip invalid entries in alist. */
6356 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6357 || !CONSP (XCDR (this_entry))
6358 || !SYMBOLP (XCAR (XCDR (this_entry))))
6359 continue;
6360
6361 x_charset = SDATA (XCAR (this_entry));
6362 w32_charset = XCAR (XCDR (this_entry));
6363 codepage = XCDR (XCDR (this_entry));
6364
6365 /* Look for Same charset and a valid codepage (or non-int
6366 which means ignore). */
6367 if (w32_charset == charset_type
6368 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6369 || IsValidCodePage (XINT (codepage))))
6370 {
6371 /* If we don't have a match already, then this is the
6372 best. */
6373 if (!best_match)
6374 best_match = x_charset;
6375 /* If this is an ISO codepage, and the best so far isn't,
6376 then this is better. */
6377 else if (strnicmp (best_match, "iso", 3) != 0
6378 && strnicmp (x_charset, "iso", 3) == 0)
6379 best_match = x_charset;
6380 /* If both are ISO8859 codepages, choose the one with the
6381 lowest number in the encoding field. */
6382 else if (strnicmp (best_match, "iso8859-", 8) == 0
6383 && strnicmp (x_charset, "iso8859-", 8) == 0)
6384 {
6385 int best_enc = atoi (best_match + 8);
6386 int this_enc = atoi (x_charset + 8);
6387 if (this_enc > 0 && this_enc < best_enc)
6388 best_match = x_charset;
6389 }
6390 }
6391 }
6392
6393 /* If no match, encode the numeric value. */
6394 if (!best_match)
6395 {
6396 sprintf (buf, "*-#%u", fncharset);
6397 return buf;
6398 }
6399
6400 strncpy(buf, best_match, 31);
6401 buf[31] = '\0';
6402 return buf;
6403 }
6404}
6405
6406
6407/* Return all the X charsets that map to a font. */
6408static Lisp_Object
6409w32_to_all_x_charsets (fncharset)
6410 int fncharset;
6411{
6412 static char buf[32];
6413 Lisp_Object charset_type;
6414 Lisp_Object retval = Qnil;
6415
6416 switch (fncharset)
6417 {
6418 case ANSI_CHARSET:
6419 /* Handle startup case of w32-charset-info-alist not
6420 being set up yet. */
6421 if (NILP(Vw32_charset_info_alist))
6422 return Fcons (build_string ("iso8859-1"), Qnil);
6423
6424 charset_type = Qw32_charset_ansi;
6425 break;
6426 case DEFAULT_CHARSET:
6427 charset_type = Qw32_charset_default;
6428 break;
6429 case SYMBOL_CHARSET:
6430 charset_type = Qw32_charset_symbol;
6431 break;
6432 case SHIFTJIS_CHARSET:
6433 charset_type = Qw32_charset_shiftjis;
6434 break;
6435 case HANGEUL_CHARSET:
6436 charset_type = Qw32_charset_hangeul;
6437 break;
6438 case GB2312_CHARSET:
6439 charset_type = Qw32_charset_gb2312;
6440 break;
6441 case CHINESEBIG5_CHARSET:
6442 charset_type = Qw32_charset_chinesebig5;
6443 break;
6444 case OEM_CHARSET:
6445 charset_type = Qw32_charset_oem;
6446 break;
6447
6448 /* More recent versions of Windows (95 and NT4.0) define more
6449 character sets. */
6450#ifdef EASTEUROPE_CHARSET
6451 case EASTEUROPE_CHARSET:
6452 charset_type = Qw32_charset_easteurope;
6453 break;
6454 case TURKISH_CHARSET:
6455 charset_type = Qw32_charset_turkish;
6456 break;
6457 case BALTIC_CHARSET:
6458 charset_type = Qw32_charset_baltic;
6459 break;
6460 case RUSSIAN_CHARSET:
6461 charset_type = Qw32_charset_russian;
6462 break;
6463 case ARABIC_CHARSET:
6464 charset_type = Qw32_charset_arabic;
6465 break;
6466 case GREEK_CHARSET:
6467 charset_type = Qw32_charset_greek;
6468 break;
6469 case HEBREW_CHARSET:
6470 charset_type = Qw32_charset_hebrew;
6471 break;
6472 case VIETNAMESE_CHARSET:
6473 charset_type = Qw32_charset_vietnamese;
6474 break;
6475 case THAI_CHARSET:
6476 charset_type = Qw32_charset_thai;
6477 break;
6478 case MAC_CHARSET:
6479 charset_type = Qw32_charset_mac;
6480 break;
6481 case JOHAB_CHARSET:
6482 charset_type = Qw32_charset_johab;
6483 break;
6484#endif
6485
6486#ifdef UNICODE_CHARSET
6487 case UNICODE_CHARSET:
6488 charset_type = Qw32_charset_unicode;
6489 break;
6490#endif
6491 default:
6492 /* Encode numerical value of unknown charset. */
6493 sprintf (buf, "*-#%u", fncharset);
6494 return Fcons (build_string (buf), Qnil);
6495 }
6496
6497 {
6498 Lisp_Object rest;
6499 /* Look through w32-charset-info-alist for the character set.
6500 Only return charsets for codepages which are installed.
6501
6502 Format of each entry in Vw32_charset_info_alist is
6503 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
6504 */
6505 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6506 {
6507 Lisp_Object x_charset;
6508 Lisp_Object w32_charset;
6509 Lisp_Object codepage;
6510
6511 Lisp_Object this_entry = XCAR (rest);
6512
6513 /* Skip invalid entries in alist. */
6514 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
6515 || !CONSP (XCDR (this_entry))
6516 || !SYMBOLP (XCAR (XCDR (this_entry))))
6517 continue;
6518
6519 x_charset = XCAR (this_entry);
6520 w32_charset = XCAR (XCDR (this_entry));
6521 codepage = XCDR (XCDR (this_entry));
6522
6523 /* Look for Same charset and a valid codepage (or non-int
6524 which means ignore). */
6525 if (w32_charset == charset_type
6526 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
6527 || IsValidCodePage (XINT (codepage))))
6528 {
6529 retval = Fcons (x_charset, retval);
6530 }
6531 }
6532
6533 /* If no match, encode the numeric value. */
6534 if (NILP (retval))
6535 {
6536 sprintf (buf, "*-#%u", fncharset);
6537 return Fcons (build_string (buf), Qnil);
6538 }
6539
6540 return retval;
6541 }
6542}
6543
6544/* Get the Windows codepage corresponding to the specified font. The
6545 charset info in the font name is used to look up
6546 w32-charset-to-codepage-alist. */
6547int
6548w32_codepage_for_font (char *fontname)
6549{
6550 Lisp_Object codepage, entry;
6551 char *charset_str, *charset, *end;
6552
6553 if (NILP (Vw32_charset_info_alist))
6554 return CP_DEFAULT;
6555
6556 /* Extract charset part of font string. */
6557 charset = xlfd_charset_of_font (fontname);
6558
6559 if (!charset)
6560 return CP_UNKNOWN;
6561
6562 charset_str = (char *) alloca (strlen (charset) + 1);
6563 strcpy (charset_str, charset);
6564
6565#if 0
6566 /* Remove leading "*-". */
6567 if (strncmp ("*-", charset_str, 2) == 0)
6568 charset = charset_str + 2;
6569 else
6570#endif
6571 charset = charset_str;
6572
6573 /* Stop match at wildcard (including preceding '-'). */
6574 if (end = strchr (charset, '*'))
6575 {
6576 if (end > charset && *(end-1) == '-')
6577 end--;
6578 *end = '\0';
6579 }
6580
6581 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
6582 if (NILP (entry))
6583 return CP_UNKNOWN;
6584
6585 codepage = Fcdr (Fcdr (entry));
6586
6587 if (NILP (codepage))
6588 return CP_8BIT;
6589 else if (XFASTINT (codepage) == XFASTINT (Qt))
6590 return CP_UNICODE;
6591 else if (INTEGERP (codepage))
6592 return XINT (codepage);
6593 else
6594 return CP_UNKNOWN;
6595}
6596
6597
6598static BOOL
6599w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
6600 LOGFONT * lplogfont;
6601 char * lpxstr;
6602 int len;
6603 char * specific_charset;
6604{
6605 char* fonttype;
6606 char *fontname;
6607 char height_pixels[8];
6608 char height_dpi[8];
6609 char width_pixels[8];
6610 char *fontname_dash;
6611 int display_resy = (int) one_w32_display_info.resy;
6612 int display_resx = (int) one_w32_display_info.resx;
6613 int bufsz;
6614 struct coding_system coding;
6615
6616 if (!lpxstr) abort ();
6617
6618 if (!lplogfont)
6619 return FALSE;
6620
6621 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
6622 fonttype = "raster";
6623 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
6624 fonttype = "outline";
6625 else
6626 fonttype = "unknown";
6627
6628 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
6629 &coding);
6630 coding.src_multibyte = 0;
6631 coding.dst_multibyte = 1;
6632 coding.mode |= CODING_MODE_LAST_BLOCK;
6633 /* We explicitely disable composition handling because selection
6634 data should not contain any composition sequence. */
6635 coding.composing = COMPOSITION_DISABLED;
6636 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
6637
6638 fontname = alloca(sizeof(*fontname) * bufsz);
6639 decode_coding (&coding, lplogfont->lfFaceName, fontname,
6640 strlen(lplogfont->lfFaceName), bufsz - 1);
6641 *(fontname + coding.produced) = '\0';
6642
6643 /* Replace dashes with underscores so the dashes are not
6644 misinterpreted. */
6645 fontname_dash = fontname;
6646 while (fontname_dash = strchr (fontname_dash, '-'))
6647 *fontname_dash = '_';
6648
6649 if (lplogfont->lfHeight)
6650 {
6651 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
6652 sprintf (height_dpi, "%u",
6653 abs (lplogfont->lfHeight) * 720 / display_resy);
6654 }
6655 else
6656 {
6657 strcpy (height_pixels, "*");
6658 strcpy (height_dpi, "*");
6659 }
6660 if (lplogfont->lfWidth)
6661 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
6662 else
6663 strcpy (width_pixels, "*");
6664
6665 _snprintf (lpxstr, len - 1,
6666 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
6667 fonttype, /* foundry */
6668 fontname, /* family */
6669 w32_to_x_weight (lplogfont->lfWeight), /* weight */
6670 lplogfont->lfItalic?'i':'r', /* slant */
6671 /* setwidth name */
6672 /* add style name */
6673 height_pixels, /* pixel size */
6674 height_dpi, /* point size */
6675 display_resx, /* resx */
6676 display_resy, /* resy */
6677 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
6678 ? 'p' : 'c', /* spacing */
6679 width_pixels, /* avg width */
6680 specific_charset ? specific_charset
6681 : w32_to_x_charset (lplogfont->lfCharSet)
6682 /* charset registry and encoding */
6683 );
6684
6685 lpxstr[len - 1] = 0; /* just to be sure */
6686 return (TRUE);
6687}
6688
6689static BOOL
6690x_to_w32_font (lpxstr, lplogfont)
6691 char * lpxstr;
6692 LOGFONT * lplogfont;
6693{
6694 struct coding_system coding;
6695
6696 if (!lplogfont) return (FALSE);
6697
6698 memset (lplogfont, 0, sizeof (*lplogfont));
6699
6700 /* Set default value for each field. */
6701#if 1
6702 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
6703 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
6704 lplogfont->lfQuality = DEFAULT_QUALITY;
6705#else
6706 /* go for maximum quality */
6707 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
6708 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
6709 lplogfont->lfQuality = PROOF_QUALITY;
6710#endif
6711
6712 lplogfont->lfCharSet = DEFAULT_CHARSET;
6713 lplogfont->lfWeight = FW_DONTCARE;
6714 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
6715
6716 if (!lpxstr)
6717 return FALSE;
6718
6719 /* Provide a simple escape mechanism for specifying Windows font names
6720 * directly -- if font spec does not beginning with '-', assume this
6721 * format:
6722 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
6723 */
6724
6725 if (*lpxstr == '-')
6726 {
6727 int fields, tem;
6728 char name[50], weight[20], slant, pitch, pixels[10], height[10],
6729 width[10], resy[10], remainder[50];
6730 char * encoding;
6731 int dpi = (int) one_w32_display_info.resy;
6732
6733 fields = sscanf (lpxstr,
6734 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
6735 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
6736 if (fields == EOF)
6737 return (FALSE);
6738
6739 /* In the general case when wildcards cover more than one field,
6740 we don't know which field is which, so don't fill any in.
6741 However, we need to cope with this particular form, which is
6742 generated by font_list_1 (invoked by try_font_list):
6743 "-raster-6x10-*-gb2312*-*"
6744 and make sure to correctly parse the charset field. */
6745 if (fields == 3)
6746 {
6747 fields = sscanf (lpxstr,
6748 "-%*[^-]-%49[^-]-*-%49s",
6749 name, remainder);
6750 }
6751 else if (fields < 9)
6752 {
6753 fields = 0;
6754 remainder[0] = 0;
6755 }
6756
6757 if (fields > 0 && name[0] != '*')
6758 {
6759 int bufsize;
6760 unsigned char *buf;
6761
6762 setup_coding_system
6763 (Fcheck_coding_system (Vlocale_coding_system), &coding);
6764 coding.src_multibyte = 1;
6765 coding.dst_multibyte = 1;
6766 bufsize = encoding_buffer_size (&coding, strlen (name));
6767 buf = (unsigned char *) alloca (bufsize);
6768 coding.mode |= CODING_MODE_LAST_BLOCK;
6769 encode_coding (&coding, name, buf, strlen (name), bufsize);
6770 if (coding.produced >= LF_FACESIZE)
6771 coding.produced = LF_FACESIZE - 1;
6772 buf[coding.produced] = 0;
6773 strcpy (lplogfont->lfFaceName, buf);
6774 }
6775 else
6776 {
6777 lplogfont->lfFaceName[0] = '\0';
6778 }
6779
6780 fields--;
6781
6782 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6783
6784 fields--;
6785
6786 lplogfont->lfItalic = (fields > 0 && slant == 'i');
6787
6788 fields--;
6789
6790 if (fields > 0 && pixels[0] != '*')
6791 lplogfont->lfHeight = atoi (pixels);
6792
6793 fields--;
6794 fields--;
6795 if (fields > 0 && resy[0] != '*')
6796 {
6797 tem = atoi (resy);
6798 if (tem > 0) dpi = tem;
6799 }
6800
6801 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
6802 lplogfont->lfHeight = atoi (height) * dpi / 720;
6803
6804 if (fields > 0)
6805 lplogfont->lfPitchAndFamily =
6806 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
6807
6808 fields--;
6809
6810 if (fields > 0 && width[0] != '*')
6811 lplogfont->lfWidth = atoi (width) / 10;
6812
6813 fields--;
6814
6815 /* Strip the trailing '-' if present. (it shouldn't be, as it
6816 fails the test against xlfd-tight-regexp in fontset.el). */
6817 {
6818 int len = strlen (remainder);
6819 if (len > 0 && remainder[len-1] == '-')
6820 remainder[len-1] = 0;
6821 }
6822 encoding = remainder;
6823#if 0
6824 if (strncmp (encoding, "*-", 2) == 0)
6825 encoding += 2;
6826#endif
6827 lplogfont->lfCharSet = x_to_w32_charset (encoding);
6828 }
6829 else
6830 {
6831 int fields;
6832 char name[100], height[10], width[10], weight[20];
6833
6834 fields = sscanf (lpxstr,
6835 "%99[^:]:%9[^:]:%9[^:]:%19s",
6836 name, height, width, weight);
6837
6838 if (fields == EOF) return (FALSE);
6839
6840 if (fields > 0)
6841 {
6842 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
6843 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
6844 }
6845 else
6846 {
6847 lplogfont->lfFaceName[0] = 0;
6848 }
6849
6850 fields--;
6851
6852 if (fields > 0)
6853 lplogfont->lfHeight = atoi (height);
6854
6855 fields--;
6856
6857 if (fields > 0)
6858 lplogfont->lfWidth = atoi (width);
6859
6860 fields--;
6861
6862 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
6863 }
6864
6865 /* This makes TrueType fonts work better. */
6866 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6867
6868 return (TRUE);
6869}
6870
6871/* Strip the pixel height and point height from the given xlfd, and
6872 return the pixel height. If no pixel height is specified, calculate
6873 one from the point height, or if that isn't defined either, return
6874 0 (which usually signifies a scalable font).
6875*/
6876static int
6877xlfd_strip_height (char *fontname)
6878{
6879 int pixel_height, field_number;
6880 char *read_from, *write_to;
6881
6882 xassert (fontname);
6883
6884 pixel_height = field_number = 0;
6885 write_to = NULL;
6886
6887 /* Look for height fields. */
6888 for (read_from = fontname; *read_from; read_from++)
6889 {
6890 if (*read_from == '-')
6891 {
6892 field_number++;
6893 if (field_number == 7) /* Pixel height. */
6894 {
6895 read_from++;
6896 write_to = read_from;
6897
6898 /* Find end of field. */
6899 for (;*read_from && *read_from != '-'; read_from++)
6900 ;
6901
6902 /* Split the fontname at end of field. */
6903 if (*read_from)
6904 {
6905 *read_from = '\0';
6906 read_from++;
6907 }
6908 pixel_height = atoi (write_to);
6909 /* Blank out field. */
6910 if (read_from > write_to)
6911 {
6912 *write_to = '-';
6913 write_to++;
6914 }
6915 /* If the pixel height field is at the end (partial xlfd),
6916 return now. */
6917 else
6918 return pixel_height;
6919
6920 /* If we got a pixel height, the point height can be
6921 ignored. Just blank it out and break now. */
6922 if (pixel_height)
6923 {
6924 /* Find end of point size field. */
6925 for (; *read_from && *read_from != '-'; read_from++)
6926 ;
6927
6928 if (*read_from)
6929 read_from++;
6930
6931 /* Blank out the point size field. */
6932 if (read_from > write_to)
6933 {
6934 *write_to = '-';
6935 write_to++;
6936 }
6937 else
6938 return pixel_height;
6939
6940 break;
6941 }
6942 /* If the point height is already blank, break now. */
6943 if (*read_from == '-')
6944 {
6945 read_from++;
6946 break;
6947 }
6948 }
6949 else if (field_number == 8)
6950 {
6951 /* If we didn't get a pixel height, try to get the point
6952 height and convert that. */
6953 int point_size;
6954 char *point_size_start = read_from++;
6955
6956 /* Find end of field. */
6957 for (; *read_from && *read_from != '-'; read_from++)
6958 ;
6959
6960 if (*read_from)
6961 {
6962 *read_from = '\0';
6963 read_from++;
6964 }
6965
6966 point_size = atoi (point_size_start);
6967
6968 /* Convert to pixel height. */
6969 pixel_height = point_size
6970 * one_w32_display_info.height_in / 720;
6971
6972 /* Blank out this field and break. */
6973 *write_to = '-';
6974 write_to++;
6975 break;
6976 }
6977 }
6978 }
6979
6980 /* Shift the rest of the font spec into place. */
6981 if (write_to && read_from > write_to)
6982 {
6983 for (; *read_from; read_from++, write_to++)
6984 *write_to = *read_from;
6985 *write_to = '\0';
6986 }
6987
6988 return pixel_height;
6989}
6990
6991/* Assume parameter 1 is fully qualified, no wildcards. */
6992static BOOL
6993w32_font_match (fontname, pattern)
6994 char * fontname;
6995 char * pattern;
6996{
6997 char *regex = alloca (strlen (pattern) * 2 + 3);
6998 char *font_name_copy = alloca (strlen (fontname) + 1);
6999 char *ptr;
7000
7001 /* Copy fontname so we can modify it during comparison. */
7002 strcpy (font_name_copy, fontname);
7003
7004 ptr = regex;
7005 *ptr++ = '^';
7006
7007 /* Turn pattern into a regexp and do a regexp match. */
7008 for (; *pattern; pattern++)
7009 {
7010 if (*pattern == '?')
7011 *ptr++ = '.';
7012 else if (*pattern == '*')
7013 {
7014 *ptr++ = '.';
7015 *ptr++ = '*';
7016 }
7017 else
7018 *ptr++ = *pattern;
7019 }
7020 *ptr = '$';
7021 *(ptr + 1) = '\0';
7022
7023 /* Strip out font heights and compare them seperately, since
7024 rounding error can cause mismatches. This also allows a
7025 comparison between a font that declares only a pixel height and a
7026 pattern that declares the point height.
7027 */
7028 {
7029 int font_height, pattern_height;
7030
7031 font_height = xlfd_strip_height (font_name_copy);
7032 pattern_height = xlfd_strip_height (regex);
7033
7034 /* Compare now, and don't bother doing expensive regexp matching
7035 if the heights differ. */
7036 if (font_height && pattern_height && (font_height != pattern_height))
7037 return FALSE;
7038 }
7039
7040 return (fast_c_string_match_ignore_case (build_string (regex),
7041 font_name_copy) >= 0);
7042}
7043
7044/* Callback functions, and a structure holding info they need, for
7045 listing system fonts on W32. We need one set of functions to do the
7046 job properly, but these don't work on NT 3.51 and earlier, so we
7047 have a second set which don't handle character sets properly to
7048 fall back on.
7049
7050 In both cases, there are two passes made. The first pass gets one
7051 font from each family, the second pass lists all the fonts from
7052 each family. */
7053
7054typedef struct enumfont_t
7055{
7056 HDC hdc;
7057 int numFonts;
7058 LOGFONT logfont;
7059 XFontStruct *size_ref;
7060 Lisp_Object pattern;
7061 Lisp_Object list;
7062} enumfont_t;
7063
7064
7065static void
7066enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
7067
7068
7069static int CALLBACK
7070enum_font_cb2 (lplf, lptm, FontType, lpef)
7071 ENUMLOGFONT * lplf;
7072 NEWTEXTMETRIC * lptm;
7073 int FontType;
7074 enumfont_t * lpef;
7075{
7076 /* Ignore struck out and underlined versions of fonts. */
7077 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
7078 return 1;
7079
7080 /* Only return fonts with names starting with @ if they were
7081 explicitly specified, since Microsoft uses an initial @ to
7082 denote fonts for vertical writing, without providing a more
7083 convenient way of identifying them. */
7084 if (lplf->elfLogFont.lfFaceName[0] == '@'
7085 && lpef->logfont.lfFaceName[0] != '@')
7086 return 1;
7087
7088 /* Check that the character set matches if it was specified */
7089 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
7090 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
7091 return 1;
7092
7093 if (FontType == RASTER_FONTTYPE)
7094 {
7095 /* DBCS raster fonts have problems displaying, so skip them. */
7096 int charset = lplf->elfLogFont.lfCharSet;
7097 if (charset == SHIFTJIS_CHARSET
7098 || charset == HANGEUL_CHARSET
7099 || charset == CHINESEBIG5_CHARSET
7100 || charset == GB2312_CHARSET
7101#ifdef JOHAB_CHARSET
7102 || charset == JOHAB_CHARSET
7103#endif
7104 )
7105 return 1;
7106 }
7107
7108 {
7109 char buf[100];
7110 Lisp_Object width = Qnil;
7111 Lisp_Object charset_list = Qnil;
7112 char *charset = NULL;
7113
7114 /* Truetype fonts do not report their true metrics until loaded */
7115 if (FontType != RASTER_FONTTYPE)
7116 {
7117 if (!NILP (lpef->pattern))
7118 {
7119 /* Scalable fonts are as big as you want them to be. */
7120 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
7121 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
7122 width = make_number (lpef->logfont.lfWidth);
7123 }
7124 else
7125 {
7126 lplf->elfLogFont.lfHeight = 0;
7127 lplf->elfLogFont.lfWidth = 0;
7128 }
7129 }
7130
7131 /* Make sure the height used here is the same as everywhere
7132 else (ie character height, not cell height). */
7133 if (lplf->elfLogFont.lfHeight > 0)
7134 {
7135 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
7136 if (FontType == RASTER_FONTTYPE)
7137 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
7138 else
7139 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
7140 }
7141
7142 if (!NILP (lpef->pattern))
7143 {
7144 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
7145
7146 /* We already checked charsets above, but DEFAULT_CHARSET
7147 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
7148 if (charset
7149 && strncmp (charset, "*-*", 3) != 0
7150 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
7151 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
7152 return 1;
7153 }
7154
7155 if (charset)
7156 charset_list = Fcons (build_string (charset), Qnil);
7157 else
7158 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
7159
7160 /* Loop through the charsets. */
7161 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
7162 {
7163 Lisp_Object this_charset = Fcar (charset_list);
7164 charset = SDATA (this_charset);
7165
7166 /* List bold and italic variations if w32-enable-synthesized-fonts
7167 is non-nil and this is a plain font. */
7168 if (w32_enable_synthesized_fonts
7169 && lplf->elfLogFont.lfWeight == FW_NORMAL
7170 && lplf->elfLogFont.lfItalic == FALSE)
7171 {
7172 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7173 charset, width);
7174 /* bold. */
7175 lplf->elfLogFont.lfWeight = FW_BOLD;
7176 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7177 charset, width);
7178 /* bold italic. */
7179 lplf->elfLogFont.lfItalic = TRUE;
7180 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7181 charset, width);
7182 /* italic. */
7183 lplf->elfLogFont.lfWeight = FW_NORMAL;
7184 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7185 charset, width);
7186 }
7187 else
7188 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
7189 charset, width);
7190 }
7191 }
7192
7193 return 1;
7194}
7195
7196static void
7197enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
7198 enumfont_t * lpef;
7199 LOGFONT * logfont;
7200 char * match_charset;
7201 Lisp_Object width;
7202{
7203 char buf[100];
7204
7205 if (!w32_to_x_font (logfont, buf, 100, match_charset))
7206 return;
7207
7208 if (NILP (lpef->pattern)
7209 || w32_font_match (buf, SDATA (lpef->pattern)))
7210 {
7211 /* Check if we already listed this font. This may happen if
7212 w32_enable_synthesized_fonts is non-nil, and there are real
7213 bold and italic versions of the font. */
7214 Lisp_Object font_name = build_string (buf);
7215 if (NILP (Fmember (font_name, lpef->list)))
7216 {
7217 Lisp_Object entry = Fcons (font_name, width);
7218 lpef->list = Fcons (entry, lpef->list);
7219 lpef->numFonts++;
7220 }
7221 }
7222}
7223
7224
7225static int CALLBACK
7226enum_font_cb1 (lplf, lptm, FontType, lpef)
7227 ENUMLOGFONT * lplf;
7228 NEWTEXTMETRIC * lptm;
7229 int FontType;
7230 enumfont_t * lpef;
7231{
7232 return EnumFontFamilies (lpef->hdc,
7233 lplf->elfLogFont.lfFaceName,
7234 (FONTENUMPROC) enum_font_cb2,
7235 (LPARAM) lpef);
7236}
7237
7238
7239static int CALLBACK
7240enum_fontex_cb2 (lplf, lptm, font_type, lpef)
7241 ENUMLOGFONTEX * lplf;
7242 NEWTEXTMETRICEX * lptm;
7243 int font_type;
7244 enumfont_t * lpef;
7245{
7246 /* We are not interested in the extra info we get back from the 'Ex
7247 version - only the fact that we get character set variations
7248 enumerated seperately. */
7249 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
7250 font_type, lpef);
7251}
7252
7253static int CALLBACK
7254enum_fontex_cb1 (lplf, lptm, font_type, lpef)
7255 ENUMLOGFONTEX * lplf;
7256 NEWTEXTMETRICEX * lptm;
7257 int font_type;
7258 enumfont_t * lpef;
7259{
7260 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7261 FARPROC enum_font_families_ex
7262 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7263 /* We don't really expect EnumFontFamiliesEx to disappear once we
7264 get here, so don't bother handling it gracefully. */
7265 if (enum_font_families_ex == NULL)
7266 error ("gdi32.dll has disappeared!");
7267 return enum_font_families_ex (lpef->hdc,
7268 &lplf->elfLogFont,
7269 (FONTENUMPROC) enum_fontex_cb2,
7270 (LPARAM) lpef, 0);
7271}
7272
7273/* Interface to fontset handler. (adapted from mw32font.c in Meadow
7274 and xterm.c in Emacs 20.3) */
7275
7276static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
7277{
7278 char *fontname, *ptnstr;
7279 Lisp_Object list, tem, newlist = Qnil;
7280 int n_fonts = 0;
7281
7282 list = Vw32_bdf_filename_alist;
7283 ptnstr = SDATA (pattern);
7284
7285 for ( ; CONSP (list); list = XCDR (list))
7286 {
7287 tem = XCAR (list);
7288 if (CONSP (tem))
7289 fontname = SDATA (XCAR (tem));
7290 else if (STRINGP (tem))
7291 fontname = SDATA (tem);
7292 else
7293 continue;
7294
7295 if (w32_font_match (fontname, ptnstr))
7296 {
7297 newlist = Fcons (XCAR (tem), newlist);
7298 n_fonts++;
7299 if (n_fonts >= max_names)
7300 break;
7301 }
7302 }
7303
7304 return newlist;
7305}
7306
7307
7308/* Return a list of names of available fonts matching PATTERN on frame
7309 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
7310 to be listed. Frame F NULL means we have not yet created any
7311 frame, which means we can't get proper size info, as we don't have
7312 a device context to use for GetTextMetrics.
7313 MAXNAMES sets a limit on how many fonts to match. */
7314
7315Lisp_Object
7316w32_list_fonts (f, pattern, size, maxnames)
7317 struct frame *f;
7318 Lisp_Object pattern;
7319 int size;
7320 int maxnames;
7321{
7322 Lisp_Object patterns, key = Qnil, tem, tpat;
7323 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
7324 struct w32_display_info *dpyinfo = &one_w32_display_info;
7325 int n_fonts = 0;
7326
7327 patterns = Fassoc (pattern, Valternate_fontname_alist);
7328 if (NILP (patterns))
7329 patterns = Fcons (pattern, Qnil);
7330
7331 for (; CONSP (patterns); patterns = XCDR (patterns))
7332 {
7333 enumfont_t ef;
7334 int codepage;
7335
7336 tpat = XCAR (patterns);
7337
7338 if (!STRINGP (tpat))
7339 continue;
7340
7341 /* Avoid expensive EnumFontFamilies functions if we are not
7342 going to be able to output one of these anyway. */
7343 codepage = w32_codepage_for_font (SDATA (tpat));
7344 if (codepage != CP_8BIT && codepage != CP_UNICODE
7345 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
7346 && !IsValidCodePage(codepage))
7347 continue;
7348
7349 /* See if we cached the result for this particular query.
7350 The cache is an alist of the form:
7351 ((PATTERN (FONTNAME . WIDTH) ...) ...)
7352 */
7353 if (tem = XCDR (dpyinfo->name_list_element),
7354 !NILP (list = Fassoc (tpat, tem)))
7355 {
7356 list = Fcdr_safe (list);
7357 /* We have a cached list. Don't have to get the list again. */
7358 goto label_cached;
7359 }
7360
7361 BLOCK_INPUT;
7362 /* At first, put PATTERN in the cache. */
7363 ef.pattern = tpat;
7364 ef.list = Qnil;
7365 ef.numFonts = 0;
7366
7367 /* Use EnumFontFamiliesEx where it is available, as it knows
7368 about character sets. Fall back to EnumFontFamilies for
7369 older versions of NT that don't support the 'Ex function. */
7370 x_to_w32_font (SDATA (tpat), &ef.logfont);
7371 {
7372 LOGFONT font_match_pattern;
7373 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
7374 FARPROC enum_font_families_ex
7375 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
7376
7377 /* We do our own pattern matching so we can handle wildcards. */
7378 font_match_pattern.lfFaceName[0] = 0;
7379 font_match_pattern.lfPitchAndFamily = 0;
7380 /* We can use the charset, because if it is a wildcard it will
7381 be DEFAULT_CHARSET anyway. */
7382 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
7383
7384 ef.hdc = GetDC (dpyinfo->root_window);
7385
7386 if (enum_font_families_ex)
7387 enum_font_families_ex (ef.hdc,
7388 &font_match_pattern,
7389 (FONTENUMPROC) enum_fontex_cb1,
7390 (LPARAM) &ef, 0);
7391 else
7392 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
7393 (LPARAM)&ef);
7394
7395 ReleaseDC (dpyinfo->root_window, ef.hdc);
7396 }
7397
7398 UNBLOCK_INPUT;
7399 list = ef.list;
7400
7401 /* Make a list of the fonts we got back.
7402 Store that in the font cache for the display. */
7403 XSETCDR (dpyinfo->name_list_element,
7404 Fcons (Fcons (tpat, list),
7405 XCDR (dpyinfo->name_list_element)));
7406
7407 label_cached:
7408 if (NILP (list)) continue; /* Try the remaining alternatives. */
7409
7410 newlist = second_best = Qnil;
7411
7412 /* Make a list of the fonts that have the right width. */
7413 for (; CONSP (list); list = XCDR (list))
7414 {
7415 int found_size;
7416 tem = XCAR (list);
7417
7418 if (!CONSP (tem))
7419 continue;
7420 if (NILP (XCAR (tem)))
7421 continue;
7422 if (!size)
7423 {
7424 newlist = Fcons (XCAR (tem), newlist);
7425 n_fonts++;
7426 if (n_fonts >= maxnames)
7427 break;
7428 else
7429 continue;
7430 }
7431 if (!INTEGERP (XCDR (tem)))
7432 {
7433 /* Since we don't yet know the size of the font, we must
7434 load it and try GetTextMetrics. */
7435 W32FontStruct thisinfo;
7436 LOGFONT lf;
7437 HDC hdc;
7438 HANDLE oldobj;
7439
7440 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
7441 continue;
7442
7443 BLOCK_INPUT;
7444 thisinfo.bdf = NULL;
7445 thisinfo.hfont = CreateFontIndirect (&lf);
7446 if (thisinfo.hfont == NULL)
7447 continue;
7448
7449 hdc = GetDC (dpyinfo->root_window);
7450 oldobj = SelectObject (hdc, thisinfo.hfont);
7451 if (GetTextMetrics (hdc, &thisinfo.tm))
7452 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
7453 else
7454 XSETCDR (tem, make_number (0));
7455 SelectObject (hdc, oldobj);
7456 ReleaseDC (dpyinfo->root_window, hdc);
7457 DeleteObject(thisinfo.hfont);
7458 UNBLOCK_INPUT;
7459 }
7460 found_size = XINT (XCDR (tem));
7461 if (found_size == size)
7462 {
7463 newlist = Fcons (XCAR (tem), newlist);
7464 n_fonts++;
7465 if (n_fonts >= maxnames)
7466 break;
7467 }
7468 /* keep track of the closest matching size in case
7469 no exact match is found. */
7470 else if (found_size > 0)
7471 {
7472 if (NILP (second_best))
7473 second_best = tem;
7474
7475 else if (found_size < size)
7476 {
7477 if (XINT (XCDR (second_best)) > size
7478 || XINT (XCDR (second_best)) < found_size)
7479 second_best = tem;
7480 }
7481 else
7482 {
7483 if (XINT (XCDR (second_best)) > size
7484 && XINT (XCDR (second_best)) >
7485 found_size)
7486 second_best = tem;
7487 }
7488 }
7489 }
7490
7491 if (!NILP (newlist))
7492 break;
7493 else if (!NILP (second_best))
7494 {
7495 newlist = Fcons (XCAR (second_best), Qnil);
7496 break;
7497 }
7498 }
7499
7500 /* Include any bdf fonts. */
7501 if (n_fonts < maxnames)
7502 {
7503 Lisp_Object combined[2];
7504 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
7505 combined[1] = newlist;
7506 newlist = Fnconc(2, combined);
7507 }
7508
7509 return newlist;
7510}
7511
7512
7513/* Return a pointer to struct font_info of font FONT_IDX of frame F. */
7514struct font_info *
7515w32_get_font_info (f, font_idx)
7516 FRAME_PTR f;
7517 int font_idx;
7518{
7519 return (FRAME_W32_FONT_TABLE (f) + font_idx);
7520}
7521
7522
7523struct font_info*
7524w32_query_font (struct frame *f, char *fontname)
7525{
7526 int i;
7527 struct font_info *pfi;
7528
7529 pfi = FRAME_W32_FONT_TABLE (f);
7530
7531 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
7532 {
7533 if (strcmp(pfi->name, fontname) == 0) return pfi;
7534 }
7535
7536 return NULL;
7537}
7538
7539/* Find a CCL program for a font specified by FONTP, and set the member
7540 `encoder' of the structure. */
7541
7542void
7543w32_find_ccl_program (fontp)
7544 struct font_info *fontp;
7545{
7546 Lisp_Object list, elt;
7547
7548 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7549 {
7550 elt = XCAR (list);
7551 if (CONSP (elt)
7552 && STRINGP (XCAR (elt))
7553 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7554 >= 0))
7555 break;
7556 }
7557 if (! NILP (list))
7558 {
7559 struct ccl_program *ccl
7560 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7561
7562 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7563 xfree (ccl);
7564 else
7565 fontp->font_encoder = ccl;
7566 }
7567}
7568
7569\f
7570/* Find BDF files in a specified directory. (use GCPRO when calling,
7571 as this calls lisp to get a directory listing). */
7572static Lisp_Object
7573w32_find_bdf_fonts_in_dir (Lisp_Object directory)
7574{
7575 Lisp_Object filelist, list = Qnil;
7576 char fontname[100];
7577
7578 if (!STRINGP(directory))
7579 return Qnil;
7580
7581 filelist = Fdirectory_files (directory, Qt,
7582 build_string (".*\\.[bB][dD][fF]"), Qt);
7583
7584 for ( ; CONSP(filelist); filelist = XCDR (filelist))
7585 {
7586 Lisp_Object filename = XCAR (filelist);
7587 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
7588 store_in_alist (&list, build_string (fontname), filename);
7589 }
7590 return list;
7591}
7592
7593DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
7594 1, 1, 0,
7595 doc: /* Return a list of BDF fonts in DIR.
7596The list is suitable for appending to w32-bdf-filename-alist. Fonts
7597which do not contain an xlfd description will not be included in the
7598list. DIR may be a list of directories. */)
7599 (directory)
7600 Lisp_Object directory;
7601{
7602 Lisp_Object list = Qnil;
7603 struct gcpro gcpro1, gcpro2;
7604
7605 if (!CONSP (directory))
7606 return w32_find_bdf_fonts_in_dir (directory);
7607
7608 for ( ; CONSP (directory); directory = XCDR (directory))
7609 {
7610 Lisp_Object pair[2];
7611 pair[0] = list;
7612 pair[1] = Qnil;
7613 GCPRO2 (directory, list);
7614 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
7615 list = Fnconc( 2, pair );
7616 UNGCPRO;
7617 }
7618 return list;
7619}
7620
7621\f
7622DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
7623 doc: /* Internal function called by `color-defined-p', which see. */)
7624 (color, frame)
7625 Lisp_Object color, frame;
7626{
7627 XColor foo;
7628 FRAME_PTR f = check_x_frame (frame);
7629
7630 CHECK_STRING (color);
7631
7632 if (w32_defined_color (f, SDATA (color), &foo, 0))
7633 return Qt;
7634 else
7635 return Qnil;
7636}
7637
7638DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
7639 doc: /* Internal function called by `color-values', which see. */)
7640 (color, frame)
7641 Lisp_Object color, frame;
7642{
7643 XColor foo;
7644 FRAME_PTR f = check_x_frame (frame);
7645
7646 CHECK_STRING (color);
7647
7648 if (w32_defined_color (f, SDATA (color), &foo, 0))
7649 {
7650 Lisp_Object rgb[3];
7651
7652 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
7653 | GetRValue (foo.pixel));
7654 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
7655 | GetGValue (foo.pixel));
7656 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
7657 | GetBValue (foo.pixel));
7658 return Flist (3, rgb);
7659 }
7660 else
7661 return Qnil;
7662}
7663
7664DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
7665 doc: /* Internal function called by `display-color-p', which see. */)
7666 (display)
7667 Lisp_Object display;
7668{
7669 struct w32_display_info *dpyinfo = check_x_display_info (display);
7670
7671 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
7672 return Qnil;
7673
7674 return Qt;
7675}
7676
7677DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
7678 Sx_display_grayscale_p, 0, 1, 0,
7679 doc: /* Return t if the X display supports shades of gray.
7680Note that color displays do support shades of gray.
7681The optional argument DISPLAY specifies which display to ask about.
7682DISPLAY should be either a frame or a display name (a string).
7683If omitted or nil, that stands for the selected frame's display. */)
7684 (display)
7685 Lisp_Object display;
7686{
7687 struct w32_display_info *dpyinfo = check_x_display_info (display);
7688
7689 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
7690 return Qnil;
7691
7692 return Qt;
7693}
7694
7695DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
7696 Sx_display_pixel_width, 0, 1, 0,
7697 doc: /* Returns the width in pixels of DISPLAY.
7698The optional argument DISPLAY specifies which display to ask about.
7699DISPLAY should be either a frame or a display name (a string).
7700If omitted or nil, that stands for the selected frame's display. */)
7701 (display)
7702 Lisp_Object display;
7703{
7704 struct w32_display_info *dpyinfo = check_x_display_info (display);
7705
7706 return make_number (dpyinfo->width);
7707}
7708
7709DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
7710 Sx_display_pixel_height, 0, 1, 0,
7711 doc: /* Returns the height in pixels of DISPLAY.
7712The optional argument DISPLAY specifies which display to ask about.
7713DISPLAY should be either a frame or a display name (a string).
7714If omitted or nil, that stands for the selected frame's display. */)
7715 (display)
7716 Lisp_Object display;
7717{
7718 struct w32_display_info *dpyinfo = check_x_display_info (display);
7719
7720 return make_number (dpyinfo->height);
7721}
7722
7723DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
7724 0, 1, 0,
7725 doc: /* Returns the number of bitplanes of DISPLAY.
7726The optional argument DISPLAY specifies which display to ask about.
7727DISPLAY should be either a frame or a display name (a string).
7728If omitted or nil, that stands for the selected frame's display. */)
7729 (display)
7730 Lisp_Object display;
7731{
7732 struct w32_display_info *dpyinfo = check_x_display_info (display);
7733
7734 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
7735}
7736
7737DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
7738 0, 1, 0,
7739 doc: /* Returns the number of color cells of DISPLAY.
7740The optional argument DISPLAY specifies which display to ask about.
7741DISPLAY should be either a frame or a display name (a string).
7742If omitted or nil, that stands for the selected frame's display. */)
7743 (display)
7744 Lisp_Object display;
7745{
7746 struct w32_display_info *dpyinfo = check_x_display_info (display);
7747 HDC hdc;
7748 int cap;
7749
7750 hdc = GetDC (dpyinfo->root_window);
7751 if (dpyinfo->has_palette)
7752 cap = GetDeviceCaps (hdc,SIZEPALETTE);
7753 else
7754 cap = GetDeviceCaps (hdc,NUMCOLORS);
7755
7756 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
7757 and because probably is more meaningful on Windows anyway */
7758 if (cap < 0)
7759 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
7760
7761 ReleaseDC (dpyinfo->root_window, hdc);
7762
7763 return make_number (cap);
7764}
7765
7766DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
7767 Sx_server_max_request_size,
7768 0, 1, 0,
7769 doc: /* Returns the maximum request size of the server of DISPLAY.
7770The optional argument DISPLAY specifies which display to ask about.
7771DISPLAY should be either a frame or a display name (a string).
7772If omitted or nil, that stands for the selected frame's display. */)
7773 (display)
7774 Lisp_Object display;
7775{
7776 struct w32_display_info *dpyinfo = check_x_display_info (display);
7777
7778 return make_number (1);
7779}
7780
7781DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
7782 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
7783The optional argument DISPLAY specifies which display to ask about.
7784DISPLAY should be either a frame or a display name (a string).
7785If omitted or nil, that stands for the selected frame's display. */)
7786 (display)
7787 Lisp_Object display;
7788{
7789 return build_string ("Microsoft Corp.");
7790}
7791
7792DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
7793 doc: /* Returns the version numbers of the server of DISPLAY.
7794The value is a list of three integers: the major and minor
7795version numbers, and the vendor-specific release
7796number. See also the function `x-server-vendor'.
7797
7798The optional argument DISPLAY specifies which display to ask about.
7799DISPLAY should be either a frame or a display name (a string).
7800If omitted or nil, that stands for the selected frame's display. */)
7801 (display)
7802 Lisp_Object display;
7803{
7804 return Fcons (make_number (w32_major_version),
7805 Fcons (make_number (w32_minor_version),
7806 Fcons (make_number (w32_build_number), Qnil)));
7807}
7808
7809DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
7810 doc: /* Returns the number of screens on the server of DISPLAY.
7811The optional argument DISPLAY specifies which display to ask about.
7812DISPLAY should be either a frame or a display name (a string).
7813If omitted or nil, that stands for the selected frame's display. */)
7814 (display)
7815 Lisp_Object display;
7816{
7817 return make_number (1);
7818}
7819
7820DEFUN ("x-display-mm-height", Fx_display_mm_height,
7821 Sx_display_mm_height, 0, 1, 0,
7822 doc: /* Returns the height in millimeters of DISPLAY.
7823The optional argument DISPLAY specifies which display to ask about.
7824DISPLAY should be either a frame or a display name (a string).
7825If omitted or nil, that stands for the selected frame's display. */)
7826 (display)
7827 Lisp_Object display;
7828{
7829 struct w32_display_info *dpyinfo = check_x_display_info (display);
7830 HDC hdc;
7831 int cap;
7832
7833 hdc = GetDC (dpyinfo->root_window);
7834
7835 cap = GetDeviceCaps (hdc, VERTSIZE);
7836
7837 ReleaseDC (dpyinfo->root_window, hdc);
7838
7839 return make_number (cap);
7840}
7841
7842DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
7843 doc: /* Returns the width in millimeters of DISPLAY.
7844The optional argument DISPLAY specifies which display to ask about.
7845DISPLAY should be either a frame or a display name (a string).
7846If omitted or nil, that stands for the selected frame's display. */)
7847 (display)
7848 Lisp_Object display;
7849{
7850 struct w32_display_info *dpyinfo = check_x_display_info (display);
7851
7852 HDC hdc;
7853 int cap;
7854
7855 hdc = GetDC (dpyinfo->root_window);
7856
7857 cap = GetDeviceCaps (hdc, HORZSIZE);
7858
7859 ReleaseDC (dpyinfo->root_window, hdc);
7860
7861 return make_number (cap);
7862}
7863
7864DEFUN ("x-display-backing-store", Fx_display_backing_store,
7865 Sx_display_backing_store, 0, 1, 0,
7866 doc: /* Returns an indication of whether DISPLAY does backing store.
7867The value may be `always', `when-mapped', or `not-useful'.
7868The optional argument DISPLAY specifies which display to ask about.
7869DISPLAY should be either a frame or a display name (a string).
7870If omitted or nil, that stands for the selected frame's display. */)
7871 (display)
7872 Lisp_Object display;
7873{
7874 return intern ("not-useful");
7875}
7876
7877DEFUN ("x-display-visual-class", Fx_display_visual_class,
7878 Sx_display_visual_class, 0, 1, 0,
7879 doc: /* Returns the visual class of DISPLAY.
7880The value is one of the symbols `static-gray', `gray-scale',
7881`static-color', `pseudo-color', `true-color', or `direct-color'.
7882
7883The optional argument DISPLAY specifies which display to ask about.
7884DISPLAY should be either a frame or a display name (a string).
7885If omitted or nil, that stands for the selected frame's display. */)
7886 (display)
7887 Lisp_Object display;
7888{
7889 struct w32_display_info *dpyinfo = check_x_display_info (display);
7890 Lisp_Object result = Qnil;
7891
7892 if (dpyinfo->has_palette)
7893 result = intern ("pseudo-color");
7894 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
7895 result = intern ("static-grey");
7896 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
7897 result = intern ("static-color");
7898 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
7899 result = intern ("true-color");
7900
7901 return result;
7902}
7903
7904DEFUN ("x-display-save-under", Fx_display_save_under,
7905 Sx_display_save_under, 0, 1, 0,
7906 doc: /* Returns t if DISPLAY supports the save-under feature.
7907The optional argument DISPLAY specifies which display to ask about.
7908DISPLAY should be either a frame or a display name (a string).
7909If omitted or nil, that stands for the selected frame's display. */)
7910 (display)
7911 Lisp_Object display;
7912{
7913 return Qnil;
7914}
7915\f
7916int
7917x_pixel_width (f)
7918 register struct frame *f;
7919{
7920 return PIXEL_WIDTH (f);
7921}
7922
7923int
7924x_pixel_height (f)
7925 register struct frame *f;
7926{
7927 return PIXEL_HEIGHT (f);
7928}
7929
7930int
7931x_char_width (f)
7932 register struct frame *f;
7933{
7934 return FONT_WIDTH (f->output_data.w32->font);
7935}
7936
7937int
7938x_char_height (f)
7939 register struct frame *f;
7940{
7941 return f->output_data.w32->line_height;
7942}
7943
7944int
7945x_screen_planes (f)
7946 register struct frame *f;
7947{
7948 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
7949}
7950\f
7951/* Return the display structure for the display named NAME.
7952 Open a new connection if necessary. */
7953
7954struct w32_display_info *
7955x_display_info_for_name (name)
7956 Lisp_Object name;
7957{
7958 Lisp_Object names;
7959 struct w32_display_info *dpyinfo;
7960
7961 CHECK_STRING (name);
7962
7963 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7964 dpyinfo;
7965 dpyinfo = dpyinfo->next, names = XCDR (names))
7966 {
7967 Lisp_Object tem;
7968 tem = Fstring_equal (XCAR (XCAR (names)), name);
7969 if (!NILP (tem))
7970 return dpyinfo;
7971 }
7972
7973 /* Use this general default value to start with. */
7974 Vx_resource_name = Vinvocation_name;
7975
7976 validate_x_resource_name ();
7977
7978 dpyinfo = w32_term_init (name, (unsigned char *)0,
7979 (char *) SDATA (Vx_resource_name));
7980
7981 if (dpyinfo == 0)
7982 error ("Cannot connect to server %s", SDATA (name));
7983
7984 w32_in_use = 1;
7985 XSETFASTINT (Vwindow_system_version, 3);
7986
7987 return dpyinfo;
7988}
7989
7990DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7991 1, 3, 0, doc: /* Open a connection to a server.
7992DISPLAY is the name of the display to connect to.
7993Optional second arg XRM-STRING is a string of resources in xrdb format.
7994If the optional third arg MUST-SUCCEED is non-nil,
7995terminate Emacs if we can't open the connection. */)
7996 (display, xrm_string, must_succeed)
7997 Lisp_Object display, xrm_string, must_succeed;
7998{
7999 unsigned char *xrm_option;
8000 struct w32_display_info *dpyinfo;
8001
8002 /* If initialization has already been done, return now to avoid
8003 overwriting critical parts of one_w32_display_info. */
8004 if (w32_in_use)
8005 return Qnil;
8006
8007 CHECK_STRING (display);
8008 if (! NILP (xrm_string))
8009 CHECK_STRING (xrm_string);
8010
8011 if (! EQ (Vwindow_system, intern ("w32")))
8012 error ("Not using Microsoft Windows");
8013
8014 /* Allow color mapping to be defined externally; first look in user's
8015 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
8016 {
8017 Lisp_Object color_file;
8018 struct gcpro gcpro1;
8019
8020 color_file = build_string("~/rgb.txt");
8021
8022 GCPRO1 (color_file);
8023
8024 if (NILP (Ffile_readable_p (color_file)))
8025 color_file =
8026 Fexpand_file_name (build_string ("rgb.txt"),
8027 Fsymbol_value (intern ("data-directory")));
8028
8029 Vw32_color_map = Fw32_load_color_file (color_file);
8030
8031 UNGCPRO;
8032 }
8033 if (NILP (Vw32_color_map))
8034 Vw32_color_map = Fw32_default_color_map ();
8035
8036 if (! NILP (xrm_string))
8037 xrm_option = (unsigned char *) SDATA (xrm_string);
8038 else
8039 xrm_option = (unsigned char *) 0;
8040
8041 /* Use this general default value to start with. */
8042 /* First remove .exe suffix from invocation-name - it looks ugly. */
8043 {
8044 char basename[ MAX_PATH ], *str;
8045
8046 strcpy (basename, SDATA (Vinvocation_name));
8047 str = strrchr (basename, '.');
8048 if (str) *str = 0;
8049 Vinvocation_name = build_string (basename);
8050 }
8051 Vx_resource_name = Vinvocation_name;
8052
8053 validate_x_resource_name ();
8054
8055 /* This is what opens the connection and sets x_current_display.
8056 This also initializes many symbols, such as those used for input. */
8057 dpyinfo = w32_term_init (display, xrm_option,
8058 (char *) SDATA (Vx_resource_name));
8059
8060 if (dpyinfo == 0)
8061 {
8062 if (!NILP (must_succeed))
8063 fatal ("Cannot connect to server %s.\n",
8064 SDATA (display));
8065 else
8066 error ("Cannot connect to server %s", SDATA (display));
8067 }
8068
8069 w32_in_use = 1;
8070
8071 XSETFASTINT (Vwindow_system_version, 3);
8072 return Qnil;
8073}
8074
8075DEFUN ("x-close-connection", Fx_close_connection,
8076 Sx_close_connection, 1, 1, 0,
8077 doc: /* Close the connection to DISPLAY's server.
8078For DISPLAY, specify either a frame or a display name (a string).
8079If DISPLAY is nil, that stands for the selected frame's display. */)
8080 (display)
8081 Lisp_Object display;
8082{
8083 struct w32_display_info *dpyinfo = check_x_display_info (display);
8084 int i;
8085
8086 if (dpyinfo->reference_count > 0)
8087 error ("Display still has frames on it");
8088
8089 BLOCK_INPUT;
8090 /* Free the fonts in the font table. */
8091 for (i = 0; i < dpyinfo->n_fonts; i++)
8092 if (dpyinfo->font_table[i].name)
8093 {
8094 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
8095 xfree (dpyinfo->font_table[i].full_name);
8096 xfree (dpyinfo->font_table[i].name);
8097 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
8098 }
8099 x_destroy_all_bitmaps (dpyinfo);
8100
8101 x_delete_display (dpyinfo);
8102 UNBLOCK_INPUT;
8103
8104 return Qnil;
8105}
8106
8107DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
8108 doc: /* Return the list of display names that Emacs has connections to. */)
8109 ()
8110{
8111 Lisp_Object tail, result;
8112
8113 result = Qnil;
8114 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
8115 result = Fcons (XCAR (XCAR (tail)), result);
8116
8117 return result;
8118}
8119
8120DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
8121 doc: /* This is a noop on W32 systems. */)
8122 (on, display)
8123 Lisp_Object display, on;
8124{
8125 return Qnil;
8126}
8127
8128\f
8129/***********************************************************************
8130 Image types
8131 ***********************************************************************/
8132
8133/* Value is the number of elements of vector VECTOR. */
8134
8135#define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
8136
8137/* List of supported image types. Use define_image_type to add new
8138 types. Use lookup_image_type to find a type for a given symbol. */
8139
8140static struct image_type *image_types;
8141
8142/* The symbol `image' which is the car of the lists used to represent
8143 images in Lisp. */
8144
8145extern Lisp_Object Qimage;
8146
8147/* The symbol `xbm' which is used as the type symbol for XBM images. */
8148
8149Lisp_Object Qxbm;
8150
8151/* Keywords. */
8152
8153extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
8154extern Lisp_Object QCdata, QCtype;
8155Lisp_Object QCascent, QCmargin, QCrelief;
8156Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
8157Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
8158
8159/* Other symbols. */
8160
8161Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
8162
8163/* Time in seconds after which images should be removed from the cache
8164 if not displayed. */
8165
8166Lisp_Object Vimage_cache_eviction_delay;
8167
8168/* Function prototypes. */
8169
8170static void define_image_type P_ ((struct image_type *type));
8171static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
8172static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
8173static void x_laplace P_ ((struct frame *, struct image *));
8174static void x_emboss P_ ((struct frame *, struct image *));
8175static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
8176 Lisp_Object));
8177
8178
8179/* Define a new image type from TYPE. This adds a copy of TYPE to
8180 image_types and adds the symbol *TYPE->type to Vimage_types. */
8181
8182static void
8183define_image_type (type)
8184 struct image_type *type;
8185{
8186 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
8187 The initialized data segment is read-only. */
8188 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
8189 bcopy (type, p, sizeof *p);
8190 p->next = image_types;
8191 image_types = p;
8192 Vimage_types = Fcons (*p->type, Vimage_types);
8193}
8194
8195
8196/* Look up image type SYMBOL, and return a pointer to its image_type
8197 structure. Value is null if SYMBOL is not a known image type. */
8198
8199static INLINE struct image_type *
8200lookup_image_type (symbol)
8201 Lisp_Object symbol;
8202{
8203 struct image_type *type;
8204
8205 for (type = image_types; type; type = type->next)
8206 if (EQ (symbol, *type->type))
8207 break;
8208
8209 return type;
8210}
8211
8212
8213/* Value is non-zero if OBJECT is a valid Lisp image specification. A
8214 valid image specification is a list whose car is the symbol
8215 `image', and whose rest is a property list. The property list must
8216 contain a value for key `:type'. That value must be the name of a
8217 supported image type. The rest of the property list depends on the
8218 image type. */
8219
8220int
8221valid_image_p (object)
8222 Lisp_Object object;
8223{
8224 int valid_p = 0;
8225
8226 if (CONSP (object) && EQ (XCAR (object), Qimage))
8227 {
8228 Lisp_Object tem;
8229
8230 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
8231 if (EQ (XCAR (tem), QCtype))
8232 {
8233 tem = XCDR (tem);
8234 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
8235 {
8236 struct image_type *type;
8237 type = lookup_image_type (XCAR (tem));
8238 if (type)
8239 valid_p = type->valid_p (object);
8240 }
8241
8242 break;
8243 }
8244 }
8245
8246 return valid_p;
8247}
8248
8249
8250/* Log error message with format string FORMAT and argument ARG.
8251 Signaling an error, e.g. when an image cannot be loaded, is not a
8252 good idea because this would interrupt redisplay, and the error
8253 message display would lead to another redisplay. This function
8254 therefore simply displays a message. */
8255
8256static void
8257image_error (format, arg1, arg2)
8258 char *format;
8259 Lisp_Object arg1, arg2;
8260{
8261 add_to_log (format, arg1, arg2);
8262}
8263
8264
8265\f
8266/***********************************************************************
8267 Image specifications
8268 ***********************************************************************/
8269
8270enum image_value_type
8271{
8272 IMAGE_DONT_CHECK_VALUE_TYPE,
8273 IMAGE_STRING_VALUE,
8274 IMAGE_STRING_OR_NIL_VALUE,
8275 IMAGE_SYMBOL_VALUE,
8276 IMAGE_POSITIVE_INTEGER_VALUE,
8277 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
8278 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
8279 IMAGE_ASCENT_VALUE,
8280 IMAGE_INTEGER_VALUE,
8281 IMAGE_FUNCTION_VALUE,
8282 IMAGE_NUMBER_VALUE,
8283 IMAGE_BOOL_VALUE
8284};
8285
8286/* Structure used when parsing image specifications. */
8287
8288struct image_keyword
8289{
8290 /* Name of keyword. */
8291 char *name;
8292
8293 /* The type of value allowed. */
8294 enum image_value_type type;
8295
8296 /* Non-zero means key must be present. */
8297 int mandatory_p;
8298
8299 /* Used to recognize duplicate keywords in a property list. */
8300 int count;
8301
8302 /* The value that was found. */
8303 Lisp_Object value;
8304};
8305
8306
8307static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
8308 int, Lisp_Object));
8309static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
8310
8311
8312/* Parse image spec SPEC according to KEYWORDS. A valid image spec
8313 has the format (image KEYWORD VALUE ...). One of the keyword/
8314 value pairs must be `:type TYPE'. KEYWORDS is a vector of
8315 image_keywords structures of size NKEYWORDS describing other
8316 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
8317
8318static int
8319parse_image_spec (spec, keywords, nkeywords, type)
8320 Lisp_Object spec;
8321 struct image_keyword *keywords;
8322 int nkeywords;
8323 Lisp_Object type;
8324{
8325 int i;
8326 Lisp_Object plist;
8327
8328 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
8329 return 0;
8330
8331 plist = XCDR (spec);
8332 while (CONSP (plist))
8333 {
8334 Lisp_Object key, value;
8335
8336 /* First element of a pair must be a symbol. */
8337 key = XCAR (plist);
8338 plist = XCDR (plist);
8339 if (!SYMBOLP (key))
8340 return 0;
8341
8342 /* There must follow a value. */
8343 if (!CONSP (plist))
8344 return 0;
8345 value = XCAR (plist);
8346 plist = XCDR (plist);
8347
8348 /* Find key in KEYWORDS. Error if not found. */
8349 for (i = 0; i < nkeywords; ++i)
8350 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
8351 break;
8352
8353 if (i == nkeywords)
8354 continue;
8355
8356 /* Record that we recognized the keyword. If a keywords
8357 was found more than once, it's an error. */
8358 keywords[i].value = value;
8359 ++keywords[i].count;
8360
8361 if (keywords[i].count > 1)
8362 return 0;
8363
8364 /* Check type of value against allowed type. */
8365 switch (keywords[i].type)
8366 {
8367 case IMAGE_STRING_VALUE:
8368 if (!STRINGP (value))
8369 return 0;
8370 break;
8371
8372 case IMAGE_STRING_OR_NIL_VALUE:
8373 if (!STRINGP (value) && !NILP (value))
8374 return 0;
8375 break;
8376
8377 case IMAGE_SYMBOL_VALUE:
8378 if (!SYMBOLP (value))
8379 return 0;
8380 break;
8381
8382 case IMAGE_POSITIVE_INTEGER_VALUE:
8383 if (!INTEGERP (value) || XINT (value) <= 0)
8384 return 0;
8385 break;
8386
8387 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
8388 if (INTEGERP (value) && XINT (value) >= 0)
8389 break;
8390 if (CONSP (value)
8391 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
8392 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
8393 break;
8394 return 0;
8395
8396 case IMAGE_ASCENT_VALUE:
8397 if (SYMBOLP (value) && EQ (value, Qcenter))
8398 break;
8399 else if (INTEGERP (value)
8400 && XINT (value) >= 0
8401 && XINT (value) <= 100)
8402 break;
8403 return 0;
8404
8405 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
8406 if (!INTEGERP (value) || XINT (value) < 0)
8407 return 0;
8408 break;
8409
8410 case IMAGE_DONT_CHECK_VALUE_TYPE:
8411 break;
8412
8413 case IMAGE_FUNCTION_VALUE:
8414 value = indirect_function (value);
8415 if (SUBRP (value)
8416 || COMPILEDP (value)
8417 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
8418 break;
8419 return 0;
8420
8421 case IMAGE_NUMBER_VALUE:
8422 if (!INTEGERP (value) && !FLOATP (value))
8423 return 0;
8424 break;
8425
8426 case IMAGE_INTEGER_VALUE:
8427 if (!INTEGERP (value))
8428 return 0;
8429 break;
8430
8431 case IMAGE_BOOL_VALUE:
8432 if (!NILP (value) && !EQ (value, Qt))
8433 return 0;
8434 break;
8435
8436 default:
8437 abort ();
8438 break;
8439 }
8440
8441 if (EQ (key, QCtype) && !EQ (type, value))
8442 return 0;
8443 }
8444
8445 /* Check that all mandatory fields are present. */
8446 for (i = 0; i < nkeywords; ++i)
8447 if (keywords[i].mandatory_p && keywords[i].count == 0)
8448 return 0;
8449
8450 return NILP (plist);
8451}
8452
8453
8454/* Return the value of KEY in image specification SPEC. Value is nil
8455 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
8456 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
8457
8458static Lisp_Object
8459image_spec_value (spec, key, found)
8460 Lisp_Object spec, key;
8461 int *found;
8462{
8463 Lisp_Object tail;
8464
8465 xassert (valid_image_p (spec));
8466
8467 for (tail = XCDR (spec);
8468 CONSP (tail) && CONSP (XCDR (tail));
8469 tail = XCDR (XCDR (tail)))
8470 {
8471 if (EQ (XCAR (tail), key))
8472 {
8473 if (found)
8474 *found = 1;
8475 return XCAR (XCDR (tail));
8476 }
8477 }
8478
8479 if (found)
8480 *found = 0;
8481 return Qnil;
8482}
8483
8484
8485DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
8486 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
8487PIXELS non-nil means return the size in pixels, otherwise return the
8488size in canonical character units.
8489FRAME is the frame on which the image will be displayed. FRAME nil
8490or omitted means use the selected frame. */)
8491 (spec, pixels, frame)
8492 Lisp_Object spec, pixels, frame;
8493{
8494 Lisp_Object size;
8495
8496 size = Qnil;
8497 if (valid_image_p (spec))
8498 {
8499 struct frame *f = check_x_frame (frame);
8500 int id = lookup_image (f, spec);
8501 struct image *img = IMAGE_FROM_ID (f, id);
8502 int width = img->width + 2 * img->hmargin;
8503 int height = img->height + 2 * img->vmargin;
8504
8505 if (NILP (pixels))
8506 size = Fcons (make_float ((double) width / CANON_X_UNIT (f)),
8507 make_float ((double) height / CANON_Y_UNIT (f)));
8508 else
8509 size = Fcons (make_number (width), make_number (height));
8510 }
8511 else
8512 error ("Invalid image specification");
8513
8514 return size;
8515}
8516
8517
8518DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
8519 doc: /* Return t if image SPEC has a mask bitmap.
8520FRAME is the frame on which the image will be displayed. FRAME nil
8521or omitted means use the selected frame. */)
8522 (spec, frame)
8523 Lisp_Object spec, frame;
8524{
8525 Lisp_Object mask;
8526
8527 mask = Qnil;
8528 if (valid_image_p (spec))
8529 {
8530 struct frame *f = check_x_frame (frame);
8531 int id = lookup_image (f, spec);
8532 struct image *img = IMAGE_FROM_ID (f, id);
8533 if (img->mask)
8534 mask = Qt;
8535 }
8536 else
8537 error ("Invalid image specification");
8538
8539 return mask;
8540}
8541
8542\f
8543/***********************************************************************
8544 Image type independent image structures
8545 ***********************************************************************/
8546
8547static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
8548static void free_image P_ ((struct frame *f, struct image *img));
8549static void x_destroy_x_image P_ ((XImage *));
8550
8551
8552/* Allocate and return a new image structure for image specification
8553 SPEC. SPEC has a hash value of HASH. */
8554
8555static struct image *
8556make_image (spec, hash)
8557 Lisp_Object spec;
8558 unsigned hash;
8559{
8560 struct image *img = (struct image *) xmalloc (sizeof *img);
8561
8562 xassert (valid_image_p (spec));
8563 bzero (img, sizeof *img);
8564 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
8565 xassert (img->type != NULL);
8566 img->spec = spec;
8567 img->data.lisp_val = Qnil;
8568 img->ascent = DEFAULT_IMAGE_ASCENT;
8569 img->hash = hash;
8570 return img;
8571}
8572
8573
8574/* Free image IMG which was used on frame F, including its resources. */
8575
8576static void
8577free_image (f, img)
8578 struct frame *f;
8579 struct image *img;
8580{
8581 if (img)
8582 {
8583 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8584
8585 /* Remove IMG from the hash table of its cache. */
8586 if (img->prev)
8587 img->prev->next = img->next;
8588 else
8589 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
8590
8591 if (img->next)
8592 img->next->prev = img->prev;
8593
8594 c->images[img->id] = NULL;
8595
8596 /* Free resources, then free IMG. */
8597 img->type->free (f, img);
8598 xfree (img);
8599 }
8600}
8601
8602
8603/* Prepare image IMG for display on frame F. Must be called before
8604 drawing an image. */
8605
8606void
8607prepare_image_for_display (f, img)
8608 struct frame *f;
8609 struct image *img;
8610{
8611 EMACS_TIME t;
8612
8613 /* We're about to display IMG, so set its timestamp to `now'. */
8614 EMACS_GET_TIME (t);
8615 img->timestamp = EMACS_SECS (t);
8616
8617 /* If IMG doesn't have a pixmap yet, load it now, using the image
8618 type dependent loader function. */
8619 if (img->pixmap == 0 && !img->load_failed_p)
8620 img->load_failed_p = img->type->load (f, img) == 0;
8621}
8622
8623
8624/* Value is the number of pixels for the ascent of image IMG when
8625 drawn in face FACE. */
8626
8627int
8628image_ascent (img, face)
8629 struct image *img;
8630 struct face *face;
8631{
8632 int height = img->height + img->vmargin;
8633 int ascent;
8634
8635 if (img->ascent == CENTERED_IMAGE_ASCENT)
8636 {
8637 if (face->font)
8638 ascent = height / 2 - (FONT_DESCENT(face->font)
8639 - FONT_BASE(face->font)) / 2;
8640 else
8641 ascent = height / 2;
8642 }
8643 else
8644 ascent = (int) (height * img->ascent / 100.0);
8645
8646 return ascent;
8647}
8648
8649
8650\f
8651/* Image background colors. */
8652
8653/* Find the "best" corner color of a bitmap. XIMG is assumed to a device
8654 context with the bitmap selected. */
8655static COLORREF
8656four_corners_best (img_dc, width, height)
8657 HDC img_dc;
8658 unsigned long width, height;
8659{
8660 COLORREF corners[4], best;
8661 int i, best_count;
8662
8663 /* Get the colors at the corners of img_dc. */
8664 corners[0] = GetPixel (img_dc, 0, 0);
8665 corners[1] = GetPixel (img_dc, width - 1, 0);
8666 corners[2] = GetPixel (img_dc, width - 1, height - 1);
8667 corners[3] = GetPixel (img_dc, 0, height - 1);
8668
8669 /* Choose the most frequently found color as background. */
8670 for (i = best_count = 0; i < 4; ++i)
8671 {
8672 int j, n;
8673
8674 for (j = n = 0; j < 4; ++j)
8675 if (corners[i] == corners[j])
8676 ++n;
8677
8678 if (n > best_count)
8679 best = corners[i], best_count = n;
8680 }
8681
8682 return best;
8683}
8684
8685/* Return the `background' field of IMG. If IMG doesn't have one yet,
8686 it is guessed heuristically. If non-zero, IMG_DC is an existing
8687 device context with the image selected to use for the heuristic. */
8688
8689unsigned long
8690image_background (img, f, img_dc)
8691 struct image *img;
8692 struct frame *f;
8693 HDC img_dc;
8694{
8695 if (! img->background_valid)
8696 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8697 {
8698 int free_ximg = !img_dc;
8699 HGDIOBJ prev;
8700
8701 if (free_ximg)
8702 {
8703 HDC frame_dc = get_frame_dc (f);
8704 img_dc = CreateCompatibleDC (frame_dc);
8705 release_frame_dc (f, frame_dc);
8706
8707 prev = SelectObject (img_dc, img->pixmap);
8708 }
8709
8710 img->background = four_corners_best (img_dc, img->width, img->height);
8711
8712 if (free_ximg)
8713 {
8714 SelectObject (img_dc, prev);
8715 DeleteDC (img_dc);
8716 }
8717
8718 img->background_valid = 1;
8719 }
8720
8721 return img->background;
8722}
8723
8724/* Return the `background_transparent' field of IMG. If IMG doesn't
8725 have one yet, it is guessed heuristically. If non-zero, MASK is an
8726 existing XImage object to use for the heuristic. */
8727
8728int
8729image_background_transparent (img, f, mask)
8730 struct image *img;
8731 struct frame *f;
8732 HDC mask;
8733{
8734 if (! img->background_transparent_valid)
8735 /* IMG doesn't have a background yet, try to guess a reasonable value. */
8736 {
8737 if (img->mask)
8738 {
8739 int free_mask = !mask;
8740 HGDIOBJ prev;
8741
8742 if (free_mask)
8743 {
8744 HDC frame_dc = get_frame_dc (f);
8745 mask = CreateCompatibleDC (frame_dc);
8746 release_frame_dc (f, frame_dc);
8747
8748 prev = SelectObject (mask, img->mask);
8749 }
8750
8751 img->background_transparent
8752 = !four_corners_best (mask, img->width, img->height);
8753
8754 if (free_mask)
8755 {
8756 SelectObject (mask, prev);
8757 DeleteDC (mask);
8758 }
8759 }
8760 else
8761 img->background_transparent = 0;
8762
8763 img->background_transparent_valid = 1;
8764 }
8765
8766 return img->background_transparent;
8767}
8768
8769\f
8770/***********************************************************************
8771 Helper functions for X image types
8772 ***********************************************************************/
8773
8774static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
8775 int, int));
8776static void x_clear_image P_ ((struct frame *f, struct image *img));
8777static unsigned long x_alloc_image_color P_ ((struct frame *f,
8778 struct image *img,
8779 Lisp_Object color_name,
8780 unsigned long dflt));
8781
8782
8783/* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
8784 free the pixmap if any. MASK_P non-zero means clear the mask
8785 pixmap if any. COLORS_P non-zero means free colors allocated for
8786 the image, if any. */
8787
8788static void
8789x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
8790 struct frame *f;
8791 struct image *img;
8792 int pixmap_p, mask_p, colors_p;
8793{
8794 if (pixmap_p && img->pixmap)
8795 {
8796 DeleteObject (img->pixmap);
8797 img->pixmap = NULL;
8798 img->background_valid = 0;
8799 }
8800
8801 if (mask_p && img->mask)
8802 {
8803 DeleteObject (img->mask);
8804 img->mask = NULL;
8805 img->background_transparent_valid = 0;
8806 }
8807
8808 if (colors_p && img->ncolors)
8809 {
8810#if 0 /* TODO: color table support. */
8811 x_free_colors (f, img->colors, img->ncolors);
8812#endif
8813 xfree (img->colors);
8814 img->colors = NULL;
8815 img->ncolors = 0;
8816 }
8817}
8818
8819/* Free X resources of image IMG which is used on frame F. */
8820
8821static void
8822x_clear_image (f, img)
8823 struct frame *f;
8824 struct image *img;
8825{
8826 if (img->pixmap)
8827 {
8828 BLOCK_INPUT;
8829 DeleteObject (img->pixmap);
8830 img->pixmap = 0;
8831 UNBLOCK_INPUT;
8832 }
8833
8834 if (img->ncolors)
8835 {
8836#if 0 /* TODO: color table support */
8837
8838 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
8839
8840 /* If display has an immutable color map, freeing colors is not
8841 necessary and some servers don't allow it. So don't do it. */
8842 if (class != StaticColor
8843 && class != StaticGray
8844 && class != TrueColor)
8845 {
8846 Colormap cmap;
8847 BLOCK_INPUT;
8848 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
8849 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
8850 img->ncolors, 0);
8851 UNBLOCK_INPUT;
8852 }
8853#endif
8854
8855 xfree (img->colors);
8856 img->colors = NULL;
8857 img->ncolors = 0;
8858 }
8859}
8860
8861
8862/* Allocate color COLOR_NAME for image IMG on frame F. If color
8863 cannot be allocated, use DFLT. Add a newly allocated color to
8864 IMG->colors, so that it can be freed again. Value is the pixel
8865 color. */
8866
8867static unsigned long
8868x_alloc_image_color (f, img, color_name, dflt)
8869 struct frame *f;
8870 struct image *img;
8871 Lisp_Object color_name;
8872 unsigned long dflt;
8873{
8874 XColor color;
8875 unsigned long result;
8876
8877 xassert (STRINGP (color_name));
8878
8879 if (w32_defined_color (f, SDATA (color_name), &color, 1))
8880 {
8881 /* This isn't called frequently so we get away with simply
8882 reallocating the color vector to the needed size, here. */
8883 ++img->ncolors;
8884 img->colors =
8885 (unsigned long *) xrealloc (img->colors,
8886 img->ncolors * sizeof *img->colors);
8887 img->colors[img->ncolors - 1] = color.pixel;
8888 result = color.pixel;
8889 }
8890 else
8891 result = dflt;
8892 return result;
8893}
8894
8895
8896\f
8897/***********************************************************************
8898 Image Cache
8899 ***********************************************************************/
8900
8901static void cache_image P_ ((struct frame *f, struct image *img));
8902static void postprocess_image P_ ((struct frame *, struct image *));
8903static void x_disable_image P_ ((struct frame *, struct image *));
8904
8905
8906/* Return a new, initialized image cache that is allocated from the
8907 heap. Call free_image_cache to free an image cache. */
8908
8909struct image_cache *
8910make_image_cache ()
8911{
8912 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
8913 int size;
8914
8915 bzero (c, sizeof *c);
8916 c->size = 50;
8917 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
8918 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
8919 c->buckets = (struct image **) xmalloc (size);
8920 bzero (c->buckets, size);
8921 return c;
8922}
8923
8924
8925/* Free image cache of frame F. Be aware that X frames share images
8926 caches. */
8927
8928void
8929free_image_cache (f)
8930 struct frame *f;
8931{
8932 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8933 if (c)
8934 {
8935 int i;
8936
8937 /* Cache should not be referenced by any frame when freed. */
8938 xassert (c->refcount == 0);
8939
8940 for (i = 0; i < c->used; ++i)
8941 free_image (f, c->images[i]);
8942 xfree (c->images);
8943 xfree (c);
8944 xfree (c->buckets);
8945 FRAME_X_IMAGE_CACHE (f) = NULL;
8946 }
8947}
8948
8949
8950/* Clear image cache of frame F. FORCE_P non-zero means free all
8951 images. FORCE_P zero means clear only images that haven't been
8952 displayed for some time. Should be called from time to time to
8953 reduce the number of loaded images. If image-eviction-seconds is
8954 non-nil, this frees images in the cache which weren't displayed for
8955 at least that many seconds. */
8956
8957void
8958clear_image_cache (f, force_p)
8959 struct frame *f;
8960 int force_p;
8961{
8962 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8963
8964 if (c && INTEGERP (Vimage_cache_eviction_delay))
8965 {
8966 EMACS_TIME t;
8967 unsigned long old;
8968 int i, nfreed;
8969
8970 EMACS_GET_TIME (t);
8971 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
8972
8973 /* Block input so that we won't be interrupted by a SIGIO
8974 while being in an inconsistent state. */
8975 BLOCK_INPUT;
8976
8977 for (i = nfreed = 0; i < c->used; ++i)
8978 {
8979 struct image *img = c->images[i];
8980 if (img != NULL
8981 && (force_p || (img->timestamp < old)))
8982 {
8983 free_image (f, img);
8984 ++nfreed;
8985 }
8986 }
8987
8988 /* We may be clearing the image cache because, for example,
8989 Emacs was iconified for a longer period of time. In that
8990 case, current matrices may still contain references to
8991 images freed above. So, clear these matrices. */
8992 if (nfreed)
8993 {
8994 Lisp_Object tail, frame;
8995
8996 FOR_EACH_FRAME (tail, frame)
8997 {
8998 struct frame *f = XFRAME (frame);
8999 if (FRAME_W32_P (f)
9000 && FRAME_X_IMAGE_CACHE (f) == c)
9001 clear_current_matrices (f);
9002 }
9003
9004 ++windows_or_buffers_changed;
9005 }
9006
9007 UNBLOCK_INPUT;
9008 }
9009}
9010
9011
9012DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
9013 0, 1, 0,
9014 doc: /* Clear the image cache of FRAME.
9015FRAME nil or omitted means use the selected frame.
9016FRAME t means clear the image caches of all frames. */)
9017 (frame)
9018 Lisp_Object frame;
9019{
9020 if (EQ (frame, Qt))
9021 {
9022 Lisp_Object tail;
9023
9024 FOR_EACH_FRAME (tail, frame)
9025 if (FRAME_W32_P (XFRAME (frame)))
9026 clear_image_cache (XFRAME (frame), 1);
9027 }
9028 else
9029 clear_image_cache (check_x_frame (frame), 1);
9030
9031 return Qnil;
9032}
9033
9034
9035/* Compute masks and transform image IMG on frame F, as specified
9036 by the image's specification, */
9037
9038static void
9039postprocess_image (f, img)
9040 struct frame *f;
9041 struct image *img;
9042{
9043 /* Manipulation of the image's mask. */
9044 if (img->pixmap)
9045 {
9046 Lisp_Object conversion, spec;
9047 Lisp_Object mask;
9048
9049 spec = img->spec;
9050
9051 /* `:heuristic-mask t'
9052 `:mask heuristic'
9053 means build a mask heuristically.
9054 `:heuristic-mask (R G B)'
9055 `:mask (heuristic (R G B))'
9056 means build a mask from color (R G B) in the
9057 image.
9058 `:mask nil'
9059 means remove a mask, if any. */
9060
9061 mask = image_spec_value (spec, QCheuristic_mask, NULL);
9062 if (!NILP (mask))
9063 x_build_heuristic_mask (f, img, mask);
9064 else
9065 {
9066 int found_p;
9067
9068 mask = image_spec_value (spec, QCmask, &found_p);
9069
9070 if (EQ (mask, Qheuristic))
9071 x_build_heuristic_mask (f, img, Qt);
9072 else if (CONSP (mask)
9073 && EQ (XCAR (mask), Qheuristic))
9074 {
9075 if (CONSP (XCDR (mask)))
9076 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
9077 else
9078 x_build_heuristic_mask (f, img, XCDR (mask));
9079 }
9080 else if (NILP (mask) && found_p && img->mask)
9081 {
9082 DeleteObject (img->mask);
9083 img->mask = NULL;
9084 }
9085 }
9086
9087
9088 /* Should we apply an image transformation algorithm? */
9089 conversion = image_spec_value (spec, QCconversion, NULL);
9090 if (EQ (conversion, Qdisabled))
9091 x_disable_image (f, img);
9092 else if (EQ (conversion, Qlaplace))
9093 x_laplace (f, img);
9094 else if (EQ (conversion, Qemboss))
9095 x_emboss (f, img);
9096 else if (CONSP (conversion)
9097 && EQ (XCAR (conversion), Qedge_detection))
9098 {
9099 Lisp_Object tem;
9100 tem = XCDR (conversion);
9101 if (CONSP (tem))
9102 x_edge_detection (f, img,
9103 Fplist_get (tem, QCmatrix),
9104 Fplist_get (tem, QCcolor_adjustment));
9105 }
9106 }
9107}
9108
9109
9110/* Return the id of image with Lisp specification SPEC on frame F.
9111 SPEC must be a valid Lisp image specification (see valid_image_p). */
9112
9113int
9114lookup_image (f, spec)
9115 struct frame *f;
9116 Lisp_Object spec;
9117{
9118 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9119 struct image *img;
9120 int i;
9121 unsigned hash;
9122 struct gcpro gcpro1;
9123 EMACS_TIME now;
9124
9125 /* F must be a window-system frame, and SPEC must be a valid image
9126 specification. */
9127 xassert (FRAME_WINDOW_P (f));
9128 xassert (valid_image_p (spec));
9129
9130 GCPRO1 (spec);
9131
9132 /* Look up SPEC in the hash table of the image cache. */
9133 hash = sxhash (spec, 0);
9134 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
9135
9136 for (img = c->buckets[i]; img; img = img->next)
9137 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
9138 break;
9139
9140 /* If not found, create a new image and cache it. */
9141 if (img == NULL)
9142 {
9143 extern Lisp_Object Qpostscript;
9144
9145 BLOCK_INPUT;
9146 img = make_image (spec, hash);
9147 cache_image (f, img);
9148 img->load_failed_p = img->type->load (f, img) == 0;
9149
9150 /* If we can't load the image, and we don't have a width and
9151 height, use some arbitrary width and height so that we can
9152 draw a rectangle for it. */
9153 if (img->load_failed_p)
9154 {
9155 Lisp_Object value;
9156
9157 value = image_spec_value (spec, QCwidth, NULL);
9158 img->width = (INTEGERP (value)
9159 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
9160 value = image_spec_value (spec, QCheight, NULL);
9161 img->height = (INTEGERP (value)
9162 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
9163 }
9164 else
9165 {
9166 /* Handle image type independent image attributes
9167 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
9168 `:background COLOR'. */
9169 Lisp_Object ascent, margin, relief, bg;
9170
9171 ascent = image_spec_value (spec, QCascent, NULL);
9172 if (INTEGERP (ascent))
9173 img->ascent = XFASTINT (ascent);
9174 else if (EQ (ascent, Qcenter))
9175 img->ascent = CENTERED_IMAGE_ASCENT;
9176
9177 margin = image_spec_value (spec, QCmargin, NULL);
9178 if (INTEGERP (margin) && XINT (margin) >= 0)
9179 img->vmargin = img->hmargin = XFASTINT (margin);
9180 else if (CONSP (margin) && INTEGERP (XCAR (margin))
9181 && INTEGERP (XCDR (margin)))
9182 {
9183 if (XINT (XCAR (margin)) > 0)
9184 img->hmargin = XFASTINT (XCAR (margin));
9185 if (XINT (XCDR (margin)) > 0)
9186 img->vmargin = XFASTINT (XCDR (margin));
9187 }
9188
9189 relief = image_spec_value (spec, QCrelief, NULL);
9190 if (INTEGERP (relief))
9191 {
9192 img->relief = XINT (relief);
9193 img->hmargin += abs (img->relief);
9194 img->vmargin += abs (img->relief);
9195 }
9196
9197 if (! img->background_valid)
9198 {
9199 bg = image_spec_value (img->spec, QCbackground, NULL);
9200 if (!NILP (bg))
9201 {
9202 img->background
9203 = x_alloc_image_color (f, img, bg,
9204 FRAME_BACKGROUND_PIXEL (f));
9205 img->background_valid = 1;
9206 }
9207 }
9208
9209 /* Do image transformations and compute masks, unless we
9210 don't have the image yet. */
9211 if (!EQ (*img->type->type, Qpostscript))
9212 postprocess_image (f, img);
9213 }
9214
9215 UNBLOCK_INPUT;
9216 xassert (!interrupt_input_blocked);
9217 }
9218
9219 /* We're using IMG, so set its timestamp to `now'. */
9220 EMACS_GET_TIME (now);
9221 img->timestamp = EMACS_SECS (now);
9222
9223 UNGCPRO;
9224
9225 /* Value is the image id. */
9226 return img->id;
9227}
9228
9229
9230/* Cache image IMG in the image cache of frame F. */
9231
9232static void
9233cache_image (f, img)
9234 struct frame *f;
9235 struct image *img;
9236{
9237 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9238 int i;
9239
9240 /* Find a free slot in c->images. */
9241 for (i = 0; i < c->used; ++i)
9242 if (c->images[i] == NULL)
9243 break;
9244
9245 /* If no free slot found, maybe enlarge c->images. */
9246 if (i == c->used && c->used == c->size)
9247 {
9248 c->size *= 2;
9249 c->images = (struct image **) xrealloc (c->images,
9250 c->size * sizeof *c->images);
9251 }
9252
9253 /* Add IMG to c->images, and assign IMG an id. */
9254 c->images[i] = img;
9255 img->id = i;
9256 if (i == c->used)
9257 ++c->used;
9258
9259 /* Add IMG to the cache's hash table. */
9260 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
9261 img->next = c->buckets[i];
9262 if (img->next)
9263 img->next->prev = img;
9264 img->prev = NULL;
9265 c->buckets[i] = img;
9266}
9267
9268
9269/* Call FN on every image in the image cache of frame F. Used to mark
9270 Lisp Objects in the image cache. */
9271
9272void
9273forall_images_in_image_cache (f, fn)
9274 struct frame *f;
9275 void (*fn) P_ ((struct image *img));
9276{
9277 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
9278 {
9279 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
9280 if (c)
9281 {
9282 int i;
9283 for (i = 0; i < c->used; ++i)
9284 if (c->images[i])
9285 fn (c->images[i]);
9286 }
9287 }
9288}
9289
9290
9291\f
9292/***********************************************************************
9293 W32 support code
9294 ***********************************************************************/
9295
9296static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
9297 XImage **, Pixmap *));
9298static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
9299
9300
9301/* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
9302 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
9303 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
9304 via xmalloc. DEPTH of zero signifies a 24 bit image, otherwise
9305 DEPTH should indicate the bit depth of the image. Print error
9306 messages via image_error if an error occurs. Value is non-zero if
9307 successful. */
9308
9309static int
9310x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
9311 struct frame *f;
9312 int width, height, depth;
9313 XImage **ximg;
9314 Pixmap *pixmap;
9315{
9316 BITMAPINFOHEADER *header;
9317 HDC hdc;
9318 int scanline_width_bits;
9319 int remainder;
9320 int palette_colors = 0;
9321
9322 if (depth == 0)
9323 depth = 24;
9324
9325 if (depth != 1 && depth != 4 && depth != 8
9326 && depth != 16 && depth != 24 && depth != 32)
9327 {
9328 image_error ("Invalid image bit depth specified", Qnil, Qnil);
9329 return 0;
9330 }
9331
9332 scanline_width_bits = width * depth;
9333 remainder = scanline_width_bits % 32;
9334
9335 if (remainder)
9336 scanline_width_bits += 32 - remainder;
9337
9338 /* Bitmaps with a depth less than 16 need a palette. */
9339 /* BITMAPINFO structure already contains the first RGBQUAD. */
9340 if (depth < 16)
9341 palette_colors = 1 << depth - 1;
9342
9343 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
9344 if (*ximg == NULL)
9345 {
9346 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
9347 return 0;
9348 }
9349
9350 header = &((*ximg)->info.bmiHeader);
9351 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
9352 header->biSize = sizeof (*header);
9353 header->biWidth = width;
9354 header->biHeight = -height; /* negative indicates a top-down bitmap. */
9355 header->biPlanes = 1;
9356 header->biBitCount = depth;
9357 header->biCompression = BI_RGB;
9358 header->biClrUsed = palette_colors;
9359
9360 /* TODO: fill in palette. */
9361 if (depth == 1)
9362 {
9363 (*ximg)->info.bmiColors[0].rgbBlue = 0;
9364 (*ximg)->info.bmiColors[0].rgbGreen = 0;
9365 (*ximg)->info.bmiColors[0].rgbRed = 0;
9366 (*ximg)->info.bmiColors[0].rgbReserved = 0;
9367 (*ximg)->info.bmiColors[1].rgbBlue = 255;
9368 (*ximg)->info.bmiColors[1].rgbGreen = 255;
9369 (*ximg)->info.bmiColors[1].rgbRed = 255;
9370 (*ximg)->info.bmiColors[1].rgbReserved = 0;
9371 }
9372
9373 hdc = get_frame_dc (f);
9374
9375 /* Create a DIBSection and raster array for the bitmap,
9376 and store its handle in *pixmap. */
9377 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
9378 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
9379 &((*ximg)->data), NULL, 0);
9380
9381 /* Realize display palette and garbage all frames. */
9382 release_frame_dc (f, hdc);
9383
9384 if (*pixmap == NULL)
9385 {
9386 DWORD err = GetLastError();
9387 Lisp_Object errcode;
9388 /* All system errors are < 10000, so the following is safe. */
9389 XSETINT (errcode, (int) err);
9390 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
9391 x_destroy_x_image (*ximg);
9392 return 0;
9393 }
9394
9395 return 1;
9396}
9397
9398
9399/* Destroy XImage XIMG. Free XIMG->data. */
9400
9401static void
9402x_destroy_x_image (ximg)
9403 XImage *ximg;
9404{
9405 xassert (interrupt_input_blocked);
9406 if (ximg)
9407 {
9408 /* Data will be freed by DestroyObject. */
9409 ximg->data = NULL;
9410 xfree (ximg);
9411 }
9412}
9413
9414
9415/* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
9416 are width and height of both the image and pixmap. */
9417
9418static void
9419x_put_x_image (f, ximg, pixmap, width, height)
9420 struct frame *f;
9421 XImage *ximg;
9422 Pixmap pixmap;
9423{
9424#if 0 /* I don't think this is necessary looking at where it is used. */
9425 HDC hdc = get_frame_dc (f);
9426 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
9427 release_frame_dc (f, hdc);
9428#endif
9429}
9430
9431\f
9432/***********************************************************************
9433 File Handling
9434 ***********************************************************************/
9435
9436static Lisp_Object x_find_image_file P_ ((Lisp_Object));
9437static char *slurp_file P_ ((char *, int *));
9438
9439
9440/* Find image file FILE. Look in data-directory, then
9441 x-bitmap-file-path. Value is the full name of the file found, or
9442 nil if not found. */
9443
9444static Lisp_Object
9445x_find_image_file (file)
9446 Lisp_Object file;
9447{
9448 Lisp_Object file_found, search_path;
9449 struct gcpro gcpro1, gcpro2;
9450 int fd;
9451
9452 file_found = Qnil;
9453 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
9454 GCPRO2 (file_found, search_path);
9455
9456 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
9457 fd = openp (search_path, file, Qnil, &file_found, Qnil);
9458
9459 if (fd == -1)
9460 file_found = Qnil;
9461 else
9462 close (fd);
9463
9464 UNGCPRO;
9465 return file_found;
9466}
9467
9468
9469/* Read FILE into memory. Value is a pointer to a buffer allocated
9470 with xmalloc holding FILE's contents. Value is null if an error
9471 occurred. *SIZE is set to the size of the file. */
9472
9473static char *
9474slurp_file (file, size)
9475 char *file;
9476 int *size;
9477{
9478 FILE *fp = NULL;
9479 char *buf = NULL;
9480 struct stat st;
9481
9482 if (stat (file, &st) == 0
9483 && (fp = fopen (file, "r")) != NULL
9484 && (buf = (char *) xmalloc (st.st_size),
9485 fread (buf, 1, st.st_size, fp) == st.st_size))
9486 {
9487 *size = st.st_size;
9488 fclose (fp);
9489 }
9490 else
9491 {
9492 if (fp)
9493 fclose (fp);
9494 if (buf)
9495 {
9496 xfree (buf);
9497 buf = NULL;
9498 }
9499 }
9500
9501 return buf;
9502}
9503
9504
9505\f
9506/***********************************************************************
9507 XBM images
9508 ***********************************************************************/
9509
9510static int xbm_scan P_ ((char **, char *, char *, int *));
9511static int xbm_load P_ ((struct frame *f, struct image *img));
9512static int xbm_load_image P_ ((struct frame *f, struct image *img,
9513 char *, char *));
9514static int xbm_image_p P_ ((Lisp_Object object));
9515static int xbm_read_bitmap_data P_ ((char *, char *, int *, int *,
9516 unsigned char **));
9517static int xbm_file_p P_ ((Lisp_Object));
9518
9519
9520/* Indices of image specification fields in xbm_format, below. */
9521
9522enum xbm_keyword_index
9523{
9524 XBM_TYPE,
9525 XBM_FILE,
9526 XBM_WIDTH,
9527 XBM_HEIGHT,
9528 XBM_DATA,
9529 XBM_FOREGROUND,
9530 XBM_BACKGROUND,
9531 XBM_ASCENT,
9532 XBM_MARGIN,
9533 XBM_RELIEF,
9534 XBM_ALGORITHM,
9535 XBM_HEURISTIC_MASK,
9536 XBM_MASK,
9537 XBM_LAST
9538};
9539
9540/* Vector of image_keyword structures describing the format
9541 of valid XBM image specifications. */
9542
9543static struct image_keyword xbm_format[XBM_LAST] =
9544{
9545 {":type", IMAGE_SYMBOL_VALUE, 1},
9546 {":file", IMAGE_STRING_VALUE, 0},
9547 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9548 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9549 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9550 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
9551 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
9552 {":ascent", IMAGE_ASCENT_VALUE, 0},
9553 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
9554 {":relief", IMAGE_INTEGER_VALUE, 0},
9555 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9556 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9557 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9558};
9559
9560/* Structure describing the image type XBM. */
9561
9562static struct image_type xbm_type =
9563{
9564 &Qxbm,
9565 xbm_image_p,
9566 xbm_load,
9567 x_clear_image,
9568 NULL
9569};
9570
9571/* Tokens returned from xbm_scan. */
9572
9573enum xbm_token
9574{
9575 XBM_TK_IDENT = 256,
9576 XBM_TK_NUMBER
9577};
9578
9579
9580/* Return non-zero if OBJECT is a valid XBM-type image specification.
9581 A valid specification is a list starting with the symbol `image'
9582 The rest of the list is a property list which must contain an
9583 entry `:type xbm..
9584
9585 If the specification specifies a file to load, it must contain
9586 an entry `:file FILENAME' where FILENAME is a string.
9587
9588 If the specification is for a bitmap loaded from memory it must
9589 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
9590 WIDTH and HEIGHT are integers > 0. DATA may be:
9591
9592 1. a string large enough to hold the bitmap data, i.e. it must
9593 have a size >= (WIDTH + 7) / 8 * HEIGHT
9594
9595 2. a bool-vector of size >= WIDTH * HEIGHT
9596
9597 3. a vector of strings or bool-vectors, one for each line of the
9598 bitmap.
9599
9600 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
9601 may not be specified in this case because they are defined in the
9602 XBM file.
9603
9604 Both the file and data forms may contain the additional entries
9605 `:background COLOR' and `:foreground COLOR'. If not present,
9606 foreground and background of the frame on which the image is
9607 displayed is used. */
9608
9609static int
9610xbm_image_p (object)
9611 Lisp_Object object;
9612{
9613 struct image_keyword kw[XBM_LAST];
9614
9615 bcopy (xbm_format, kw, sizeof kw);
9616 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
9617 return 0;
9618
9619 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
9620
9621 if (kw[XBM_FILE].count)
9622 {
9623 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
9624 return 0;
9625 }
9626 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
9627 {
9628 /* In-memory XBM file. */
9629 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
9630 return 0;
9631 }
9632 else
9633 {
9634 Lisp_Object data;
9635 int width, height;
9636
9637 /* Entries for `:width', `:height' and `:data' must be present. */
9638 if (!kw[XBM_WIDTH].count
9639 || !kw[XBM_HEIGHT].count
9640 || !kw[XBM_DATA].count)
9641 return 0;
9642
9643 data = kw[XBM_DATA].value;
9644 width = XFASTINT (kw[XBM_WIDTH].value);
9645 height = XFASTINT (kw[XBM_HEIGHT].value);
9646
9647 /* Check type of data, and width and height against contents of
9648 data. */
9649 if (VECTORP (data))
9650 {
9651 int i;
9652
9653 /* Number of elements of the vector must be >= height. */
9654 if (XVECTOR (data)->size < height)
9655 return 0;
9656
9657 /* Each string or bool-vector in data must be large enough
9658 for one line of the image. */
9659 for (i = 0; i < height; ++i)
9660 {
9661 Lisp_Object elt = XVECTOR (data)->contents[i];
9662
9663 if (STRINGP (elt))
9664 {
9665 if (SCHARS (elt)
9666 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
9667 return 0;
9668 }
9669 else if (BOOL_VECTOR_P (elt))
9670 {
9671 if (XBOOL_VECTOR (elt)->size < width)
9672 return 0;
9673 }
9674 else
9675 return 0;
9676 }
9677 }
9678 else if (STRINGP (data))
9679 {
9680 if (SCHARS (data)
9681 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
9682 return 0;
9683 }
9684 else if (BOOL_VECTOR_P (data))
9685 {
9686 if (XBOOL_VECTOR (data)->size < width * height)
9687 return 0;
9688 }
9689 else
9690 return 0;
9691 }
9692
9693 return 1;
9694}
9695
9696
9697/* Scan a bitmap file. FP is the stream to read from. Value is
9698 either an enumerator from enum xbm_token, or a character for a
9699 single-character token, or 0 at end of file. If scanning an
9700 identifier, store the lexeme of the identifier in SVAL. If
9701 scanning a number, store its value in *IVAL. */
9702
9703static int
9704xbm_scan (s, end, sval, ival)
9705 char **s, *end;
9706 char *sval;
9707 int *ival;
9708{
9709 int c;
9710
9711 loop:
9712
9713 /* Skip white space. */
9714 while (*s < end && (c = *(*s)++, isspace (c)))
9715 ;
9716
9717 if (*s >= end)
9718 c = 0;
9719 else if (isdigit (c))
9720 {
9721 int value = 0, digit;
9722
9723 if (c == '0' && *s < end)
9724 {
9725 c = *(*s)++;
9726 if (c == 'x' || c == 'X')
9727 {
9728 while (*s < end)
9729 {
9730 c = *(*s)++;
9731 if (isdigit (c))
9732 digit = c - '0';
9733 else if (c >= 'a' && c <= 'f')
9734 digit = c - 'a' + 10;
9735 else if (c >= 'A' && c <= 'F')
9736 digit = c - 'A' + 10;
9737 else
9738 break;
9739 value = 16 * value + digit;
9740 }
9741 }
9742 else if (isdigit (c))
9743 {
9744 value = c - '0';
9745 while (*s < end
9746 && (c = *(*s)++, isdigit (c)))
9747 value = 8 * value + c - '0';
9748 }
9749 }
9750 else
9751 {
9752 value = c - '0';
9753 while (*s < end
9754 && (c = *(*s)++, isdigit (c)))
9755 value = 10 * value + c - '0';
9756 }
9757
9758 if (*s < end)
9759 *s = *s - 1;
9760 *ival = value;
9761 c = XBM_TK_NUMBER;
9762 }
9763 else if (isalpha (c) || c == '_')
9764 {
9765 *sval++ = c;
9766 while (*s < end
9767 && (c = *(*s)++, (isalnum (c) || c == '_')))
9768 *sval++ = c;
9769 *sval = 0;
9770 if (*s < end)
9771 *s = *s - 1;
9772 c = XBM_TK_IDENT;
9773 }
9774 else if (c == '/' && **s == '*')
9775 {
9776 /* C-style comment. */
9777 ++*s;
9778 while (**s && (**s != '*' || *(*s + 1) != '/'))
9779 ++*s;
9780 if (**s)
9781 {
9782 *s += 2;
9783 goto loop;
9784 }
9785 }
9786
9787 return c;
9788}
9789
9790
9791/* XBM bits seem to be backward within bytes compared with how
9792 Windows does things. */
9793static unsigned char reflect_byte (unsigned char orig)
9794{
9795 int i;
9796 unsigned char reflected = 0x00;
9797 for (i = 0; i < 8; i++)
9798 {
9799 if (orig & (0x01 << i))
9800 reflected |= 0x80 >> i;
9801 }
9802 return reflected;
9803}
9804
9805
9806/* Create a Windows bitmap from X bitmap data. */
9807static HBITMAP
9808w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
9809{
9810 int i, j, w1, w2;
9811 char *bits, *p;
9812 HBITMAP bmp;
9813
9814 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
9815 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
9816 bits = (char *) xmalloc (height * w2);
9817 bzero (bits, height * w2);
9818 for (i = 0; i < height; i++)
9819 {
9820 p = bits + i*w2;
9821 for (j = 0; j < w1; j++)
9822 *p++ = reflect_byte(*data++);
9823 }
9824 bmp = CreateBitmap (width, height, 1, 1, bits);
9825 xfree (bits);
9826
9827 return bmp;
9828}
9829
9830
9831/* Replacement for XReadBitmapFileData which isn't available under old
9832 X versions. CONTENTS is a pointer to a buffer to parse; END is the
9833 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
9834 the image. Return in *DATA the bitmap data allocated with xmalloc.
9835 Value is non-zero if successful. DATA null means just test if
9836 CONTENTS looks like an in-memory XBM file. */
9837
9838static int
9839xbm_read_bitmap_data (contents, end, width, height, data)
9840 char *contents, *end;
9841 int *width, *height;
9842 unsigned char **data;
9843{
9844 char *s = contents;
9845 char buffer[BUFSIZ];
9846 int padding_p = 0;
9847 int v10 = 0;
9848 int bytes_per_line, i, nbytes;
9849 unsigned char *p;
9850 int value;
9851 int LA1;
9852
9853#define match() \
9854 LA1 = xbm_scan (&s, end, buffer, &value)
9855
9856#define expect(TOKEN) \
9857 if (LA1 != (TOKEN)) \
9858 goto failure; \
9859 else \
9860 match ()
9861
9862#define expect_ident(IDENT) \
9863 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
9864 match (); \
9865 else \
9866 goto failure
9867
9868 *width = *height = -1;
9869 if (data)
9870 *data = NULL;
9871 LA1 = xbm_scan (&s, end, buffer, &value);
9872
9873 /* Parse defines for width, height and hot-spots. */
9874 while (LA1 == '#')
9875 {
9876 match ();
9877 expect_ident ("define");
9878 expect (XBM_TK_IDENT);
9879
9880 if (LA1 == XBM_TK_NUMBER);
9881 {
9882 char *p = strrchr (buffer, '_');
9883 p = p ? p + 1 : buffer;
9884 if (strcmp (p, "width") == 0)
9885 *width = value;
9886 else if (strcmp (p, "height") == 0)
9887 *height = value;
9888 }
9889 expect (XBM_TK_NUMBER);
9890 }
9891
9892 if (*width < 0 || *height < 0)
9893 goto failure;
9894 else if (data == NULL)
9895 goto success;
9896
9897 /* Parse bits. Must start with `static'. */
9898 expect_ident ("static");
9899 if (LA1 == XBM_TK_IDENT)
9900 {
9901 if (strcmp (buffer, "unsigned") == 0)
9902 {
9903 match ();
9904 expect_ident ("char");
9905 }
9906 else if (strcmp (buffer, "short") == 0)
9907 {
9908 match ();
9909 v10 = 1;
9910 if (*width % 16 && *width % 16 < 9)
9911 padding_p = 1;
9912 }
9913 else if (strcmp (buffer, "char") == 0)
9914 match ();
9915 else
9916 goto failure;
9917 }
9918 else
9919 goto failure;
9920
9921 expect (XBM_TK_IDENT);
9922 expect ('[');
9923 expect (']');
9924 expect ('=');
9925 expect ('{');
9926
9927 bytes_per_line = (*width + 7) / 8 + padding_p;
9928 nbytes = bytes_per_line * *height;
9929 p = *data = (char *) xmalloc (nbytes);
9930
9931 if (v10)
9932 {
9933 for (i = 0; i < nbytes; i += 2)
9934 {
9935 int val = value;
9936 expect (XBM_TK_NUMBER);
9937
9938 *p++ = ~ val;
9939 if (!padding_p || ((i + 2) % bytes_per_line))
9940 *p++ = ~ (value >> 8);
9941
9942 if (LA1 == ',' || LA1 == '}')
9943 match ();
9944 else
9945 goto failure;
9946 }
9947 }
9948 else
9949 {
9950 for (i = 0; i < nbytes; ++i)
9951 {
9952 int val = value;
9953 expect (XBM_TK_NUMBER);
9954
9955 *p++ = ~ val;
9956
9957 if (LA1 == ',' || LA1 == '}')
9958 match ();
9959 else
9960 goto failure;
9961 }
9962 }
9963
9964 success:
9965 return 1;
9966
9967 failure:
9968
9969 if (data && *data)
9970 {
9971 xfree (*data);
9972 *data = NULL;
9973 }
9974 return 0;
9975
9976#undef match
9977#undef expect
9978#undef expect_ident
9979}
9980
9981static void convert_mono_to_color_image (f, img, foreground, background)
9982 struct frame *f;
9983 struct image *img;
9984 COLORREF foreground, background;
9985{
9986 HDC hdc, old_img_dc, new_img_dc;
9987 HGDIOBJ old_prev, new_prev;
9988 HBITMAP new_pixmap;
9989
9990 hdc = get_frame_dc (f);
9991 old_img_dc = CreateCompatibleDC (hdc);
9992 new_img_dc = CreateCompatibleDC (hdc);
9993 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
9994 release_frame_dc (f, hdc);
9995 old_prev = SelectObject (old_img_dc, img->pixmap);
9996 new_prev = SelectObject (new_img_dc, new_pixmap);
9997 SetTextColor (new_img_dc, foreground);
9998 SetBkColor (new_img_dc, background);
9999
10000 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
10001 0, 0, SRCCOPY);
10002
10003 SelectObject (old_img_dc, old_prev);
10004 SelectObject (new_img_dc, new_prev);
10005 DeleteDC (old_img_dc);
10006 DeleteDC (new_img_dc);
10007 DeleteObject (img->pixmap);
10008 if (new_pixmap == 0)
10009 fprintf (stderr, "Failed to convert image to color.\n");
10010 else
10011 img->pixmap = new_pixmap;
10012}
10013
10014/* Load XBM image IMG which will be displayed on frame F from buffer
10015 CONTENTS. END is the end of the buffer. Value is non-zero if
10016 successful. */
10017
10018static int
10019xbm_load_image (f, img, contents, end)
10020 struct frame *f;
10021 struct image *img;
10022 char *contents, *end;
10023{
10024 int rc;
10025 unsigned char *data;
10026 int success_p = 0;
10027
10028 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
10029 if (rc)
10030 {
10031 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
10032 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
10033 int non_default_colors = 0;
10034 Lisp_Object value;
10035
10036 xassert (img->width > 0 && img->height > 0);
10037
10038 /* Get foreground and background colors, maybe allocate colors. */
10039 value = image_spec_value (img->spec, QCforeground, NULL);
10040 if (!NILP (value))
10041 {
10042 foreground = x_alloc_image_color (f, img, value, foreground);
10043 non_default_colors = 1;
10044 }
10045 value = image_spec_value (img->spec, QCbackground, NULL);
10046 if (!NILP (value))
10047 {
10048 background = x_alloc_image_color (f, img, value, background);
10049 img->background = background;
10050 img->background_valid = 1;
10051 non_default_colors = 1;
10052 }
10053 img->pixmap
10054 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
10055
10056 /* If colors were specified, transfer the bitmap to a color one. */
10057 if (non_default_colors)
10058 convert_mono_to_color_image (f, img, foreground, background);
10059
10060 xfree (data);
10061
10062 if (img->pixmap == 0)
10063 {
10064 x_clear_image (f, img);
10065 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
10066 }
10067 else
10068 success_p = 1;
10069 }
10070 else
10071 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10072
10073 return success_p;
10074}
10075
10076
10077/* Value is non-zero if DATA looks like an in-memory XBM file. */
10078
10079static int
10080xbm_file_p (data)
10081 Lisp_Object data;
10082{
10083 int w, h;
10084 return (STRINGP (data)
10085 && xbm_read_bitmap_data (SDATA (data),
10086 (SDATA (data)
10087 + SBYTES (data)),
10088 &w, &h, NULL));
10089}
10090
10091
10092/* Fill image IMG which is used on frame F with pixmap data. Value is
10093 non-zero if successful. */
10094
10095static int
10096xbm_load (f, img)
10097 struct frame *f;
10098 struct image *img;
10099{
10100 int success_p = 0;
10101 Lisp_Object file_name;
10102
10103 xassert (xbm_image_p (img->spec));
10104
10105 /* If IMG->spec specifies a file name, create a non-file spec from it. */
10106 file_name = image_spec_value (img->spec, QCfile, NULL);
10107 if (STRINGP (file_name))
10108 {
10109 Lisp_Object file;
10110 char *contents;
10111 int size;
10112 struct gcpro gcpro1;
10113
10114 file = x_find_image_file (file_name);
10115 GCPRO1 (file);
10116 if (!STRINGP (file))
10117 {
10118 image_error ("Cannot find image file `%s'", file_name, Qnil);
10119 UNGCPRO;
10120 return 0;
10121 }
10122
10123 contents = slurp_file (SDATA (file), &size);
10124 if (contents == NULL)
10125 {
10126 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
10127 UNGCPRO;
10128 return 0;
10129 }
10130
10131 success_p = xbm_load_image (f, img, contents, contents + size);
10132 UNGCPRO;
10133 }
10134 else
10135 {
10136 struct image_keyword fmt[XBM_LAST];
10137 Lisp_Object data;
10138 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
10139 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
10140 int non_default_colors = 0;
10141 char *bits;
10142 int parsed_p;
10143 int in_memory_file_p = 0;
10144
10145 /* See if data looks like an in-memory XBM file. */
10146 data = image_spec_value (img->spec, QCdata, NULL);
10147 in_memory_file_p = xbm_file_p (data);
10148
10149 /* Parse the image specification. */
10150 bcopy (xbm_format, fmt, sizeof fmt);
10151 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
10152 xassert (parsed_p);
10153
10154 /* Get specified width, and height. */
10155 if (!in_memory_file_p)
10156 {
10157 img->width = XFASTINT (fmt[XBM_WIDTH].value);
10158 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
10159 xassert (img->width > 0 && img->height > 0);
10160 }
10161
10162 /* Get foreground and background colors, maybe allocate colors. */
10163 if (fmt[XBM_FOREGROUND].count
10164 && STRINGP (fmt[XBM_FOREGROUND].value))
10165 {
10166 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
10167 foreground);
10168 non_default_colors = 1;
10169 }
10170
10171 if (fmt[XBM_BACKGROUND].count
10172 && STRINGP (fmt[XBM_BACKGROUND].value))
10173 {
10174 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
10175 background);
10176 non_default_colors = 1;
10177 }
10178
10179 if (in_memory_file_p)
10180 success_p = xbm_load_image (f, img, SDATA (data),
10181 (SDATA (data)
10182 + SBYTES (data)));
10183 else
10184 {
10185 if (VECTORP (data))
10186 {
10187 int i;
10188 char *p;
10189 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
10190
10191 p = bits = (char *) alloca (nbytes * img->height);
10192 for (i = 0; i < img->height; ++i, p += nbytes)
10193 {
10194 Lisp_Object line = XVECTOR (data)->contents[i];
10195 if (STRINGP (line))
10196 bcopy (SDATA (line), p, nbytes);
10197 else
10198 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
10199 }
10200 }
10201 else if (STRINGP (data))
10202 bits = SDATA (data);
10203 else
10204 bits = XBOOL_VECTOR (data)->data;
10205
10206 /* Create the pixmap. */
10207 img->pixmap
10208 = w32_create_pixmap_from_bitmap_data (img->width, img->height,
10209 bits);
10210
10211 /* If colors were specified, transfer the bitmap to a color one. */
10212 if (non_default_colors)
10213 convert_mono_to_color_image (f, img, foreground, background);
10214
10215 if (img->pixmap)
10216 success_p = 1;
10217 else
10218 {
10219 image_error ("Unable to create pixmap for XBM image `%s'",
10220 img->spec, Qnil);
10221 x_clear_image (f, img);
10222 }
10223 }
10224 }
10225
10226 return success_p;
10227}
10228
10229
10230\f
10231/***********************************************************************
10232 XPM images
10233 ***********************************************************************/
10234
10235#if HAVE_XPM
10236
10237static int xpm_image_p P_ ((Lisp_Object object));
10238static int xpm_load P_ ((struct frame *f, struct image *img));
10239static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
10240
10241#include "X11/xpm.h"
10242
10243/* The symbol `xpm' identifying XPM-format images. */
10244
10245Lisp_Object Qxpm;
10246
10247/* Indices of image specification fields in xpm_format, below. */
10248
10249enum xpm_keyword_index
10250{
10251 XPM_TYPE,
10252 XPM_FILE,
10253 XPM_DATA,
10254 XPM_ASCENT,
10255 XPM_MARGIN,
10256 XPM_RELIEF,
10257 XPM_ALGORITHM,
10258 XPM_HEURISTIC_MASK,
10259 XPM_MASK,
10260 XPM_COLOR_SYMBOLS,
10261 XPM_BACKGROUND,
10262 XPM_LAST
10263};
10264
10265/* Vector of image_keyword structures describing the format
10266 of valid XPM image specifications. */
10267
10268static struct image_keyword xpm_format[XPM_LAST] =
10269{
10270 {":type", IMAGE_SYMBOL_VALUE, 1},
10271 {":file", IMAGE_STRING_VALUE, 0},
10272 {":data", IMAGE_STRING_VALUE, 0},
10273 {":ascent", IMAGE_ASCENT_VALUE, 0},
10274 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
10275 {":relief", IMAGE_INTEGER_VALUE, 0},
10276 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10277 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10278 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10279 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10280 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
10281};
10282
10283/* Structure describing the image type XPM. */
10284
10285static struct image_type xpm_type =
10286{
10287 &Qxpm,
10288 xpm_image_p,
10289 xpm_load,
10290 x_clear_image,
10291 NULL
10292};
10293
10294
10295/* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
10296 for XPM images. Such a list must consist of conses whose car and
10297 cdr are strings. */
10298
10299static int
10300xpm_valid_color_symbols_p (color_symbols)
10301 Lisp_Object color_symbols;
10302{
10303 while (CONSP (color_symbols))
10304 {
10305 Lisp_Object sym = XCAR (color_symbols);
10306 if (!CONSP (sym)
10307 || !STRINGP (XCAR (sym))
10308 || !STRINGP (XCDR (sym)))
10309 break;
10310 color_symbols = XCDR (color_symbols);
10311 }
10312
10313 return NILP (color_symbols);
10314}
10315
10316
10317/* Value is non-zero if OBJECT is a valid XPM image specification. */
10318
10319static int
10320xpm_image_p (object)
10321 Lisp_Object object;
10322{
10323 struct image_keyword fmt[XPM_LAST];
10324 bcopy (xpm_format, fmt, sizeof fmt);
10325 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
10326 /* Either `:file' or `:data' must be present. */
10327 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
10328 /* Either no `:color-symbols' or it's a list of conses
10329 whose car and cdr are strings. */
10330 && (fmt[XPM_COLOR_SYMBOLS].count == 0
10331 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
10332}
10333
10334
10335/* Load image IMG which will be displayed on frame F. Value is
10336 non-zero if successful. */
10337
10338static int
10339xpm_load (f, img)
10340 struct frame *f;
10341 struct image *img;
10342{
10343 int rc, i;
10344 XpmAttributes attrs;
10345 Lisp_Object specified_file, color_symbols;
10346
10347 /* Configure the XPM lib. Use the visual of frame F. Allocate
10348 close colors. Return colors allocated. */
10349 bzero (&attrs, sizeof attrs);
10350 attrs.visual = FRAME_X_VISUAL (f);
10351 attrs.colormap = FRAME_X_COLORMAP (f);
10352 attrs.valuemask |= XpmVisual;
10353 attrs.valuemask |= XpmColormap;
10354 attrs.valuemask |= XpmReturnAllocPixels;
10355#ifdef XpmAllocCloseColors
10356 attrs.alloc_close_colors = 1;
10357 attrs.valuemask |= XpmAllocCloseColors;
10358#else
10359 attrs.closeness = 600;
10360 attrs.valuemask |= XpmCloseness;
10361#endif
10362
10363 /* If image specification contains symbolic color definitions, add
10364 these to `attrs'. */
10365 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
10366 if (CONSP (color_symbols))
10367 {
10368 Lisp_Object tail;
10369 XpmColorSymbol *xpm_syms;
10370 int i, size;
10371
10372 attrs.valuemask |= XpmColorSymbols;
10373
10374 /* Count number of symbols. */
10375 attrs.numsymbols = 0;
10376 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
10377 ++attrs.numsymbols;
10378
10379 /* Allocate an XpmColorSymbol array. */
10380 size = attrs.numsymbols * sizeof *xpm_syms;
10381 xpm_syms = (XpmColorSymbol *) alloca (size);
10382 bzero (xpm_syms, size);
10383 attrs.colorsymbols = xpm_syms;
10384
10385 /* Fill the color symbol array. */
10386 for (tail = color_symbols, i = 0;
10387 CONSP (tail);
10388 ++i, tail = XCDR (tail))
10389 {
10390 Lisp_Object name = XCAR (XCAR (tail));
10391 Lisp_Object color = XCDR (XCAR (tail));
10392 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
10393 strcpy (xpm_syms[i].name, SDATA (name));
10394 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
10395 strcpy (xpm_syms[i].value, SDATA (color));
10396 }
10397 }
10398
10399 /* Create a pixmap for the image, either from a file, or from a
10400 string buffer containing data in the same format as an XPM file. */
10401 BLOCK_INPUT;
10402 specified_file = image_spec_value (img->spec, QCfile, NULL);
10403 if (STRINGP (specified_file))
10404 {
10405 Lisp_Object file = x_find_image_file (specified_file);
10406 if (!STRINGP (file))
10407 {
10408 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10409 UNBLOCK_INPUT;
10410 return 0;
10411 }
10412
10413 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
10414 SDATA (file), &img->pixmap, &img->mask,
10415 &attrs);
10416 }
10417 else
10418 {
10419 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
10420 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
10421 SDATA (buffer),
10422 &img->pixmap, &img->mask,
10423 &attrs);
10424 }
10425 UNBLOCK_INPUT;
10426
10427 if (rc == XpmSuccess)
10428 {
10429 /* Remember allocated colors. */
10430 img->ncolors = attrs.nalloc_pixels;
10431 img->colors = (unsigned long *) xmalloc (img->ncolors
10432 * sizeof *img->colors);
10433 for (i = 0; i < attrs.nalloc_pixels; ++i)
10434 img->colors[i] = attrs.alloc_pixels[i];
10435
10436 img->width = attrs.width;
10437 img->height = attrs.height;
10438 xassert (img->width > 0 && img->height > 0);
10439
10440 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
10441 BLOCK_INPUT;
10442 XpmFreeAttributes (&attrs);
10443 UNBLOCK_INPUT;
10444 }
10445 else
10446 {
10447 switch (rc)
10448 {
10449 case XpmOpenFailed:
10450 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
10451 break;
10452
10453 case XpmFileInvalid:
10454 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
10455 break;
10456
10457 case XpmNoMemory:
10458 image_error ("Out of memory (%s)", img->spec, Qnil);
10459 break;
10460
10461 case XpmColorFailed:
10462 image_error ("Color allocation error (%s)", img->spec, Qnil);
10463 break;
10464
10465 default:
10466 image_error ("Unknown error (%s)", img->spec, Qnil);
10467 break;
10468 }
10469 }
10470
10471 return rc == XpmSuccess;
10472}
10473
10474#endif /* HAVE_XPM != 0 */
10475
10476\f
10477#if 0 /* TODO : Color tables on W32. */
10478/***********************************************************************
10479 Color table
10480 ***********************************************************************/
10481
10482/* An entry in the color table mapping an RGB color to a pixel color. */
10483
10484struct ct_color
10485{
10486 int r, g, b;
10487 unsigned long pixel;
10488
10489 /* Next in color table collision list. */
10490 struct ct_color *next;
10491};
10492
10493/* The bucket vector size to use. Must be prime. */
10494
10495#define CT_SIZE 101
10496
10497/* Value is a hash of the RGB color given by R, G, and B. */
10498
10499#define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
10500
10501/* The color hash table. */
10502
10503struct ct_color **ct_table;
10504
10505/* Number of entries in the color table. */
10506
10507int ct_colors_allocated;
10508
10509/* Function prototypes. */
10510
10511static void init_color_table P_ ((void));
10512static void free_color_table P_ ((void));
10513static unsigned long *colors_in_color_table P_ ((int *n));
10514static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
10515static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
10516
10517
10518/* Initialize the color table. */
10519
10520static void
10521init_color_table ()
10522{
10523 int size = CT_SIZE * sizeof (*ct_table);
10524 ct_table = (struct ct_color **) xmalloc (size);
10525 bzero (ct_table, size);
10526 ct_colors_allocated = 0;
10527}
10528
10529
10530/* Free memory associated with the color table. */
10531
10532static void
10533free_color_table ()
10534{
10535 int i;
10536 struct ct_color *p, *next;
10537
10538 for (i = 0; i < CT_SIZE; ++i)
10539 for (p = ct_table[i]; p; p = next)
10540 {
10541 next = p->next;
10542 xfree (p);
10543 }
10544
10545 xfree (ct_table);
10546 ct_table = NULL;
10547}
10548
10549
10550/* Value is a pixel color for RGB color R, G, B on frame F. If an
10551 entry for that color already is in the color table, return the
10552 pixel color of that entry. Otherwise, allocate a new color for R,
10553 G, B, and make an entry in the color table. */
10554
10555static unsigned long
10556lookup_rgb_color (f, r, g, b)
10557 struct frame *f;
10558 int r, g, b;
10559{
10560 unsigned hash = CT_HASH_RGB (r, g, b);
10561 int i = hash % CT_SIZE;
10562 struct ct_color *p;
10563
10564 for (p = ct_table[i]; p; p = p->next)
10565 if (p->r == r && p->g == g && p->b == b)
10566 break;
10567
10568 if (p == NULL)
10569 {
10570 COLORREF color;
10571 Colormap cmap;
10572 int rc;
10573
10574 color = PALETTERGB (r, g, b);
10575
10576 ++ct_colors_allocated;
10577
10578 p = (struct ct_color *) xmalloc (sizeof *p);
10579 p->r = r;
10580 p->g = g;
10581 p->b = b;
10582 p->pixel = color;
10583 p->next = ct_table[i];
10584 ct_table[i] = p;
10585 }
10586
10587 return p->pixel;
10588}
10589
10590
10591/* Look up pixel color PIXEL which is used on frame F in the color
10592 table. If not already present, allocate it. Value is PIXEL. */
10593
10594static unsigned long
10595lookup_pixel_color (f, pixel)
10596 struct frame *f;
10597 unsigned long pixel;
10598{
10599 int i = pixel % CT_SIZE;
10600 struct ct_color *p;
10601
10602 for (p = ct_table[i]; p; p = p->next)
10603 if (p->pixel == pixel)
10604 break;
10605
10606 if (p == NULL)
10607 {
10608 XColor color;
10609 Colormap cmap;
10610 int rc;
10611
10612 BLOCK_INPUT;
10613
10614 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10615 color.pixel = pixel;
10616 XQueryColor (NULL, cmap, &color);
10617 rc = x_alloc_nearest_color (f, cmap, &color);
10618 UNBLOCK_INPUT;
10619
10620 if (rc)
10621 {
10622 ++ct_colors_allocated;
10623
10624 p = (struct ct_color *) xmalloc (sizeof *p);
10625 p->r = color.red;
10626 p->g = color.green;
10627 p->b = color.blue;
10628 p->pixel = pixel;
10629 p->next = ct_table[i];
10630 ct_table[i] = p;
10631 }
10632 else
10633 return FRAME_FOREGROUND_PIXEL (f);
10634 }
10635 return p->pixel;
10636}
10637
10638
10639/* Value is a vector of all pixel colors contained in the color table,
10640 allocated via xmalloc. Set *N to the number of colors. */
10641
10642static unsigned long *
10643colors_in_color_table (n)
10644 int *n;
10645{
10646 int i, j;
10647 struct ct_color *p;
10648 unsigned long *colors;
10649
10650 if (ct_colors_allocated == 0)
10651 {
10652 *n = 0;
10653 colors = NULL;
10654 }
10655 else
10656 {
10657 colors = (unsigned long *) xmalloc (ct_colors_allocated
10658 * sizeof *colors);
10659 *n = ct_colors_allocated;
10660
10661 for (i = j = 0; i < CT_SIZE; ++i)
10662 for (p = ct_table[i]; p; p = p->next)
10663 colors[j++] = p->pixel;
10664 }
10665
10666 return colors;
10667}
10668
10669#endif /* TODO */
10670
10671\f
10672/***********************************************************************
10673 Algorithms
10674 ***********************************************************************/
10675static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
10676static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
10677static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
10678static void XPutPixel (XImage *, int, int, COLORREF);
10679
10680/* Non-zero means draw a cross on images having `:conversion
10681 disabled'. */
10682
10683int cross_disabled_images;
10684
10685/* Edge detection matrices for different edge-detection
10686 strategies. */
10687
10688static int emboss_matrix[9] = {
10689 /* x - 1 x x + 1 */
10690 2, -1, 0, /* y - 1 */
10691 -1, 0, 1, /* y */
10692 0, 1, -2 /* y + 1 */
10693};
10694
10695static int laplace_matrix[9] = {
10696 /* x - 1 x x + 1 */
10697 1, 0, 0, /* y - 1 */
10698 0, 0, 0, /* y */
10699 0, 0, -1 /* y + 1 */
10700};
10701
10702/* Value is the intensity of the color whose red/green/blue values
10703 are R, G, and B. */
10704
10705#define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
10706
10707
10708/* On frame F, return an array of XColor structures describing image
10709 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
10710 non-zero means also fill the red/green/blue members of the XColor
10711 structures. Value is a pointer to the array of XColors structures,
10712 allocated with xmalloc; it must be freed by the caller. */
10713
10714static XColor *
10715x_to_xcolors (f, img, rgb_p)
10716 struct frame *f;
10717 struct image *img;
10718 int rgb_p;
10719{
10720 int x, y;
10721 XColor *colors, *p;
10722 HDC hdc, bmpdc;
10723 HGDIOBJ prev;
10724
10725 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
10726
10727 /* Load the image into a memory device context. */
10728 hdc = get_frame_dc (f);
10729 bmpdc = CreateCompatibleDC (hdc);
10730 release_frame_dc (f, hdc);
10731 prev = SelectObject (bmpdc, img->pixmap);
10732
10733 /* Fill the `pixel' members of the XColor array. I wished there
10734 were an easy and portable way to circumvent XGetPixel. */
10735 p = colors;
10736 for (y = 0; y < img->height; ++y)
10737 {
10738 XColor *row = p;
10739
10740 for (x = 0; x < img->width; ++x, ++p)
10741 {
10742 /* TODO: palette support needed here? */
10743 p->pixel = GetPixel (bmpdc, x, y);
10744
10745 if (rgb_p)
10746 {
10747 p->red = 256 * GetRValue (p->pixel);
10748 p->green = 256 * GetGValue (p->pixel);
10749 p->blue = 256 * GetBValue (p->pixel);
10750 }
10751 }
10752 }
10753
10754 SelectObject (bmpdc, prev);
10755 DeleteDC (bmpdc);
10756
10757 return colors;
10758}
10759
10760/* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
10761 created with CreateDIBSection, with the pointer to the bit values
10762 stored in ximg->data. */
10763
10764static void XPutPixel (ximg, x, y, color)
10765 XImage * ximg;
10766 int x, y;
10767 COLORREF color;
10768{
10769 int width = ximg->info.bmiHeader.biWidth;
10770 int height = ximg->info.bmiHeader.biHeight;
10771 int rowbytes = width * 3;
10772 unsigned char * pixel;
10773
10774 /* Don't support putting pixels in images with palettes. */
10775 xassert (ximg->info.bmiHeader.biBitCount == 24);
10776
10777 /* Ensure scanlines are aligned on 4 byte boundaries. */
10778 if (rowbytes % 4)
10779 rowbytes += 4 - (rowbytes % 4);
10780
10781 pixel = ximg->data + y * rowbytes + x * 3;
10782 /* Windows bitmaps are in BGR order. */
10783 *pixel = GetBValue (color);
10784 *(pixel + 1) = GetGValue (color);
10785 *(pixel + 2) = GetRValue (color);
10786}
10787
10788
10789/* Create IMG->pixmap from an array COLORS of XColor structures, whose
10790 RGB members are set. F is the frame on which this all happens.
10791 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
10792
10793static void
10794x_from_xcolors (f, img, colors)
10795 struct frame *f;
10796 struct image *img;
10797 XColor *colors;
10798{
10799 int x, y;
10800 XImage *oimg;
10801 Pixmap pixmap;
10802 XColor *p;
10803#if 0 /* TODO: color tables. */
10804 init_color_table ();
10805#endif
10806 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
10807 &oimg, &pixmap);
10808 p = colors;
10809 for (y = 0; y < img->height; ++y)
10810 for (x = 0; x < img->width; ++x, ++p)
10811 {
10812 unsigned long pixel;
10813#if 0 /* TODO: color tables. */
10814 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
10815#else
10816 pixel = PALETTERGB (p->red / 256, p->green / 256, p->blue / 256);
10817#endif
10818 XPutPixel (oimg, x, y, pixel);
10819 }
10820
10821 xfree (colors);
10822 x_clear_image_1 (f, img, 1, 0, 1);
10823
10824 x_put_x_image (f, oimg, pixmap, img->width, img->height);
10825 x_destroy_x_image (oimg);
10826 img->pixmap = pixmap;
10827#if 0 /* TODO: color tables. */
10828 img->colors = colors_in_color_table (&img->ncolors);
10829 free_color_table ();
10830#endif
10831}
10832
10833
10834/* On frame F, perform edge-detection on image IMG.
10835
10836 MATRIX is a nine-element array specifying the transformation
10837 matrix. See emboss_matrix for an example.
10838
10839 COLOR_ADJUST is a color adjustment added to each pixel of the
10840 outgoing image. */
10841
10842static void
10843x_detect_edges (f, img, matrix, color_adjust)
10844 struct frame *f;
10845 struct image *img;
10846 int matrix[9], color_adjust;
10847{
10848 XColor *colors = x_to_xcolors (f, img, 1);
10849 XColor *new, *p;
10850 int x, y, i, sum;
10851
10852 for (i = sum = 0; i < 9; ++i)
10853 sum += abs (matrix[i]);
10854
10855#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
10856
10857 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
10858
10859 for (y = 0; y < img->height; ++y)
10860 {
10861 p = COLOR (new, 0, y);
10862 p->red = p->green = p->blue = 0xffff/2;
10863 p = COLOR (new, img->width - 1, y);
10864 p->red = p->green = p->blue = 0xffff/2;
10865 }
10866
10867 for (x = 1; x < img->width - 1; ++x)
10868 {
10869 p = COLOR (new, x, 0);
10870 p->red = p->green = p->blue = 0xffff/2;
10871 p = COLOR (new, x, img->height - 1);
10872 p->red = p->green = p->blue = 0xffff/2;
10873 }
10874
10875 for (y = 1; y < img->height - 1; ++y)
10876 {
10877 p = COLOR (new, 1, y);
10878
10879 for (x = 1; x < img->width - 1; ++x, ++p)
10880 {
10881 int r, g, b, y1, x1;
10882
10883 r = g = b = i = 0;
10884 for (y1 = y - 1; y1 < y + 2; ++y1)
10885 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
10886 if (matrix[i])
10887 {
10888 XColor *t = COLOR (colors, x1, y1);
10889 r += matrix[i] * t->red;
10890 g += matrix[i] * t->green;
10891 b += matrix[i] * t->blue;
10892 }
10893
10894 r = (r / sum + color_adjust) & 0xffff;
10895 g = (g / sum + color_adjust) & 0xffff;
10896 b = (b / sum + color_adjust) & 0xffff;
10897 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
10898 }
10899 }
10900
10901 xfree (colors);
10902 x_from_xcolors (f, img, new);
10903
10904#undef COLOR
10905}
10906
10907
10908/* Perform the pre-defined `emboss' edge-detection on image IMG
10909 on frame F. */
10910
10911static void
10912x_emboss (f, img)
10913 struct frame *f;
10914 struct image *img;
10915{
10916 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
10917}
10918
10919
10920/* Transform image IMG which is used on frame F with a Laplace
10921 edge-detection algorithm. The result is an image that can be used
10922 to draw disabled buttons, for example. */
10923
10924static void
10925x_laplace (f, img)
10926 struct frame *f;
10927 struct image *img;
10928{
10929 x_detect_edges (f, img, laplace_matrix, 45000);
10930}
10931
10932
10933/* Perform edge-detection on image IMG on frame F, with specified
10934 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
10935
10936 MATRIX must be either
10937
10938 - a list of at least 9 numbers in row-major form
10939 - a vector of at least 9 numbers
10940
10941 COLOR_ADJUST nil means use a default; otherwise it must be a
10942 number. */
10943
10944static void
10945x_edge_detection (f, img, matrix, color_adjust)
10946 struct frame *f;
10947 struct image *img;
10948 Lisp_Object matrix, color_adjust;
10949{
10950 int i = 0;
10951 int trans[9];
10952
10953 if (CONSP (matrix))
10954 {
10955 for (i = 0;
10956 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
10957 ++i, matrix = XCDR (matrix))
10958 trans[i] = XFLOATINT (XCAR (matrix));
10959 }
10960 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
10961 {
10962 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
10963 trans[i] = XFLOATINT (AREF (matrix, i));
10964 }
10965
10966 if (NILP (color_adjust))
10967 color_adjust = make_number (0xffff / 2);
10968
10969 if (i == 9 && NUMBERP (color_adjust))
10970 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
10971}
10972
10973
10974/* Transform image IMG on frame F so that it looks disabled. */
10975
10976static void
10977x_disable_image (f, img)
10978 struct frame *f;
10979 struct image *img;
10980{
10981 struct w32_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
10982
10983 if (dpyinfo->n_planes * dpyinfo->n_cbits >= 2)
10984 {
10985 /* Color (or grayscale). Convert to gray, and equalize. Just
10986 drawing such images with a stipple can look very odd, so
10987 we're using this method instead. */
10988 XColor *colors = x_to_xcolors (f, img, 1);
10989 XColor *p, *end;
10990 const int h = 15000;
10991 const int l = 30000;
10992
10993 for (p = colors, end = colors + img->width * img->height;
10994 p < end;
10995 ++p)
10996 {
10997 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
10998 int i2 = (0xffff - h - l) * i / 0xffff + l;
10999 p->red = p->green = p->blue = i2;
11000 }
11001
11002 x_from_xcolors (f, img, colors);
11003 }
11004
11005 /* Draw a cross over the disabled image, if we must or if we
11006 should. */
11007 if (dpyinfo->n_planes * dpyinfo->n_cbits < 2 || cross_disabled_images)
11008 {
11009 HDC hdc, bmpdc;
11010 HGDIOBJ prev;
11011
11012 hdc = get_frame_dc (f);
11013 bmpdc = CreateCompatibleDC (hdc);
11014 release_frame_dc (f, hdc);
11015
11016 prev = SelectObject (bmpdc, img->pixmap);
11017
11018 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
11019 MoveToEx (bmpdc, 0, 0, NULL);
11020 LineTo (bmpdc, img->width - 1, img->height - 1);
11021 MoveToEx (bmpdc, 0, img->height - 1, NULL);
11022 LineTo (bmpdc, img->width - 1, 0);
11023
11024 if (img->mask)
11025 {
11026 SelectObject (bmpdc, img->mask);
11027 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
11028 MoveToEx (bmpdc, 0, 0, NULL);
11029 LineTo (bmpdc, img->width - 1, img->height - 1);
11030 MoveToEx (bmpdc, 0, img->height - 1, NULL);
11031 LineTo (bmpdc, img->width - 1, 0);
11032 }
11033 SelectObject (bmpdc, prev);
11034 DeleteDC (bmpdc);
11035 }
11036}
11037
11038
11039/* Build a mask for image IMG which is used on frame F. FILE is the
11040 name of an image file, for error messages. HOW determines how to
11041 determine the background color of IMG. If it is a list '(R G B)',
11042 with R, G, and B being integers >= 0, take that as the color of the
11043 background. Otherwise, determine the background color of IMG
11044 heuristically. Value is non-zero if successful. */
11045
11046static int
11047x_build_heuristic_mask (f, img, how)
11048 struct frame *f;
11049 struct image *img;
11050 Lisp_Object how;
11051{
11052 HDC img_dc, frame_dc;
11053 HGDIOBJ prev;
11054 char *mask_img;
11055 int x, y, rc, use_img_background;
11056 unsigned long bg = 0;
11057 int row_width;
11058
11059 if (img->mask)
11060 {
11061 DeleteObject (img->mask);
11062 img->mask = NULL;
11063 img->background_transparent_valid = 0;
11064 }
11065
11066 /* Create the bit array serving as mask. */
11067 row_width = (img->width + 7) / 8;
11068 mask_img = xmalloc (row_width * img->height);
11069 bzero (mask_img, row_width * img->height);
11070
11071 /* Create a memory device context for IMG->pixmap. */
11072 frame_dc = get_frame_dc (f);
11073 img_dc = CreateCompatibleDC (frame_dc);
11074 release_frame_dc (f, frame_dc);
11075 prev = SelectObject (img_dc, img->pixmap);
11076
11077 /* Determine the background color of img_dc. If HOW is `(R G B)'
11078 take that as color. Otherwise, use the image's background color. */
11079 use_img_background = 1;
11080
11081 if (CONSP (how))
11082 {
11083 int rgb[3], i;
11084
11085 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
11086 {
11087 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
11088 how = XCDR (how);
11089 }
11090
11091 if (i == 3 && NILP (how))
11092 {
11093 char color_name[30];
11094 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
11095 bg = x_alloc_image_color (f, img, build_string (color_name), 0)
11096 & 0x00ffffff; /* Filter out palette info. */
11097 use_img_background = 0;
11098 }
11099 }
11100
11101 if (use_img_background)
11102 bg = four_corners_best (img_dc, img->width, img->height);
11103
11104 /* Set all bits in mask_img to 1 whose color in ximg is different
11105 from the background color bg. */
11106 for (y = 0; y < img->height; ++y)
11107 for (x = 0; x < img->width; ++x)
11108 {
11109 COLORREF p = GetPixel (img_dc, x, y);
11110 if (p != bg)
11111 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
11112 }
11113
11114 /* Create the mask image. */
11115 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
11116 mask_img);
11117
11118 /* Fill in the background_transparent field while we have the mask handy. */
11119 SelectObject (img_dc, img->mask);
11120
11121 image_background_transparent (img, f, img_dc);
11122
11123 /* Put mask_img into img->mask. */
11124 x_destroy_x_image (mask_img);
11125 SelectObject (img_dc, prev);
11126 DeleteDC (img_dc);
11127
11128 return 1;
11129}
11130
11131\f
11132/***********************************************************************
11133 PBM (mono, gray, color)
11134 ***********************************************************************/
11135
11136static int pbm_image_p P_ ((Lisp_Object object));
11137static int pbm_load P_ ((struct frame *f, struct image *img));
11138static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
11139
11140/* The symbol `pbm' identifying images of this type. */
11141
11142Lisp_Object Qpbm;
11143
11144/* Indices of image specification fields in gs_format, below. */
11145
11146enum pbm_keyword_index
11147{
11148 PBM_TYPE,
11149 PBM_FILE,
11150 PBM_DATA,
11151 PBM_ASCENT,
11152 PBM_MARGIN,
11153 PBM_RELIEF,
11154 PBM_ALGORITHM,
11155 PBM_HEURISTIC_MASK,
11156 PBM_MASK,
11157 PBM_FOREGROUND,
11158 PBM_BACKGROUND,
11159 PBM_LAST
11160};
11161
11162/* Vector of image_keyword structures describing the format
11163 of valid user-defined image specifications. */
11164
11165static struct image_keyword pbm_format[PBM_LAST] =
11166{
11167 {":type", IMAGE_SYMBOL_VALUE, 1},
11168 {":file", IMAGE_STRING_VALUE, 0},
11169 {":data", IMAGE_STRING_VALUE, 0},
11170 {":ascent", IMAGE_ASCENT_VALUE, 0},
11171 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11172 {":relief", IMAGE_INTEGER_VALUE, 0},
11173 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11174 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11175 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11176 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
11177 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11178};
11179
11180/* Structure describing the image type `pbm'. */
11181
11182static struct image_type pbm_type =
11183{
11184 &Qpbm,
11185 pbm_image_p,
11186 pbm_load,
11187 x_clear_image,
11188 NULL
11189};
11190
11191
11192/* Return non-zero if OBJECT is a valid PBM image specification. */
11193
11194static int
11195pbm_image_p (object)
11196 Lisp_Object object;
11197{
11198 struct image_keyword fmt[PBM_LAST];
11199
11200 bcopy (pbm_format, fmt, sizeof fmt);
11201
11202 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
11203 return 0;
11204
11205 /* Must specify either :data or :file. */
11206 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
11207}
11208
11209
11210/* Scan a decimal number from *S and return it. Advance *S while
11211 reading the number. END is the end of the string. Value is -1 at
11212 end of input. */
11213
11214static int
11215pbm_scan_number (s, end)
11216 unsigned char **s, *end;
11217{
11218 int c, val = -1;
11219
11220 while (*s < end)
11221 {
11222 /* Skip white-space. */
11223 while (*s < end && (c = *(*s)++, isspace (c)))
11224 ;
11225
11226 if (c == '#')
11227 {
11228 /* Skip comment to end of line. */
11229 while (*s < end && (c = *(*s)++, c != '\n'))
11230 ;
11231 }
11232 else if (isdigit (c))
11233 {
11234 /* Read decimal number. */
11235 val = c - '0';
11236 while (*s < end && (c = *(*s)++, isdigit (c)))
11237 val = 10 * val + c - '0';
11238 break;
11239 }
11240 else
11241 break;
11242 }
11243
11244 return val;
11245}
11246
11247
11248/* Read FILE into memory. Value is a pointer to a buffer allocated
11249 with xmalloc holding FILE's contents. Value is null if an error
11250 occurred. *SIZE is set to the size of the file. */
11251
11252static char *
11253pbm_read_file (file, size)
11254 Lisp_Object file;
11255 int *size;
11256{
11257 FILE *fp = NULL;
11258 char *buf = NULL;
11259 struct stat st;
11260
11261 if (stat (SDATA (file), &st) == 0
11262 && (fp = fopen (SDATA (file), "r")) != NULL
11263 && (buf = (char *) xmalloc (st.st_size),
11264 fread (buf, 1, st.st_size, fp) == st.st_size))
11265 {
11266 *size = st.st_size;
11267 fclose (fp);
11268 }
11269 else
11270 {
11271 if (fp)
11272 fclose (fp);
11273 if (buf)
11274 {
11275 xfree (buf);
11276 buf = NULL;
11277 }
11278 }
11279
11280 return buf;
11281}
11282
11283
11284/* Load PBM image IMG for use on frame F. */
11285
11286static int
11287pbm_load (f, img)
11288 struct frame *f;
11289 struct image *img;
11290{
11291 int raw_p, x, y;
11292 int width, height, max_color_idx = 0;
11293 XImage *ximg;
11294 Lisp_Object file, specified_file;
11295 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
11296 struct gcpro gcpro1;
11297 unsigned char *contents = NULL;
11298 unsigned char *end, *p;
11299 int size;
11300
11301 specified_file = image_spec_value (img->spec, QCfile, NULL);
11302 file = Qnil;
11303 GCPRO1 (file);
11304
11305 if (STRINGP (specified_file))
11306 {
11307 file = x_find_image_file (specified_file);
11308 if (!STRINGP (file))
11309 {
11310 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11311 UNGCPRO;
11312 return 0;
11313 }
11314
11315 contents = slurp_file (SDATA (file), &size);
11316 if (contents == NULL)
11317 {
11318 image_error ("Error reading `%s'", file, Qnil);
11319 UNGCPRO;
11320 return 0;
11321 }
11322
11323 p = contents;
11324 end = contents + size;
11325 }
11326 else
11327 {
11328 Lisp_Object data;
11329 data = image_spec_value (img->spec, QCdata, NULL);
11330 p = SDATA (data);
11331 end = p + SBYTES (data);
11332 }
11333
11334 /* Check magic number. */
11335 if (end - p < 2 || *p++ != 'P')
11336 {
11337 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11338 error:
11339 xfree (contents);
11340 UNGCPRO;
11341 return 0;
11342 }
11343
11344 switch (*p++)
11345 {
11346 case '1':
11347 raw_p = 0, type = PBM_MONO;
11348 break;
11349
11350 case '2':
11351 raw_p = 0, type = PBM_GRAY;
11352 break;
11353
11354 case '3':
11355 raw_p = 0, type = PBM_COLOR;
11356 break;
11357
11358 case '4':
11359 raw_p = 1, type = PBM_MONO;
11360 break;
11361
11362 case '5':
11363 raw_p = 1, type = PBM_GRAY;
11364 break;
11365
11366 case '6':
11367 raw_p = 1, type = PBM_COLOR;
11368 break;
11369
11370 default:
11371 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
11372 goto error;
11373 }
11374
11375 /* Read width, height, maximum color-component. Characters
11376 starting with `#' up to the end of a line are ignored. */
11377 width = pbm_scan_number (&p, end);
11378 height = pbm_scan_number (&p, end);
11379
11380 if (type != PBM_MONO)
11381 {
11382 max_color_idx = pbm_scan_number (&p, end);
11383 if (raw_p && max_color_idx > 255)
11384 max_color_idx = 255;
11385 }
11386
11387 if (width < 0
11388 || height < 0
11389 || (type != PBM_MONO && max_color_idx < 0))
11390 goto error;
11391
11392 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11393 goto error;
11394
11395#if 0 /* TODO: color tables. */
11396 /* Initialize the color hash table. */
11397 init_color_table ();
11398#endif
11399
11400 if (type == PBM_MONO)
11401 {
11402 int c = 0, g;
11403 struct image_keyword fmt[PBM_LAST];
11404 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
11405 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
11406
11407 /* Parse the image specification. */
11408 bcopy (pbm_format, fmt, sizeof fmt);
11409 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
11410
11411 /* Get foreground and background colors, maybe allocate colors. */
11412 if (fmt[PBM_FOREGROUND].count
11413 && STRINGP (fmt[PBM_FOREGROUND].value))
11414 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
11415 if (fmt[PBM_BACKGROUND].count
11416 && STRINGP (fmt[PBM_BACKGROUND].value))
11417 {
11418 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
11419 img->background = bg;
11420 img->background_valid = 1;
11421 }
11422
11423 for (y = 0; y < height; ++y)
11424 for (x = 0; x < width; ++x)
11425 {
11426 if (raw_p)
11427 {
11428 if ((x & 7) == 0)
11429 c = *p++;
11430 g = c & 0x80;
11431 c <<= 1;
11432 }
11433 else
11434 g = pbm_scan_number (&p, end);
11435
11436 XPutPixel (ximg, x, y, g ? fg : bg);
11437 }
11438 }
11439 else
11440 {
11441 for (y = 0; y < height; ++y)
11442 for (x = 0; x < width; ++x)
11443 {
11444 int r, g, b;
11445
11446 if (type == PBM_GRAY)
11447 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
11448 else if (raw_p)
11449 {
11450 r = *p++;
11451 g = *p++;
11452 b = *p++;
11453 }
11454 else
11455 {
11456 r = pbm_scan_number (&p, end);
11457 g = pbm_scan_number (&p, end);
11458 b = pbm_scan_number (&p, end);
11459 }
11460
11461 if (r < 0 || g < 0 || b < 0)
11462 {
11463 x_destroy_x_image (ximg);
11464 image_error ("Invalid pixel value in image `%s'",
11465 img->spec, Qnil);
11466 goto error;
11467 }
11468
11469 /* RGB values are now in the range 0..max_color_idx.
11470 Scale this to the range 0..0xff supported by W32. */
11471 r = (int) ((double) r * 255 / max_color_idx);
11472 g = (int) ((double) g * 255 / max_color_idx);
11473 b = (int) ((double) b * 255 / max_color_idx);
11474 XPutPixel (ximg, x, y,
11475#if 0 /* TODO: color tables. */
11476 lookup_rgb_color (f, r, g, b));
11477#else
11478 PALETTERGB (r, g, b));
11479#endif
11480 }
11481 }
11482
11483#if 0 /* TODO: color tables. */
11484 /* Store in IMG->colors the colors allocated for the image, and
11485 free the color table. */
11486 img->colors = colors_in_color_table (&img->ncolors);
11487 free_color_table ();
11488#endif
11489 /* Maybe fill in the background field while we have ximg handy. */
11490 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11491 IMAGE_BACKGROUND (img, f, ximg);
11492
11493 /* Put the image into a pixmap. */
11494 x_put_x_image (f, ximg, img->pixmap, width, height);
11495 x_destroy_x_image (ximg);
11496
11497 img->width = width;
11498 img->height = height;
11499
11500 UNGCPRO;
11501 xfree (contents);
11502 return 1;
11503}
11504
11505\f
11506/***********************************************************************
11507 PNG
11508 ***********************************************************************/
11509
11510#if HAVE_PNG
11511
11512#include <png.h>
11513
11514/* Function prototypes. */
11515
11516static int png_image_p P_ ((Lisp_Object object));
11517static int png_load P_ ((struct frame *f, struct image *img));
11518
11519/* The symbol `png' identifying images of this type. */
11520
11521Lisp_Object Qpng;
11522
11523/* Indices of image specification fields in png_format, below. */
11524
11525enum png_keyword_index
11526{
11527 PNG_TYPE,
11528 PNG_DATA,
11529 PNG_FILE,
11530 PNG_ASCENT,
11531 PNG_MARGIN,
11532 PNG_RELIEF,
11533 PNG_ALGORITHM,
11534 PNG_HEURISTIC_MASK,
11535 PNG_MASK,
11536 PNG_BACKGROUND,
11537 PNG_LAST
11538};
11539
11540/* Vector of image_keyword structures describing the format
11541 of valid user-defined image specifications. */
11542
11543static struct image_keyword png_format[PNG_LAST] =
11544{
11545 {":type", IMAGE_SYMBOL_VALUE, 1},
11546 {":data", IMAGE_STRING_VALUE, 0},
11547 {":file", IMAGE_STRING_VALUE, 0},
11548 {":ascent", IMAGE_ASCENT_VALUE, 0},
11549 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
11550 {":relief", IMAGE_INTEGER_VALUE, 0},
11551 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11552 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11553 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11554 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
11555};
11556
11557/* Structure describing the image type `png'. */
11558
11559static struct image_type png_type =
11560{
11561 &Qpng,
11562 png_image_p,
11563 png_load,
11564 x_clear_image,
11565 NULL
11566};
11567
11568
11569/* Return non-zero if OBJECT is a valid PNG image specification. */
11570
11571static int
11572png_image_p (object)
11573 Lisp_Object object;
11574{
11575 struct image_keyword fmt[PNG_LAST];
11576 bcopy (png_format, fmt, sizeof fmt);
11577
11578 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
11579 return 0;
11580
11581 /* Must specify either the :data or :file keyword. */
11582 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
11583}
11584
11585
11586/* Error and warning handlers installed when the PNG library
11587 is initialized. */
11588
11589static void
11590my_png_error (png_ptr, msg)
11591 png_struct *png_ptr;
11592 char *msg;
11593{
11594 xassert (png_ptr != NULL);
11595 image_error ("PNG error: %s", build_string (msg), Qnil);
11596 longjmp (png_ptr->jmpbuf, 1);
11597}
11598
11599
11600static void
11601my_png_warning (png_ptr, msg)
11602 png_struct *png_ptr;
11603 char *msg;
11604{
11605 xassert (png_ptr != NULL);
11606 image_error ("PNG warning: %s", build_string (msg), Qnil);
11607}
11608
11609/* Memory source for PNG decoding. */
11610
11611struct png_memory_storage
11612{
11613 unsigned char *bytes; /* The data */
11614 size_t len; /* How big is it? */
11615 int index; /* Where are we? */
11616};
11617
11618
11619/* Function set as reader function when reading PNG image from memory.
11620 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
11621 bytes from the input to DATA. */
11622
11623static void
11624png_read_from_memory (png_ptr, data, length)
11625 png_structp png_ptr;
11626 png_bytep data;
11627 png_size_t length;
11628{
11629 struct png_memory_storage *tbr
11630 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
11631
11632 if (length > tbr->len - tbr->index)
11633 png_error (png_ptr, "Read error");
11634
11635 bcopy (tbr->bytes + tbr->index, data, length);
11636 tbr->index = tbr->index + length;
11637}
11638
11639/* Load PNG image IMG for use on frame F. Value is non-zero if
11640 successful. */
11641
11642static int
11643png_load (f, img)
11644 struct frame *f;
11645 struct image *img;
11646{
11647 Lisp_Object file, specified_file;
11648 Lisp_Object specified_data;
11649 int x, y, i;
11650 XImage *ximg, *mask_img = NULL;
11651 struct gcpro gcpro1;
11652 png_struct *png_ptr = NULL;
11653 png_info *info_ptr = NULL, *end_info = NULL;
11654 FILE *volatile fp = NULL;
11655 png_byte sig[8];
11656 png_byte *volatile pixels = NULL;
11657 png_byte **volatile rows = NULL;
11658 png_uint_32 width, height;
11659 int bit_depth, color_type, interlace_type;
11660 png_byte channels;
11661 png_uint_32 row_bytes;
11662 int transparent_p;
11663 char *gamma_str;
11664 double screen_gamma, image_gamma;
11665 int intent;
11666 struct png_memory_storage tbr; /* Data to be read */
11667
11668 /* Find out what file to load. */
11669 specified_file = image_spec_value (img->spec, QCfile, NULL);
11670 specified_data = image_spec_value (img->spec, QCdata, NULL);
11671 file = Qnil;
11672 GCPRO1 (file);
11673
11674 if (NILP (specified_data))
11675 {
11676 file = x_find_image_file (specified_file);
11677 if (!STRINGP (file))
11678 {
11679 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11680 UNGCPRO;
11681 return 0;
11682 }
11683
11684 /* Open the image file. */
11685 fp = fopen (SDATA (file), "rb");
11686 if (!fp)
11687 {
11688 image_error ("Cannot open image file `%s'", file, Qnil);
11689 UNGCPRO;
11690 fclose (fp);
11691 return 0;
11692 }
11693
11694 /* Check PNG signature. */
11695 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
11696 || !png_check_sig (sig, sizeof sig))
11697 {
11698 image_error ("Not a PNG file:` %s'", file, Qnil);
11699 UNGCPRO;
11700 fclose (fp);
11701 return 0;
11702 }
11703 }
11704 else
11705 {
11706 /* Read from memory. */
11707 tbr.bytes = SDATA (specified_data);
11708 tbr.len = SBYTES (specified_data);
11709 tbr.index = 0;
11710
11711 /* Check PNG signature. */
11712 if (tbr.len < sizeof sig
11713 || !png_check_sig (tbr.bytes, sizeof sig))
11714 {
11715 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
11716 UNGCPRO;
11717 return 0;
11718 }
11719
11720 /* Need to skip past the signature. */
11721 tbr.bytes += sizeof (sig);
11722 }
11723
11724 /* Initialize read and info structs for PNG lib. */
11725 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
11726 my_png_error, my_png_warning);
11727 if (!png_ptr)
11728 {
11729 if (fp) fclose (fp);
11730 UNGCPRO;
11731 return 0;
11732 }
11733
11734 info_ptr = png_create_info_struct (png_ptr);
11735 if (!info_ptr)
11736 {
11737 png_destroy_read_struct (&png_ptr, NULL, NULL);
11738 if (fp) fclose (fp);
11739 UNGCPRO;
11740 return 0;
11741 }
11742
11743 end_info = png_create_info_struct (png_ptr);
11744 if (!end_info)
11745 {
11746 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
11747 if (fp) fclose (fp);
11748 UNGCPRO;
11749 return 0;
11750 }
11751
11752 /* Set error jump-back. We come back here when the PNG library
11753 detects an error. */
11754 if (setjmp (png_ptr->jmpbuf))
11755 {
11756 error:
11757 if (png_ptr)
11758 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11759 xfree (pixels);
11760 xfree (rows);
11761 if (fp) fclose (fp);
11762 UNGCPRO;
11763 return 0;
11764 }
11765
11766 /* Read image info. */
11767 if (!NILP (specified_data))
11768 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
11769 else
11770 png_init_io (png_ptr, fp);
11771
11772 png_set_sig_bytes (png_ptr, sizeof sig);
11773 png_read_info (png_ptr, info_ptr);
11774 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
11775 &interlace_type, NULL, NULL);
11776
11777 /* If image contains simply transparency data, we prefer to
11778 construct a clipping mask. */
11779 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
11780 transparent_p = 1;
11781 else
11782 transparent_p = 0;
11783
11784 /* This function is easier to write if we only have to handle
11785 one data format: RGB or RGBA with 8 bits per channel. Let's
11786 transform other formats into that format. */
11787
11788 /* Strip more than 8 bits per channel. */
11789 if (bit_depth == 16)
11790 png_set_strip_16 (png_ptr);
11791
11792 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
11793 if available. */
11794 png_set_expand (png_ptr);
11795
11796 /* Convert grayscale images to RGB. */
11797 if (color_type == PNG_COLOR_TYPE_GRAY
11798 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
11799 png_set_gray_to_rgb (png_ptr);
11800
11801 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
11802 gamma_str = getenv ("SCREEN_GAMMA");
11803 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
11804
11805 /* Tell the PNG lib to handle gamma correction for us. */
11806
11807#if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
11808 if (png_get_sRGB (png_ptr, info_ptr, &intent))
11809 /* There is a special chunk in the image specifying the gamma. */
11810 png_set_sRGB (png_ptr, info_ptr, intent);
11811 else
11812#endif
11813 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
11814 /* Image contains gamma information. */
11815 png_set_gamma (png_ptr, screen_gamma, image_gamma);
11816 else
11817 /* Use a default of 0.5 for the image gamma. */
11818 png_set_gamma (png_ptr, screen_gamma, 0.5);
11819
11820 /* Handle alpha channel by combining the image with a background
11821 color. Do this only if a real alpha channel is supplied. For
11822 simple transparency, we prefer a clipping mask. */
11823 if (!transparent_p)
11824 {
11825 png_color_16 *image_background;
11826 Lisp_Object specified_bg
11827 = image_spec_value (img->spec, QCbackground, NULL);
11828
11829
11830 if (STRINGP (specified_bg))
11831 /* The user specified `:background', use that. */
11832 {
11833 COLORREF color;
11834 if (w32_defined_color (f, SDATA (specified_bg), &color, 0))
11835 {
11836 png_color_16 user_bg;
11837
11838 bzero (&user_bg, sizeof user_bg);
11839 user_bg.red = color.red;
11840 user_bg.green = color.green;
11841 user_bg.blue = color.blue;
11842
11843 png_set_background (png_ptr, &user_bg,
11844 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11845 }
11846 }
11847 else if (png_get_bKGD (png_ptr, info_ptr, &image_background))
11848 /* Image contains a background color with which to
11849 combine the image. */
11850 png_set_background (png_ptr, image_background,
11851 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
11852 else
11853 {
11854 /* Image does not contain a background color with which
11855 to combine the image data via an alpha channel. Use
11856 the frame's background instead. */
11857 XColor color;
11858 Colormap cmap;
11859 png_color_16 frame_background;
11860
11861 cmap = FRAME_X_COLORMAP (f);
11862 color.pixel = FRAME_BACKGROUND_PIXEL (f);
11863 x_query_color (f, &color);
11864
11865 bzero (&frame_background, sizeof frame_background);
11866 frame_background.red = color.red;
11867 frame_background.green = color.green;
11868 frame_background.blue = color.blue;
11869
11870 png_set_background (png_ptr, &frame_background,
11871 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
11872 }
11873 }
11874
11875 /* Update info structure. */
11876 png_read_update_info (png_ptr, info_ptr);
11877
11878 /* Get number of channels. Valid values are 1 for grayscale images
11879 and images with a palette, 2 for grayscale images with transparency
11880 information (alpha channel), 3 for RGB images, and 4 for RGB
11881 images with alpha channel, i.e. RGBA. If conversions above were
11882 sufficient we should only have 3 or 4 channels here. */
11883 channels = png_get_channels (png_ptr, info_ptr);
11884 xassert (channels == 3 || channels == 4);
11885
11886 /* Number of bytes needed for one row of the image. */
11887 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
11888
11889 /* Allocate memory for the image. */
11890 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
11891 rows = (png_byte **) xmalloc (height * sizeof *rows);
11892 for (i = 0; i < height; ++i)
11893 rows[i] = pixels + i * row_bytes;
11894
11895 /* Read the entire image. */
11896 png_read_image (png_ptr, rows);
11897 png_read_end (png_ptr, info_ptr);
11898 if (fp)
11899 {
11900 fclose (fp);
11901 fp = NULL;
11902 }
11903
11904 /* Create the X image and pixmap. */
11905 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
11906 &img->pixmap))
11907 goto error;
11908
11909 /* Create an image and pixmap serving as mask if the PNG image
11910 contains an alpha channel. */
11911 if (channels == 4
11912 && !transparent_p
11913 && !x_create_x_image_and_pixmap (f, width, height, 1,
11914 &mask_img, &img->mask))
11915 {
11916 x_destroy_x_image (ximg);
11917 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
11918 img->pixmap = 0;
11919 goto error;
11920 }
11921
11922 /* Fill the X image and mask from PNG data. */
11923 init_color_table ();
11924
11925 for (y = 0; y < height; ++y)
11926 {
11927 png_byte *p = rows[y];
11928
11929 for (x = 0; x < width; ++x)
11930 {
11931 unsigned r, g, b;
11932
11933 r = *p++ << 8;
11934 g = *p++ << 8;
11935 b = *p++ << 8;
11936 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
11937
11938 /* An alpha channel, aka mask channel, associates variable
11939 transparency with an image. Where other image formats
11940 support binary transparency---fully transparent or fully
11941 opaque---PNG allows up to 254 levels of partial transparency.
11942 The PNG library implements partial transparency by combining
11943 the image with a specified background color.
11944
11945 I'm not sure how to handle this here nicely: because the
11946 background on which the image is displayed may change, for
11947 real alpha channel support, it would be necessary to create
11948 a new image for each possible background.
11949
11950 What I'm doing now is that a mask is created if we have
11951 boolean transparency information. Otherwise I'm using
11952 the frame's background color to combine the image with. */
11953
11954 if (channels == 4)
11955 {
11956 if (mask_img)
11957 XPutPixel (mask_img, x, y, *p > 0);
11958 ++p;
11959 }
11960 }
11961 }
11962
11963 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11964 /* Set IMG's background color from the PNG image, unless the user
11965 overrode it. */
11966 {
11967 png_color_16 *bg;
11968 if (png_get_bKGD (png_ptr, info_ptr, &bg))
11969 {
11970 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
11971 img->background_valid = 1;
11972 }
11973 }
11974
11975 /* Remember colors allocated for this image. */
11976 img->colors = colors_in_color_table (&img->ncolors);
11977 free_color_table ();
11978
11979 /* Clean up. */
11980 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
11981 xfree (rows);
11982 xfree (pixels);
11983
11984 img->width = width;
11985 img->height = height;
11986
11987 /* Maybe fill in the background field while we have ximg handy. */
11988 IMAGE_BACKGROUND (img, f, ximg);
11989
11990 /* Put the image into the pixmap, then free the X image and its buffer. */
11991 x_put_x_image (f, ximg, img->pixmap, width, height);
11992 x_destroy_x_image (ximg);
11993
11994 /* Same for the mask. */
11995 if (mask_img)
11996 {
11997 /* Fill in the background_transparent field while we have the mask
11998 handy. */
11999 image_background_transparent (img, f, mask_img);
12000
12001 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
12002 x_destroy_x_image (mask_img);
12003 }
12004
12005 UNGCPRO;
12006 return 1;
12007}
12008
12009#endif /* HAVE_PNG != 0 */
12010
12011
12012\f
12013/***********************************************************************
12014 JPEG
12015 ***********************************************************************/
12016
12017#if HAVE_JPEG
12018
12019/* Work around a warning about HAVE_STDLIB_H being redefined in
12020 jconfig.h. */
12021#ifdef HAVE_STDLIB_H
12022#define HAVE_STDLIB_H_1
12023#undef HAVE_STDLIB_H
12024#endif /* HAVE_STLIB_H */
12025
12026#include <jpeglib.h>
12027#include <jerror.h>
12028#include <setjmp.h>
12029
12030#ifdef HAVE_STLIB_H_1
12031#define HAVE_STDLIB_H 1
12032#endif
12033
12034static int jpeg_image_p P_ ((Lisp_Object object));
12035static int jpeg_load P_ ((struct frame *f, struct image *img));
12036
12037/* The symbol `jpeg' identifying images of this type. */
12038
12039Lisp_Object Qjpeg;
12040
12041/* Indices of image specification fields in gs_format, below. */
12042
12043enum jpeg_keyword_index
12044{
12045 JPEG_TYPE,
12046 JPEG_DATA,
12047 JPEG_FILE,
12048 JPEG_ASCENT,
12049 JPEG_MARGIN,
12050 JPEG_RELIEF,
12051 JPEG_ALGORITHM,
12052 JPEG_HEURISTIC_MASK,
12053 JPEG_MASK,
12054 JPEG_BACKGROUND,
12055 JPEG_LAST
12056};
12057
12058/* Vector of image_keyword structures describing the format
12059 of valid user-defined image specifications. */
12060
12061static struct image_keyword jpeg_format[JPEG_LAST] =
12062{
12063 {":type", IMAGE_SYMBOL_VALUE, 1},
12064 {":data", IMAGE_STRING_VALUE, 0},
12065 {":file", IMAGE_STRING_VALUE, 0},
12066 {":ascent", IMAGE_ASCENT_VALUE, 0},
12067 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12068 {":relief", IMAGE_INTEGER_VALUE, 0},
12069 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12070 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12071 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12072 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12073};
12074
12075/* Structure describing the image type `jpeg'. */
12076
12077static struct image_type jpeg_type =
12078{
12079 &Qjpeg,
12080 jpeg_image_p,
12081 jpeg_load,
12082 x_clear_image,
12083 NULL
12084};
12085
12086
12087/* Return non-zero if OBJECT is a valid JPEG image specification. */
12088
12089static int
12090jpeg_image_p (object)
12091 Lisp_Object object;
12092{
12093 struct image_keyword fmt[JPEG_LAST];
12094
12095 bcopy (jpeg_format, fmt, sizeof fmt);
12096
12097 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
12098 return 0;
12099
12100 /* Must specify either the :data or :file keyword. */
12101 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
12102}
12103
12104
12105struct my_jpeg_error_mgr
12106{
12107 struct jpeg_error_mgr pub;
12108 jmp_buf setjmp_buffer;
12109};
12110
12111static void
12112my_error_exit (cinfo)
12113 j_common_ptr cinfo;
12114{
12115 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
12116 longjmp (mgr->setjmp_buffer, 1);
12117}
12118
12119/* Init source method for JPEG data source manager. Called by
12120 jpeg_read_header() before any data is actually read. See
12121 libjpeg.doc from the JPEG lib distribution. */
12122
12123static void
12124our_init_source (cinfo)
12125 j_decompress_ptr cinfo;
12126{
12127}
12128
12129
12130/* Fill input buffer method for JPEG data source manager. Called
12131 whenever more data is needed. We read the whole image in one step,
12132 so this only adds a fake end of input marker at the end. */
12133
12134static boolean
12135our_fill_input_buffer (cinfo)
12136 j_decompress_ptr cinfo;
12137{
12138 /* Insert a fake EOI marker. */
12139 struct jpeg_source_mgr *src = cinfo->src;
12140 static JOCTET buffer[2];
12141
12142 buffer[0] = (JOCTET) 0xFF;
12143 buffer[1] = (JOCTET) JPEG_EOI;
12144
12145 src->next_input_byte = buffer;
12146 src->bytes_in_buffer = 2;
12147 return TRUE;
12148}
12149
12150
12151/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
12152 is the JPEG data source manager. */
12153
12154static void
12155our_skip_input_data (cinfo, num_bytes)
12156 j_decompress_ptr cinfo;
12157 long num_bytes;
12158{
12159 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
12160
12161 if (src)
12162 {
12163 if (num_bytes > src->bytes_in_buffer)
12164 ERREXIT (cinfo, JERR_INPUT_EOF);
12165
12166 src->bytes_in_buffer -= num_bytes;
12167 src->next_input_byte += num_bytes;
12168 }
12169}
12170
12171
12172/* Method to terminate data source. Called by
12173 jpeg_finish_decompress() after all data has been processed. */
12174
12175static void
12176our_term_source (cinfo)
12177 j_decompress_ptr cinfo;
12178{
12179}
12180
12181
12182/* Set up the JPEG lib for reading an image from DATA which contains
12183 LEN bytes. CINFO is the decompression info structure created for
12184 reading the image. */
12185
12186static void
12187jpeg_memory_src (cinfo, data, len)
12188 j_decompress_ptr cinfo;
12189 JOCTET *data;
12190 unsigned int len;
12191{
12192 struct jpeg_source_mgr *src;
12193
12194 if (cinfo->src == NULL)
12195 {
12196 /* First time for this JPEG object? */
12197 cinfo->src = (struct jpeg_source_mgr *)
12198 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
12199 sizeof (struct jpeg_source_mgr));
12200 src = (struct jpeg_source_mgr *) cinfo->src;
12201 src->next_input_byte = data;
12202 }
12203
12204 src = (struct jpeg_source_mgr *) cinfo->src;
12205 src->init_source = our_init_source;
12206 src->fill_input_buffer = our_fill_input_buffer;
12207 src->skip_input_data = our_skip_input_data;
12208 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
12209 src->term_source = our_term_source;
12210 src->bytes_in_buffer = len;
12211 src->next_input_byte = data;
12212}
12213
12214
12215/* Load image IMG for use on frame F. Patterned after example.c
12216 from the JPEG lib. */
12217
12218static int
12219jpeg_load (f, img)
12220 struct frame *f;
12221 struct image *img;
12222{
12223 struct jpeg_decompress_struct cinfo;
12224 struct my_jpeg_error_mgr mgr;
12225 Lisp_Object file, specified_file;
12226 Lisp_Object specified_data;
12227 FILE * volatile fp = NULL;
12228 JSAMPARRAY buffer;
12229 int row_stride, x, y;
12230 XImage *ximg = NULL;
12231 int rc;
12232 unsigned long *colors;
12233 int width, height;
12234 struct gcpro gcpro1;
12235
12236 /* Open the JPEG file. */
12237 specified_file = image_spec_value (img->spec, QCfile, NULL);
12238 specified_data = image_spec_value (img->spec, QCdata, NULL);
12239 file = Qnil;
12240 GCPRO1 (file);
12241
12242 if (NILP (specified_data))
12243 {
12244 file = x_find_image_file (specified_file);
12245 if (!STRINGP (file))
12246 {
12247 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12248 UNGCPRO;
12249 return 0;
12250 }
12251
12252 fp = fopen (SDATA (file), "r");
12253 if (fp == NULL)
12254 {
12255 image_error ("Cannot open `%s'", file, Qnil);
12256 UNGCPRO;
12257 return 0;
12258 }
12259 }
12260
12261 /* Customize libjpeg's error handling to call my_error_exit when an
12262 error is detected. This function will perform a longjmp. */
12263 cinfo.err = jpeg_std_error (&mgr.pub);
12264 mgr.pub.error_exit = my_error_exit;
12265
12266 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
12267 {
12268 if (rc == 1)
12269 {
12270 /* Called from my_error_exit. Display a JPEG error. */
12271 char buffer[JMSG_LENGTH_MAX];
12272 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
12273 image_error ("Error reading JPEG image `%s': %s", img->spec,
12274 build_string (buffer));
12275 }
12276
12277 /* Close the input file and destroy the JPEG object. */
12278 if (fp)
12279 fclose (fp);
12280 jpeg_destroy_decompress (&cinfo);
12281
12282 /* If we already have an XImage, free that. */
12283 x_destroy_x_image (ximg);
12284
12285 /* Free pixmap and colors. */
12286 x_clear_image (f, img);
12287
12288 UNGCPRO;
12289 return 0;
12290 }
12291
12292 /* Create the JPEG decompression object. Let it read from fp.
12293 Read the JPEG image header. */
12294 jpeg_create_decompress (&cinfo);
12295
12296 if (NILP (specified_data))
12297 jpeg_stdio_src (&cinfo, fp);
12298 else
12299 jpeg_memory_src (&cinfo, SDATA (specified_data),
12300 SBYTES (specified_data));
12301
12302 jpeg_read_header (&cinfo, TRUE);
12303
12304 /* Customize decompression so that color quantization will be used.
12305 Start decompression. */
12306 cinfo.quantize_colors = TRUE;
12307 jpeg_start_decompress (&cinfo);
12308 width = img->width = cinfo.output_width;
12309 height = img->height = cinfo.output_height;
12310
12311 /* Create X image and pixmap. */
12312 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
12313 &img->pixmap))
12314 longjmp (mgr.setjmp_buffer, 2);
12315
12316 /* Allocate colors. When color quantization is used,
12317 cinfo.actual_number_of_colors has been set with the number of
12318 colors generated, and cinfo.colormap is a two-dimensional array
12319 of color indices in the range 0..cinfo.actual_number_of_colors.
12320 No more than 255 colors will be generated. */
12321 {
12322 int i, ir, ig, ib;
12323
12324 if (cinfo.out_color_components > 2)
12325 ir = 0, ig = 1, ib = 2;
12326 else if (cinfo.out_color_components > 1)
12327 ir = 0, ig = 1, ib = 0;
12328 else
12329 ir = 0, ig = 0, ib = 0;
12330
12331 /* Use the color table mechanism because it handles colors that
12332 cannot be allocated nicely. Such colors will be replaced with
12333 a default color, and we don't have to care about which colors
12334 can be freed safely, and which can't. */
12335 init_color_table ();
12336 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
12337 * sizeof *colors);
12338
12339 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
12340 {
12341 /* Multiply RGB values with 255 because X expects RGB values
12342 in the range 0..0xffff. */
12343 int r = cinfo.colormap[ir][i] << 8;
12344 int g = cinfo.colormap[ig][i] << 8;
12345 int b = cinfo.colormap[ib][i] << 8;
12346 colors[i] = lookup_rgb_color (f, r, g, b);
12347 }
12348
12349 /* Remember those colors actually allocated. */
12350 img->colors = colors_in_color_table (&img->ncolors);
12351 free_color_table ();
12352 }
12353
12354 /* Read pixels. */
12355 row_stride = width * cinfo.output_components;
12356 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
12357 row_stride, 1);
12358 for (y = 0; y < height; ++y)
12359 {
12360 jpeg_read_scanlines (&cinfo, buffer, 1);
12361 for (x = 0; x < cinfo.output_width; ++x)
12362 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
12363 }
12364
12365 /* Clean up. */
12366 jpeg_finish_decompress (&cinfo);
12367 jpeg_destroy_decompress (&cinfo);
12368 if (fp)
12369 fclose (fp);
12370
12371 /* Maybe fill in the background field while we have ximg handy. */
12372 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12373 IMAGE_BACKGROUND (img, f, ximg);
12374
12375 /* Put the image into the pixmap. */
12376 x_put_x_image (f, ximg, img->pixmap, width, height);
12377 x_destroy_x_image (ximg);
12378 UNBLOCK_INPUT;
12379 UNGCPRO;
12380 return 1;
12381}
12382
12383#endif /* HAVE_JPEG */
12384
12385
12386\f
12387/***********************************************************************
12388 TIFF
12389 ***********************************************************************/
12390
12391#if HAVE_TIFF
12392
12393#include <tiffio.h>
12394
12395static int tiff_image_p P_ ((Lisp_Object object));
12396static int tiff_load P_ ((struct frame *f, struct image *img));
12397
12398/* The symbol `tiff' identifying images of this type. */
12399
12400Lisp_Object Qtiff;
12401
12402/* Indices of image specification fields in tiff_format, below. */
12403
12404enum tiff_keyword_index
12405{
12406 TIFF_TYPE,
12407 TIFF_DATA,
12408 TIFF_FILE,
12409 TIFF_ASCENT,
12410 TIFF_MARGIN,
12411 TIFF_RELIEF,
12412 TIFF_ALGORITHM,
12413 TIFF_HEURISTIC_MASK,
12414 TIFF_MASK,
12415 TIFF_BACKGROUND,
12416 TIFF_LAST
12417};
12418
12419/* Vector of image_keyword structures describing the format
12420 of valid user-defined image specifications. */
12421
12422static struct image_keyword tiff_format[TIFF_LAST] =
12423{
12424 {":type", IMAGE_SYMBOL_VALUE, 1},
12425 {":data", IMAGE_STRING_VALUE, 0},
12426 {":file", IMAGE_STRING_VALUE, 0},
12427 {":ascent", IMAGE_ASCENT_VALUE, 0},
12428 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12429 {":relief", IMAGE_INTEGER_VALUE, 0},
12430 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12431 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12432 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12433 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12434};
12435
12436/* Structure describing the image type `tiff'. */
12437
12438static struct image_type tiff_type =
12439{
12440 &Qtiff,
12441 tiff_image_p,
12442 tiff_load,
12443 x_clear_image,
12444 NULL
12445};
12446
12447
12448/* Return non-zero if OBJECT is a valid TIFF image specification. */
12449
12450static int
12451tiff_image_p (object)
12452 Lisp_Object object;
12453{
12454 struct image_keyword fmt[TIFF_LAST];
12455 bcopy (tiff_format, fmt, sizeof fmt);
12456
12457 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
12458 return 0;
12459
12460 /* Must specify either the :data or :file keyword. */
12461 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
12462}
12463
12464
12465/* Reading from a memory buffer for TIFF images Based on the PNG
12466 memory source, but we have to provide a lot of extra functions.
12467 Blah.
12468
12469 We really only need to implement read and seek, but I am not
12470 convinced that the TIFF library is smart enough not to destroy
12471 itself if we only hand it the function pointers we need to
12472 override. */
12473
12474typedef struct
12475{
12476 unsigned char *bytes;
12477 size_t len;
12478 int index;
12479}
12480tiff_memory_source;
12481
12482static size_t
12483tiff_read_from_memory (data, buf, size)
12484 thandle_t data;
12485 tdata_t buf;
12486 tsize_t size;
12487{
12488 tiff_memory_source *src = (tiff_memory_source *) data;
12489
12490 if (size > src->len - src->index)
12491 return (size_t) -1;
12492 bcopy (src->bytes + src->index, buf, size);
12493 src->index += size;
12494 return size;
12495}
12496
12497static size_t
12498tiff_write_from_memory (data, buf, size)
12499 thandle_t data;
12500 tdata_t buf;
12501 tsize_t size;
12502{
12503 return (size_t) -1;
12504}
12505
12506static toff_t
12507tiff_seek_in_memory (data, off, whence)
12508 thandle_t data;
12509 toff_t off;
12510 int whence;
12511{
12512 tiff_memory_source *src = (tiff_memory_source *) data;
12513 int idx;
12514
12515 switch (whence)
12516 {
12517 case SEEK_SET: /* Go from beginning of source. */
12518 idx = off;
12519 break;
12520
12521 case SEEK_END: /* Go from end of source. */
12522 idx = src->len + off;
12523 break;
12524
12525 case SEEK_CUR: /* Go from current position. */
12526 idx = src->index + off;
12527 break;
12528
12529 default: /* Invalid `whence'. */
12530 return -1;
12531 }
12532
12533 if (idx > src->len || idx < 0)
12534 return -1;
12535
12536 src->index = idx;
12537 return src->index;
12538}
12539
12540static int
12541tiff_close_memory (data)
12542 thandle_t data;
12543{
12544 /* NOOP */
12545 return 0;
12546}
12547
12548static int
12549tiff_mmap_memory (data, pbase, psize)
12550 thandle_t data;
12551 tdata_t *pbase;
12552 toff_t *psize;
12553{
12554 /* It is already _IN_ memory. */
12555 return 0;
12556}
12557
12558static void
12559tiff_unmap_memory (data, base, size)
12560 thandle_t data;
12561 tdata_t base;
12562 toff_t size;
12563{
12564 /* We don't need to do this. */
12565}
12566
12567static toff_t
12568tiff_size_of_memory (data)
12569 thandle_t data;
12570{
12571 return ((tiff_memory_source *) data)->len;
12572}
12573
12574
12575static void
12576tiff_error_handler (title, format, ap)
12577 const char *title, *format;
12578 va_list ap;
12579{
12580 char buf[512];
12581 int len;
12582
12583 len = sprintf (buf, "TIFF error: %s ", title);
12584 vsprintf (buf + len, format, ap);
12585 add_to_log (buf, Qnil, Qnil);
12586}
12587
12588
12589static void
12590tiff_warning_handler (title, format, ap)
12591 const char *title, *format;
12592 va_list ap;
12593{
12594 char buf[512];
12595 int len;
12596
12597 len = sprintf (buf, "TIFF warning: %s ", title);
12598 vsprintf (buf + len, format, ap);
12599 add_to_log (buf, Qnil, Qnil);
12600}
12601
12602
12603/* Load TIFF image IMG for use on frame F. Value is non-zero if
12604 successful. */
12605
12606static int
12607tiff_load (f, img)
12608 struct frame *f;
12609 struct image *img;
12610{
12611 Lisp_Object file, specified_file;
12612 Lisp_Object specified_data;
12613 TIFF *tiff;
12614 int width, height, x, y;
12615 uint32 *buf;
12616 int rc;
12617 XImage *ximg;
12618 struct gcpro gcpro1;
12619 tiff_memory_source memsrc;
12620
12621 specified_file = image_spec_value (img->spec, QCfile, NULL);
12622 specified_data = image_spec_value (img->spec, QCdata, NULL);
12623 file = Qnil;
12624 GCPRO1 (file);
12625
12626 TIFFSetErrorHandler (tiff_error_handler);
12627 TIFFSetWarningHandler (tiff_warning_handler);
12628
12629 if (NILP (specified_data))
12630 {
12631 /* Read from a file */
12632 file = x_find_image_file (specified_file);
12633 if (!STRINGP (file))
12634 {
12635 image_error ("Cannot find image file `%s'", file, Qnil);
12636 UNGCPRO;
12637 return 0;
12638 }
12639
12640 /* Try to open the image file. */
12641 tiff = TIFFOpen (SDATA (file), "r");
12642 if (tiff == NULL)
12643 {
12644 image_error ("Cannot open `%s'", file, Qnil);
12645 UNGCPRO;
12646 return 0;
12647 }
12648 }
12649 else
12650 {
12651 /* Memory source! */
12652 memsrc.bytes = SDATA (specified_data);
12653 memsrc.len = SBYTES (specified_data);
12654 memsrc.index = 0;
12655
12656 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
12657 (TIFFReadWriteProc) tiff_read_from_memory,
12658 (TIFFReadWriteProc) tiff_write_from_memory,
12659 tiff_seek_in_memory,
12660 tiff_close_memory,
12661 tiff_size_of_memory,
12662 tiff_mmap_memory,
12663 tiff_unmap_memory);
12664
12665 if (!tiff)
12666 {
12667 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
12668 UNGCPRO;
12669 return 0;
12670 }
12671 }
12672
12673 /* Get width and height of the image, and allocate a raster buffer
12674 of width x height 32-bit values. */
12675 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
12676 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
12677 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
12678
12679 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
12680 TIFFClose (tiff);
12681 if (!rc)
12682 {
12683 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
12684 xfree (buf);
12685 UNGCPRO;
12686 return 0;
12687 }
12688
12689 /* Create the X image and pixmap. */
12690 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12691 {
12692 xfree (buf);
12693 UNGCPRO;
12694 return 0;
12695 }
12696
12697 /* Initialize the color table. */
12698 init_color_table ();
12699
12700 /* Process the pixel raster. Origin is in the lower-left corner. */
12701 for (y = 0; y < height; ++y)
12702 {
12703 uint32 *row = buf + y * width;
12704
12705 for (x = 0; x < width; ++x)
12706 {
12707 uint32 abgr = row[x];
12708 int r = TIFFGetR (abgr) << 8;
12709 int g = TIFFGetG (abgr) << 8;
12710 int b = TIFFGetB (abgr) << 8;
12711 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
12712 }
12713 }
12714
12715 /* Remember the colors allocated for the image. Free the color table. */
12716 img->colors = colors_in_color_table (&img->ncolors);
12717 free_color_table ();
12718
12719 img->width = width;
12720 img->height = height;
12721
12722 /* Maybe fill in the background field while we have ximg handy. */
12723 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12724 IMAGE_BACKGROUND (img, f, ximg);
12725
12726 /* Put the image into the pixmap, then free the X image and its buffer. */
12727 x_put_x_image (f, ximg, img->pixmap, width, height);
12728 x_destroy_x_image (ximg);
12729 xfree (buf);
12730
12731 UNGCPRO;
12732 return 1;
12733}
12734
12735#endif /* HAVE_TIFF != 0 */
12736
12737
12738\f
12739/***********************************************************************
12740 GIF
12741 ***********************************************************************/
12742
12743#if HAVE_GIF
12744
12745#include <gif_lib.h>
12746
12747static int gif_image_p P_ ((Lisp_Object object));
12748static int gif_load P_ ((struct frame *f, struct image *img));
12749
12750/* The symbol `gif' identifying images of this type. */
12751
12752Lisp_Object Qgif;
12753
12754/* Indices of image specification fields in gif_format, below. */
12755
12756enum gif_keyword_index
12757{
12758 GIF_TYPE,
12759 GIF_DATA,
12760 GIF_FILE,
12761 GIF_ASCENT,
12762 GIF_MARGIN,
12763 GIF_RELIEF,
12764 GIF_ALGORITHM,
12765 GIF_HEURISTIC_MASK,
12766 GIF_MASK,
12767 GIF_IMAGE,
12768 GIF_BACKGROUND,
12769 GIF_LAST
12770};
12771
12772/* Vector of image_keyword structures describing the format
12773 of valid user-defined image specifications. */
12774
12775static struct image_keyword gif_format[GIF_LAST] =
12776{
12777 {":type", IMAGE_SYMBOL_VALUE, 1},
12778 {":data", IMAGE_STRING_VALUE, 0},
12779 {":file", IMAGE_STRING_VALUE, 0},
12780 {":ascent", IMAGE_ASCENT_VALUE, 0},
12781 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
12782 {":relief", IMAGE_INTEGER_VALUE, 0},
12783 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12784 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12785 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12786 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
12787 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
12788};
12789
12790/* Structure describing the image type `gif'. */
12791
12792static struct image_type gif_type =
12793{
12794 &Qgif,
12795 gif_image_p,
12796 gif_load,
12797 x_clear_image,
12798 NULL
12799};
12800
12801/* Return non-zero if OBJECT is a valid GIF image specification. */
12802
12803static int
12804gif_image_p (object)
12805 Lisp_Object object;
12806{
12807 struct image_keyword fmt[GIF_LAST];
12808 bcopy (gif_format, fmt, sizeof fmt);
12809
12810 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
12811 return 0;
12812
12813 /* Must specify either the :data or :file keyword. */
12814 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
12815}
12816
12817/* Reading a GIF image from memory
12818 Based on the PNG memory stuff to a certain extent. */
12819
12820typedef struct
12821{
12822 unsigned char *bytes;
12823 size_t len;
12824 int index;
12825}
12826gif_memory_source;
12827
12828/* Make the current memory source available to gif_read_from_memory.
12829 It's done this way because not all versions of libungif support
12830 a UserData field in the GifFileType structure. */
12831static gif_memory_source *current_gif_memory_src;
12832
12833static int
12834gif_read_from_memory (file, buf, len)
12835 GifFileType *file;
12836 GifByteType *buf;
12837 int len;
12838{
12839 gif_memory_source *src = current_gif_memory_src;
12840
12841 if (len > src->len - src->index)
12842 return -1;
12843
12844 bcopy (src->bytes + src->index, buf, len);
12845 src->index += len;
12846 return len;
12847}
12848
12849
12850/* Load GIF image IMG for use on frame F. Value is non-zero if
12851 successful. */
12852
12853static int
12854gif_load (f, img)
12855 struct frame *f;
12856 struct image *img;
12857{
12858 Lisp_Object file, specified_file;
12859 Lisp_Object specified_data;
12860 int rc, width, height, x, y, i;
12861 XImage *ximg;
12862 ColorMapObject *gif_color_map;
12863 unsigned long pixel_colors[256];
12864 GifFileType *gif;
12865 struct gcpro gcpro1;
12866 Lisp_Object image;
12867 int ino, image_left, image_top, image_width, image_height;
12868 gif_memory_source memsrc;
12869 unsigned char *raster;
12870
12871 specified_file = image_spec_value (img->spec, QCfile, NULL);
12872 specified_data = image_spec_value (img->spec, QCdata, NULL);
12873 file = Qnil;
12874 GCPRO1 (file);
12875
12876 if (NILP (specified_data))
12877 {
12878 file = x_find_image_file (specified_file);
12879 if (!STRINGP (file))
12880 {
12881 image_error ("Cannot find image file `%s'", specified_file, Qnil);
12882 UNGCPRO;
12883 return 0;
12884 }
12885
12886 /* Open the GIF file. */
12887 gif = DGifOpenFileName (SDATA (file));
12888 if (gif == NULL)
12889 {
12890 image_error ("Cannot open `%s'", file, Qnil);
12891 UNGCPRO;
12892 return 0;
12893 }
12894 }
12895 else
12896 {
12897 /* Read from memory! */
12898 current_gif_memory_src = &memsrc;
12899 memsrc.bytes = SDATA (specified_data);
12900 memsrc.len = SBYTES (specified_data);
12901 memsrc.index = 0;
12902
12903 gif = DGifOpen(&memsrc, gif_read_from_memory);
12904 if (!gif)
12905 {
12906 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
12907 UNGCPRO;
12908 return 0;
12909 }
12910 }
12911
12912 /* Read entire contents. */
12913 rc = DGifSlurp (gif);
12914 if (rc == GIF_ERROR)
12915 {
12916 image_error ("Error reading `%s'", img->spec, Qnil);
12917 DGifCloseFile (gif);
12918 UNGCPRO;
12919 return 0;
12920 }
12921
12922 image = image_spec_value (img->spec, QCindex, NULL);
12923 ino = INTEGERP (image) ? XFASTINT (image) : 0;
12924 if (ino >= gif->ImageCount)
12925 {
12926 image_error ("Invalid image number `%s' in image `%s'",
12927 image, img->spec);
12928 DGifCloseFile (gif);
12929 UNGCPRO;
12930 return 0;
12931 }
12932
12933 width = img->width = gif->SWidth;
12934 height = img->height = gif->SHeight;
12935
12936 /* Create the X image and pixmap. */
12937 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
12938 {
12939 DGifCloseFile (gif);
12940 UNGCPRO;
12941 return 0;
12942 }
12943
12944 /* Allocate colors. */
12945 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
12946 if (!gif_color_map)
12947 gif_color_map = gif->SColorMap;
12948 init_color_table ();
12949 bzero (pixel_colors, sizeof pixel_colors);
12950
12951 for (i = 0; i < gif_color_map->ColorCount; ++i)
12952 {
12953 int r = gif_color_map->Colors[i].Red << 8;
12954 int g = gif_color_map->Colors[i].Green << 8;
12955 int b = gif_color_map->Colors[i].Blue << 8;
12956 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
12957 }
12958
12959 img->colors = colors_in_color_table (&img->ncolors);
12960 free_color_table ();
12961
12962 /* Clear the part of the screen image that are not covered by
12963 the image from the GIF file. Full animated GIF support
12964 requires more than can be done here (see the gif89 spec,
12965 disposal methods). Let's simply assume that the part
12966 not covered by a sub-image is in the frame's background color. */
12967 image_top = gif->SavedImages[ino].ImageDesc.Top;
12968 image_left = gif->SavedImages[ino].ImageDesc.Left;
12969 image_width = gif->SavedImages[ino].ImageDesc.Width;
12970 image_height = gif->SavedImages[ino].ImageDesc.Height;
12971
12972 for (y = 0; y < image_top; ++y)
12973 for (x = 0; x < width; ++x)
12974 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12975
12976 for (y = image_top + image_height; y < height; ++y)
12977 for (x = 0; x < width; ++x)
12978 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12979
12980 for (y = image_top; y < image_top + image_height; ++y)
12981 {
12982 for (x = 0; x < image_left; ++x)
12983 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12984 for (x = image_left + image_width; x < width; ++x)
12985 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12986 }
12987
12988 /* Read the GIF image into the X image. We use a local variable
12989 `raster' here because RasterBits below is a char *, and invites
12990 problems with bytes >= 0x80. */
12991 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
12992
12993 if (gif->SavedImages[ino].ImageDesc.Interlace)
12994 {
12995 static int interlace_start[] = {0, 4, 2, 1};
12996 static int interlace_increment[] = {8, 8, 4, 2};
12997 int pass;
12998 int row = interlace_start[0];
12999
13000 pass = 0;
13001
13002 for (y = 0; y < image_height; y++)
13003 {
13004 if (row >= image_height)
13005 {
13006 row = interlace_start[++pass];
13007 while (row >= image_height)
13008 row = interlace_start[++pass];
13009 }
13010
13011 for (x = 0; x < image_width; x++)
13012 {
13013 int i = raster[(y * image_width) + x];
13014 XPutPixel (ximg, x + image_left, row + image_top,
13015 pixel_colors[i]);
13016 }
13017
13018 row += interlace_increment[pass];
13019 }
13020 }
13021 else
13022 {
13023 for (y = 0; y < image_height; ++y)
13024 for (x = 0; x < image_width; ++x)
13025 {
13026 int i = raster[y* image_width + x];
13027 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
13028 }
13029 }
13030
13031 DGifCloseFile (gif);
13032
13033 /* Maybe fill in the background field while we have ximg handy. */
13034 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
13035 IMAGE_BACKGROUND (img, f, ximg);
13036
13037 /* Put the image into the pixmap, then free the X image and its buffer. */
13038 x_put_x_image (f, ximg, img->pixmap, width, height);
13039 x_destroy_x_image (ximg);
13040
13041 UNGCPRO;
13042 return 1;
13043}
13044
13045#endif /* HAVE_GIF != 0 */
13046
13047
13048\f
13049/***********************************************************************
13050 Ghostscript
13051 ***********************************************************************/
13052
13053Lisp_Object Qpostscript;
13054
13055#ifdef HAVE_GHOSTSCRIPT
13056static int gs_image_p P_ ((Lisp_Object object));
13057static int gs_load P_ ((struct frame *f, struct image *img));
13058static void gs_clear_image P_ ((struct frame *f, struct image *img));
13059
13060/* The symbol `postscript' identifying images of this type. */
13061
13062/* Keyword symbols. */
13063
13064Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
13065
13066/* Indices of image specification fields in gs_format, below. */
13067
13068enum gs_keyword_index
13069{
13070 GS_TYPE,
13071 GS_PT_WIDTH,
13072 GS_PT_HEIGHT,
13073 GS_FILE,
13074 GS_LOADER,
13075 GS_BOUNDING_BOX,
13076 GS_ASCENT,
13077 GS_MARGIN,
13078 GS_RELIEF,
13079 GS_ALGORITHM,
13080 GS_HEURISTIC_MASK,
13081 GS_MASK,
13082 GS_BACKGROUND,
13083 GS_LAST
13084};
13085
13086/* Vector of image_keyword structures describing the format
13087 of valid user-defined image specifications. */
13088
13089static struct image_keyword gs_format[GS_LAST] =
13090{
13091 {":type", IMAGE_SYMBOL_VALUE, 1},
13092 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13093 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
13094 {":file", IMAGE_STRING_VALUE, 1},
13095 {":loader", IMAGE_FUNCTION_VALUE, 0},
13096 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
13097 {":ascent", IMAGE_ASCENT_VALUE, 0},
13098 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
13099 {":relief", IMAGE_INTEGER_VALUE, 0},
13100 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13101 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13102 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
13103 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
13104};
13105
13106/* Structure describing the image type `ghostscript'. */
13107
13108static struct image_type gs_type =
13109{
13110 &Qpostscript,
13111 gs_image_p,
13112 gs_load,
13113 gs_clear_image,
13114 NULL
13115};
13116
13117
13118/* Free X resources of Ghostscript image IMG which is used on frame F. */
13119
13120static void
13121gs_clear_image (f, img)
13122 struct frame *f;
13123 struct image *img;
13124{
13125 /* IMG->data.ptr_val may contain a recorded colormap. */
13126 xfree (img->data.ptr_val);
13127 x_clear_image (f, img);
13128}
13129
13130
13131/* Return non-zero if OBJECT is a valid Ghostscript image
13132 specification. */
13133
13134static int
13135gs_image_p (object)
13136 Lisp_Object object;
13137{
13138 struct image_keyword fmt[GS_LAST];
13139 Lisp_Object tem;
13140 int i;
13141
13142 bcopy (gs_format, fmt, sizeof fmt);
13143
13144 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
13145 return 0;
13146
13147 /* Bounding box must be a list or vector containing 4 integers. */
13148 tem = fmt[GS_BOUNDING_BOX].value;
13149 if (CONSP (tem))
13150 {
13151 for (i = 0; i < 4; ++i, tem = XCDR (tem))
13152 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
13153 return 0;
13154 if (!NILP (tem))
13155 return 0;
13156 }
13157 else if (VECTORP (tem))
13158 {
13159 if (XVECTOR (tem)->size != 4)
13160 return 0;
13161 for (i = 0; i < 4; ++i)
13162 if (!INTEGERP (XVECTOR (tem)->contents[i]))
13163 return 0;
13164 }
13165 else
13166 return 0;
13167
13168 return 1;
13169}
13170
13171
13172/* Load Ghostscript image IMG for use on frame F. Value is non-zero
13173 if successful. */
13174
13175static int
13176gs_load (f, img)
13177 struct frame *f;
13178 struct image *img;
13179{
13180 char buffer[100];
13181 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
13182 struct gcpro gcpro1, gcpro2;
13183 Lisp_Object frame;
13184 double in_width, in_height;
13185 Lisp_Object pixel_colors = Qnil;
13186
13187 /* Compute pixel size of pixmap needed from the given size in the
13188 image specification. Sizes in the specification are in pt. 1 pt
13189 = 1/72 in, xdpi and ydpi are stored in the frame's X display
13190 info. */
13191 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
13192 in_width = XFASTINT (pt_width) / 72.0;
13193 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
13194 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
13195 in_height = XFASTINT (pt_height) / 72.0;
13196 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
13197
13198 /* Create the pixmap. */
13199 BLOCK_INPUT;
13200 xassert (img->pixmap == 0);
13201 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13202 img->width, img->height,
13203 one_w32_display_info.n_cbits);
13204 UNBLOCK_INPUT;
13205
13206 if (!img->pixmap)
13207 {
13208 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
13209 return 0;
13210 }
13211
13212 /* Call the loader to fill the pixmap. It returns a process object
13213 if successful. We do not record_unwind_protect here because
13214 other places in redisplay like calling window scroll functions
13215 don't either. Let the Lisp loader use `unwind-protect' instead. */
13216 GCPRO2 (window_and_pixmap_id, pixel_colors);
13217
13218 sprintf (buffer, "%lu %lu",
13219 (unsigned long) FRAME_W32_WINDOW (f),
13220 (unsigned long) img->pixmap);
13221 window_and_pixmap_id = build_string (buffer);
13222
13223 sprintf (buffer, "%lu %lu",
13224 FRAME_FOREGROUND_PIXEL (f),
13225 FRAME_BACKGROUND_PIXEL (f));
13226 pixel_colors = build_string (buffer);
13227
13228 XSETFRAME (frame, f);
13229 loader = image_spec_value (img->spec, QCloader, NULL);
13230 if (NILP (loader))
13231 loader = intern ("gs-load-image");
13232
13233 img->data.lisp_val = call6 (loader, frame, img->spec,
13234 make_number (img->width),
13235 make_number (img->height),
13236 window_and_pixmap_id,
13237 pixel_colors);
13238 UNGCPRO;
13239 return PROCESSP (img->data.lisp_val);
13240}
13241
13242
13243/* Kill the Ghostscript process that was started to fill PIXMAP on
13244 frame F. Called from XTread_socket when receiving an event
13245 telling Emacs that Ghostscript has finished drawing. */
13246
13247void
13248x_kill_gs_process (pixmap, f)
13249 Pixmap pixmap;
13250 struct frame *f;
13251{
13252 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
13253 int class, i;
13254 struct image *img;
13255
13256 /* Find the image containing PIXMAP. */
13257 for (i = 0; i < c->used; ++i)
13258 if (c->images[i]->pixmap == pixmap)
13259 break;
13260
13261 /* Should someone in between have cleared the image cache, for
13262 instance, give up. */
13263 if (i == c->used)
13264 return;
13265
13266 /* Kill the GS process. We should have found PIXMAP in the image
13267 cache and its image should contain a process object. */
13268 img = c->images[i];
13269 xassert (PROCESSP (img->data.lisp_val));
13270 Fkill_process (img->data.lisp_val, Qnil);
13271 img->data.lisp_val = Qnil;
13272
13273 /* On displays with a mutable colormap, figure out the colors
13274 allocated for the image by looking at the pixels of an XImage for
13275 img->pixmap. */
13276 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
13277 if (class != StaticColor && class != StaticGray && class != TrueColor)
13278 {
13279 XImage *ximg;
13280
13281 BLOCK_INPUT;
13282
13283 /* Try to get an XImage for img->pixmep. */
13284 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
13285 0, 0, img->width, img->height, ~0, ZPixmap);
13286 if (ximg)
13287 {
13288 int x, y;
13289
13290 /* Initialize the color table. */
13291 init_color_table ();
13292
13293 /* For each pixel of the image, look its color up in the
13294 color table. After having done so, the color table will
13295 contain an entry for each color used by the image. */
13296 for (y = 0; y < img->height; ++y)
13297 for (x = 0; x < img->width; ++x)
13298 {
13299 unsigned long pixel = XGetPixel (ximg, x, y);
13300 lookup_pixel_color (f, pixel);
13301 }
13302
13303 /* Record colors in the image. Free color table and XImage. */
13304 img->colors = colors_in_color_table (&img->ncolors);
13305 free_color_table ();
13306 XDestroyImage (ximg);
13307
13308#if 0 /* This doesn't seem to be the case. If we free the colors
13309 here, we get a BadAccess later in x_clear_image when
13310 freeing the colors. */
13311 /* We have allocated colors once, but Ghostscript has also
13312 allocated colors on behalf of us. So, to get the
13313 reference counts right, free them once. */
13314 if (img->ncolors)
13315 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
13316 img->colors, img->ncolors, 0);
13317#endif
13318 }
13319 else
13320 image_error ("Cannot get X image of `%s'; colors will not be freed",
13321 img->spec, Qnil);
13322
13323 UNBLOCK_INPUT;
13324 }
13325
13326 /* Now that we have the pixmap, compute mask and transform the
13327 image if requested. */
13328 BLOCK_INPUT;
13329 postprocess_image (f, img);
13330 UNBLOCK_INPUT;
13331}
13332
13333#endif /* HAVE_GHOSTSCRIPT */
13334
13335\f
13336/***********************************************************************
13337 Window properties
13338 ***********************************************************************/
13339
13340DEFUN ("x-change-window-property", Fx_change_window_property,
13341 Sx_change_window_property, 2, 3, 0,
13342 doc: /* Change window property PROP to VALUE on the X window of FRAME.
13343PROP and VALUE must be strings. FRAME nil or omitted means use the
13344selected frame. Value is VALUE. */)
13345 (prop, value, frame)
13346 Lisp_Object frame, prop, value;
13347{
13348#if 0 /* TODO : port window properties to W32 */
13349 struct frame *f = check_x_frame (frame);
13350 Atom prop_atom;
13351
13352 CHECK_STRING (prop);
13353 CHECK_STRING (value);
13354
13355 BLOCK_INPUT;
13356 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13357 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13358 prop_atom, XA_STRING, 8, PropModeReplace,
13359 SDATA (value), SCHARS (value));
13360
13361 /* Make sure the property is set when we return. */
13362 XFlush (FRAME_W32_DISPLAY (f));
13363 UNBLOCK_INPUT;
13364
13365#endif /* TODO */
13366
13367 return value;
13368}
13369
13370
13371DEFUN ("x-delete-window-property", Fx_delete_window_property,
13372 Sx_delete_window_property, 1, 2, 0,
13373 doc: /* Remove window property PROP from X window of FRAME.
13374FRAME nil or omitted means use the selected frame. Value is PROP. */)
13375 (prop, frame)
13376 Lisp_Object prop, frame;
13377{
13378#if 0 /* TODO : port window properties to W32 */
13379
13380 struct frame *f = check_x_frame (frame);
13381 Atom prop_atom;
13382
13383 CHECK_STRING (prop);
13384 BLOCK_INPUT;
13385 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13386 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
13387
13388 /* Make sure the property is removed when we return. */
13389 XFlush (FRAME_W32_DISPLAY (f));
13390 UNBLOCK_INPUT;
13391#endif /* TODO */
13392
13393 return prop;
13394}
13395
13396
13397DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
13398 1, 2, 0,
13399 doc: /* Value is the value of window property PROP on FRAME.
13400If FRAME is nil or omitted, use the selected frame. Value is nil
13401if FRAME hasn't a property with name PROP or if PROP has no string
13402value. */)
13403 (prop, frame)
13404 Lisp_Object prop, frame;
13405{
13406#if 0 /* TODO : port window properties to W32 */
13407
13408 struct frame *f = check_x_frame (frame);
13409 Atom prop_atom;
13410 int rc;
13411 Lisp_Object prop_value = Qnil;
13412 char *tmp_data = NULL;
13413 Atom actual_type;
13414 int actual_format;
13415 unsigned long actual_size, bytes_remaining;
13416
13417 CHECK_STRING (prop);
13418 BLOCK_INPUT;
13419 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
13420 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13421 prop_atom, 0, 0, False, XA_STRING,
13422 &actual_type, &actual_format, &actual_size,
13423 &bytes_remaining, (unsigned char **) &tmp_data);
13424 if (rc == Success)
13425 {
13426 int size = bytes_remaining;
13427
13428 XFree (tmp_data);
13429 tmp_data = NULL;
13430
13431 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
13432 prop_atom, 0, bytes_remaining,
13433 False, XA_STRING,
13434 &actual_type, &actual_format,
13435 &actual_size, &bytes_remaining,
13436 (unsigned char **) &tmp_data);
13437 if (rc == Success)
13438 prop_value = make_string (tmp_data, size);
13439
13440 XFree (tmp_data);
13441 }
13442
13443 UNBLOCK_INPUT;
13444
13445 return prop_value;
13446
13447#endif /* TODO */
13448 return Qnil;
13449}
13450
13451
13452\f
13453/***********************************************************************
13454 Busy cursor
13455 ***********************************************************************/
13456
13457/* If non-null, an asynchronous timer that, when it expires, displays
13458 an hourglass cursor on all frames. */
13459
13460static struct atimer *hourglass_atimer;
13461
13462/* Non-zero means an hourglass cursor is currently shown. */
13463
13464static int hourglass_shown_p;
13465
13466/* Number of seconds to wait before displaying an hourglass cursor. */
13467
13468static Lisp_Object Vhourglass_delay;
13469
13470/* Default number of seconds to wait before displaying an hourglass
13471 cursor. */
13472
13473#define DEFAULT_HOURGLASS_DELAY 1
13474
13475/* Function prototypes. */
13476
13477static void show_hourglass P_ ((struct atimer *));
13478static void hide_hourglass P_ ((void));
13479
13480
13481/* Cancel a currently active hourglass timer, and start a new one. */
13482
13483void
13484start_hourglass ()
13485{
13486#if 0 /* TODO: cursor shape changes. */
13487 EMACS_TIME delay;
13488 int secs, usecs = 0;
13489
13490 cancel_hourglass ();
13491
13492 if (INTEGERP (Vhourglass_delay)
13493 && XINT (Vhourglass_delay) > 0)
13494 secs = XFASTINT (Vhourglass_delay);
13495 else if (FLOATP (Vhourglass_delay)
13496 && XFLOAT_DATA (Vhourglass_delay) > 0)
13497 {
13498 Lisp_Object tem;
13499 tem = Ftruncate (Vhourglass_delay, Qnil);
13500 secs = XFASTINT (tem);
13501 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
13502 }
13503 else
13504 secs = DEFAULT_HOURGLASS_DELAY;
13505
13506 EMACS_SET_SECS_USECS (delay, secs, usecs);
13507 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
13508 show_hourglass, NULL);
13509#endif
13510}
13511
13512
13513/* Cancel the hourglass cursor timer if active, hide an hourglass
13514 cursor if shown. */
13515
13516void
13517cancel_hourglass ()
13518{
13519 if (hourglass_atimer)
13520 {
13521 cancel_atimer (hourglass_atimer);
13522 hourglass_atimer = NULL;
13523 }
13524
13525 if (hourglass_shown_p)
13526 hide_hourglass ();
13527}
13528
13529
13530/* Timer function of hourglass_atimer. TIMER is equal to
13531 hourglass_atimer.
13532
13533 Display an hourglass cursor on all frames by mapping the frames'
13534 hourglass_window. Set the hourglass_p flag in the frames'
13535 output_data.x structure to indicate that an hourglass cursor is
13536 shown on the frames. */
13537
13538static void
13539show_hourglass (timer)
13540 struct atimer *timer;
13541{
13542#if 0 /* TODO: cursor shape changes. */
13543 /* The timer implementation will cancel this timer automatically
13544 after this function has run. Set hourglass_atimer to null
13545 so that we know the timer doesn't have to be canceled. */
13546 hourglass_atimer = NULL;
13547
13548 if (!hourglass_shown_p)
13549 {
13550 Lisp_Object rest, frame;
13551
13552 BLOCK_INPUT;
13553
13554 FOR_EACH_FRAME (rest, frame)
13555 if (FRAME_W32_P (XFRAME (frame)))
13556 {
13557 struct frame *f = XFRAME (frame);
13558
13559 f->output_data.w32->hourglass_p = 1;
13560
13561 if (!f->output_data.w32->hourglass_window)
13562 {
13563 unsigned long mask = CWCursor;
13564 XSetWindowAttributes attrs;
13565
13566 attrs.cursor = f->output_data.w32->hourglass_cursor;
13567
13568 f->output_data.w32->hourglass_window
13569 = XCreateWindow (FRAME_X_DISPLAY (f),
13570 FRAME_OUTER_WINDOW (f),
13571 0, 0, 32000, 32000, 0, 0,
13572 InputOnly,
13573 CopyFromParent,
13574 mask, &attrs);
13575 }
13576
13577 XMapRaised (FRAME_X_DISPLAY (f),
13578 f->output_data.w32->hourglass_window);
13579 XFlush (FRAME_X_DISPLAY (f));
13580 }
13581
13582 hourglass_shown_p = 1;
13583 UNBLOCK_INPUT;
13584 }
13585#endif
13586}
13587
13588
13589/* Hide the hourglass cursor on all frames, if it is currently shown. */
13590
13591static void
13592hide_hourglass ()
13593{
13594#if 0 /* TODO: cursor shape changes. */
13595 if (hourglass_shown_p)
13596 {
13597 Lisp_Object rest, frame;
13598
13599 BLOCK_INPUT;
13600 FOR_EACH_FRAME (rest, frame)
13601 {
13602 struct frame *f = XFRAME (frame);
13603
13604 if (FRAME_W32_P (f)
13605 /* Watch out for newly created frames. */
13606 && f->output_data.x->hourglass_window)
13607 {
13608 XUnmapWindow (FRAME_X_DISPLAY (f),
13609 f->output_data.x->hourglass_window);
13610 /* Sync here because XTread_socket looks at the
13611 hourglass_p flag that is reset to zero below. */
13612 XSync (FRAME_X_DISPLAY (f), False);
13613 f->output_data.x->hourglass_p = 0;
13614 }
13615 }
13616
13617 hourglass_shown_p = 0;
13618 UNBLOCK_INPUT;
13619 }
13620#endif
13621}
13622
13623
13624\f
13625/***********************************************************************
13626 Tool tips
13627 ***********************************************************************/
13628
13629static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
13630 Lisp_Object, Lisp_Object));
13631static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
13632 Lisp_Object, int, int, int *, int *));
13633
13634/* The frame of a currently visible tooltip. */
13635
13636Lisp_Object tip_frame;
13637
13638/* If non-nil, a timer started that hides the last tooltip when it
13639 fires. */
13640
13641Lisp_Object tip_timer;
13642Window tip_window;
13643
13644/* If non-nil, a vector of 3 elements containing the last args
13645 with which x-show-tip was called. See there. */
13646
13647Lisp_Object last_show_tip_args;
13648
13649/* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
13650
13651Lisp_Object Vx_max_tooltip_size;
13652
13653
13654static Lisp_Object
13655unwind_create_tip_frame (frame)
13656 Lisp_Object frame;
13657{
13658 Lisp_Object deleted;
13659
13660 deleted = unwind_create_frame (frame);
13661 if (EQ (deleted, Qt))
13662 {
13663 tip_window = NULL;
13664 tip_frame = Qnil;
13665 }
13666
13667 return deleted;
13668}
13669
13670
13671/* Create a frame for a tooltip on the display described by DPYINFO.
13672 PARMS is a list of frame parameters. TEXT is the string to
13673 display in the tip frame. Value is the frame.
13674
13675 Note that functions called here, esp. x_default_parameter can
13676 signal errors, for instance when a specified color name is
13677 undefined. We have to make sure that we're in a consistent state
13678 when this happens. */
13679
13680static Lisp_Object
13681x_create_tip_frame (dpyinfo, parms, text)
13682 struct w32_display_info *dpyinfo;
13683 Lisp_Object parms, text;
13684{
13685 struct frame *f;
13686 Lisp_Object frame, tem;
13687 Lisp_Object name;
13688 long window_prompting = 0;
13689 int width, height;
13690 int count = SPECPDL_INDEX ();
13691 struct gcpro gcpro1, gcpro2, gcpro3;
13692 struct kboard *kb;
13693 int face_change_count_before = face_change_count;
13694 Lisp_Object buffer;
13695 struct buffer *old_buffer;
13696
13697 check_w32 ();
13698
13699 /* Use this general default value to start with until we know if
13700 this frame has a specified name. */
13701 Vx_resource_name = Vinvocation_name;
13702
13703#ifdef MULTI_KBOARD
13704 kb = dpyinfo->kboard;
13705#else
13706 kb = &the_only_kboard;
13707#endif
13708
13709 /* Get the name of the frame to use for resource lookup. */
13710 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
13711 if (!STRINGP (name)
13712 && !EQ (name, Qunbound)
13713 && !NILP (name))
13714 error ("Invalid frame name--not a string or nil");
13715 Vx_resource_name = name;
13716
13717 frame = Qnil;
13718 GCPRO3 (parms, name, frame);
13719 /* Make a frame without minibuffer nor mode-line. */
13720 f = make_frame (0);
13721 f->wants_modeline = 0;
13722 XSETFRAME (frame, f);
13723
13724 buffer = Fget_buffer_create (build_string (" *tip*"));
13725 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
13726 old_buffer = current_buffer;
13727 set_buffer_internal_1 (XBUFFER (buffer));
13728 current_buffer->truncate_lines = Qnil;
13729 Ferase_buffer ();
13730 Finsert (1, &text);
13731 set_buffer_internal_1 (old_buffer);
13732
13733 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
13734 record_unwind_protect (unwind_create_tip_frame, frame);
13735
13736 /* By setting the output method, we're essentially saying that
13737 the frame is live, as per FRAME_LIVE_P. If we get a signal
13738 from this point on, x_destroy_window might screw up reference
13739 counts etc. */
13740 f->output_method = output_w32;
13741 f->output_data.w32 =
13742 (struct w32_output *) xmalloc (sizeof (struct w32_output));
13743 bzero (f->output_data.w32, sizeof (struct w32_output));
13744
13745 FRAME_FONTSET (f) = -1;
13746 f->icon_name = Qnil;
13747
13748#if 0 /* GLYPH_DEBUG TODO: image support. */
13749 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
13750 dpyinfo_refcount = dpyinfo->reference_count;
13751#endif /* GLYPH_DEBUG */
13752#ifdef MULTI_KBOARD
13753 FRAME_KBOARD (f) = kb;
13754#endif
13755 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13756 f->output_data.w32->explicit_parent = 0;
13757
13758 /* Set the name; the functions to which we pass f expect the name to
13759 be set. */
13760 if (EQ (name, Qunbound) || NILP (name))
13761 {
13762 f->name = build_string (dpyinfo->w32_id_name);
13763 f->explicit_name = 0;
13764 }
13765 else
13766 {
13767 f->name = name;
13768 f->explicit_name = 1;
13769 /* use the frame's title when getting resources for this frame. */
13770 specbind (Qx_resource_name, name);
13771 }
13772
13773 /* Extract the window parameters from the supplied values
13774 that are needed to determine window geometry. */
13775 {
13776 Lisp_Object font;
13777
13778 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
13779
13780 BLOCK_INPUT;
13781 /* First, try whatever font the caller has specified. */
13782 if (STRINGP (font))
13783 {
13784 tem = Fquery_fontset (font, Qnil);
13785 if (STRINGP (tem))
13786 font = x_new_fontset (f, SDATA (tem));
13787 else
13788 font = x_new_font (f, SDATA (font));
13789 }
13790
13791 /* Try out a font which we hope has bold and italic variations. */
13792 if (!STRINGP (font))
13793 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
13794 if (! STRINGP (font))
13795 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
13796 /* If those didn't work, look for something which will at least work. */
13797 if (! STRINGP (font))
13798 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
13799 UNBLOCK_INPUT;
13800 if (! STRINGP (font))
13801 font = build_string ("Fixedsys");
13802
13803 x_default_parameter (f, parms, Qfont, font,
13804 "font", "Font", RES_TYPE_STRING);
13805 }
13806
13807 x_default_parameter (f, parms, Qborder_width, make_number (2),
13808 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
13809 /* This defaults to 2 in order to match xterm. We recognize either
13810 internalBorderWidth or internalBorder (which is what xterm calls
13811 it). */
13812 if (NILP (Fassq (Qinternal_border_width, parms)))
13813 {
13814 Lisp_Object value;
13815
13816 value = w32_get_arg (parms, Qinternal_border_width,
13817 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
13818 if (! EQ (value, Qunbound))
13819 parms = Fcons (Fcons (Qinternal_border_width, value),
13820 parms);
13821 }
13822 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
13823 "internalBorderWidth", "internalBorderWidth",
13824 RES_TYPE_NUMBER);
13825
13826 /* Also do the stuff which must be set before the window exists. */
13827 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
13828 "foreground", "Foreground", RES_TYPE_STRING);
13829 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
13830 "background", "Background", RES_TYPE_STRING);
13831 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
13832 "pointerColor", "Foreground", RES_TYPE_STRING);
13833 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
13834 "cursorColor", "Foreground", RES_TYPE_STRING);
13835 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
13836 "borderColor", "BorderColor", RES_TYPE_STRING);
13837
13838 /* Init faces before x_default_parameter is called for scroll-bar
13839 parameters because that function calls x_set_scroll_bar_width,
13840 which calls change_frame_size, which calls Fset_window_buffer,
13841 which runs hooks, which call Fvertical_motion. At the end, we
13842 end up in init_iterator with a null face cache, which should not
13843 happen. */
13844 init_frame_faces (f);
13845
13846 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
13847 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
13848
13849 window_prompting = x_figure_window_size (f, parms);
13850
13851 /* No fringes on tip frame. */
13852 f->output_data.w32->fringes_extra = 0;
13853 f->output_data.w32->fringe_cols = 0;
13854 f->output_data.w32->left_fringe_width = 0;
13855 f->output_data.w32->right_fringe_width = 0;
13856
13857 if (window_prompting & XNegative)
13858 {
13859 if (window_prompting & YNegative)
13860 f->output_data.w32->win_gravity = SouthEastGravity;
13861 else
13862 f->output_data.w32->win_gravity = NorthEastGravity;
13863 }
13864 else
13865 {
13866 if (window_prompting & YNegative)
13867 f->output_data.w32->win_gravity = SouthWestGravity;
13868 else
13869 f->output_data.w32->win_gravity = NorthWestGravity;
13870 }
13871
13872 f->output_data.w32->size_hint_flags = window_prompting;
13873
13874 BLOCK_INPUT;
13875 my_create_tip_window (f);
13876 UNBLOCK_INPUT;
13877
13878 x_make_gc (f);
13879
13880 x_default_parameter (f, parms, Qauto_raise, Qnil,
13881 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13882 x_default_parameter (f, parms, Qauto_lower, Qnil,
13883 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
13884 x_default_parameter (f, parms, Qcursor_type, Qbox,
13885 "cursorType", "CursorType", RES_TYPE_SYMBOL);
13886
13887 /* Dimensions, especially f->height, must be done via change_frame_size.
13888 Change will not be effected unless different from the current
13889 f->height. */
13890 width = f->width;
13891 height = f->height;
13892 f->height = 0;
13893 SET_FRAME_WIDTH (f, 0);
13894 change_frame_size (f, height, width, 1, 0, 0);
13895
13896 /* Add `tooltip' frame parameter's default value. */
13897 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
13898 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
13899 Qnil));
13900
13901 /* Set up faces after all frame parameters are known. This call
13902 also merges in face attributes specified for new frames.
13903
13904 Frame parameters may be changed if .Xdefaults contains
13905 specifications for the default font. For example, if there is an
13906 `Emacs.default.attributeBackground: pink', the `background-color'
13907 attribute of the frame get's set, which let's the internal border
13908 of the tooltip frame appear in pink. Prevent this. */
13909 {
13910 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
13911
13912 /* Set tip_frame here, so that */
13913 tip_frame = frame;
13914 call1 (Qface_set_after_frame_default, frame);
13915
13916 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
13917 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
13918 Qnil));
13919 }
13920
13921 f->no_split = 1;
13922
13923 UNGCPRO;
13924
13925 /* It is now ok to make the frame official even if we get an error
13926 below. And the frame needs to be on Vframe_list or making it
13927 visible won't work. */
13928 Vframe_list = Fcons (frame, Vframe_list);
13929
13930 /* Now that the frame is official, it counts as a reference to
13931 its display. */
13932 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
13933
13934 /* Setting attributes of faces of the tooltip frame from resources
13935 and similar will increment face_change_count, which leads to the
13936 clearing of all current matrices. Since this isn't necessary
13937 here, avoid it by resetting face_change_count to the value it
13938 had before we created the tip frame. */
13939 face_change_count = face_change_count_before;
13940
13941 /* Discard the unwind_protect. */
13942 return unbind_to (count, frame);
13943}
13944
13945
13946/* Compute where to display tip frame F. PARMS is the list of frame
13947 parameters for F. DX and DY are specified offsets from the current
13948 location of the mouse. WIDTH and HEIGHT are the width and height
13949 of the tooltip. Return coordinates relative to the root window of
13950 the display in *ROOT_X, and *ROOT_Y. */
13951
13952static void
13953compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
13954 struct frame *f;
13955 Lisp_Object parms, dx, dy;
13956 int width, height;
13957 int *root_x, *root_y;
13958{
13959 Lisp_Object left, top;
13960
13961 /* User-specified position? */
13962 left = Fcdr (Fassq (Qleft, parms));
13963 top = Fcdr (Fassq (Qtop, parms));
13964
13965 /* Move the tooltip window where the mouse pointer is. Resize and
13966 show it. */
13967 if (!INTEGERP (left) || !INTEGERP (top))
13968 {
13969 POINT pt;
13970
13971 BLOCK_INPUT;
13972 GetCursorPos (&pt);
13973 *root_x = pt.x;
13974 *root_y = pt.y;
13975 UNBLOCK_INPUT;
13976 }
13977
13978 if (INTEGERP (top))
13979 *root_y = XINT (top);
13980 else if (*root_y + XINT (dy) - height < 0)
13981 *root_y -= XINT (dy);
13982 else
13983 {
13984 *root_y -= height;
13985 *root_y += XINT (dy);
13986 }
13987
13988 if (INTEGERP (left))
13989 *root_x = XINT (left);
13990 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
13991 /* It fits to the right of the pointer. */
13992 *root_x += XINT (dx);
13993 else if (width + XINT (dx) <= *root_x)
13994 /* It fits to the left of the pointer. */
13995 *root_x -= width + XINT (dx);
13996 else
13997 /* Put it left justified on the screen -- it ought to fit that way. */
13998 *root_x = 0;
13999}
14000
14001
14002DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
14003 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
14004A tooltip window is a small window displaying a string.
14005
14006FRAME nil or omitted means use the selected frame.
14007
14008PARMS is an optional list of frame parameters which can be
14009used to change the tooltip's appearance.
14010
14011Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
14012means use the default timeout of 5 seconds.
14013
14014If the list of frame parameters PARAMS contains a `left' parameter,
14015the tooltip is displayed at that x-position. Otherwise it is
14016displayed at the mouse position, with offset DX added (default is 5 if
14017DX isn't specified). Likewise for the y-position; if a `top' frame
14018parameter is specified, it determines the y-position of the tooltip
14019window, otherwise it is displayed at the mouse position, with offset
14020DY added (default is -10).
14021
14022A tooltip's maximum size is specified by `x-max-tooltip-size'.
14023Text larger than the specified size is clipped. */)
14024 (string, frame, parms, timeout, dx, dy)
14025 Lisp_Object string, frame, parms, timeout, dx, dy;
14026{
14027 struct frame *f;
14028 struct window *w;
14029 int root_x, root_y;
14030 struct buffer *old_buffer;
14031 struct text_pos pos;
14032 int i, width, height;
14033 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
14034 int old_windows_or_buffers_changed = windows_or_buffers_changed;
14035 int count = SPECPDL_INDEX ();
14036
14037 specbind (Qinhibit_redisplay, Qt);
14038
14039 GCPRO4 (string, parms, frame, timeout);
14040
14041 CHECK_STRING (string);
14042 f = check_x_frame (frame);
14043 if (NILP (timeout))
14044 timeout = make_number (5);
14045 else
14046 CHECK_NATNUM (timeout);
14047
14048 if (NILP (dx))
14049 dx = make_number (5);
14050 else
14051 CHECK_NUMBER (dx);
14052
14053 if (NILP (dy))
14054 dy = make_number (-10);
14055 else
14056 CHECK_NUMBER (dy);
14057
14058 if (NILP (last_show_tip_args))
14059 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
14060
14061 if (!NILP (tip_frame))
14062 {
14063 Lisp_Object last_string = AREF (last_show_tip_args, 0);
14064 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
14065 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
14066
14067 if (EQ (frame, last_frame)
14068 && !NILP (Fequal (last_string, string))
14069 && !NILP (Fequal (last_parms, parms)))
14070 {
14071 struct frame *f = XFRAME (tip_frame);
14072
14073 /* Only DX and DY have changed. */
14074 if (!NILP (tip_timer))
14075 {
14076 Lisp_Object timer = tip_timer;
14077 tip_timer = Qnil;
14078 call1 (Qcancel_timer, timer);
14079 }
14080
14081 BLOCK_INPUT;
14082 compute_tip_xy (f, parms, dx, dy, PIXEL_WIDTH (f),
14083 PIXEL_HEIGHT (f), &root_x, &root_y);
14084
14085 /* Put tooltip in topmost group and in position. */
14086 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14087 root_x, root_y, 0, 0,
14088 SWP_NOSIZE | SWP_NOACTIVATE);
14089
14090 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14091 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14092 0, 0, 0, 0,
14093 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14094
14095 UNBLOCK_INPUT;
14096 goto start_timer;
14097 }
14098 }
14099
14100 /* Hide a previous tip, if any. */
14101 Fx_hide_tip ();
14102
14103 ASET (last_show_tip_args, 0, string);
14104 ASET (last_show_tip_args, 1, frame);
14105 ASET (last_show_tip_args, 2, parms);
14106
14107 /* Add default values to frame parameters. */
14108 if (NILP (Fassq (Qname, parms)))
14109 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
14110 if (NILP (Fassq (Qinternal_border_width, parms)))
14111 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
14112 if (NILP (Fassq (Qborder_width, parms)))
14113 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
14114 if (NILP (Fassq (Qborder_color, parms)))
14115 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
14116 if (NILP (Fassq (Qbackground_color, parms)))
14117 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
14118 parms);
14119
14120 /* Block input until the tip has been fully drawn, to avoid crashes
14121 when drawing tips in menus. */
14122 BLOCK_INPUT;
14123
14124 /* Create a frame for the tooltip, and record it in the global
14125 variable tip_frame. */
14126 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
14127 f = XFRAME (frame);
14128
14129 /* Set up the frame's root window. */
14130 w = XWINDOW (FRAME_ROOT_WINDOW (f));
14131 w->left = w->top = make_number (0);
14132
14133 if (CONSP (Vx_max_tooltip_size)
14134 && INTEGERP (XCAR (Vx_max_tooltip_size))
14135 && XINT (XCAR (Vx_max_tooltip_size)) > 0
14136 && INTEGERP (XCDR (Vx_max_tooltip_size))
14137 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
14138 {
14139 w->width = XCAR (Vx_max_tooltip_size);
14140 w->height = XCDR (Vx_max_tooltip_size);
14141 }
14142 else
14143 {
14144 w->width = make_number (80);
14145 w->height = make_number (40);
14146 }
14147
14148 f->window_width = XINT (w->width);
14149 adjust_glyphs (f);
14150 w->pseudo_window_p = 1;
14151
14152 /* Display the tooltip text in a temporary buffer. */
14153 old_buffer = current_buffer;
14154 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
14155 current_buffer->truncate_lines = Qnil;
14156 clear_glyph_matrix (w->desired_matrix);
14157 clear_glyph_matrix (w->current_matrix);
14158 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
14159 try_window (FRAME_ROOT_WINDOW (f), pos);
14160
14161 /* Compute width and height of the tooltip. */
14162 width = height = 0;
14163 for (i = 0; i < w->desired_matrix->nrows; ++i)
14164 {
14165 struct glyph_row *row = &w->desired_matrix->rows[i];
14166 struct glyph *last;
14167 int row_width;
14168
14169 /* Stop at the first empty row at the end. */
14170 if (!row->enabled_p || !row->displays_text_p)
14171 break;
14172
14173 /* Let the row go over the full width of the frame. */
14174 row->full_width_p = 1;
14175
14176#ifdef TODO /* Investigate why some fonts need more width than is
14177 calculated for some tooltips. */
14178 /* There's a glyph at the end of rows that is use to place
14179 the cursor there. Don't include the width of this glyph. */
14180 if (row->used[TEXT_AREA])
14181 {
14182 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
14183 row_width = row->pixel_width - last->pixel_width;
14184 }
14185 else
14186#endif
14187 row_width = row->pixel_width;
14188
14189 /* TODO: find why tips do not draw along baseline as instructed. */
14190 height += row->height;
14191 width = max (width, row_width);
14192 }
14193
14194 /* Add the frame's internal border to the width and height the X
14195 window should have. */
14196 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14197 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
14198
14199 /* Move the tooltip window where the mouse pointer is. Resize and
14200 show it. */
14201 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
14202
14203 {
14204 /* Adjust Window size to take border into account. */
14205 RECT rect;
14206 rect.left = rect.top = 0;
14207 rect.right = width;
14208 rect.bottom = height;
14209 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
14210 FRAME_EXTERNAL_MENU_BAR (f));
14211
14212 /* Position and size tooltip, and put it in the topmost group. */
14213 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
14214 root_x, root_y, rect.right - rect.left,
14215 rect.bottom - rect.top, SWP_NOACTIVATE);
14216
14217 /* Ensure tooltip is on top of other topmost windows (eg menus). */
14218 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
14219 0, 0, 0, 0,
14220 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
14221
14222 /* Let redisplay know that we have made the frame visible already. */
14223 f->async_visible = 1;
14224
14225 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
14226 }
14227
14228 /* Draw into the window. */
14229 w->must_be_updated_p = 1;
14230 update_single_window (w, 1);
14231
14232 UNBLOCK_INPUT;
14233
14234 /* Restore original current buffer. */
14235 set_buffer_internal_1 (old_buffer);
14236 windows_or_buffers_changed = old_windows_or_buffers_changed;
14237
14238 start_timer:
14239 /* Let the tip disappear after timeout seconds. */
14240 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
14241 intern ("x-hide-tip"));
14242
14243 UNGCPRO;
14244 return unbind_to (count, Qnil);
14245}
14246
14247
14248DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
14249 doc: /* Hide the current tooltip window, if there is any.
14250Value is t if tooltip was open, nil otherwise. */)
14251 ()
14252{
14253 int count;
14254 Lisp_Object deleted, frame, timer;
14255 struct gcpro gcpro1, gcpro2;
14256
14257 /* Return quickly if nothing to do. */
14258 if (NILP (tip_timer) && NILP (tip_frame))
14259 return Qnil;
14260
14261 frame = tip_frame;
14262 timer = tip_timer;
14263 GCPRO2 (frame, timer);
14264 tip_frame = tip_timer = deleted = Qnil;
14265
14266 count = SPECPDL_INDEX ();
14267 specbind (Qinhibit_redisplay, Qt);
14268 specbind (Qinhibit_quit, Qt);
14269
14270 if (!NILP (timer))
14271 call1 (Qcancel_timer, timer);
14272
14273 if (FRAMEP (frame))
14274 {
14275 Fdelete_frame (frame, Qnil);
14276 deleted = Qt;
14277 }
14278
14279 UNGCPRO;
14280 return unbind_to (count, deleted);
14281}
14282
14283
14284\f
14285/***********************************************************************
14286 File selection dialog
14287 ***********************************************************************/
14288extern Lisp_Object Qfile_name_history;
14289
14290/* Callback for altering the behaviour of the Open File dialog.
14291 Makes the Filename text field contain "Current Directory" and be
14292 read-only when "Directories" is selected in the filter. This
14293 allows us to work around the fact that the standard Open File
14294 dialog does not support directories. */
14295UINT CALLBACK
14296file_dialog_callback (hwnd, msg, wParam, lParam)
14297 HWND hwnd;
14298 UINT msg;
14299 WPARAM wParam;
14300 LPARAM lParam;
14301{
14302 if (msg == WM_NOTIFY)
14303 {
14304 OFNOTIFY * notify = (OFNOTIFY *)lParam;
14305 /* Detect when the Filter dropdown is changed. */
14306 if (notify->hdr.code == CDN_TYPECHANGE)
14307 {
14308 HWND dialog = GetParent (hwnd);
14309 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
14310
14311 /* Directories is in index 2. */
14312 if (notify->lpOFN->nFilterIndex == 2)
14313 {
14314 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14315 "Current Directory");
14316 EnableWindow (edit_control, FALSE);
14317 }
14318 else
14319 {
14320 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
14321 "");
14322 EnableWindow (edit_control, TRUE);
14323 }
14324 }
14325 }
14326 return 0;
14327}
14328
14329DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
14330 doc: /* Read file name, prompting with PROMPT in directory DIR.
14331Use a file selection dialog.
14332Select DEFAULT-FILENAME in the dialog's file selection box, if
14333specified. Ensure that file exists if MUSTMATCH is non-nil. */)
14334 (prompt, dir, default_filename, mustmatch)
14335 Lisp_Object prompt, dir, default_filename, mustmatch;
14336{
14337 struct frame *f = SELECTED_FRAME ();
14338 Lisp_Object file = Qnil;
14339 int count = SPECPDL_INDEX ();
14340 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
14341 char filename[MAX_PATH + 1];
14342 char init_dir[MAX_PATH + 1];
14343
14344 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
14345 CHECK_STRING (prompt);
14346 CHECK_STRING (dir);
14347
14348 /* Create the dialog with PROMPT as title, using DIR as initial
14349 directory and using "*" as pattern. */
14350 dir = Fexpand_file_name (dir, Qnil);
14351 strncpy (init_dir, SDATA (dir), MAX_PATH);
14352 init_dir[MAX_PATH] = '\0';
14353 unixtodos_filename (init_dir);
14354
14355 if (STRINGP (default_filename))
14356 {
14357 char *file_name_only;
14358 char *full_path_name = SDATA (default_filename);
14359
14360 unixtodos_filename (full_path_name);
14361
14362 file_name_only = strrchr (full_path_name, '\\');
14363 if (!file_name_only)
14364 file_name_only = full_path_name;
14365 else
14366 {
14367 file_name_only++;
14368 }
14369
14370 strncpy (filename, file_name_only, MAX_PATH);
14371 filename[MAX_PATH] = '\0';
14372 }
14373 else
14374 filename[0] = '\0';
14375
14376 {
14377 OPENFILENAME file_details;
14378
14379 /* Prevent redisplay. */
14380 specbind (Qinhibit_redisplay, Qt);
14381 BLOCK_INPUT;
14382
14383 bzero (&file_details, sizeof (file_details));
14384 file_details.lStructSize = sizeof (file_details);
14385 file_details.hwndOwner = FRAME_W32_WINDOW (f);
14386 /* Undocumented Bug in Common File Dialog:
14387 If a filter is not specified, shell links are not resolved. */
14388 file_details.lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
14389 file_details.lpstrFile = filename;
14390 file_details.nMaxFile = sizeof (filename);
14391 file_details.lpstrInitialDir = init_dir;
14392 file_details.lpstrTitle = SDATA (prompt);
14393 file_details.Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
14394 | OFN_EXPLORER | OFN_ENABLEHOOK);
14395 if (!NILP (mustmatch))
14396 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
14397
14398 file_details.lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
14399
14400 if (GetOpenFileName (&file_details))
14401 {
14402 dostounix_filename (filename);
14403 if (file_details.nFilterIndex == 2)
14404 {
14405 /* "Folder Only" selected - strip dummy file name. */
14406 char * last = strrchr (filename, '/');
14407 *last = '\0';
14408 }
14409
14410 file = DECODE_FILE(build_string (filename));
14411 }
14412 /* User cancelled the dialog without making a selection. */
14413 else if (!CommDlgExtendedError ())
14414 file = Qnil;
14415 /* An error occurred, fallback on reading from the mini-buffer. */
14416 else
14417 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
14418 dir, mustmatch, dir, Qfile_name_history,
14419 default_filename, Qnil);
14420
14421 UNBLOCK_INPUT;
14422 file = unbind_to (count, file);
14423 }
14424
14425 UNGCPRO;
14426
14427 /* Make "Cancel" equivalent to C-g. */
14428 if (NILP (file))
14429 Fsignal (Qquit, Qnil);
14430
14431 return unbind_to (count, file);
14432}
14433
14434
14435\f
14436/***********************************************************************
14437 w32 specialized functions
14438 ***********************************************************************/
14439
14440DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
14441 doc: /* Select a font using the W32 font dialog.
14442Returns an X font string corresponding to the selection. */)
14443 (frame, include_proportional)
14444 Lisp_Object frame, include_proportional;
14445{
14446 FRAME_PTR f = check_x_frame (frame);
14447 CHOOSEFONT cf;
14448 LOGFONT lf;
14449 TEXTMETRIC tm;
14450 HDC hdc;
14451 HANDLE oldobj;
14452 char buf[100];
14453
14454 bzero (&cf, sizeof (cf));
14455 bzero (&lf, sizeof (lf));
14456
14457 cf.lStructSize = sizeof (cf);
14458 cf.hwndOwner = FRAME_W32_WINDOW (f);
14459 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
14460
14461 /* Unless include_proportional is non-nil, limit the selection to
14462 monospaced fonts. */
14463 if (NILP (include_proportional))
14464 cf.Flags |= CF_FIXEDPITCHONLY;
14465
14466 cf.lpLogFont = &lf;
14467
14468 /* Initialize as much of the font details as we can from the current
14469 default font. */
14470 hdc = GetDC (FRAME_W32_WINDOW (f));
14471 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
14472 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
14473 if (GetTextMetrics (hdc, &tm))
14474 {
14475 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
14476 lf.lfWeight = tm.tmWeight;
14477 lf.lfItalic = tm.tmItalic;
14478 lf.lfUnderline = tm.tmUnderlined;
14479 lf.lfStrikeOut = tm.tmStruckOut;
14480 lf.lfCharSet = tm.tmCharSet;
14481 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
14482 }
14483 SelectObject (hdc, oldobj);
14484 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
14485
14486 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
14487 return Qnil;
14488
14489 return build_string (buf);
14490}
14491
14492DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
14493 Sw32_send_sys_command, 1, 2, 0,
14494 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
14495Some useful values for command are #xf030 to maximise frame (#xf020
14496to minimize), #xf120 to restore frame to original size, and #xf100
14497to activate the menubar for keyboard access. #xf140 activates the
14498screen saver if defined.
14499
14500If optional parameter FRAME is not specified, use selected frame. */)
14501 (command, frame)
14502 Lisp_Object command, frame;
14503{
14504 FRAME_PTR f = check_x_frame (frame);
14505
14506 CHECK_NUMBER (command);
14507
14508 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
14509
14510 return Qnil;
14511}
14512
14513DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
14514 doc: /* Get Windows to perform OPERATION on DOCUMENT.
14515This is a wrapper around the ShellExecute system function, which
14516invokes the application registered to handle OPERATION for DOCUMENT.
14517OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
14518nil for the default action), and DOCUMENT is typically the name of a
14519document file or URL, but can also be a program executable to run or
14520a directory to open in the Windows Explorer.
14521
14522If DOCUMENT is a program executable, PARAMETERS can be a string
14523containing command line parameters, but otherwise should be nil.
14524
14525SHOW-FLAG can be used to control whether the invoked application is hidden
14526or minimized. If SHOW-FLAG is nil, the application is displayed normally,
14527otherwise it is an integer representing a ShowWindow flag:
14528
14529 0 - start hidden
14530 1 - start normally
14531 3 - start maximized
14532 6 - start minimized */)
14533 (operation, document, parameters, show_flag)
14534 Lisp_Object operation, document, parameters, show_flag;
14535{
14536 Lisp_Object current_dir;
14537
14538 CHECK_STRING (document);
14539
14540 /* Encode filename and current directory. */
14541 current_dir = ENCODE_FILE (current_buffer->directory);
14542 document = ENCODE_FILE (document);
14543 if ((int) ShellExecute (NULL,
14544 (STRINGP (operation) ?
14545 SDATA (operation) : NULL),
14546 SDATA (document),
14547 (STRINGP (parameters) ?
14548 SDATA (parameters) : NULL),
14549 SDATA (current_dir),
14550 (INTEGERP (show_flag) ?
14551 XINT (show_flag) : SW_SHOWDEFAULT))
14552 > 32)
14553 return Qt;
14554 error ("ShellExecute failed: %s", w32_strerror (0));
14555}
14556
14557/* Lookup virtual keycode from string representing the name of a
14558 non-ascii keystroke into the corresponding virtual key, using
14559 lispy_function_keys. */
14560static int
14561lookup_vk_code (char *key)
14562{
14563 int i;
14564
14565 for (i = 0; i < 256; i++)
14566 if (lispy_function_keys[i] != 0
14567 && strcmp (lispy_function_keys[i], key) == 0)
14568 return i;
14569
14570 return -1;
14571}
14572
14573/* Convert a one-element vector style key sequence to a hot key
14574 definition. */
14575static int
14576w32_parse_hot_key (key)
14577 Lisp_Object key;
14578{
14579 /* Copied from Fdefine_key and store_in_keymap. */
14580 register Lisp_Object c;
14581 int vk_code;
14582 int lisp_modifiers;
14583 int w32_modifiers;
14584 struct gcpro gcpro1;
14585
14586 CHECK_VECTOR (key);
14587
14588 if (XFASTINT (Flength (key)) != 1)
14589 return Qnil;
14590
14591 GCPRO1 (key);
14592
14593 c = Faref (key, make_number (0));
14594
14595 if (CONSP (c) && lucid_event_type_list_p (c))
14596 c = Fevent_convert_list (c);
14597
14598 UNGCPRO;
14599
14600 if (! INTEGERP (c) && ! SYMBOLP (c))
14601 error ("Key definition is invalid");
14602
14603 /* Work out the base key and the modifiers. */
14604 if (SYMBOLP (c))
14605 {
14606 c = parse_modifiers (c);
14607 lisp_modifiers = Fcar (Fcdr (c));
14608 c = Fcar (c);
14609 if (!SYMBOLP (c))
14610 abort ();
14611 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
14612 }
14613 else if (INTEGERP (c))
14614 {
14615 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
14616 /* Many ascii characters are their own virtual key code. */
14617 vk_code = XINT (c) & CHARACTERBITS;
14618 }
14619
14620 if (vk_code < 0 || vk_code > 255)
14621 return Qnil;
14622
14623 if ((lisp_modifiers & meta_modifier) != 0
14624 && !NILP (Vw32_alt_is_meta))
14625 lisp_modifiers |= alt_modifier;
14626
14627 /* Supply defs missing from mingw32. */
14628#ifndef MOD_ALT
14629#define MOD_ALT 0x0001
14630#define MOD_CONTROL 0x0002
14631#define MOD_SHIFT 0x0004
14632#define MOD_WIN 0x0008
14633#endif
14634
14635 /* Convert lisp modifiers to Windows hot-key form. */
14636 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
14637 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
14638 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
14639 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
14640
14641 return HOTKEY (vk_code, w32_modifiers);
14642}
14643
14644DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
14645 Sw32_register_hot_key, 1, 1, 0,
14646 doc: /* Register KEY as a hot-key combination.
14647Certain key combinations like Alt-Tab are reserved for system use on
14648Windows, and therefore are normally intercepted by the system. However,
14649most of these key combinations can be received by registering them as
14650hot-keys, overriding their special meaning.
14651
14652KEY must be a one element key definition in vector form that would be
14653acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
14654modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
14655is always interpreted as the Windows modifier keys.
14656
14657The return value is the hotkey-id if registered, otherwise nil. */)
14658 (key)
14659 Lisp_Object key;
14660{
14661 key = w32_parse_hot_key (key);
14662
14663 if (NILP (Fmemq (key, w32_grabbed_keys)))
14664 {
14665 /* Reuse an empty slot if possible. */
14666 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
14667
14668 /* Safe to add new key to list, even if we have focus. */
14669 if (NILP (item))
14670 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
14671 else
14672 XSETCAR (item, key);
14673
14674 /* Notify input thread about new hot-key definition, so that it
14675 takes effect without needing to switch focus. */
14676 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
14677 (WPARAM) key, 0);
14678 }
14679
14680 return key;
14681}
14682
14683DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
14684 Sw32_unregister_hot_key, 1, 1, 0,
14685 doc: /* Unregister HOTKEY as a hot-key combination. */)
14686 (key)
14687 Lisp_Object key;
14688{
14689 Lisp_Object item;
14690
14691 if (!INTEGERP (key))
14692 key = w32_parse_hot_key (key);
14693
14694 item = Fmemq (key, w32_grabbed_keys);
14695
14696 if (!NILP (item))
14697 {
14698 /* Notify input thread about hot-key definition being removed, so
14699 that it takes effect without needing focus switch. */
14700 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
14701 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
14702 {
14703 MSG msg;
14704 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14705 }
14706 return Qt;
14707 }
14708 return Qnil;
14709}
14710
14711DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
14712 Sw32_registered_hot_keys, 0, 0, 0,
14713 doc: /* Return list of registered hot-key IDs. */)
14714 ()
14715{
14716 return Fcopy_sequence (w32_grabbed_keys);
14717}
14718
14719DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
14720 Sw32_reconstruct_hot_key, 1, 1, 0,
14721 doc: /* Convert hot-key ID to a lisp key combination. */)
14722 (hotkeyid)
14723 Lisp_Object hotkeyid;
14724{
14725 int vk_code, w32_modifiers;
14726 Lisp_Object key;
14727
14728 CHECK_NUMBER (hotkeyid);
14729
14730 vk_code = HOTKEY_VK_CODE (hotkeyid);
14731 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
14732
14733 if (lispy_function_keys[vk_code])
14734 key = intern (lispy_function_keys[vk_code]);
14735 else
14736 key = make_number (vk_code);
14737
14738 key = Fcons (key, Qnil);
14739 if (w32_modifiers & MOD_SHIFT)
14740 key = Fcons (Qshift, key);
14741 if (w32_modifiers & MOD_CONTROL)
14742 key = Fcons (Qctrl, key);
14743 if (w32_modifiers & MOD_ALT)
14744 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
14745 if (w32_modifiers & MOD_WIN)
14746 key = Fcons (Qhyper, key);
14747
14748 return key;
14749}
14750
14751DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
14752 Sw32_toggle_lock_key, 1, 2, 0,
14753 doc: /* Toggle the state of the lock key KEY.
14754KEY can be `capslock', `kp-numlock', or `scroll'.
14755If the optional parameter NEW-STATE is a number, then the state of KEY
14756is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
14757 (key, new_state)
14758 Lisp_Object key, new_state;
14759{
14760 int vk_code;
14761
14762 if (EQ (key, intern ("capslock")))
14763 vk_code = VK_CAPITAL;
14764 else if (EQ (key, intern ("kp-numlock")))
14765 vk_code = VK_NUMLOCK;
14766 else if (EQ (key, intern ("scroll")))
14767 vk_code = VK_SCROLL;
14768 else
14769 return Qnil;
14770
14771 if (!dwWindowsThreadId)
14772 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
14773
14774 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
14775 (WPARAM) vk_code, (LPARAM) new_state))
14776 {
14777 MSG msg;
14778 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
14779 return make_number (msg.wParam);
14780 }
14781 return Qnil;
14782}
14783\f
14784DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
14785 doc: /* Return storage information about the file system FILENAME is on.
14786Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
14787storage of the file system, FREE is the free storage, and AVAIL is the
14788storage available to a non-superuser. All 3 numbers are in bytes.
14789If the underlying system call fails, value is nil. */)
14790 (filename)
14791 Lisp_Object filename;
14792{
14793 Lisp_Object encoded, value;
14794
14795 CHECK_STRING (filename);
14796 filename = Fexpand_file_name (filename, Qnil);
14797 encoded = ENCODE_FILE (filename);
14798
14799 value = Qnil;
14800
14801 /* Determining the required information on Windows turns out, sadly,
14802 to be more involved than one would hope. The original Win32 api
14803 call for this will return bogus information on some systems, but we
14804 must dynamically probe for the replacement api, since that was
14805 added rather late on. */
14806 {
14807 HMODULE hKernel = GetModuleHandle ("kernel32");
14808 BOOL (*pfn_GetDiskFreeSpaceEx)
14809 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
14810 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
14811
14812 /* On Windows, we may need to specify the root directory of the
14813 volume holding FILENAME. */
14814 char rootname[MAX_PATH];
14815 char *name = SDATA (encoded);
14816
14817 /* find the root name of the volume if given */
14818 if (isalpha (name[0]) && name[1] == ':')
14819 {
14820 rootname[0] = name[0];
14821 rootname[1] = name[1];
14822 rootname[2] = '\\';
14823 rootname[3] = 0;
14824 }
14825 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
14826 {
14827 char *str = rootname;
14828 int slashes = 4;
14829 do
14830 {
14831 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
14832 break;
14833 *str++ = *name++;
14834 }
14835 while ( *name );
14836
14837 *str++ = '\\';
14838 *str = 0;
14839 }
14840
14841 if (pfn_GetDiskFreeSpaceEx)
14842 {
14843 /* Unsigned large integers cannot be cast to double, so
14844 use signed ones instead. */
14845 LARGE_INTEGER availbytes;
14846 LARGE_INTEGER freebytes;
14847 LARGE_INTEGER totalbytes;
14848
14849 if (pfn_GetDiskFreeSpaceEx(rootname,
14850 (ULARGE_INTEGER *)&availbytes,
14851 (ULARGE_INTEGER *)&totalbytes,
14852 (ULARGE_INTEGER *)&freebytes))
14853 value = list3 (make_float ((double) totalbytes.QuadPart),
14854 make_float ((double) freebytes.QuadPart),
14855 make_float ((double) availbytes.QuadPart));
14856 }
14857 else
14858 {
14859 DWORD sectors_per_cluster;
14860 DWORD bytes_per_sector;
14861 DWORD free_clusters;
14862 DWORD total_clusters;
14863
14864 if (GetDiskFreeSpace(rootname,
14865 &sectors_per_cluster,
14866 &bytes_per_sector,
14867 &free_clusters,
14868 &total_clusters))
14869 value = list3 (make_float ((double) total_clusters
14870 * sectors_per_cluster * bytes_per_sector),
14871 make_float ((double) free_clusters
14872 * sectors_per_cluster * bytes_per_sector),
14873 make_float ((double) free_clusters
14874 * sectors_per_cluster * bytes_per_sector));
14875 }
14876 }
14877
14878 return value;
14879}
14880\f
14881/***********************************************************************
14882 Initialization
14883 ***********************************************************************/
14884
14885void
14886syms_of_w32fns ()
14887{
14888 globals_of_w32fns ();
14889 /* This is zero if not using MS-Windows. */
14890 w32_in_use = 0;
14891 track_mouse_window = NULL;
14892
14893 w32_visible_system_caret_hwnd = NULL;
14894
14895 Qauto_raise = intern ("auto-raise");
14896 staticpro (&Qauto_raise);
14897 Qauto_lower = intern ("auto-lower");
14898 staticpro (&Qauto_lower);
14899 Qborder_color = intern ("border-color");
14900 staticpro (&Qborder_color);
14901 Qborder_width = intern ("border-width");
14902 staticpro (&Qborder_width);
14903 Qcursor_color = intern ("cursor-color");
14904 staticpro (&Qcursor_color);
14905 Qcursor_type = intern ("cursor-type");
14906 staticpro (&Qcursor_type);
14907 Qgeometry = intern ("geometry");
14908 staticpro (&Qgeometry);
14909 Qicon_left = intern ("icon-left");
14910 staticpro (&Qicon_left);
14911 Qicon_top = intern ("icon-top");
14912 staticpro (&Qicon_top);
14913 Qicon_type = intern ("icon-type");
14914 staticpro (&Qicon_type);
14915 Qicon_name = intern ("icon-name");
14916 staticpro (&Qicon_name);
14917 Qinternal_border_width = intern ("internal-border-width");
14918 staticpro (&Qinternal_border_width);
14919 Qleft = intern ("left");
14920 staticpro (&Qleft);
14921 Qright = intern ("right");
14922 staticpro (&Qright);
14923 Qmouse_color = intern ("mouse-color");
14924 staticpro (&Qmouse_color);
14925 Qnone = intern ("none");
14926 staticpro (&Qnone);
14927 Qparent_id = intern ("parent-id");
14928 staticpro (&Qparent_id);
14929 Qscroll_bar_width = intern ("scroll-bar-width");
14930 staticpro (&Qscroll_bar_width);
14931 Qsuppress_icon = intern ("suppress-icon");
14932 staticpro (&Qsuppress_icon);
14933 Qundefined_color = intern ("undefined-color");
14934 staticpro (&Qundefined_color);
14935 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
14936 staticpro (&Qvertical_scroll_bars);
14937 Qvisibility = intern ("visibility");
14938 staticpro (&Qvisibility);
14939 Qwindow_id = intern ("window-id");
14940 staticpro (&Qwindow_id);
14941 Qx_frame_parameter = intern ("x-frame-parameter");
14942 staticpro (&Qx_frame_parameter);
14943 Qx_resource_name = intern ("x-resource-name");
14944 staticpro (&Qx_resource_name);
14945 Quser_position = intern ("user-position");
14946 staticpro (&Quser_position);
14947 Quser_size = intern ("user-size");
14948 staticpro (&Quser_size);
14949 Qscreen_gamma = intern ("screen-gamma");
14950 staticpro (&Qscreen_gamma);
14951 Qline_spacing = intern ("line-spacing");
14952 staticpro (&Qline_spacing);
14953 Qcenter = intern ("center");
14954 staticpro (&Qcenter);
14955 Qcancel_timer = intern ("cancel-timer");
14956 staticpro (&Qcancel_timer);
14957 Qfullscreen = intern ("fullscreen");
14958 staticpro (&Qfullscreen);
14959 Qfullwidth = intern ("fullwidth");
14960 staticpro (&Qfullwidth);
14961 Qfullheight = intern ("fullheight");
14962 staticpro (&Qfullheight);
14963 Qfullboth = intern ("fullboth");
14964 staticpro (&Qfullboth);
14965
14966 Qhyper = intern ("hyper");
14967 staticpro (&Qhyper);
14968 Qsuper = intern ("super");
14969 staticpro (&Qsuper);
14970 Qmeta = intern ("meta");
14971 staticpro (&Qmeta);
14972 Qalt = intern ("alt");
14973 staticpro (&Qalt);
14974 Qctrl = intern ("ctrl");
14975 staticpro (&Qctrl);
14976 Qcontrol = intern ("control");
14977 staticpro (&Qcontrol);
14978 Qshift = intern ("shift");
14979 staticpro (&Qshift);
14980 /* This is the end of symbol initialization. */
14981
14982 /* Text property `display' should be nonsticky by default. */
14983 Vtext_property_default_nonsticky
14984 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
14985
14986
14987 Qlaplace = intern ("laplace");
14988 staticpro (&Qlaplace);
14989 Qemboss = intern ("emboss");
14990 staticpro (&Qemboss);
14991 Qedge_detection = intern ("edge-detection");
14992 staticpro (&Qedge_detection);
14993 Qheuristic = intern ("heuristic");
14994 staticpro (&Qheuristic);
14995 QCmatrix = intern (":matrix");
14996 staticpro (&QCmatrix);
14997 QCcolor_adjustment = intern (":color-adjustment");
14998 staticpro (&QCcolor_adjustment);
14999 QCmask = intern (":mask");
15000 staticpro (&QCmask);
15001
15002 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
15003 staticpro (&Qface_set_after_frame_default);
15004
15005 Fput (Qundefined_color, Qerror_conditions,
15006 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
15007 Fput (Qundefined_color, Qerror_message,
15008 build_string ("Undefined color"));
15009
15010 staticpro (&w32_grabbed_keys);
15011 w32_grabbed_keys = Qnil;
15012
15013 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
15014 doc: /* An array of color name mappings for windows. */);
15015 Vw32_color_map = Qnil;
15016
15017 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
15018 doc: /* Non-nil if alt key presses are passed on to Windows.
15019When non-nil, for example, alt pressed and released and then space will
15020open the System menu. When nil, Emacs silently swallows alt key events. */);
15021 Vw32_pass_alt_to_system = Qnil;
15022
15023 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
15024 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
15025When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
15026 Vw32_alt_is_meta = Qt;
15027
15028 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
15029 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
15030 XSETINT (Vw32_quit_key, 0);
15031
15032 DEFVAR_LISP ("w32-pass-lwindow-to-system",
15033 &Vw32_pass_lwindow_to_system,
15034 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
15035When non-nil, the Start menu is opened by tapping the key. */);
15036 Vw32_pass_lwindow_to_system = Qt;
15037
15038 DEFVAR_LISP ("w32-pass-rwindow-to-system",
15039 &Vw32_pass_rwindow_to_system,
15040 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
15041When non-nil, the Start menu is opened by tapping the key. */);
15042 Vw32_pass_rwindow_to_system = Qt;
15043
15044 DEFVAR_INT ("w32-phantom-key-code",
15045 &Vw32_phantom_key_code,
15046 doc: /* Virtual key code used to generate \"phantom\" key presses.
15047Value is a number between 0 and 255.
15048
15049Phantom key presses are generated in order to stop the system from
15050acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
15051`w32-pass-rwindow-to-system' is nil. */);
15052 /* Although 255 is technically not a valid key code, it works and
15053 means that this hack won't interfere with any real key code. */
15054 Vw32_phantom_key_code = 255;
15055
15056 DEFVAR_LISP ("w32-enable-num-lock",
15057 &Vw32_enable_num_lock,
15058 doc: /* Non-nil if Num Lock should act normally.
15059Set to nil to see Num Lock as the key `kp-numlock'. */);
15060 Vw32_enable_num_lock = Qt;
15061
15062 DEFVAR_LISP ("w32-enable-caps-lock",
15063 &Vw32_enable_caps_lock,
15064 doc: /* Non-nil if Caps Lock should act normally.
15065Set to nil to see Caps Lock as the key `capslock'. */);
15066 Vw32_enable_caps_lock = Qt;
15067
15068 DEFVAR_LISP ("w32-scroll-lock-modifier",
15069 &Vw32_scroll_lock_modifier,
15070 doc: /* Modifier to use for the Scroll Lock on state.
15071The value can be hyper, super, meta, alt, control or shift for the
15072respective modifier, or nil to see Scroll Lock as the key `scroll'.
15073Any other value will cause the key to be ignored. */);
15074 Vw32_scroll_lock_modifier = Qt;
15075
15076 DEFVAR_LISP ("w32-lwindow-modifier",
15077 &Vw32_lwindow_modifier,
15078 doc: /* Modifier to use for the left \"Windows\" key.
15079The value can be hyper, super, meta, alt, control or shift for the
15080respective modifier, or nil to appear as the key `lwindow'.
15081Any other value will cause the key to be ignored. */);
15082 Vw32_lwindow_modifier = Qnil;
15083
15084 DEFVAR_LISP ("w32-rwindow-modifier",
15085 &Vw32_rwindow_modifier,
15086 doc: /* Modifier to use for the right \"Windows\" key.
15087The value can be hyper, super, meta, alt, control or shift for the
15088respective modifier, or nil to appear as the key `rwindow'.
15089Any other value will cause the key to be ignored. */);
15090 Vw32_rwindow_modifier = Qnil;
15091
15092 DEFVAR_LISP ("w32-apps-modifier",
15093 &Vw32_apps_modifier,
15094 doc: /* Modifier to use for the \"Apps\" key.
15095The value can be hyper, super, meta, alt, control or shift for the
15096respective modifier, or nil to appear as the key `apps'.
15097Any other value will cause the key to be ignored. */);
15098 Vw32_apps_modifier = Qnil;
15099
15100 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
15101 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
15102 w32_enable_synthesized_fonts = 0;
15103
15104 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
15105 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
15106 Vw32_enable_palette = Qt;
15107
15108 DEFVAR_INT ("w32-mouse-button-tolerance",
15109 &Vw32_mouse_button_tolerance,
15110 doc: /* Analogue of double click interval for faking middle mouse events.
15111The value is the minimum time in milliseconds that must elapse between
15112left/right button down events before they are considered distinct events.
15113If both mouse buttons are depressed within this interval, a middle mouse
15114button down event is generated instead. */);
15115 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
15116
15117 DEFVAR_INT ("w32-mouse-move-interval",
15118 &Vw32_mouse_move_interval,
15119 doc: /* Minimum interval between mouse move events.
15120The value is the minimum time in milliseconds that must elapse between
15121successive mouse move (or scroll bar drag) events before they are
15122reported as lisp events. */);
15123 XSETINT (Vw32_mouse_move_interval, 0);
15124
15125 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
15126 &w32_pass_extra_mouse_buttons_to_system,
15127 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
15128Recent versions of Windows support mice with up to five buttons.
15129Since most applications don't support these extra buttons, most mouse
15130drivers will allow you to map them to functions at the system level.
15131If this variable is non-nil, Emacs will pass them on, allowing the
15132system to handle them. */);
15133 w32_pass_extra_mouse_buttons_to_system = 0;
15134
15135 init_x_parm_symbols ();
15136
15137 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
15138 doc: /* List of directories to search for window system bitmap files. */);
15139 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
15140
15141 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
15142 doc: /* The shape of the pointer when over text.
15143Changing the value does not affect existing frames
15144unless you set the mouse color. */);
15145 Vx_pointer_shape = Qnil;
15146
15147 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
15148 doc: /* The name Emacs uses to look up resources; for internal use only.
15149`x-get-resource' uses this as the first component of the instance name
15150when requesting resource values.
15151Emacs initially sets `x-resource-name' to the name under which Emacs
15152was invoked, or to the value specified with the `-name' or `-rn'
15153switches, if present. */);
15154 Vx_resource_name = Qnil;
15155
15156 Vx_nontext_pointer_shape = Qnil;
15157
15158 Vx_mode_pointer_shape = Qnil;
15159
15160 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
15161 doc: /* The shape of the pointer when Emacs is busy.
15162This variable takes effect when you create a new frame
15163or when you set the mouse color. */);
15164 Vx_hourglass_pointer_shape = Qnil;
15165
15166 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
15167 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
15168 display_hourglass_p = 1;
15169
15170 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
15171 doc: /* *Seconds to wait before displaying an hourglass pointer.
15172Value must be an integer or float. */);
15173 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
15174
15175 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
15176 &Vx_sensitive_text_pointer_shape,
15177 doc: /* The shape of the pointer when over mouse-sensitive text.
15178This variable takes effect when you create a new frame
15179or when you set the mouse color. */);
15180 Vx_sensitive_text_pointer_shape = Qnil;
15181
15182 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
15183 &Vx_window_horizontal_drag_shape,
15184 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
15185This variable takes effect when you create a new frame
15186or when you set the mouse color. */);
15187 Vx_window_horizontal_drag_shape = Qnil;
15188
15189 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
15190 doc: /* A string indicating the foreground color of the cursor box. */);
15191 Vx_cursor_fore_pixel = Qnil;
15192
15193 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
15194 doc: /* Maximum size for tooltips.
15195Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
15196 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
15197
15198 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
15199 doc: /* Non-nil if no window manager is in use.
15200Emacs doesn't try to figure this out; this is always nil
15201unless you set it to something else. */);
15202 /* We don't have any way to find this out, so set it to nil
15203 and maybe the user would like to set it to t. */
15204 Vx_no_window_manager = Qnil;
15205
15206 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
15207 &Vx_pixel_size_width_font_regexp,
15208 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
15209
15210Since Emacs gets width of a font matching with this regexp from
15211PIXEL_SIZE field of the name, font finding mechanism gets faster for
15212such a font. This is especially effective for such large fonts as
15213Chinese, Japanese, and Korean. */);
15214 Vx_pixel_size_width_font_regexp = Qnil;
15215
15216 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
15217 doc: /* Time after which cached images are removed from the cache.
15218When an image has not been displayed this many seconds, remove it
15219from the image cache. Value must be an integer or nil with nil
15220meaning don't clear the cache. */);
15221 Vimage_cache_eviction_delay = make_number (30 * 60);
15222
15223 DEFVAR_LISP ("w32-bdf-filename-alist",
15224 &Vw32_bdf_filename_alist,
15225 doc: /* List of bdf fonts and their corresponding filenames. */);
15226 Vw32_bdf_filename_alist = Qnil;
15227
15228 DEFVAR_BOOL ("w32-strict-fontnames",
15229 &w32_strict_fontnames,
15230 doc: /* Non-nil means only use fonts that are exact matches for those requested.
15231Default is nil, which allows old fontnames that are not XLFD compliant,
15232and allows third-party CJK display to work by specifying false charset
15233fields to trick Emacs into translating to Big5, SJIS etc.
15234Setting this to t will prevent wrong fonts being selected when
15235fontsets are automatically created. */);
15236 w32_strict_fontnames = 0;
15237
15238 DEFVAR_BOOL ("w32-strict-painting",
15239 &w32_strict_painting,
15240 doc: /* Non-nil means use strict rules for repainting frames.
15241Set this to nil to get the old behaviour for repainting; this should
15242only be necessary if the default setting causes problems. */);
15243 w32_strict_painting = 1;
15244
15245 DEFVAR_LISP ("w32-charset-info-alist",
15246 &Vw32_charset_info_alist,
15247 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
15248Each entry should be of the form:
15249
15250 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
15251
15252where CHARSET_NAME is a string used in font names to identify the charset,
15253WINDOWS_CHARSET is a symbol that can be one of:
15254w32-charset-ansi, w32-charset-default, w32-charset-symbol,
15255w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
15256w32-charset-chinesebig5,
15257#ifdef JOHAB_CHARSET
15258w32-charset-johab, w32-charset-hebrew,
15259w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
15260w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
15261w32-charset-russian, w32-charset-mac, w32-charset-baltic,
15262#endif
15263#ifdef UNICODE_CHARSET
15264w32-charset-unicode,
15265#endif
15266or w32-charset-oem.
15267CODEPAGE should be an integer specifying the codepage that should be used
15268to display the character set, t to do no translation and output as Unicode,
15269or nil to do no translation and output as 8 bit (or multibyte on far-east
15270versions of Windows) characters. */);
15271 Vw32_charset_info_alist = Qnil;
15272
15273 staticpro (&Qw32_charset_ansi);
15274 Qw32_charset_ansi = intern ("w32-charset-ansi");
15275 staticpro (&Qw32_charset_symbol);
15276 Qw32_charset_symbol = intern ("w32-charset-symbol");
15277 staticpro (&Qw32_charset_shiftjis);
15278 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
15279 staticpro (&Qw32_charset_hangeul);
15280 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
15281 staticpro (&Qw32_charset_chinesebig5);
15282 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
15283 staticpro (&Qw32_charset_gb2312);
15284 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
15285 staticpro (&Qw32_charset_oem);
15286 Qw32_charset_oem = intern ("w32-charset-oem");
15287
15288#ifdef JOHAB_CHARSET
15289 {
15290 static int w32_extra_charsets_defined = 1;
15291 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
15292 doc: /* Internal variable. */);
15293
15294 staticpro (&Qw32_charset_johab);
15295 Qw32_charset_johab = intern ("w32-charset-johab");
15296 staticpro (&Qw32_charset_easteurope);
15297 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
15298 staticpro (&Qw32_charset_turkish);
15299 Qw32_charset_turkish = intern ("w32-charset-turkish");
15300 staticpro (&Qw32_charset_baltic);
15301 Qw32_charset_baltic = intern ("w32-charset-baltic");
15302 staticpro (&Qw32_charset_russian);
15303 Qw32_charset_russian = intern ("w32-charset-russian");
15304 staticpro (&Qw32_charset_arabic);
15305 Qw32_charset_arabic = intern ("w32-charset-arabic");
15306 staticpro (&Qw32_charset_greek);
15307 Qw32_charset_greek = intern ("w32-charset-greek");
15308 staticpro (&Qw32_charset_hebrew);
15309 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
15310 staticpro (&Qw32_charset_vietnamese);
15311 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
15312 staticpro (&Qw32_charset_thai);
15313 Qw32_charset_thai = intern ("w32-charset-thai");
15314 staticpro (&Qw32_charset_mac);
15315 Qw32_charset_mac = intern ("w32-charset-mac");
15316 }
15317#endif
15318
15319#ifdef UNICODE_CHARSET
15320 {
15321 static int w32_unicode_charset_defined = 1;
15322 DEFVAR_BOOL ("w32-unicode-charset-defined",
15323 &w32_unicode_charset_defined,
15324 doc: /* Internal variable. */);
15325
15326 staticpro (&Qw32_charset_unicode);
15327 Qw32_charset_unicode = intern ("w32-charset-unicode");
15328#endif
15329
15330 defsubr (&Sx_get_resource);
15331#if 0 /* TODO: Port to W32 */
15332 defsubr (&Sx_change_window_property);
15333 defsubr (&Sx_delete_window_property);
15334 defsubr (&Sx_window_property);
15335#endif
15336 defsubr (&Sxw_display_color_p);
15337 defsubr (&Sx_display_grayscale_p);
15338 defsubr (&Sxw_color_defined_p);
15339 defsubr (&Sxw_color_values);
15340 defsubr (&Sx_server_max_request_size);
15341 defsubr (&Sx_server_vendor);
15342 defsubr (&Sx_server_version);
15343 defsubr (&Sx_display_pixel_width);
15344 defsubr (&Sx_display_pixel_height);
15345 defsubr (&Sx_display_mm_width);
15346 defsubr (&Sx_display_mm_height);
15347 defsubr (&Sx_display_screens);
15348 defsubr (&Sx_display_planes);
15349 defsubr (&Sx_display_color_cells);
15350 defsubr (&Sx_display_visual_class);
15351 defsubr (&Sx_display_backing_store);
15352 defsubr (&Sx_display_save_under);
15353 defsubr (&Sx_parse_geometry);
15354 defsubr (&Sx_create_frame);
15355 defsubr (&Sx_open_connection);
15356 defsubr (&Sx_close_connection);
15357 defsubr (&Sx_display_list);
15358 defsubr (&Sx_synchronize);
15359
15360 /* W32 specific functions */
15361
15362 defsubr (&Sw32_focus_frame);
15363 defsubr (&Sw32_select_font);
15364 defsubr (&Sw32_define_rgb_color);
15365 defsubr (&Sw32_default_color_map);
15366 defsubr (&Sw32_load_color_file);
15367 defsubr (&Sw32_send_sys_command);
15368 defsubr (&Sw32_shell_execute);
15369 defsubr (&Sw32_register_hot_key);
15370 defsubr (&Sw32_unregister_hot_key);
15371 defsubr (&Sw32_registered_hot_keys);
15372 defsubr (&Sw32_reconstruct_hot_key);
15373 defsubr (&Sw32_toggle_lock_key);
15374 defsubr (&Sw32_find_bdf_fonts);
15375
15376 defsubr (&Sfile_system_info);
15377
15378 /* Setting callback functions for fontset handler. */
15379 get_font_info_func = w32_get_font_info;
15380
15381#if 0 /* This function pointer doesn't seem to be used anywhere.
15382 And the pointer assigned has the wrong type, anyway. */
15383 list_fonts_func = w32_list_fonts;
15384#endif
15385
15386 load_font_func = w32_load_font;
15387 find_ccl_program_func = w32_find_ccl_program;
15388 query_font_func = w32_query_font;
15389 set_frame_fontset_func = x_set_font;
15390 check_window_system_func = check_w32;
15391
15392 /* Images. */
15393 Qxbm = intern ("xbm");
15394 staticpro (&Qxbm);
15395 QCconversion = intern (":conversion");
15396 staticpro (&QCconversion);
15397 QCheuristic_mask = intern (":heuristic-mask");
15398 staticpro (&QCheuristic_mask);
15399 QCcolor_symbols = intern (":color-symbols");
15400 staticpro (&QCcolor_symbols);
15401 QCascent = intern (":ascent");
15402 staticpro (&QCascent);
15403 QCmargin = intern (":margin");
15404 staticpro (&QCmargin);
15405 QCrelief = intern (":relief");
15406 staticpro (&QCrelief);
15407 Qpostscript = intern ("postscript");
15408 staticpro (&Qpostscript);
15409#if 0 /* TODO: These need entries at top of file. */
15410 QCloader = intern (":loader");
15411 staticpro (&QCloader);
15412 QCbounding_box = intern (":bounding-box");
15413 staticpro (&QCbounding_box);
15414 QCpt_width = intern (":pt-width");
15415 staticpro (&QCpt_width);
15416 QCpt_height = intern (":pt-height");
15417 staticpro (&QCpt_height);
15418#endif
15419 QCindex = intern (":index");
15420 staticpro (&QCindex);
15421 Qpbm = intern ("pbm");
15422 staticpro (&Qpbm);
15423
15424#if HAVE_XPM
15425 Qxpm = intern ("xpm");
15426 staticpro (&Qxpm);
15427#endif
15428
15429#if HAVE_JPEG
15430 Qjpeg = intern ("jpeg");
15431 staticpro (&Qjpeg);
15432#endif
15433
15434#if HAVE_TIFF
15435 Qtiff = intern ("tiff");
15436 staticpro (&Qtiff);
15437#endif
15438
15439#if HAVE_GIF
15440 Qgif = intern ("gif");
15441 staticpro (&Qgif);
15442#endif
15443
15444#if HAVE_PNG
15445 Qpng = intern ("png");
15446 staticpro (&Qpng);
15447#endif
15448
15449 defsubr (&Sclear_image_cache);
15450 defsubr (&Simage_size);
15451 defsubr (&Simage_mask_p);
15452
15453#if GLYPH_DEBUG
15454 defsubr (&Simagep);
15455 defsubr (&Slookup_image);
15456#endif
15457
15458 hourglass_atimer = NULL;
15459 hourglass_shown_p = 0;
15460 defsubr (&Sx_show_tip);
15461 defsubr (&Sx_hide_tip);
15462 tip_timer = Qnil;
15463 staticpro (&tip_timer);
15464 tip_frame = Qnil;
15465 staticpro (&tip_frame);
15466
15467 last_show_tip_args = Qnil;
15468 staticpro (&last_show_tip_args);
15469
15470 defsubr (&Sx_file_dialog);
15471}
15472
15473
15474/*
15475 globals_of_w32fns is used to initialize those global variables that
15476 must always be initialized on startup even when the global variable
15477 initialized is non zero (see the function main in emacs.c).
15478 globals_of_w32fns is called from syms_of_w32fns when the global
15479 variable initialized is 0 and directly from main when initialized
15480 is non zero.
15481 */
15482void globals_of_w32fns ()
15483{
15484 HMODULE user32_lib = GetModuleHandle ("user32.dll");
15485 /*
15486 TrackMouseEvent not available in all versions of Windows, so must load
15487 it dynamically. Do it once, here, instead of every time it is used.
15488 */
15489 track_mouse_event_fn = (TrackMouseEvent_Proc) GetProcAddress (user32_lib, "TrackMouseEvent");
15490}
15491
15492
15493void
15494init_xfns ()
15495{
15496 image_types = NULL;
15497 Vimage_types = Qnil;
15498
15499 define_image_type (&pbm_type);
15500 define_image_type (&xbm_type);
15501#if 0 /* TODO : Image support for W32 */
15502 define_image_type (&gs_type);
15503#endif
15504
15505#if HAVE_XPM
15506 define_image_type (&xpm_type);
15507#endif
15508
15509#if HAVE_JPEG
15510 define_image_type (&jpeg_type);
15511#endif
15512
15513#if HAVE_TIFF
15514 define_image_type (&tiff_type);
15515#endif
15516
15517#if HAVE_GIF
15518 define_image_type (&gif_type);
15519#endif
15520
15521#if HAVE_PNG
15522 define_image_type (&png_type);
15523#endif
15524}
15525
15526#undef abort
15527
15528void
15529w32_abort()
15530{
15531 int button;
15532 button = MessageBox (NULL,
15533 "A fatal error has occurred!\n\n"
15534 "Select Abort to exit, Retry to debug, Ignore to continue",
15535 "Emacs Abort Dialog",
15536 MB_ICONEXCLAMATION | MB_TASKMODAL
15537 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
15538 switch (button)
15539 {
15540 case IDRETRY:
15541 DebugBreak ();
15542 break;
15543 case IDIGNORE:
15544 break;
15545 case IDABORT:
15546 default:
15547 abort ();
15548 break;
15549 }
15550}
15551
15552/* For convenience when debugging. */
15553int
15554w32_last_error()
15555{
15556 return GetLastError ();
15557}