(temacs): Increase EMHEAP further to avoid startup message about low memory.
[bpt/emacs.git] / src / w32fns.c
CommitLineData
e9e23e23 1/* Graphical user interface functions for the Microsoft W32 API.
a93f4566 2 Copyright (C) 1989, 92, 93, 94, 95, 1996, 1997, 1998, 1999, 2000, 2001
6fc2811b 3 Free Software Foundation, Inc.
ee78dc32
GV
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
3b7ad313
EN
19the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20Boston, MA 02111-1307, USA. */
ee78dc32
GV
21
22/* Added by Kevin Gallo */
23
ee78dc32 24#include <config.h>
1edf84e7
GV
25
26#include <signal.h>
ee78dc32 27#include <stdio.h>
1edf84e7
GV
28#include <limits.h>
29#include <errno.h>
ee78dc32
GV
30
31#include "lisp.h"
32#include "w32term.h"
33#include "frame.h"
34#include "window.h"
35#include "buffer.h"
6fc2811b 36#include "intervals.h"
10b4bc33
JR
37#include "dispextern.h"
38#include "keyboard.h"
ee78dc32 39#include "blockinput.h"
57bda87a 40#include "epaths.h"
10b4bc33
JR
41#include "character.h"
42#include "charset.h"
4587b026 43#include "coding.h"
3545439c 44#include "ccl.h"
10b4bc33 45#include "fontset.h"
6fc2811b 46#include "systime.h"
10b4bc33
JR
47#include "termhooks.h"
48#include "w32heap.h"
6fc2811b
JR
49
50#include "bitmaps/gray.xbm"
ee78dc32
GV
51
52#include <commdlg.h>
cb9e33d4 53#include <shellapi.h>
6fc2811b 54#include <ctype.h>
ee78dc32 55
1030b26b
JR
56#include <dlgs.h>
57#define FILE_NAME_TEXT_FIELD edt1
58
9785d95b
BK
59void syms_of_w32fns ();
60void globals_of_w32fns ();
839b1909 61static void init_external_image_libraries ();
9785d95b 62
ee78dc32 63extern void free_frame_menubar ();
6fc2811b 64extern double atof ();
9eb16b62
JR
65extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
66extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
67extern void w32_free_menu_strings P_ ((HWND));
68
5ac45f98 69extern int quit_char;
ee78dc32 70
ccc2d29c
GV
71extern char *lispy_function_keys[];
72
6fc2811b
JR
73/* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
74 it, and including `bitmaps/gray' more than once is a problem when
75 config.h defines `static' as an empty replacement string. */
76
77int gray_bitmap_width = gray_width;
78int gray_bitmap_height = gray_height;
79unsigned char *gray_bitmap_bits = gray_bits;
80
ee78dc32 81/* The colormap for converting color names to RGB values */
fbd6baed 82Lisp_Object Vw32_color_map;
ee78dc32 83
da36a4d6 84/* Non nil if alt key presses are passed on to Windows. */
fbd6baed 85Lisp_Object Vw32_pass_alt_to_system;
da36a4d6 86
8c205c63
RS
87/* Non nil if alt key is translated to meta_modifier, nil if it is translated
88 to alt_modifier. */
fbd6baed 89Lisp_Object Vw32_alt_is_meta;
8c205c63 90
7d081355
AI
91/* If non-zero, the windows virtual key code for an alternative quit key. */
92Lisp_Object Vw32_quit_key;
93
ccc2d29c
GV
94/* Non nil if left window key events are passed on to Windows (this only
95 affects whether "tapping" the key opens the Start menu). */
96Lisp_Object Vw32_pass_lwindow_to_system;
97
98/* Non nil if right window key events are passed on to Windows (this
99 only affects whether "tapping" the key opens the Start menu). */
100Lisp_Object Vw32_pass_rwindow_to_system;
101
adcc3809
GV
102/* Virtual key code used to generate "phantom" key presses in order
103 to stop system from acting on Windows key events. */
104Lisp_Object Vw32_phantom_key_code;
105
ccc2d29c
GV
106/* Modifier associated with the left "Windows" key, or nil to act as a
107 normal key. */
108Lisp_Object Vw32_lwindow_modifier;
109
110/* Modifier associated with the right "Windows" key, or nil to act as a
111 normal key. */
112Lisp_Object Vw32_rwindow_modifier;
113
114/* Modifier associated with the "Apps" key, or nil to act as a normal
115 key. */
116Lisp_Object Vw32_apps_modifier;
117
118/* Value is nil if Num Lock acts as a function key. */
119Lisp_Object Vw32_enable_num_lock;
120
121/* Value is nil if Caps Lock acts as a function key. */
122Lisp_Object Vw32_enable_caps_lock;
123
124/* Modifier associated with Scroll Lock, or nil to act as a normal key. */
125Lisp_Object Vw32_scroll_lock_modifier;
da36a4d6 126
7ce9aaca 127/* Switch to control whether we inhibit requests for synthesized bold
6fc2811b 128 and italic versions of fonts. */
d84b082d 129int w32_enable_synthesized_fonts;
5ac45f98
GV
130
131/* Enable palette management. */
fbd6baed 132Lisp_Object Vw32_enable_palette;
5ac45f98
GV
133
134/* Control how close left/right button down events must be to
135 be converted to a middle button down event. */
fbd6baed 136Lisp_Object Vw32_mouse_button_tolerance;
5ac45f98 137
84fb1139
KH
138/* Minimum interval between mouse movement (and scroll bar drag)
139 events that are passed on to the event loop. */
fbd6baed 140Lisp_Object Vw32_mouse_move_interval;
84fb1139 141
74214547
JR
142/* Flag to indicate if XBUTTON events should be passed on to Windows. */
143int w32_pass_extra_mouse_buttons_to_system;
144
ee78dc32
GV
145/* Non nil if no window manager is in use. */
146Lisp_Object Vx_no_window_manager;
147
0af913d7 148/* Non-zero means we're allowed to display a hourglass pointer. */
dfff8a69 149
0af913d7 150int display_hourglass_p;
6fc2811b 151
ee78dc32
GV
152/* The background and shape of the mouse pointer, and shape when not
153 over text or in the modeline. */
dfff8a69 154
ee78dc32 155Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
c9b2104d 156Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape, Vx_hand_shape;
6fc2811b 157
ee78dc32 158/* The shape when over mouse-sensitive text. */
dfff8a69 159
ee78dc32
GV
160Lisp_Object Vx_sensitive_text_pointer_shape;
161
c9b2104d
JR
162#ifndef IDC_HAND
163#define IDC_HAND MAKEINTRESOURCE(32649)
164#endif
165
ee78dc32 166/* Color of chars displayed in cursor box. */
dfff8a69 167
ee78dc32
GV
168Lisp_Object Vx_cursor_fore_pixel;
169
1edf84e7 170/* Nonzero if using Windows. */
dfff8a69 171
1edf84e7
GV
172static int w32_in_use;
173
ee78dc32 174/* Search path for bitmap files. */
dfff8a69 175
ee78dc32
GV
176Lisp_Object Vx_bitmap_file_path;
177
4587b026 178/* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
dfff8a69 179
4587b026
GV
180Lisp_Object Vx_pixel_size_width_font_regexp;
181
33d52f9c
GV
182/* Alist of bdf fonts and the files that define them. */
183Lisp_Object Vw32_bdf_filename_alist;
184
f46e6225 185/* A flag to control whether fonts are matched strictly or not. */
1075afa9
GV
186int w32_strict_fontnames;
187
c0611964
AI
188/* A flag to control whether we should only repaint if GetUpdateRect
189 indicates there is an update region. */
190int w32_strict_painting;
191
dfff8a69
JR
192/* Associative list linking character set strings to Windows codepages. */
193Lisp_Object Vw32_charset_info_alist;
194
195/* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
196#ifndef VIETNAMESE_CHARSET
197#define VIETNAMESE_CHARSET 163
198#endif
199
ee78dc32 200Lisp_Object Qnone;
ee78dc32 201Lisp_Object Qsuppress_icon;
ee78dc32 202Lisp_Object Qundefined_color;
dfff8a69 203Lisp_Object Qcenter;
dc220243 204Lisp_Object Qcancel_timer;
adcc3809
GV
205Lisp_Object Qhyper;
206Lisp_Object Qsuper;
207Lisp_Object Qmeta;
208Lisp_Object Qalt;
209Lisp_Object Qctrl;
210Lisp_Object Qcontrol;
211Lisp_Object Qshift;
212
dfff8a69
JR
213Lisp_Object Qw32_charset_ansi;
214Lisp_Object Qw32_charset_default;
215Lisp_Object Qw32_charset_symbol;
216Lisp_Object Qw32_charset_shiftjis;
767b1ff0 217Lisp_Object Qw32_charset_hangeul;
dfff8a69
JR
218Lisp_Object Qw32_charset_gb2312;
219Lisp_Object Qw32_charset_chinesebig5;
220Lisp_Object Qw32_charset_oem;
221
71eab8d1
AI
222#ifndef JOHAB_CHARSET
223#define JOHAB_CHARSET 130
224#endif
dfff8a69
JR
225#ifdef JOHAB_CHARSET
226Lisp_Object Qw32_charset_easteurope;
227Lisp_Object Qw32_charset_turkish;
228Lisp_Object Qw32_charset_baltic;
229Lisp_Object Qw32_charset_russian;
230Lisp_Object Qw32_charset_arabic;
231Lisp_Object Qw32_charset_greek;
232Lisp_Object Qw32_charset_hebrew;
767b1ff0 233Lisp_Object Qw32_charset_vietnamese;
dfff8a69
JR
234Lisp_Object Qw32_charset_thai;
235Lisp_Object Qw32_charset_johab;
236Lisp_Object Qw32_charset_mac;
237#endif
238
239#ifdef UNICODE_CHARSET
240Lisp_Object Qw32_charset_unicode;
241#endif
242
5a8a15ec
JR
243/* Prefix for system colors. */
244#define SYSTEM_COLOR_PREFIX "System"
245#define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
246
5ac45f98
GV
247/* State variables for emulating a three button mouse. */
248#define LMOUSE 1
249#define MMOUSE 2
250#define RMOUSE 4
251
252static int button_state = 0;
fbd6baed 253static W32Msg saved_mouse_button_msg;
48094ace 254static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
fbd6baed 255static W32Msg saved_mouse_move_msg;
48094ace 256static unsigned mouse_move_timer = 0;
84fb1139 257
9eb16b62
JR
258/* Window that is tracking the mouse. */
259static HWND track_mouse_window;
f60ae425 260
ccc0fdaa
JR
261typedef BOOL (WINAPI * TrackMouseEvent_Proc)
262 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
f60ae425 263
ccc0fdaa
JR
264TrackMouseEvent_Proc track_mouse_event_fn = NULL;
265ClipboardSequence_Proc clipboard_sequence_fn = NULL;
9eb16b62 266
93fbe8b7 267/* W95 mousewheel handler */
7d0393cf 268unsigned int msh_mousewheel = 0;
93fbe8b7 269
48094ace 270/* Timers */
84fb1139
KH
271#define MOUSE_BUTTON_ID 1
272#define MOUSE_MOVE_ID 2
48094ace
JR
273#define MENU_FREE_ID 3
274/* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
275 is received. */
276#define MENU_FREE_DELAY 1000
277static unsigned menu_free_timer = 0;
5ac45f98 278
ee78dc32 279/* The below are defined in frame.c. */
dfff8a69 280
ee78dc32
GV
281extern Lisp_Object Vwindow_system_version;
282
937e601e
AI
283#ifdef GLYPH_DEBUG
284int image_cache_refcount, dpyinfo_refcount;
285#endif
286
287
fbd6baed
GV
288/* From w32term.c. */
289extern Lisp_Object Vw32_num_mouse_buttons;
ccc2d29c 290extern Lisp_Object Vw32_recognize_altgr;
5ac45f98 291
65906840 292extern HWND w32_system_caret_hwnd;
93f2ca61 293
65906840
JR
294extern int w32_system_caret_height;
295extern int w32_system_caret_x;
296extern int w32_system_caret_y;
93f2ca61
JR
297extern int w32_use_visible_system_caret;
298
d285988b 299static HWND w32_visible_system_caret_hwnd;
65906840 300
ee78dc32 301\f
1edf84e7
GV
302/* Error if we are not connected to MS-Windows. */
303void
304check_w32 ()
305{
306 if (! w32_in_use)
307 error ("MS-Windows not in use or not initialized");
308}
309
310/* Nonzero if we can use mouse menus.
311 You should not call this unless HAVE_MENUS is defined. */
7d0393cf 312
1edf84e7
GV
313int
314have_menus_p ()
315{
316 return w32_in_use;
317}
318
ee78dc32 319/* Extract a frame as a FRAME_PTR, defaulting to the selected frame
fbd6baed 320 and checking validity for W32. */
ee78dc32
GV
321
322FRAME_PTR
323check_x_frame (frame)
324 Lisp_Object frame;
325{
326 FRAME_PTR f;
327
328 if (NILP (frame))
6fc2811b 329 frame = selected_frame;
b7826503 330 CHECK_LIVE_FRAME (frame);
6fc2811b 331 f = XFRAME (frame);
fbd6baed
GV
332 if (! FRAME_W32_P (f))
333 error ("non-w32 frame used");
ee78dc32
GV
334 return f;
335}
336
7d0393cf 337/* Let the user specify a display with a frame.
fbd6baed 338 nil stands for the selected frame--or, if that is not a w32 frame,
ee78dc32
GV
339 the first display on the list. */
340
6d906347 341struct w32_display_info *
ee78dc32
GV
342check_x_display_info (frame)
343 Lisp_Object frame;
344{
345 if (NILP (frame))
346 {
6fc2811b 347 struct frame *sf = XFRAME (selected_frame);
7d0393cf 348
6fc2811b
JR
349 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
350 return FRAME_W32_DISPLAY_INFO (sf);
ee78dc32 351 else
fbd6baed 352 return &one_w32_display_info;
ee78dc32
GV
353 }
354 else if (STRINGP (frame))
355 return x_display_info_for_name (frame);
356 else
357 {
358 FRAME_PTR f;
359
b7826503 360 CHECK_LIVE_FRAME (frame);
ee78dc32 361 f = XFRAME (frame);
fbd6baed
GV
362 if (! FRAME_W32_P (f))
363 error ("non-w32 frame used");
364 return FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
365 }
366}
367\f
fbd6baed 368/* Return the Emacs frame-object corresponding to an w32 window.
ee78dc32
GV
369 It could be the frame's main window or an icon window. */
370
371/* This function can be called during GC, so use GC_xxx type test macros. */
372
373struct frame *
374x_window_to_frame (dpyinfo, wdesc)
fbd6baed 375 struct w32_display_info *dpyinfo;
ee78dc32
GV
376 HWND wdesc;
377{
378 Lisp_Object tail, frame;
379 struct frame *f;
380
8e713be6 381 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
ee78dc32 382 {
8e713be6 383 frame = XCAR (tail);
ee78dc32
GV
384 if (!GC_FRAMEP (frame))
385 continue;
386 f = XFRAME (frame);
2d764c78 387 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
ee78dc32 388 continue;
0af913d7 389 if (f->output_data.w32->hourglass_window == wdesc)
f79e6790
JR
390 return f;
391
fbd6baed 392 if (FRAME_W32_WINDOW (f) == wdesc)
ee78dc32
GV
393 return f;
394 }
395 return 0;
396}
397
398\f
399
400/* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
401 id, which is just an int that this section returns. Bitmaps are
402 reference counted so they can be shared among frames.
403
404 Bitmap indices are guaranteed to be > 0, so a negative number can
405 be used to indicate no bitmap.
406
407 If you use x_create_bitmap_from_data, then you must keep track of
408 the bitmaps yourself. That is, creating a bitmap from the same
409 data more than once will not be caught. */
410
411
412/* Functions to access the contents of a bitmap, given an id. */
413
414int
415x_bitmap_height (f, id)
416 FRAME_PTR f;
417 int id;
418{
fbd6baed 419 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
ee78dc32
GV
420}
421
422int
423x_bitmap_width (f, id)
424 FRAME_PTR f;
425 int id;
426{
fbd6baed 427 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
ee78dc32
GV
428}
429
430int
431x_bitmap_pixmap (f, id)
432 FRAME_PTR f;
433 int id;
434{
fbd6baed 435 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
ee78dc32
GV
436}
437
438
439/* Allocate a new bitmap record. Returns index of new record. */
440
441static int
442x_allocate_bitmap_record (f)
443 FRAME_PTR f;
444{
fbd6baed 445 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
446 int i;
447
448 if (dpyinfo->bitmaps == NULL)
449 {
450 dpyinfo->bitmaps_size = 10;
451 dpyinfo->bitmaps
fbd6baed 452 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
ee78dc32
GV
453 dpyinfo->bitmaps_last = 1;
454 return 1;
455 }
456
457 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
458 return ++dpyinfo->bitmaps_last;
459
460 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
461 if (dpyinfo->bitmaps[i].refcount == 0)
462 return i + 1;
463
464 dpyinfo->bitmaps_size *= 2;
465 dpyinfo->bitmaps
fbd6baed
GV
466 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
467 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
ee78dc32
GV
468 return ++dpyinfo->bitmaps_last;
469}
470
471/* Add one reference to the reference count of the bitmap with id ID. */
472
473void
474x_reference_bitmap (f, id)
475 FRAME_PTR f;
476 int id;
477{
fbd6baed 478 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
ee78dc32
GV
479}
480
481/* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
482
483int
484x_create_bitmap_from_data (f, bits, width, height)
485 struct frame *f;
486 char *bits;
487 unsigned int width, height;
488{
fbd6baed 489 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
490 Pixmap bitmap;
491 int id;
492
493 bitmap = CreateBitmap (width, height,
fbd6baed
GV
494 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
495 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
ee78dc32
GV
496 bits);
497
498 if (! bitmap)
499 return -1;
500
501 id = x_allocate_bitmap_record (f);
502 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
503 dpyinfo->bitmaps[id - 1].file = NULL;
504 dpyinfo->bitmaps[id - 1].hinst = NULL;
505 dpyinfo->bitmaps[id - 1].refcount = 1;
506 dpyinfo->bitmaps[id - 1].depth = 1;
507 dpyinfo->bitmaps[id - 1].height = height;
508 dpyinfo->bitmaps[id - 1].width = width;
509
510 return id;
511}
512
513/* Create bitmap from file FILE for frame F. */
514
515int
516x_create_bitmap_from_file (f, file)
517 struct frame *f;
518 Lisp_Object file;
519{
520 return -1;
767b1ff0 521#if 0 /* TODO : bitmap support */
fbd6baed 522 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32 523 unsigned int width, height;
6fc2811b 524 HBITMAP bitmap;
ee78dc32
GV
525 int xhot, yhot, result, id;
526 Lisp_Object found;
527 int fd;
528 char *filename;
529 HINSTANCE hinst;
530
531 /* Look for an existing bitmap with the same name. */
532 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
533 {
534 if (dpyinfo->bitmaps[id].refcount
535 && dpyinfo->bitmaps[id].file
d5db4077 536 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
ee78dc32
GV
537 {
538 ++dpyinfo->bitmaps[id].refcount;
539 return id + 1;
540 }
541 }
542
543 /* Search bitmap-file-path for the file, if appropriate. */
de2413e9 544 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
ee78dc32
GV
545 if (fd < 0)
546 return -1;
6fc2811b 547 emacs_close (fd);
ee78dc32 548
d5db4077 549 filename = (char *) SDATA (found);
ee78dc32
GV
550
551 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
552
553 if (hinst == NULL)
554 return -1;
555
7d0393cf 556
fbd6baed 557 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
ee78dc32
GV
558 filename, &width, &height, &bitmap, &xhot, &yhot);
559 if (result != BitmapSuccess)
560 return -1;
561
562 id = x_allocate_bitmap_record (f);
563 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
564 dpyinfo->bitmaps[id - 1].refcount = 1;
d5db4077 565 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SCHARS (file) + 1);
ee78dc32
GV
566 dpyinfo->bitmaps[id - 1].depth = 1;
567 dpyinfo->bitmaps[id - 1].height = height;
568 dpyinfo->bitmaps[id - 1].width = width;
d5db4077 569 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
ee78dc32
GV
570
571 return id;
767b1ff0 572#endif /* TODO */
ee78dc32
GV
573}
574
575/* Remove reference to bitmap with id number ID. */
576
33d52f9c 577void
ee78dc32
GV
578x_destroy_bitmap (f, id)
579 FRAME_PTR f;
580 int id;
581{
fbd6baed 582 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
583
584 if (id > 0)
585 {
586 --dpyinfo->bitmaps[id - 1].refcount;
587 if (dpyinfo->bitmaps[id - 1].refcount == 0)
588 {
589 BLOCK_INPUT;
590 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
591 if (dpyinfo->bitmaps[id - 1].file)
592 {
6fc2811b 593 xfree (dpyinfo->bitmaps[id - 1].file);
ee78dc32
GV
594 dpyinfo->bitmaps[id - 1].file = NULL;
595 }
596 UNBLOCK_INPUT;
597 }
598 }
599}
600
601/* Free all the bitmaps for the display specified by DPYINFO. */
602
603static void
604x_destroy_all_bitmaps (dpyinfo)
fbd6baed 605 struct w32_display_info *dpyinfo;
ee78dc32
GV
606{
607 int i;
608 for (i = 0; i < dpyinfo->bitmaps_last; i++)
609 if (dpyinfo->bitmaps[i].refcount > 0)
610 {
611 DeleteObject (dpyinfo->bitmaps[i].pixmap);
612 if (dpyinfo->bitmaps[i].file)
6fc2811b 613 xfree (dpyinfo->bitmaps[i].file);
ee78dc32
GV
614 }
615 dpyinfo->bitmaps_last = 0;
616}
617\f
ca56d953
JR
618BOOL my_show_window P_ ((struct frame *, HWND, int));
619void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
937e601e
AI
620static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
621static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
6d906347 622
767b1ff0 623/* TODO: Native Input Method support; see x_create_im. */
6fc2811b
JR
624void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
625void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
626void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
627void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
628void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
629void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
630void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
631void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 632void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 633void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 634void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 635void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
3cf3436e
JR
636static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
637 Lisp_Object));
ee78dc32 638
ee78dc32 639
ee78dc32 640\f
ee78dc32
GV
641
642/* Store the screen positions of frame F into XPTR and YPTR.
643 These are the positions of the containing window manager window,
644 not Emacs's own window. */
645
646void
647x_real_positions (f, xptr, yptr)
648 FRAME_PTR f;
649 int *xptr, *yptr;
650{
651 POINT pt;
f7b9d4d1 652 RECT rect;
3c190163 653
f7b9d4d1
JR
654 GetClientRect(FRAME_W32_WINDOW(f), &rect);
655 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
656
657 pt.x = rect.left;
658 pt.y = rect.top;
ee78dc32 659
fbd6baed 660 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
ee78dc32 661
f7b9d4d1 662 /* Remember x_pixels_diff and y_pixels_diff. */
be786000
KS
663 f->x_pixels_diff = pt.x - rect.left;
664 f->y_pixels_diff = pt.y - rect.top;
f7b9d4d1 665
ee78dc32
GV
666 *xptr = pt.x;
667 *yptr = pt.y;
668}
669
ee78dc32
GV
670\f
671
74e1aeec
JR
672DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
673 Sw32_define_rgb_color, 4, 4, 0,
674 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
675This adds or updates a named color to w32-color-map, making it
676available for use. The original entry's RGB ref is returned, or nil
677if the entry is new. */)
5ac45f98
GV
678 (red, green, blue, name)
679 Lisp_Object red, green, blue, name;
ee78dc32 680{
5ac45f98
GV
681 Lisp_Object rgb;
682 Lisp_Object oldrgb = Qnil;
683 Lisp_Object entry;
684
b7826503
PJ
685 CHECK_NUMBER (red);
686 CHECK_NUMBER (green);
687 CHECK_NUMBER (blue);
688 CHECK_STRING (name);
ee78dc32 689
5ac45f98 690 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
ee78dc32 691
5ac45f98 692 BLOCK_INPUT;
ee78dc32 693
fbd6baed
GV
694 /* replace existing entry in w32-color-map or add new entry. */
695 entry = Fassoc (name, Vw32_color_map);
5ac45f98
GV
696 if (NILP (entry))
697 {
698 entry = Fcons (name, rgb);
fbd6baed 699 Vw32_color_map = Fcons (entry, Vw32_color_map);
5ac45f98
GV
700 }
701 else
702 {
703 oldrgb = Fcdr (entry);
704 Fsetcdr (entry, rgb);
705 }
706
707 UNBLOCK_INPUT;
708
709 return (oldrgb);
ee78dc32
GV
710}
711
74e1aeec
JR
712DEFUN ("w32-load-color-file", Fw32_load_color_file,
713 Sw32_load_color_file, 1, 1, 0,
714 doc: /* Create an alist of color entries from an external file.
715Assign this value to w32-color-map to replace the existing color map.
716
717The file should define one named RGB color per line like so:
718 R G B name
719where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
5ac45f98
GV
720 (filename)
721 Lisp_Object filename;
722{
723 FILE *fp;
724 Lisp_Object cmap = Qnil;
725 Lisp_Object abspath;
726
b7826503 727 CHECK_STRING (filename);
5ac45f98
GV
728 abspath = Fexpand_file_name (filename, Qnil);
729
d5db4077 730 fp = fopen (SDATA (filename), "rt");
5ac45f98
GV
731 if (fp)
732 {
733 char buf[512];
734 int red, green, blue;
735 int num;
736
737 BLOCK_INPUT;
738
739 while (fgets (buf, sizeof (buf), fp) != NULL) {
740 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
741 {
742 char *name = buf + num;
743 num = strlen (name) - 1;
744 if (name[num] == '\n')
745 name[num] = 0;
746 cmap = Fcons (Fcons (build_string (name),
747 make_number (RGB (red, green, blue))),
748 cmap);
749 }
750 }
751 fclose (fp);
752
753 UNBLOCK_INPUT;
754 }
755
756 return cmap;
757}
ee78dc32 758
fbd6baed 759/* The default colors for the w32 color map */
7d0393cf 760typedef struct colormap_t
ee78dc32
GV
761{
762 char *name;
763 COLORREF colorref;
764} colormap_t;
765
7d0393cf 766colormap_t w32_color_map[] =
ee78dc32 767{
1da8a614
GV
768 {"snow" , PALETTERGB (255,250,250)},
769 {"ghost white" , PALETTERGB (248,248,255)},
770 {"GhostWhite" , PALETTERGB (248,248,255)},
771 {"white smoke" , PALETTERGB (245,245,245)},
772 {"WhiteSmoke" , PALETTERGB (245,245,245)},
773 {"gainsboro" , PALETTERGB (220,220,220)},
774 {"floral white" , PALETTERGB (255,250,240)},
775 {"FloralWhite" , PALETTERGB (255,250,240)},
776 {"old lace" , PALETTERGB (253,245,230)},
777 {"OldLace" , PALETTERGB (253,245,230)},
778 {"linen" , PALETTERGB (250,240,230)},
779 {"antique white" , PALETTERGB (250,235,215)},
780 {"AntiqueWhite" , PALETTERGB (250,235,215)},
781 {"papaya whip" , PALETTERGB (255,239,213)},
782 {"PapayaWhip" , PALETTERGB (255,239,213)},
783 {"blanched almond" , PALETTERGB (255,235,205)},
784 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
785 {"bisque" , PALETTERGB (255,228,196)},
786 {"peach puff" , PALETTERGB (255,218,185)},
787 {"PeachPuff" , PALETTERGB (255,218,185)},
788 {"navajo white" , PALETTERGB (255,222,173)},
789 {"NavajoWhite" , PALETTERGB (255,222,173)},
790 {"moccasin" , PALETTERGB (255,228,181)},
791 {"cornsilk" , PALETTERGB (255,248,220)},
792 {"ivory" , PALETTERGB (255,255,240)},
793 {"lemon chiffon" , PALETTERGB (255,250,205)},
794 {"LemonChiffon" , PALETTERGB (255,250,205)},
795 {"seashell" , PALETTERGB (255,245,238)},
796 {"honeydew" , PALETTERGB (240,255,240)},
797 {"mint cream" , PALETTERGB (245,255,250)},
798 {"MintCream" , PALETTERGB (245,255,250)},
799 {"azure" , PALETTERGB (240,255,255)},
800 {"alice blue" , PALETTERGB (240,248,255)},
801 {"AliceBlue" , PALETTERGB (240,248,255)},
802 {"lavender" , PALETTERGB (230,230,250)},
803 {"lavender blush" , PALETTERGB (255,240,245)},
804 {"LavenderBlush" , PALETTERGB (255,240,245)},
805 {"misty rose" , PALETTERGB (255,228,225)},
806 {"MistyRose" , PALETTERGB (255,228,225)},
807 {"white" , PALETTERGB (255,255,255)},
808 {"black" , PALETTERGB ( 0, 0, 0)},
809 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
810 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
811 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
812 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
813 {"dim gray" , PALETTERGB (105,105,105)},
814 {"DimGray" , PALETTERGB (105,105,105)},
815 {"dim grey" , PALETTERGB (105,105,105)},
816 {"DimGrey" , PALETTERGB (105,105,105)},
817 {"slate gray" , PALETTERGB (112,128,144)},
818 {"SlateGray" , PALETTERGB (112,128,144)},
819 {"slate grey" , PALETTERGB (112,128,144)},
820 {"SlateGrey" , PALETTERGB (112,128,144)},
821 {"light slate gray" , PALETTERGB (119,136,153)},
822 {"LightSlateGray" , PALETTERGB (119,136,153)},
823 {"light slate grey" , PALETTERGB (119,136,153)},
824 {"LightSlateGrey" , PALETTERGB (119,136,153)},
825 {"gray" , PALETTERGB (190,190,190)},
826 {"grey" , PALETTERGB (190,190,190)},
827 {"light grey" , PALETTERGB (211,211,211)},
828 {"LightGrey" , PALETTERGB (211,211,211)},
829 {"light gray" , PALETTERGB (211,211,211)},
830 {"LightGray" , PALETTERGB (211,211,211)},
831 {"midnight blue" , PALETTERGB ( 25, 25,112)},
832 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
833 {"navy" , PALETTERGB ( 0, 0,128)},
834 {"navy blue" , PALETTERGB ( 0, 0,128)},
835 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
836 {"cornflower blue" , PALETTERGB (100,149,237)},
837 {"CornflowerBlue" , PALETTERGB (100,149,237)},
838 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
839 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
840 {"slate blue" , PALETTERGB (106, 90,205)},
841 {"SlateBlue" , PALETTERGB (106, 90,205)},
842 {"medium slate blue" , PALETTERGB (123,104,238)},
843 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
844 {"light slate blue" , PALETTERGB (132,112,255)},
845 {"LightSlateBlue" , PALETTERGB (132,112,255)},
846 {"medium blue" , PALETTERGB ( 0, 0,205)},
847 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
848 {"royal blue" , PALETTERGB ( 65,105,225)},
849 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
850 {"blue" , PALETTERGB ( 0, 0,255)},
851 {"dodger blue" , PALETTERGB ( 30,144,255)},
852 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
853 {"deep sky blue" , PALETTERGB ( 0,191,255)},
854 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
855 {"sky blue" , PALETTERGB (135,206,235)},
856 {"SkyBlue" , PALETTERGB (135,206,235)},
857 {"light sky blue" , PALETTERGB (135,206,250)},
858 {"LightSkyBlue" , PALETTERGB (135,206,250)},
859 {"steel blue" , PALETTERGB ( 70,130,180)},
860 {"SteelBlue" , PALETTERGB ( 70,130,180)},
861 {"light steel blue" , PALETTERGB (176,196,222)},
862 {"LightSteelBlue" , PALETTERGB (176,196,222)},
863 {"light blue" , PALETTERGB (173,216,230)},
864 {"LightBlue" , PALETTERGB (173,216,230)},
865 {"powder blue" , PALETTERGB (176,224,230)},
866 {"PowderBlue" , PALETTERGB (176,224,230)},
867 {"pale turquoise" , PALETTERGB (175,238,238)},
868 {"PaleTurquoise" , PALETTERGB (175,238,238)},
869 {"dark turquoise" , PALETTERGB ( 0,206,209)},
870 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
871 {"medium turquoise" , PALETTERGB ( 72,209,204)},
872 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
873 {"turquoise" , PALETTERGB ( 64,224,208)},
874 {"cyan" , PALETTERGB ( 0,255,255)},
875 {"light cyan" , PALETTERGB (224,255,255)},
876 {"LightCyan" , PALETTERGB (224,255,255)},
877 {"cadet blue" , PALETTERGB ( 95,158,160)},
878 {"CadetBlue" , PALETTERGB ( 95,158,160)},
879 {"medium aquamarine" , PALETTERGB (102,205,170)},
880 {"MediumAquamarine" , PALETTERGB (102,205,170)},
881 {"aquamarine" , PALETTERGB (127,255,212)},
882 {"dark green" , PALETTERGB ( 0,100, 0)},
883 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
884 {"dark olive green" , PALETTERGB ( 85,107, 47)},
885 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
886 {"dark sea green" , PALETTERGB (143,188,143)},
887 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
888 {"sea green" , PALETTERGB ( 46,139, 87)},
889 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
890 {"medium sea green" , PALETTERGB ( 60,179,113)},
891 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
892 {"light sea green" , PALETTERGB ( 32,178,170)},
893 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
894 {"pale green" , PALETTERGB (152,251,152)},
895 {"PaleGreen" , PALETTERGB (152,251,152)},
896 {"spring green" , PALETTERGB ( 0,255,127)},
897 {"SpringGreen" , PALETTERGB ( 0,255,127)},
898 {"lawn green" , PALETTERGB (124,252, 0)},
899 {"LawnGreen" , PALETTERGB (124,252, 0)},
900 {"green" , PALETTERGB ( 0,255, 0)},
901 {"chartreuse" , PALETTERGB (127,255, 0)},
902 {"medium spring green" , PALETTERGB ( 0,250,154)},
903 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
904 {"green yellow" , PALETTERGB (173,255, 47)},
905 {"GreenYellow" , PALETTERGB (173,255, 47)},
906 {"lime green" , PALETTERGB ( 50,205, 50)},
907 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
908 {"yellow green" , PALETTERGB (154,205, 50)},
909 {"YellowGreen" , PALETTERGB (154,205, 50)},
910 {"forest green" , PALETTERGB ( 34,139, 34)},
911 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
912 {"olive drab" , PALETTERGB (107,142, 35)},
913 {"OliveDrab" , PALETTERGB (107,142, 35)},
914 {"dark khaki" , PALETTERGB (189,183,107)},
915 {"DarkKhaki" , PALETTERGB (189,183,107)},
916 {"khaki" , PALETTERGB (240,230,140)},
917 {"pale goldenrod" , PALETTERGB (238,232,170)},
918 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
919 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
920 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
921 {"light yellow" , PALETTERGB (255,255,224)},
922 {"LightYellow" , PALETTERGB (255,255,224)},
923 {"yellow" , PALETTERGB (255,255, 0)},
924 {"gold" , PALETTERGB (255,215, 0)},
925 {"light goldenrod" , PALETTERGB (238,221,130)},
926 {"LightGoldenrod" , PALETTERGB (238,221,130)},
927 {"goldenrod" , PALETTERGB (218,165, 32)},
928 {"dark goldenrod" , PALETTERGB (184,134, 11)},
929 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
930 {"rosy brown" , PALETTERGB (188,143,143)},
931 {"RosyBrown" , PALETTERGB (188,143,143)},
932 {"indian red" , PALETTERGB (205, 92, 92)},
933 {"IndianRed" , PALETTERGB (205, 92, 92)},
934 {"saddle brown" , PALETTERGB (139, 69, 19)},
935 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
936 {"sienna" , PALETTERGB (160, 82, 45)},
937 {"peru" , PALETTERGB (205,133, 63)},
938 {"burlywood" , PALETTERGB (222,184,135)},
939 {"beige" , PALETTERGB (245,245,220)},
940 {"wheat" , PALETTERGB (245,222,179)},
941 {"sandy brown" , PALETTERGB (244,164, 96)},
942 {"SandyBrown" , PALETTERGB (244,164, 96)},
943 {"tan" , PALETTERGB (210,180,140)},
944 {"chocolate" , PALETTERGB (210,105, 30)},
945 {"firebrick" , PALETTERGB (178,34, 34)},
946 {"brown" , PALETTERGB (165,42, 42)},
947 {"dark salmon" , PALETTERGB (233,150,122)},
948 {"DarkSalmon" , PALETTERGB (233,150,122)},
949 {"salmon" , PALETTERGB (250,128,114)},
950 {"light salmon" , PALETTERGB (255,160,122)},
951 {"LightSalmon" , PALETTERGB (255,160,122)},
952 {"orange" , PALETTERGB (255,165, 0)},
953 {"dark orange" , PALETTERGB (255,140, 0)},
954 {"DarkOrange" , PALETTERGB (255,140, 0)},
955 {"coral" , PALETTERGB (255,127, 80)},
956 {"light coral" , PALETTERGB (240,128,128)},
957 {"LightCoral" , PALETTERGB (240,128,128)},
958 {"tomato" , PALETTERGB (255, 99, 71)},
959 {"orange red" , PALETTERGB (255, 69, 0)},
960 {"OrangeRed" , PALETTERGB (255, 69, 0)},
961 {"red" , PALETTERGB (255, 0, 0)},
962 {"hot pink" , PALETTERGB (255,105,180)},
963 {"HotPink" , PALETTERGB (255,105,180)},
964 {"deep pink" , PALETTERGB (255, 20,147)},
965 {"DeepPink" , PALETTERGB (255, 20,147)},
966 {"pink" , PALETTERGB (255,192,203)},
967 {"light pink" , PALETTERGB (255,182,193)},
968 {"LightPink" , PALETTERGB (255,182,193)},
969 {"pale violet red" , PALETTERGB (219,112,147)},
970 {"PaleVioletRed" , PALETTERGB (219,112,147)},
971 {"maroon" , PALETTERGB (176, 48, 96)},
972 {"medium violet red" , PALETTERGB (199, 21,133)},
973 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
974 {"violet red" , PALETTERGB (208, 32,144)},
975 {"VioletRed" , PALETTERGB (208, 32,144)},
976 {"magenta" , PALETTERGB (255, 0,255)},
977 {"violet" , PALETTERGB (238,130,238)},
978 {"plum" , PALETTERGB (221,160,221)},
979 {"orchid" , PALETTERGB (218,112,214)},
980 {"medium orchid" , PALETTERGB (186, 85,211)},
981 {"MediumOrchid" , PALETTERGB (186, 85,211)},
982 {"dark orchid" , PALETTERGB (153, 50,204)},
983 {"DarkOrchid" , PALETTERGB (153, 50,204)},
984 {"dark violet" , PALETTERGB (148, 0,211)},
985 {"DarkViolet" , PALETTERGB (148, 0,211)},
986 {"blue violet" , PALETTERGB (138, 43,226)},
987 {"BlueViolet" , PALETTERGB (138, 43,226)},
988 {"purple" , PALETTERGB (160, 32,240)},
989 {"medium purple" , PALETTERGB (147,112,219)},
990 {"MediumPurple" , PALETTERGB (147,112,219)},
991 {"thistle" , PALETTERGB (216,191,216)},
992 {"gray0" , PALETTERGB ( 0, 0, 0)},
993 {"grey0" , PALETTERGB ( 0, 0, 0)},
994 {"dark grey" , PALETTERGB (169,169,169)},
995 {"DarkGrey" , PALETTERGB (169,169,169)},
996 {"dark gray" , PALETTERGB (169,169,169)},
997 {"DarkGray" , PALETTERGB (169,169,169)},
998 {"dark blue" , PALETTERGB ( 0, 0,139)},
999 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1000 {"dark cyan" , PALETTERGB ( 0,139,139)},
1001 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1002 {"dark magenta" , PALETTERGB (139, 0,139)},
1003 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1004 {"dark red" , PALETTERGB (139, 0, 0)},
1005 {"DarkRed" , PALETTERGB (139, 0, 0)},
1006 {"light green" , PALETTERGB (144,238,144)},
1007 {"LightGreen" , PALETTERGB (144,238,144)},
ee78dc32
GV
1008};
1009
fbd6baed 1010DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
74e1aeec 1011 0, 0, 0, doc: /* Return the default color map. */)
ee78dc32
GV
1012 ()
1013{
1014 int i;
fbd6baed 1015 colormap_t *pc = w32_color_map;
ee78dc32 1016 Lisp_Object cmap;
7d0393cf 1017
ee78dc32 1018 BLOCK_INPUT;
7d0393cf 1019
ee78dc32 1020 cmap = Qnil;
7d0393cf
JB
1021
1022 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
ee78dc32
GV
1023 pc++, i++)
1024 cmap = Fcons (Fcons (build_string (pc->name),
1025 make_number (pc->colorref)),
1026 cmap);
7d0393cf 1027
ee78dc32 1028 UNBLOCK_INPUT;
7d0393cf 1029
ee78dc32
GV
1030 return (cmap);
1031}
ee78dc32 1032
7d0393cf 1033Lisp_Object
fbd6baed 1034w32_to_x_color (rgb)
ee78dc32
GV
1035 Lisp_Object rgb;
1036{
1037 Lisp_Object color;
7d0393cf 1038
b7826503 1039 CHECK_NUMBER (rgb);
7d0393cf 1040
ee78dc32 1041 BLOCK_INPUT;
7d0393cf 1042
fbd6baed 1043 color = Frassq (rgb, Vw32_color_map);
7d0393cf 1044
ee78dc32 1045 UNBLOCK_INPUT;
7d0393cf 1046
ee78dc32
GV
1047 if (!NILP (color))
1048 return (Fcar (color));
1049 else
1050 return Qnil;
1051}
1052
5d7fed93
GV
1053COLORREF
1054w32_color_map_lookup (colorname)
1055 char *colorname;
1056{
1057 Lisp_Object tail, ret = Qnil;
1058
1059 BLOCK_INPUT;
1060
1061 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1062 {
1063 register Lisp_Object elt, tem;
1064
1065 elt = Fcar (tail);
1066 if (!CONSP (elt)) continue;
1067
1068 tem = Fcar (elt);
1069
d5db4077 1070 if (lstrcmpi (SDATA (tem), colorname) == 0)
5d7fed93
GV
1071 {
1072 ret = XUINT (Fcdr (elt));
1073 break;
1074 }
1075
1076 QUIT;
1077 }
1078
1079
1080 UNBLOCK_INPUT;
1081
1082 return ret;
1083}
1084
5a8a15ec
JR
1085
1086static void
1087add_system_logical_colors_to_map (system_colors)
1088 Lisp_Object *system_colors;
1089{
1090 HKEY colors_key;
1091
1092 /* Other registry operations are done with input blocked. */
1093 BLOCK_INPUT;
1094
1095 /* Look for "Control Panel/Colors" under User and Machine registry
1096 settings. */
1097 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
1098 KEY_READ, &colors_key) == ERROR_SUCCESS
1099 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
1100 KEY_READ, &colors_key) == ERROR_SUCCESS)
1101 {
1102 /* List all keys. */
1103 char color_buffer[64];
1104 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
1105 int index = 0;
1106 DWORD name_size, color_size;
1107 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
1108
1109 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
1110 color_size = sizeof (color_buffer);
1111
1112 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
1113
1114 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
1115 NULL, NULL, color_buffer, &color_size)
1116 == ERROR_SUCCESS)
1117 {
1118 int r, g, b;
1119 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
1120 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
1121 make_number (RGB (r, g, b))),
1122 *system_colors);
1123
1124 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
1125 color_size = sizeof (color_buffer);
1126 index++;
1127 }
1128 RegCloseKey (colors_key);
1129 }
1130
1131 UNBLOCK_INPUT;
1132}
1133
1134
7d0393cf 1135COLORREF
fbd6baed 1136x_to_w32_color (colorname)
ee78dc32
GV
1137 char * colorname;
1138{
8edb0a6f
JR
1139 register Lisp_Object ret = Qnil;
1140
ee78dc32 1141 BLOCK_INPUT;
1edf84e7
GV
1142
1143 if (colorname[0] == '#')
1144 {
1145 /* Could be an old-style RGB Device specification. */
1146 char *color;
1147 int size;
1148 color = colorname + 1;
7d0393cf 1149
1edf84e7
GV
1150 size = strlen(color);
1151 if (size == 3 || size == 6 || size == 9 || size == 12)
1152 {
1153 UINT colorval;
1154 int i, pos;
1155 pos = 0;
1156 size /= 3;
1157 colorval = 0;
7d0393cf 1158
1edf84e7
GV
1159 for (i = 0; i < 3; i++)
1160 {
1161 char *end;
1162 char t;
1163 unsigned long value;
1164
1165 /* The check for 'x' in the following conditional takes into
1166 account the fact that strtol allows a "0x" in front of
1167 our numbers, and we don't. */
1168 if (!isxdigit(color[0]) || color[1] == 'x')
1169 break;
1170 t = color[size];
1171 color[size] = '\0';
1172 value = strtoul(color, &end, 16);
1173 color[size] = t;
1174 if (errno == ERANGE || end - color != size)
1175 break;
1176 switch (size)
1177 {
1178 case 1:
1179 value = value * 0x10;
1180 break;
1181 case 2:
1182 break;
1183 case 3:
1184 value /= 0x10;
1185 break;
1186 case 4:
1187 value /= 0x100;
1188 break;
1189 }
1190 colorval |= (value << pos);
1191 pos += 0x8;
1192 if (i == 2)
1193 {
1194 UNBLOCK_INPUT;
1195 return (colorval);
1196 }
1197 color = end;
1198 }
1199 }
1200 }
1201 else if (strnicmp(colorname, "rgb:", 4) == 0)
1202 {
1203 char *color;
1204 UINT colorval;
1205 int i, pos;
1206 pos = 0;
1207
1208 colorval = 0;
1209 color = colorname + 4;
1210 for (i = 0; i < 3; i++)
1211 {
1212 char *end;
1213 unsigned long value;
7d0393cf 1214
1edf84e7
GV
1215 /* The check for 'x' in the following conditional takes into
1216 account the fact that strtol allows a "0x" in front of
1217 our numbers, and we don't. */
1218 if (!isxdigit(color[0]) || color[1] == 'x')
1219 break;
1220 value = strtoul(color, &end, 16);
1221 if (errno == ERANGE)
1222 break;
1223 switch (end - color)
1224 {
1225 case 1:
1226 value = value * 0x10 + value;
1227 break;
1228 case 2:
1229 break;
1230 case 3:
1231 value /= 0x10;
1232 break;
1233 case 4:
1234 value /= 0x100;
1235 break;
1236 default:
1237 value = ULONG_MAX;
1238 }
1239 if (value == ULONG_MAX)
1240 break;
1241 colorval |= (value << pos);
1242 pos += 0x8;
1243 if (i == 2)
1244 {
1245 if (*end != '\0')
1246 break;
1247 UNBLOCK_INPUT;
1248 return (colorval);
1249 }
1250 if (*end != '/')
1251 break;
1252 color = end + 1;
1253 }
1254 }
1255 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1256 {
1257 /* This is an RGB Intensity specification. */
1258 char *color;
1259 UINT colorval;
1260 int i, pos;
1261 pos = 0;
1262
1263 colorval = 0;
1264 color = colorname + 5;
1265 for (i = 0; i < 3; i++)
1266 {
1267 char *end;
1268 double value;
1269 UINT val;
1270
1271 value = strtod(color, &end);
1272 if (errno == ERANGE)
1273 break;
1274 if (value < 0.0 || value > 1.0)
1275 break;
1276 val = (UINT)(0x100 * value);
7d0393cf 1277 /* We used 0x100 instead of 0xFF to give a continuous
1edf84e7
GV
1278 range between 0.0 and 1.0 inclusive. The next statement
1279 fixes the 1.0 case. */
1280 if (val == 0x100)
1281 val = 0xFF;
1282 colorval |= (val << pos);
1283 pos += 0x8;
1284 if (i == 2)
1285 {
1286 if (*end != '\0')
1287 break;
1288 UNBLOCK_INPUT;
1289 return (colorval);
1290 }
1291 if (*end != '/')
1292 break;
1293 color = end + 1;
1294 }
1295 }
1296 /* I am not going to attempt to handle any of the CIE color schemes
1297 or TekHVC, since I don't know the algorithms for conversion to
1298 RGB. */
f695b4b1
GV
1299
1300 /* If we fail to lookup the color name in w32_color_map, then check the
7d0393cf 1301 colorname to see if it can be crudely approximated: If the X color
f695b4b1
GV
1302 ends in a number (e.g., "darkseagreen2"), strip the number and
1303 return the result of looking up the base color name. */
1304 ret = w32_color_map_lookup (colorname);
7d0393cf 1305 if (NILP (ret))
ee78dc32 1306 {
f695b4b1 1307 int len = strlen (colorname);
ee78dc32 1308
7d0393cf 1309 if (isdigit (colorname[len - 1]))
f695b4b1 1310 {
8b77111c 1311 char *ptr, *approx = alloca (len + 1);
ee78dc32 1312
f695b4b1
GV
1313 strcpy (approx, colorname);
1314 ptr = &approx[len - 1];
7d0393cf 1315 while (ptr > approx && isdigit (*ptr))
f695b4b1 1316 *ptr-- = '\0';
ee78dc32 1317
f695b4b1 1318 ret = w32_color_map_lookup (approx);
ee78dc32 1319 }
ee78dc32 1320 }
7d0393cf 1321
ee78dc32 1322 UNBLOCK_INPUT;
ee78dc32
GV
1323 return ret;
1324}
1325
5ac45f98 1326void
fbd6baed 1327w32_regenerate_palette (FRAME_PTR f)
5ac45f98 1328{
fbd6baed 1329 struct w32_palette_entry * list;
5ac45f98
GV
1330 LOGPALETTE * log_palette;
1331 HPALETTE new_palette;
1332 int i;
1333
1334 /* don't bother trying to create palette if not supported */
fbd6baed 1335 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
5ac45f98
GV
1336 return;
1337
1338 log_palette = (LOGPALETTE *)
1339 alloca (sizeof (LOGPALETTE) +
fbd6baed 1340 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
5ac45f98 1341 log_palette->palVersion = 0x300;
fbd6baed 1342 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
5ac45f98 1343
fbd6baed 1344 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
5ac45f98 1345 for (i = 0;
fbd6baed 1346 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
5ac45f98
GV
1347 i++, list = list->next)
1348 log_palette->palPalEntry[i] = list->entry;
1349
1350 new_palette = CreatePalette (log_palette);
1351
1352 enter_crit ();
1353
fbd6baed
GV
1354 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1355 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1356 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
5ac45f98
GV
1357
1358 /* Realize display palette and garbage all frames. */
1359 release_frame_dc (f, get_frame_dc (f));
1360
1361 leave_crit ();
1362}
1363
fbd6baed
GV
1364#define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1365#define SET_W32_COLOR(pe, color) \
5ac45f98
GV
1366 do \
1367 { \
1368 pe.peRed = GetRValue (color); \
1369 pe.peGreen = GetGValue (color); \
1370 pe.peBlue = GetBValue (color); \
1371 pe.peFlags = 0; \
1372 } while (0)
1373
1374#if 0
1375/* Keep these around in case we ever want to track color usage. */
1376void
fbd6baed 1377w32_map_color (FRAME_PTR f, COLORREF color)
5ac45f98 1378{
fbd6baed 1379 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
5ac45f98 1380
fbd6baed 1381 if (NILP (Vw32_enable_palette))
5ac45f98
GV
1382 return;
1383
1384 /* check if color is already mapped */
1385 while (list)
1386 {
fbd6baed 1387 if (W32_COLOR (list->entry) == color)
5ac45f98
GV
1388 {
1389 ++list->refcount;
1390 return;
1391 }
1392 list = list->next;
1393 }
1394
1395 /* not already mapped, so add to list and recreate Windows palette */
fbd6baed
GV
1396 list = (struct w32_palette_entry *)
1397 xmalloc (sizeof (struct w32_palette_entry));
1398 SET_W32_COLOR (list->entry, color);
5ac45f98 1399 list->refcount = 1;
fbd6baed
GV
1400 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1401 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1402 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
5ac45f98
GV
1403
1404 /* set flag that palette must be regenerated */
fbd6baed 1405 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
5ac45f98
GV
1406}
1407
1408void
fbd6baed 1409w32_unmap_color (FRAME_PTR f, COLORREF color)
5ac45f98 1410{
fbd6baed
GV
1411 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1412 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
5ac45f98 1413
fbd6baed 1414 if (NILP (Vw32_enable_palette))
5ac45f98
GV
1415 return;
1416
1417 /* check if color is already mapped */
1418 while (list)
1419 {
fbd6baed 1420 if (W32_COLOR (list->entry) == color)
5ac45f98
GV
1421 {
1422 if (--list->refcount == 0)
1423 {
1424 *prev = list->next;
1425 xfree (list);
fbd6baed 1426 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
5ac45f98
GV
1427 break;
1428 }
1429 else
1430 return;
1431 }
1432 prev = &list->next;
1433 list = list->next;
1434 }
1435
1436 /* set flag that palette must be regenerated */
fbd6baed 1437 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
5ac45f98
GV
1438}
1439#endif
1440
6fc2811b
JR
1441
1442/* Gamma-correct COLOR on frame F. */
1443
1444void
1445gamma_correct (f, color)
1446 struct frame *f;
1447 COLORREF *color;
1448{
1449 if (f->gamma)
1450 {
1451 *color = PALETTERGB (
1452 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1453 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1454 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1455 }
1456}
1457
1458
ee78dc32
GV
1459/* Decide if color named COLOR is valid for the display associated with
1460 the selected frame; if so, return the rgb values in COLOR_DEF.
1461 If ALLOC is nonzero, allocate a new colormap cell. */
1462
1463int
6fc2811b 1464w32_defined_color (f, color, color_def, alloc)
ee78dc32
GV
1465 FRAME_PTR f;
1466 char *color;
6fc2811b 1467 XColor *color_def;
ee78dc32
GV
1468 int alloc;
1469{
1470 register Lisp_Object tem;
6fc2811b 1471 COLORREF w32_color_ref;
3c190163 1472
fbd6baed 1473 tem = x_to_w32_color (color);
3c190163 1474
7d0393cf 1475 if (!NILP (tem))
ee78dc32 1476 {
d88c567c
JR
1477 if (f)
1478 {
1479 /* Apply gamma correction. */
1480 w32_color_ref = XUINT (tem);
1481 gamma_correct (f, &w32_color_ref);
1482 XSETINT (tem, w32_color_ref);
1483 }
9badad41
JR
1484
1485 /* Map this color to the palette if it is enabled. */
fbd6baed 1486 if (!NILP (Vw32_enable_palette))
5ac45f98 1487 {
fbd6baed 1488 struct w32_palette_entry * entry =
d88c567c 1489 one_w32_display_info.color_list;
fbd6baed 1490 struct w32_palette_entry ** prev =
d88c567c 1491 &one_w32_display_info.color_list;
7d0393cf 1492
5ac45f98
GV
1493 /* check if color is already mapped */
1494 while (entry)
1495 {
fbd6baed 1496 if (W32_COLOR (entry->entry) == XUINT (tem))
5ac45f98
GV
1497 break;
1498 prev = &entry->next;
1499 entry = entry->next;
1500 }
1501
1502 if (entry == NULL && alloc)
1503 {
1504 /* not already mapped, so add to list */
fbd6baed
GV
1505 entry = (struct w32_palette_entry *)
1506 xmalloc (sizeof (struct w32_palette_entry));
1507 SET_W32_COLOR (entry->entry, XUINT (tem));
5ac45f98
GV
1508 entry->next = NULL;
1509 *prev = entry;
d88c567c 1510 one_w32_display_info.num_colors++;
5ac45f98
GV
1511
1512 /* set flag that palette must be regenerated */
d88c567c 1513 one_w32_display_info.regen_palette = TRUE;
5ac45f98
GV
1514 }
1515 }
1516 /* Ensure COLORREF value is snapped to nearest color in (default)
1517 palette by simulating the PALETTERGB macro. This works whether
1518 or not the display device has a palette. */
6fc2811b
JR
1519 w32_color_ref = XUINT (tem) | 0x2000000;
1520
6fc2811b 1521 color_def->pixel = w32_color_ref;
197edd35
JR
1522 color_def->red = GetRValue (w32_color_ref) * 256;
1523 color_def->green = GetGValue (w32_color_ref) * 256;
1524 color_def->blue = GetBValue (w32_color_ref) * 256;
6fc2811b 1525
ee78dc32 1526 return 1;
5ac45f98 1527 }
7d0393cf 1528 else
3c190163
GV
1529 {
1530 return 0;
1531 }
ee78dc32
GV
1532}
1533
1534/* Given a string ARG naming a color, compute a pixel value from it
1535 suitable for screen F.
1536 If F is not a color screen, return DEF (default) regardless of what
1537 ARG says. */
1538
1539int
1540x_decode_color (f, arg, def)
1541 FRAME_PTR f;
1542 Lisp_Object arg;
1543 int def;
1544{
6fc2811b 1545 XColor cdef;
ee78dc32 1546
b7826503 1547 CHECK_STRING (arg);
ee78dc32 1548
d5db4077 1549 if (strcmp (SDATA (arg), "black") == 0)
ee78dc32 1550 return BLACK_PIX_DEFAULT (f);
d5db4077 1551 else if (strcmp (SDATA (arg), "white") == 0)
ee78dc32
GV
1552 return WHITE_PIX_DEFAULT (f);
1553
fbd6baed 1554 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
ee78dc32
GV
1555 return def;
1556
6fc2811b 1557 /* w32_defined_color is responsible for coping with failures
ee78dc32 1558 by looking for a near-miss. */
d5db4077 1559 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
6fc2811b 1560 return cdef.pixel;
ee78dc32
GV
1561
1562 /* defined_color failed; return an ultimate default. */
1563 return def;
1564}
1565\f
6fc2811b
JR
1566
1567
ee78dc32
GV
1568/* Functions called only from `x_set_frame_param'
1569 to set individual parameters.
1570
fbd6baed 1571 If FRAME_W32_WINDOW (f) is 0,
ee78dc32
GV
1572 the frame is being created and its window does not exist yet.
1573 In that case, just record the parameter's new value
1574 in the standard place; do not attempt to change the window. */
1575
1576void
1577x_set_foreground_color (f, arg, oldval)
1578 struct frame *f;
1579 Lisp_Object arg, oldval;
1580{
3cf3436e
JR
1581 struct w32_output *x = f->output_data.w32;
1582 PIX_TYPE fg, old_fg;
1583
1584 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1585 old_fg = FRAME_FOREGROUND_PIXEL (f);
1586 FRAME_FOREGROUND_PIXEL (f) = fg;
5ac45f98 1587
fbd6baed 1588 if (FRAME_W32_WINDOW (f) != 0)
ee78dc32 1589 {
3cf3436e
JR
1590 if (x->cursor_pixel == old_fg)
1591 x->cursor_pixel = fg;
1592
6fc2811b 1593 update_face_from_frame_parameter (f, Qforeground_color, arg);
ee78dc32
GV
1594 if (FRAME_VISIBLE_P (f))
1595 redraw_frame (f);
1596 }
1597}
1598
1599void
1600x_set_background_color (f, arg, oldval)
1601 struct frame *f;
1602 Lisp_Object arg, oldval;
1603{
6fc2811b 1604 FRAME_BACKGROUND_PIXEL (f)
ee78dc32
GV
1605 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1606
fbd6baed 1607 if (FRAME_W32_WINDOW (f) != 0)
ee78dc32 1608 {
6fc2811b
JR
1609 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1610 FRAME_BACKGROUND_PIXEL (f));
ee78dc32 1611
6fc2811b 1612 update_face_from_frame_parameter (f, Qbackground_color, arg);
ee78dc32
GV
1613
1614 if (FRAME_VISIBLE_P (f))
1615 redraw_frame (f);
1616 }
1617}
1618
1619void
1620x_set_mouse_color (f, arg, oldval)
1621 struct frame *f;
1622 Lisp_Object arg, oldval;
1623{
7d63e5e3 1624 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
dfc465d3 1625 int count;
ee78dc32
GV
1626 int mask_color;
1627
1628 if (!EQ (Qnil, arg))
fbd6baed 1629 f->output_data.w32->mouse_pixel
ee78dc32 1630 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
6fc2811b
JR
1631 mask_color = FRAME_BACKGROUND_PIXEL (f);
1632
1633 /* Don't let pointers be invisible. */
fbd6baed 1634 if (mask_color == f->output_data.w32->mouse_pixel
6fc2811b
JR
1635 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1636 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
ee78dc32 1637
767b1ff0 1638#if 0 /* TODO : cursor changes */
ee78dc32
GV
1639 BLOCK_INPUT;
1640
1641 /* It's not okay to crash if the user selects a screwy cursor. */
fadca6c6 1642 count = x_catch_errors (FRAME_W32_DISPLAY (f));
ee78dc32
GV
1643
1644 if (!EQ (Qnil, Vx_pointer_shape))
1645 {
b7826503 1646 CHECK_NUMBER (Vx_pointer_shape);
fbd6baed 1647 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
ee78dc32
GV
1648 }
1649 else
fbd6baed
GV
1650 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1651 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
ee78dc32
GV
1652
1653 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1654 {
b7826503 1655 CHECK_NUMBER (Vx_nontext_pointer_shape);
fbd6baed 1656 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
ee78dc32
GV
1657 XINT (Vx_nontext_pointer_shape));
1658 }
1659 else
fbd6baed
GV
1660 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1661 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
ee78dc32 1662
0af913d7 1663 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
6fc2811b 1664 {
b7826503 1665 CHECK_NUMBER (Vx_hourglass_pointer_shape);
0af913d7
GM
1666 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1667 XINT (Vx_hourglass_pointer_shape));
6fc2811b
JR
1668 }
1669 else
0af913d7 1670 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
6fc2811b 1671 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
7d0393cf 1672
6fc2811b 1673 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
ee78dc32
GV
1674 if (!EQ (Qnil, Vx_mode_pointer_shape))
1675 {
b7826503 1676 CHECK_NUMBER (Vx_mode_pointer_shape);
fbd6baed 1677 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
ee78dc32
GV
1678 XINT (Vx_mode_pointer_shape));
1679 }
1680 else
fbd6baed
GV
1681 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1682 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
ee78dc32
GV
1683
1684 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1685 {
b7826503 1686 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
7d63e5e3 1687 hand_cursor
fbd6baed 1688 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
ee78dc32
GV
1689 XINT (Vx_sensitive_text_pointer_shape));
1690 }
1691 else
7d63e5e3 1692 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
ee78dc32 1693
4694d762
JR
1694 if (!NILP (Vx_window_horizontal_drag_shape))
1695 {
b7826503 1696 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
4694d762
JR
1697 horizontal_drag_cursor
1698 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1699 XINT (Vx_window_horizontal_drag_shape));
1700 }
1701 else
1702 horizontal_drag_cursor
1703 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1704
ee78dc32 1705 /* Check and report errors with the above calls. */
fbd6baed 1706 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
fadca6c6 1707 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
ee78dc32
GV
1708
1709 {
1710 XColor fore_color, back_color;
1711
fbd6baed 1712 fore_color.pixel = f->output_data.w32->mouse_pixel;
ee78dc32 1713 back_color.pixel = mask_color;
fbd6baed
GV
1714 XQueryColor (FRAME_W32_DISPLAY (f),
1715 DefaultColormap (FRAME_W32_DISPLAY (f),
1716 DefaultScreen (FRAME_W32_DISPLAY (f))),
ee78dc32 1717 &fore_color);
fbd6baed
GV
1718 XQueryColor (FRAME_W32_DISPLAY (f),
1719 DefaultColormap (FRAME_W32_DISPLAY (f),
1720 DefaultScreen (FRAME_W32_DISPLAY (f))),
ee78dc32 1721 &back_color);
fbd6baed 1722 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
ee78dc32 1723 &fore_color, &back_color);
fbd6baed 1724 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
ee78dc32 1725 &fore_color, &back_color);
fbd6baed 1726 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
ee78dc32 1727 &fore_color, &back_color);
7d63e5e3 1728 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
ee78dc32 1729 &fore_color, &back_color);
0af913d7 1730 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
6fc2811b 1731 &fore_color, &back_color);
ee78dc32
GV
1732 }
1733
fbd6baed 1734 if (FRAME_W32_WINDOW (f) != 0)
6fc2811b 1735 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
ee78dc32 1736
fbd6baed
GV
1737 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1738 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1739 f->output_data.w32->text_cursor = cursor;
1740
1741 if (nontext_cursor != f->output_data.w32->nontext_cursor
1742 && f->output_data.w32->nontext_cursor != 0)
1743 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1744 f->output_data.w32->nontext_cursor = nontext_cursor;
1745
0af913d7
GM
1746 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1747 && f->output_data.w32->hourglass_cursor != 0)
1748 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1749 f->output_data.w32->hourglass_cursor = hourglass_cursor;
6fc2811b 1750
fbd6baed
GV
1751 if (mode_cursor != f->output_data.w32->modeline_cursor
1752 && f->output_data.w32->modeline_cursor != 0)
1753 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1754 f->output_data.w32->modeline_cursor = mode_cursor;
7d0393cf 1755
7d63e5e3
KS
1756 if (hand_cursor != f->output_data.w32->hand_cursor
1757 && f->output_data.w32->hand_cursor != 0)
1758 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1759 f->output_data.w32->hand_cursor = hand_cursor;
fbd6baed
GV
1760
1761 XFlush (FRAME_W32_DISPLAY (f));
ee78dc32 1762 UNBLOCK_INPUT;
6fc2811b
JR
1763
1764 update_face_from_frame_parameter (f, Qmouse_color, arg);
767b1ff0 1765#endif /* TODO */
ee78dc32
GV
1766}
1767
70a0239a 1768/* Defined in w32term.c. */
ee78dc32
GV
1769void
1770x_set_cursor_color (f, arg, oldval)
1771 struct frame *f;
1772 Lisp_Object arg, oldval;
1773{
70a0239a 1774 unsigned long fore_pixel, pixel;
ee78dc32 1775
dfff8a69 1776 if (!NILP (Vx_cursor_fore_pixel))
ee78dc32 1777 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
70a0239a 1778 WHITE_PIX_DEFAULT (f));
ee78dc32 1779 else
6fc2811b 1780 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
70a0239a 1781
6759f872 1782 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
7d0393cf 1783
ee78dc32 1784 /* Make sure that the cursor color differs from the background color. */
70a0239a 1785 if (pixel == FRAME_BACKGROUND_PIXEL (f))
ee78dc32 1786 {
70a0239a
JR
1787 pixel = f->output_data.w32->mouse_pixel;
1788 if (pixel == fore_pixel)
6fc2811b 1789 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
ee78dc32 1790 }
70a0239a 1791
ac849ba4 1792 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
70a0239a 1793 f->output_data.w32->cursor_pixel = pixel;
ee78dc32 1794
fbd6baed 1795 if (FRAME_W32_WINDOW (f) != 0)
ee78dc32 1796 {
0327b4cc
JR
1797 BLOCK_INPUT;
1798 /* Update frame's cursor_gc. */
1799 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1800 f->output_data.w32->cursor_gc->background = pixel;
1801
1802 UNBLOCK_INPUT;
1803
ee78dc32
GV
1804 if (FRAME_VISIBLE_P (f))
1805 {
70a0239a
JR
1806 x_update_cursor (f, 0);
1807 x_update_cursor (f, 1);
ee78dc32
GV
1808 }
1809 }
6fc2811b
JR
1810
1811 update_face_from_frame_parameter (f, Qcursor_color, arg);
ee78dc32
GV
1812}
1813
33d52f9c
GV
1814/* Set the border-color of frame F to pixel value PIX.
1815 Note that this does not fully take effect if done before
7d0393cf 1816 F has a window. */
6d906347 1817
33d52f9c
GV
1818void
1819x_set_border_pixel (f, pix)
1820 struct frame *f;
1821 int pix;
1822{
6d906347 1823
33d52f9c
GV
1824 f->output_data.w32->border_pixel = pix;
1825
be786000 1826 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
33d52f9c
GV
1827 {
1828 if (FRAME_VISIBLE_P (f))
1829 redraw_frame (f);
1830 }
1831}
1832
ee78dc32
GV
1833/* Set the border-color of frame F to value described by ARG.
1834 ARG can be a string naming a color.
1835 The border-color is used for the border that is drawn by the server.
1836 Note that this does not fully take effect if done before
1837 F has a window; it must be redone when the window is created. */
1838
1839void
1840x_set_border_color (f, arg, oldval)
1841 struct frame *f;
1842 Lisp_Object arg, oldval;
1843{
ee78dc32
GV
1844 int pix;
1845
b7826503 1846 CHECK_STRING (arg);
ee78dc32 1847 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
ee78dc32 1848 x_set_border_pixel (f, pix);
6fc2811b 1849 update_face_from_frame_parameter (f, Qborder_color, arg);
ee78dc32
GV
1850}
1851
dfff8a69
JR
1852
1853void
1854x_set_cursor_type (f, arg, oldval)
1855 FRAME_PTR f;
1856 Lisp_Object arg, oldval;
1857{
50e363e6 1858 set_frame_cursor_types (f, arg);
ee78dc32 1859
623cdbf2 1860 /* Make sure the cursor gets redrawn. */
c922a224 1861 cursor_type_changed = 1;
ee78dc32 1862}
dfff8a69 1863\f
ee78dc32
GV
1864void
1865x_set_icon_type (f, arg, oldval)
1866 struct frame *f;
1867 Lisp_Object arg, oldval;
1868{
ee78dc32
GV
1869 int result;
1870
eb7576ce
GV
1871 if (NILP (arg) && NILP (oldval))
1872 return;
1873
7d0393cf 1874 if (STRINGP (arg) && STRINGP (oldval)
eb7576ce
GV
1875 && EQ (Fstring_equal (oldval, arg), Qt))
1876 return;
1877
1878 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
ee78dc32
GV
1879 return;
1880
1881 BLOCK_INPUT;
ee78dc32 1882
eb7576ce 1883 result = x_bitmap_icon (f, arg);
ee78dc32
GV
1884 if (result)
1885 {
1886 UNBLOCK_INPUT;
1887 error ("No icon window available");
1888 }
1889
ee78dc32 1890 UNBLOCK_INPUT;
ee78dc32
GV
1891}
1892
ee78dc32
GV
1893void
1894x_set_icon_name (f, arg, oldval)
1895 struct frame *f;
1896 Lisp_Object arg, oldval;
1897{
ee78dc32
GV
1898 if (STRINGP (arg))
1899 {
1900 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1901 return;
1902 }
1903 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
1904 return;
1905
1906 f->icon_name = arg;
1907
1908#if 0
fbd6baed 1909 if (f->output_data.w32->icon_bitmap != 0)
ee78dc32
GV
1910 return;
1911
1912 BLOCK_INPUT;
1913
1914 result = x_text_icon (f,
d5db4077
KR
1915 (char *) SDATA ((!NILP (f->icon_name)
1916 ? f->icon_name
1917 : !NILP (f->title)
1918 ? f->title
1919 : f->name)));
ee78dc32
GV
1920
1921 if (result)
1922 {
1923 UNBLOCK_INPUT;
1924 error ("No icon window available");
1925 }
1926
1927 /* If the window was unmapped (and its icon was mapped),
1928 the new icon is not mapped, so map the window in its stead. */
1929 if (FRAME_VISIBLE_P (f))
1930 {
1931#ifdef USE_X_TOOLKIT
fbd6baed 1932 XtPopup (f->output_data.w32->widget, XtGrabNone);
ee78dc32 1933#endif
fbd6baed 1934 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
ee78dc32
GV
1935 }
1936
fbd6baed 1937 XFlush (FRAME_W32_DISPLAY (f));
ee78dc32
GV
1938 UNBLOCK_INPUT;
1939#endif
1940}
1941
a1258667 1942\f
ee78dc32
GV
1943void
1944x_set_menu_bar_lines (f, value, oldval)
1945 struct frame *f;
1946 Lisp_Object value, oldval;
1947{
1948 int nlines;
1949 int olines = FRAME_MENU_BAR_LINES (f);
1950
1951 /* Right now, menu bars don't work properly in minibuf-only frames;
1952 most of the commands try to apply themselves to the minibuffer
6fc2811b 1953 frame itself, and get an error because you can't switch buffers
ee78dc32
GV
1954 in or split the minibuffer window. */
1955 if (FRAME_MINIBUF_ONLY_P (f))
1956 return;
1957
1958 if (INTEGERP (value))
1959 nlines = XINT (value);
1960 else
1961 nlines = 0;
1962
1963 FRAME_MENU_BAR_LINES (f) = 0;
1964 if (nlines)
1965 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1966 else
1967 {
1968 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1969 free_frame_menubar (f);
1970 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1edf84e7
GV
1971
1972 /* Adjust the frame size so that the client (text) dimensions
1973 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1974 set correctly. */
be786000 1975 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
6fc2811b 1976 do_pending_window_change (0);
ee78dc32 1977 }
6fc2811b
JR
1978 adjust_glyphs (f);
1979}
1980
1981
1982/* Set the number of lines used for the tool bar of frame F to VALUE.
1983 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
1984 is the old number of tool bar lines. This function changes the
1985 height of all windows on frame F to match the new tool bar height.
1986 The frame's height doesn't change. */
1987
1988void
1989x_set_tool_bar_lines (f, value, oldval)
1990 struct frame *f;
1991 Lisp_Object value, oldval;
1992{
36f8209a
JR
1993 int delta, nlines, root_height;
1994 Lisp_Object root_window;
6fc2811b 1995
dc220243
JR
1996 /* Treat tool bars like menu bars. */
1997 if (FRAME_MINIBUF_ONLY_P (f))
1998 return;
1999
6fc2811b
JR
2000 /* Use VALUE only if an integer >= 0. */
2001 if (INTEGERP (value) && XINT (value) >= 0)
2002 nlines = XFASTINT (value);
2003 else
2004 nlines = 0;
2005
2006 /* Make sure we redisplay all windows in this frame. */
2007 ++windows_or_buffers_changed;
2008
2009 delta = nlines - FRAME_TOOL_BAR_LINES (f);
36f8209a
JR
2010
2011 /* Don't resize the tool-bar to more than we have room for. */
2012 root_window = FRAME_ROOT_WINDOW (f);
be786000 2013 root_height = WINDOW_TOTAL_LINES (XWINDOW (root_window));
36f8209a
JR
2014 if (root_height - delta < 1)
2015 {
2016 delta = root_height - 1;
2017 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
2018 }
2019
6fc2811b 2020 FRAME_TOOL_BAR_LINES (f) = nlines;
6d906347 2021 change_window_heights (root_window, delta);
6fc2811b 2022 adjust_glyphs (f);
36f8209a
JR
2023
2024 /* We also have to make sure that the internal border at the top of
2025 the frame, below the menu bar or tool bar, is redrawn when the
2026 tool bar disappears. This is so because the internal border is
2027 below the tool bar if one is displayed, but is below the menu bar
2028 if there isn't a tool bar. The tool bar draws into the area
2029 below the menu bar. */
2030 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
2031 {
2032 updating_frame = f;
2033 clear_frame ();
2034 clear_current_matrices (f);
2035 updating_frame = NULL;
2036 }
2037
2038 /* If the tool bar gets smaller, the internal border below it
2039 has to be cleared. It was formerly part of the display
2040 of the larger tool bar, and updating windows won't clear it. */
2041 if (delta < 0)
2042 {
2043 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
be786000
KS
2044 int width = FRAME_PIXEL_WIDTH (f);
2045 int y = nlines * FRAME_LINE_HEIGHT (f);
36f8209a
JR
2046
2047 BLOCK_INPUT;
2048 {
2049 HDC hdc = get_frame_dc (f);
2050 w32_clear_area (f, hdc, 0, y, width, height);
2051 release_frame_dc (f, hdc);
2052 }
2053 UNBLOCK_INPUT;
3cf3436e
JR
2054
2055 if (WINDOWP (f->tool_bar_window))
2056 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
36f8209a 2057 }
ee78dc32
GV
2058}
2059
6fc2811b 2060
ee78dc32 2061/* Change the name of frame F to NAME. If NAME is nil, set F's name to
fbd6baed 2062 w32_id_name.
ee78dc32
GV
2063
2064 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2065 name; if NAME is a string, set F's name to NAME and set
2066 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2067
2068 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2069 suggesting a new name, which lisp code should override; if
2070 F->explicit_name is set, ignore the new name; otherwise, set it. */
2071
2072void
2073x_set_name (f, name, explicit)
2074 struct frame *f;
2075 Lisp_Object name;
2076 int explicit;
2077{
7d0393cf 2078 /* Make sure that requests from lisp code override requests from
ee78dc32
GV
2079 Emacs redisplay code. */
2080 if (explicit)
2081 {
2082 /* If we're switching from explicit to implicit, we had better
2083 update the mode lines and thereby update the title. */
2084 if (f->explicit_name && NILP (name))
2085 update_mode_lines = 1;
2086
2087 f->explicit_name = ! NILP (name);
2088 }
2089 else if (f->explicit_name)
2090 return;
2091
fbd6baed 2092 /* If NAME is nil, set the name to the w32_id_name. */
ee78dc32
GV
2093 if (NILP (name))
2094 {
2095 /* Check for no change needed in this very common case
2096 before we do any consing. */
fbd6baed 2097 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
d5db4077 2098 SDATA (f->name)))
ee78dc32 2099 return;
fbd6baed 2100 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
ee78dc32
GV
2101 }
2102 else
b7826503 2103 CHECK_STRING (name);
ee78dc32
GV
2104
2105 /* Don't change the name if it's already NAME. */
2106 if (! NILP (Fstring_equal (name, f->name)))
2107 return;
2108
1edf84e7
GV
2109 f->name = name;
2110
2111 /* For setting the frame title, the title parameter should override
2112 the name parameter. */
2113 if (! NILP (f->title))
2114 name = f->title;
2115
fbd6baed 2116 if (FRAME_W32_WINDOW (f))
ee78dc32 2117 {
6fc2811b 2118 if (STRING_MULTIBYTE (name))
dfff8a69 2119 name = ENCODE_SYSTEM (name);
6fc2811b 2120
ee78dc32 2121 BLOCK_INPUT;
d5db4077 2122 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
ee78dc32
GV
2123 UNBLOCK_INPUT;
2124 }
ee78dc32
GV
2125}
2126
2127/* This function should be called when the user's lisp code has
2128 specified a name for the frame; the name will override any set by the
2129 redisplay code. */
2130void
2131x_explicitly_set_name (f, arg, oldval)
2132 FRAME_PTR f;
2133 Lisp_Object arg, oldval;
2134{
2135 x_set_name (f, arg, 1);
2136}
2137
2138/* This function should be called by Emacs redisplay code to set the
2139 name; names set this way will never override names set by the user's
2140 lisp code. */
2141void
2142x_implicitly_set_name (f, arg, oldval)
2143 FRAME_PTR f;
2144 Lisp_Object arg, oldval;
2145{
2146 x_set_name (f, arg, 0);
2147}
1edf84e7
GV
2148\f
2149/* Change the title of frame F to NAME.
2150 If NAME is nil, use the frame name as the title.
2151
2152 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2153 name; if NAME is a string, set F's name to NAME and set
2154 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2155
2156 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2157 suggesting a new name, which lisp code should override; if
2158 F->explicit_name is set, ignore the new name; otherwise, set it. */
ee78dc32 2159
1edf84e7 2160void
6fc2811b 2161x_set_title (f, name, old_name)
1edf84e7 2162 struct frame *f;
6fc2811b 2163 Lisp_Object name, old_name;
1edf84e7
GV
2164{
2165 /* Don't change the title if it's already NAME. */
2166 if (EQ (name, f->title))
2167 return;
2168
2169 update_mode_lines = 1;
2170
2171 f->title = name;
2172
2173 if (NILP (name))
2174 name = f->name;
2175
2176 if (FRAME_W32_WINDOW (f))
2177 {
6fc2811b 2178 if (STRING_MULTIBYTE (name))
dfff8a69 2179 name = ENCODE_SYSTEM (name);
6fc2811b 2180
1edf84e7 2181 BLOCK_INPUT;
d5db4077 2182 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
1edf84e7
GV
2183 UNBLOCK_INPUT;
2184 }
2185}
ee78dc32 2186
ee78dc32 2187
19f093e5 2188void x_set_scroll_bar_default_width (f)
ee78dc32 2189 struct frame *f;
ee78dc32 2190{
be786000 2191 int wid = FRAME_COLUMN_WIDTH (f);
6fc2811b 2192
be786000
KS
2193 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2194 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
2195 wid - 1) / wid;
ee78dc32 2196}
6d906347 2197
ee78dc32 2198\f
7d0393cf 2199/* Subroutines of creating a frame. */
ee78dc32 2200
ee78dc32
GV
2201
2202/* Return the value of parameter PARAM.
2203
2204 First search ALIST, then Vdefault_frame_alist, then the X defaults
2205 database, using ATTRIBUTE as the attribute name and CLASS as its class.
2206
2207 Convert the resource to the type specified by desired_type.
2208
2209 If no default is specified, return Qunbound. If you call
6fc2811b 2210 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
ee78dc32
GV
2211 and don't let it get stored in any Lisp-visible variables! */
2212
2213static Lisp_Object
6fc2811b 2214w32_get_arg (alist, param, attribute, class, type)
ee78dc32
GV
2215 Lisp_Object alist, param;
2216 char *attribute;
2217 char *class;
2218 enum resource_types type;
2219{
6d906347
KS
2220 return x_get_arg (check_x_display_info (Qnil),
2221 alist, param, attribute, class, type);
ee78dc32
GV
2222}
2223
2224\f
c9b2104d
JR
2225Cursor
2226w32_load_cursor (LPCTSTR name)
2227{
2228 /* Try first to load cursor from application resource. */
2229 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle(NULL),
2230 name, IMAGE_CURSOR, 0, 0,
2231 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2232 if (!cursor)
2233 {
2234 /* Then try to load a shared predefined cursor. */
2235 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
2236 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2237 }
2238 return cursor;
2239}
ee78dc32 2240
fbd6baed 2241extern LRESULT CALLBACK w32_wnd_proc ();
ee78dc32 2242
7d0393cf 2243BOOL
fbd6baed 2244w32_init_class (hinst)
ee78dc32
GV
2245 HINSTANCE hinst;
2246{
2247 WNDCLASS wc;
2248
5ac45f98 2249 wc.style = CS_HREDRAW | CS_VREDRAW;
fbd6baed 2250 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
ee78dc32
GV
2251 wc.cbClsExtra = 0;
2252 wc.cbWndExtra = WND_EXTRA_BYTES;
2253 wc.hInstance = hinst;
2254 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
c9b2104d 2255 wc.hCursor = w32_load_cursor (IDC_ARROW);
4587b026 2256 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
ee78dc32
GV
2257 wc.lpszMenuName = NULL;
2258 wc.lpszClassName = EMACS_CLASS;
2259
2260 return (RegisterClass (&wc));
2261}
2262
7d0393cf 2263HWND
fbd6baed 2264w32_createscrollbar (f, bar)
ee78dc32
GV
2265 struct frame *f;
2266 struct scroll_bar * bar;
2267{
2268 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2269 /* Position and size of scroll bar. */
6fc2811b 2270 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
7d0393cf 2271 XINT(bar->top),
6fc2811b
JR
2272 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
2273 XINT(bar->height),
fbd6baed 2274 FRAME_W32_WINDOW (f),
ee78dc32
GV
2275 NULL,
2276 hinst,
2277 NULL));
2278}
2279
7d0393cf 2280void
fbd6baed 2281w32_createwindow (f)
ee78dc32
GV
2282 struct frame *f;
2283{
2284 HWND hwnd;
1edf84e7
GV
2285 RECT rect;
2286
2287 rect.left = rect.top = 0;
be786000
KS
2288 rect.right = FRAME_PIXEL_WIDTH (f);
2289 rect.bottom = FRAME_PIXEL_HEIGHT (f);
7d0393cf 2290
1edf84e7
GV
2291 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2292 FRAME_EXTERNAL_MENU_BAR (f));
7d0393cf 2293
ee78dc32 2294 /* Do first time app init */
7d0393cf 2295
ee78dc32
GV
2296 if (!hprevinst)
2297 {
fbd6baed 2298 w32_init_class (hinst);
ee78dc32 2299 }
7d0393cf 2300
1edf84e7
GV
2301 FRAME_W32_WINDOW (f) = hwnd
2302 = CreateWindow (EMACS_CLASS,
2303 f->namebuf,
9ead1b60 2304 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
be786000
KS
2305 f->left_pos,
2306 f->top_pos,
1edf84e7
GV
2307 rect.right - rect.left,
2308 rect.bottom - rect.top,
2309 NULL,
2310 NULL,
2311 hinst,
2312 NULL);
2313
ee78dc32
GV
2314 if (hwnd)
2315 {
be786000
KS
2316 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2317 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2318 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2319 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->scroll_bar_actual_width);
6fc2811b 2320 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
ee78dc32 2321
cb9e33d4
RS
2322 /* Enable drag-n-drop. */
2323 DragAcceptFiles (hwnd, TRUE);
7d0393cf 2324
5ac45f98
GV
2325 /* Do this to discard the default setting specified by our parent. */
2326 ShowWindow (hwnd, SW_HIDE);
3c190163 2327 }
3c190163
GV
2328}
2329
7d0393cf 2330void
ee78dc32 2331my_post_msg (wmsg, hwnd, msg, wParam, lParam)
fbd6baed 2332 W32Msg * wmsg;
ee78dc32
GV
2333 HWND hwnd;
2334 UINT msg;
2335 WPARAM wParam;
2336 LPARAM lParam;
2337{
2338 wmsg->msg.hwnd = hwnd;
2339 wmsg->msg.message = msg;
2340 wmsg->msg.wParam = wParam;
2341 wmsg->msg.lParam = lParam;
2342 wmsg->msg.time = GetMessageTime ();
2343
2344 post_msg (wmsg);
2345}
2346
e9e23e23 2347/* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
a1a80b40
GV
2348 between left and right keys as advertised. We test for this
2349 support dynamically, and set a flag when the support is absent. If
2350 absent, we keep track of the left and right control and alt keys
2351 ourselves. This is particularly necessary on keyboards that rely
2352 upon the AltGr key, which is represented as having the left control
2353 and right alt keys pressed. For these keyboards, we need to know
2354 when the left alt key has been pressed in addition to the AltGr key
2355 so that we can properly support M-AltGr-key sequences (such as M-@
2356 on Swedish keyboards). */
2357
2358#define EMACS_LCONTROL 0
2359#define EMACS_RCONTROL 1
2360#define EMACS_LMENU 2
2361#define EMACS_RMENU 3
2362
2363static int modifiers[4];
2364static int modifiers_recorded;
2365static int modifier_key_support_tested;
2366
2367static void
2368test_modifier_support (unsigned int wparam)
2369{
2370 unsigned int l, r;
2371
2372 if (wparam != VK_CONTROL && wparam != VK_MENU)
2373 return;
2374 if (wparam == VK_CONTROL)
2375 {
2376 l = VK_LCONTROL;
2377 r = VK_RCONTROL;
2378 }
2379 else
2380 {
2381 l = VK_LMENU;
2382 r = VK_RMENU;
2383 }
2384 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2385 modifiers_recorded = 1;
2386 else
2387 modifiers_recorded = 0;
2388 modifier_key_support_tested = 1;
2389}
2390
2391static void
2392record_keydown (unsigned int wparam, unsigned int lparam)
2393{
2394 int i;
2395
2396 if (!modifier_key_support_tested)
2397 test_modifier_support (wparam);
2398
2399 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2400 return;
2401
2402 if (wparam == VK_CONTROL)
2403 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2404 else
2405 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2406
2407 modifiers[i] = 1;
2408}
2409
2410static void
2411record_keyup (unsigned int wparam, unsigned int lparam)
2412{
2413 int i;
2414
2415 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2416 return;
2417
2418 if (wparam == VK_CONTROL)
2419 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2420 else
2421 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2422
2423 modifiers[i] = 0;
2424}
2425
da36a4d6 2426/* Emacs can lose focus while a modifier key has been pressed. When
7d0393cf 2427 it regains focus, be conservative and clear all modifiers since
da36a4d6
GV
2428 we cannot reconstruct the left and right modifier state. */
2429static void
2430reset_modifiers ()
2431{
8681157a
RS
2432 SHORT ctrl, alt;
2433
adcc3809
GV
2434 if (GetFocus () == NULL)
2435 /* Emacs doesn't have keyboard focus. Do nothing. */
da36a4d6 2436 return;
8681157a
RS
2437
2438 ctrl = GetAsyncKeyState (VK_CONTROL);
2439 alt = GetAsyncKeyState (VK_MENU);
2440
8681157a
RS
2441 if (!(ctrl & 0x08000))
2442 /* Clear any recorded control modifier state. */
2443 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2444
2445 if (!(alt & 0x08000))
2446 /* Clear any recorded alt modifier state. */
2447 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2448
adcc3809
GV
2449 /* Update the state of all modifier keys, because modifiers used in
2450 hot-key combinations can get stuck on if Emacs loses focus as a
2451 result of a hot-key being pressed. */
2452 {
2453 BYTE keystate[256];
2454
2455#define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2456
2457 GetKeyboardState (keystate);
2458 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2459 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2460 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2461 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2462 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2463 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2464 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2465 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2466 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2467 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2468 SetKeyboardState (keystate);
2469 }
da36a4d6
GV
2470}
2471
7830e24b
RS
2472/* Synchronize modifier state with what is reported with the current
2473 keystroke. Even if we cannot distinguish between left and right
2474 modifier keys, we know that, if no modifiers are set, then neither
2475 the left or right modifier should be set. */
2476static void
2477sync_modifiers ()
2478{
2479 if (!modifiers_recorded)
2480 return;
2481
7d0393cf 2482 if (!(GetKeyState (VK_CONTROL) & 0x8000))
7830e24b
RS
2483 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2484
7d0393cf 2485 if (!(GetKeyState (VK_MENU) & 0x8000))
7830e24b
RS
2486 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2487}
2488
a1a80b40
GV
2489static int
2490modifier_set (int vkey)
2491{
ccc2d29c 2492 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
891560d6 2493 return (GetKeyState (vkey) & 0x1);
a1a80b40
GV
2494 if (!modifiers_recorded)
2495 return (GetKeyState (vkey) & 0x8000);
2496
2497 switch (vkey)
2498 {
2499 case VK_LCONTROL:
2500 return modifiers[EMACS_LCONTROL];
2501 case VK_RCONTROL:
2502 return modifiers[EMACS_RCONTROL];
2503 case VK_LMENU:
2504 return modifiers[EMACS_LMENU];
2505 case VK_RMENU:
2506 return modifiers[EMACS_RMENU];
a1a80b40
GV
2507 }
2508 return (GetKeyState (vkey) & 0x8000);
2509}
2510
ccc2d29c
GV
2511/* Convert between the modifier bits W32 uses and the modifier bits
2512 Emacs uses. */
2513
2514unsigned int
2515w32_key_to_modifier (int key)
2516{
2517 Lisp_Object key_mapping;
2518
2519 switch (key)
2520 {
2521 case VK_LWIN:
2522 key_mapping = Vw32_lwindow_modifier;
2523 break;
2524 case VK_RWIN:
2525 key_mapping = Vw32_rwindow_modifier;
2526 break;
2527 case VK_APPS:
2528 key_mapping = Vw32_apps_modifier;
2529 break;
2530 case VK_SCROLL:
2531 key_mapping = Vw32_scroll_lock_modifier;
2532 break;
2533 default:
2534 key_mapping = Qnil;
2535 }
2536
adcc3809
GV
2537 /* NB. This code runs in the input thread, asychronously to the lisp
2538 thread, so we must be careful to ensure access to lisp data is
2539 thread-safe. The following code is safe because the modifier
2540 variable values are updated atomically from lisp and symbols are
2541 not relocated by GC. Also, we don't have to worry about seeing GC
2542 markbits here. */
2543 if (EQ (key_mapping, Qhyper))
ccc2d29c 2544 return hyper_modifier;
adcc3809 2545 if (EQ (key_mapping, Qsuper))
ccc2d29c 2546 return super_modifier;
adcc3809 2547 if (EQ (key_mapping, Qmeta))
ccc2d29c 2548 return meta_modifier;
adcc3809 2549 if (EQ (key_mapping, Qalt))
ccc2d29c 2550 return alt_modifier;
adcc3809 2551 if (EQ (key_mapping, Qctrl))
ccc2d29c 2552 return ctrl_modifier;
adcc3809 2553 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
ccc2d29c 2554 return ctrl_modifier;
adcc3809 2555 if (EQ (key_mapping, Qshift))
ccc2d29c
GV
2556 return shift_modifier;
2557
2558 /* Don't generate any modifier if not explicitly requested. */
2559 return 0;
2560}
2561
2562unsigned int
2563w32_get_modifiers ()
2564{
2565 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2566 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2567 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2568 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2569 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2570 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2571 (modifier_set (VK_MENU) ?
2572 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2573}
2574
a1a80b40
GV
2575/* We map the VK_* modifiers into console modifier constants
2576 so that we can use the same routines to handle both console
2577 and window input. */
2578
2579static int
ccc2d29c 2580construct_console_modifiers ()
a1a80b40
GV
2581{
2582 int mods;
2583
a1a80b40
GV
2584 mods = 0;
2585 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2586 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
ccc2d29c
GV
2587 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2588 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
a1a80b40
GV
2589 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2590 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2591 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2592 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
ccc2d29c
GV
2593 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2594 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2595 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
a1a80b40
GV
2596
2597 return mods;
2598}
2599
ccc2d29c
GV
2600static int
2601w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
da36a4d6 2602{
ccc2d29c
GV
2603 int mods;
2604
2605 /* Convert to emacs modifiers. */
2606 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2607
2608 return mods;
2609}
da36a4d6 2610
ccc2d29c
GV
2611unsigned int
2612map_keypad_keys (unsigned int virt_key, unsigned int extended)
2613{
2614 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2615 return virt_key;
da36a4d6 2616
ccc2d29c 2617 if (virt_key == VK_RETURN)
da36a4d6
GV
2618 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2619
ccc2d29c
GV
2620 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2621 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2622
2623 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2624 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2625
2626 if (virt_key == VK_CLEAR)
2627 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2628
2629 return virt_key;
2630}
2631
2632/* List of special key combinations which w32 would normally capture,
2633 but emacs should grab instead. Not directly visible to lisp, to
2634 simplify synchronization. Each item is an integer encoding a virtual
2635 key code and modifier combination to capture. */
2636Lisp_Object w32_grabbed_keys;
2637
2638#define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
2639#define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2640#define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2641#define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2642
2643/* Register hot-keys for reserved key combinations when Emacs has
2644 keyboard focus, since this is the only way Emacs can receive key
2645 combinations like Alt-Tab which are used by the system. */
2646
2647static void
2648register_hot_keys (hwnd)
2649 HWND hwnd;
2650{
2651 Lisp_Object keylist;
2652
2653 /* Use GC_CONSP, since we are called asynchronously. */
2654 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2655 {
2656 Lisp_Object key = XCAR (keylist);
2657
2658 /* Deleted entries get set to nil. */
2659 if (!INTEGERP (key))
2660 continue;
2661
2662 RegisterHotKey (hwnd, HOTKEY_ID (key),
2663 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2664 }
2665}
2666
2667static void
2668unregister_hot_keys (hwnd)
2669 HWND hwnd;
2670{
2671 Lisp_Object keylist;
2672
2673 /* Use GC_CONSP, since we are called asynchronously. */
2674 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2675 {
2676 Lisp_Object key = XCAR (keylist);
2677
2678 if (!INTEGERP (key))
2679 continue;
2680
2681 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2682 }
2683}
2684
5ac45f98
GV
2685/* Main message dispatch loop. */
2686
1edf84e7
GV
2687static void
2688w32_msg_pump (deferred_msg * msg_buf)
5ac45f98
GV
2689{
2690 MSG msg;
ccc2d29c
GV
2691 int result;
2692 HWND focus_window;
93fbe8b7
GV
2693
2694 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
7d0393cf 2695
5ac45f98
GV
2696 while (GetMessage (&msg, NULL, 0, 0))
2697 {
2698 if (msg.hwnd == NULL)
2699 {
2700 switch (msg.message)
2701 {
3ef68e6b
AI
2702 case WM_NULL:
2703 /* Produced by complete_deferred_msg; just ignore. */
2704 break;
5ac45f98 2705 case WM_EMACS_CREATEWINDOW:
fbd6baed 2706 w32_createwindow ((struct frame *) msg.wParam);
1edf84e7
GV
2707 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2708 abort ();
5ac45f98 2709 break;
dfdb4047
GV
2710 case WM_EMACS_SETLOCALE:
2711 SetThreadLocale (msg.wParam);
2712 /* Reply is not expected. */
2713 break;
ccc2d29c
GV
2714 case WM_EMACS_SETKEYBOARDLAYOUT:
2715 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2716 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2717 result, 0))
2718 abort ();
2719 break;
2720 case WM_EMACS_REGISTER_HOT_KEY:
2721 focus_window = GetFocus ();
2722 if (focus_window != NULL)
2723 RegisterHotKey (focus_window,
2724 HOTKEY_ID (msg.wParam),
2725 HOTKEY_MODIFIERS (msg.wParam),
2726 HOTKEY_VK_CODE (msg.wParam));
2727 /* Reply is not expected. */
2728 break;
2729 case WM_EMACS_UNREGISTER_HOT_KEY:
2730 focus_window = GetFocus ();
2731 if (focus_window != NULL)
2732 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
adcc3809
GV
2733 /* Mark item as erased. NB: this code must be
2734 thread-safe. The next line is okay because the cons
2735 cell is never made into garbage and is not relocated by
2736 GC. */
f3fbd155 2737 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
ccc2d29c
GV
2738 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2739 abort ();
2740 break;
adcc3809
GV
2741 case WM_EMACS_TOGGLE_LOCK_KEY:
2742 {
2743 int vk_code = (int) msg.wParam;
2744 int cur_state = (GetKeyState (vk_code) & 1);
2745 Lisp_Object new_state = (Lisp_Object) msg.lParam;
2746
2747 /* NB: This code must be thread-safe. It is safe to
2748 call NILP because symbols are not relocated by GC,
2749 and pointer here is not touched by GC (so the markbit
2750 can't be set). Numbers are safe because they are
2751 immediate values. */
2752 if (NILP (new_state)
2753 || (NUMBERP (new_state)
8edb0a6f 2754 && ((XUINT (new_state)) & 1) != cur_state))
adcc3809
GV
2755 {
2756 one_w32_display_info.faked_key = vk_code;
2757
2758 keybd_event ((BYTE) vk_code,
2759 (BYTE) MapVirtualKey (vk_code, 0),
2760 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2761 keybd_event ((BYTE) vk_code,
2762 (BYTE) MapVirtualKey (vk_code, 0),
2763 KEYEVENTF_EXTENDEDKEY | 0, 0);
2764 keybd_event ((BYTE) vk_code,
2765 (BYTE) MapVirtualKey (vk_code, 0),
2766 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2767 cur_state = !cur_state;
2768 }
2769 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2770 cur_state, 0))
2771 abort ();
2772 }
2773 break;
1edf84e7 2774 default:
1edf84e7 2775 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
5ac45f98
GV
2776 }
2777 }
2778 else
2779 {
2780 DispatchMessage (&msg);
2781 }
1edf84e7
GV
2782
2783 /* Exit nested loop when our deferred message has completed. */
2784 if (msg_buf->completed)
2785 break;
5ac45f98 2786 }
1edf84e7
GV
2787}
2788
2789deferred_msg * deferred_msg_head;
2790
2791static deferred_msg *
2792find_deferred_msg (HWND hwnd, UINT msg)
2793{
2794 deferred_msg * item;
2795
2796 /* Don't actually need synchronization for read access, since
2797 modification of single pointer is always atomic. */
2798 /* enter_crit (); */
2799
2800 for (item = deferred_msg_head; item != NULL; item = item->next)
2801 if (item->w32msg.msg.hwnd == hwnd
2802 && item->w32msg.msg.message == msg)
2803 break;
2804
2805 /* leave_crit (); */
2806
2807 return item;
2808}
2809
2810static LRESULT
2811send_deferred_msg (deferred_msg * msg_buf,
2812 HWND hwnd,
2813 UINT msg,
2814 WPARAM wParam,
2815 LPARAM lParam)
2816{
2817 /* Only input thread can send deferred messages. */
2818 if (GetCurrentThreadId () != dwWindowsThreadId)
2819 abort ();
2820
2821 /* It is an error to send a message that is already deferred. */
2822 if (find_deferred_msg (hwnd, msg) != NULL)
2823 abort ();
2824
2825 /* Enforced synchronization is not needed because this is the only
2826 function that alters deferred_msg_head, and the following critical
2827 section is guaranteed to only be serially reentered (since only the
2828 input thread can call us). */
2829
2830 /* enter_crit (); */
2831
2832 msg_buf->completed = 0;
2833 msg_buf->next = deferred_msg_head;
2834 deferred_msg_head = msg_buf;
2835 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2836
2837 /* leave_crit (); */
2838
2839 /* Start a new nested message loop to process other messages until
2840 this one is completed. */
2841 w32_msg_pump (msg_buf);
2842
2843 deferred_msg_head = msg_buf->next;
2844
2845 return msg_buf->result;
2846}
2847
2848void
2849complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2850{
2851 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2852
2853 if (msg_buf == NULL)
3ef68e6b
AI
2854 /* Message may have been cancelled, so don't abort(). */
2855 return;
1edf84e7
GV
2856
2857 msg_buf->result = result;
2858 msg_buf->completed = 1;
2859
2860 /* Ensure input thread is woken so it notices the completion. */
2861 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2862}
2863
3ef68e6b
AI
2864void
2865cancel_all_deferred_msgs ()
2866{
2867 deferred_msg * item;
2868
2869 /* Don't actually need synchronization for read access, since
2870 modification of single pointer is always atomic. */
2871 /* enter_crit (); */
2872
2873 for (item = deferred_msg_head; item != NULL; item = item->next)
2874 {
2875 item->result = 0;
2876 item->completed = 1;
2877 }
2878
2879 /* leave_crit (); */
2880
2881 /* Ensure input thread is woken so it notices the completion. */
2882 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2883}
1edf84e7 2884
7d0393cf 2885DWORD
1edf84e7
GV
2886w32_msg_worker (dw)
2887 DWORD dw;
2888{
2889 MSG msg;
2890 deferred_msg dummy_buf;
2891
2892 /* Ensure our message queue is created */
7d0393cf 2893
1edf84e7 2894 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
7d0393cf 2895
1edf84e7
GV
2896 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2897 abort ();
2898
2899 memset (&dummy_buf, 0, sizeof (dummy_buf));
2900 dummy_buf.w32msg.msg.hwnd = NULL;
2901 dummy_buf.w32msg.msg.message = WM_NULL;
2902
2903 /* This is the inital message loop which should only exit when the
2904 application quits. */
2905 w32_msg_pump (&dummy_buf);
2906
2907 return 0;
5ac45f98
GV
2908}
2909
3ef68e6b
AI
2910static void
2911post_character_message (hwnd, msg, wParam, lParam, modifiers)
2912 HWND hwnd;
2913 UINT msg;
2914 WPARAM wParam;
2915 LPARAM lParam;
2916 DWORD modifiers;
2917
2918{
2919 W32Msg wmsg;
2920
2921 wmsg.dwModifiers = modifiers;
2922
2923 /* Detect quit_char and set quit-flag directly. Note that we
2924 still need to post a message to ensure the main thread will be
2925 woken up if blocked in sys_select(), but we do NOT want to post
2926 the quit_char message itself (because it will usually be as if
2927 the user had typed quit_char twice). Instead, we post a dummy
2928 message that has no particular effect. */
2929 {
2930 int c = wParam;
2931 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2932 c = make_ctrl_char (c) & 0377;
7d081355
AI
2933 if (c == quit_char
2934 || (wmsg.dwModifiers == 0 &&
2935 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
3ef68e6b
AI
2936 {
2937 Vquit_flag = Qt;
2938
2939 /* The choice of message is somewhat arbitrary, as long as
2940 the main thread handler just ignores it. */
2941 msg = WM_NULL;
2942
2943 /* Interrupt any blocking system calls. */
2944 signal_quit ();
2945
2946 /* As a safety precaution, forcibly complete any deferred
2947 messages. This is a kludge, but I don't see any particularly
2948 clean way to handle the situation where a deferred message is
2949 "dropped" in the lisp thread, and will thus never be
2950 completed, eg. by the user trying to activate the menubar
2951 when the lisp thread is busy, and then typing C-g when the
2952 menubar doesn't open promptly (with the result that the
2953 menubar never responds at all because the deferred
2954 WM_INITMENU message is never completed). Another problem
2955 situation is when the lisp thread calls SendMessage (to send
2956 a window manager command) when a message has been deferred;
2957 the lisp thread gets blocked indefinitely waiting for the
2958 deferred message to be completed, which itself is waiting for
2959 the lisp thread to respond.
2960
2961 Note that we don't want to block the input thread waiting for
2962 a reponse from the lisp thread (although that would at least
2963 solve the deadlock problem above), because we want to be able
2964 to receive C-g to interrupt the lisp thread. */
2965 cancel_all_deferred_msgs ();
2966 }
2967 }
2968
2969 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2970}
2971
ee78dc32
GV
2972/* Main window procedure */
2973
7d0393cf 2974LRESULT CALLBACK
fbd6baed 2975w32_wnd_proc (hwnd, msg, wParam, lParam)
ee78dc32
GV
2976 HWND hwnd;
2977 UINT msg;
2978 WPARAM wParam;
2979 LPARAM lParam;
2980{
2981 struct frame *f;
fbd6baed
GV
2982 struct w32_display_info *dpyinfo = &one_w32_display_info;
2983 W32Msg wmsg;
84fb1139 2984 int windows_translate;
576ba81c 2985 int key;
84fb1139 2986
a6085637
KH
2987 /* Note that it is okay to call x_window_to_frame, even though we are
2988 not running in the main lisp thread, because frame deletion
2989 requires the lisp thread to synchronize with this thread. Thus, if
2990 a frame struct is returned, it can be used without concern that the
2991 lisp thread might make it disappear while we are using it.
2992
2993 NB. Walking the frame list in this thread is safe (as long as
2994 writes of Lisp_Object slots are atomic, which they are on Windows).
2995 Although delete-frame can destructively modify the frame list while
2996 we are walking it, a garbage collection cannot occur until after
2997 delete-frame has synchronized with this thread.
2998
2999 It is also safe to use functions that make GDI calls, such as
fbd6baed 3000 w32_clear_rect, because these functions must obtain a DC handle
a6085637
KH
3001 from the frame struct using get_frame_dc which is thread-aware. */
3002
7d0393cf 3003 switch (msg)
ee78dc32
GV
3004 {
3005 case WM_ERASEBKGND:
a6085637
KH
3006 f = x_window_to_frame (dpyinfo, hwnd);
3007 if (f)
3008 {
9badad41 3009 HDC hdc = get_frame_dc (f);
a6085637 3010 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
9badad41
JR
3011 w32_clear_rect (f, hdc, &wmsg.rect);
3012 release_frame_dc (f, hdc);
ce6059da
AI
3013
3014#if defined (W32_DEBUG_DISPLAY)
18f0b342
AI
3015 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
3016 f,
3017 wmsg.rect.left, wmsg.rect.top,
3018 wmsg.rect.right, wmsg.rect.bottom));
ce6059da 3019#endif /* W32_DEBUG_DISPLAY */
a6085637 3020 }
5ac45f98
GV
3021 return 1;
3022 case WM_PALETTECHANGED:
3023 /* ignore our own changes */
3024 if ((HWND)wParam != hwnd)
3025 {
a6085637
KH
3026 f = x_window_to_frame (dpyinfo, hwnd);
3027 if (f)
3028 /* get_frame_dc will realize our palette and force all
3029 frames to be redrawn if needed. */
3030 release_frame_dc (f, get_frame_dc (f));
5ac45f98
GV
3031 }
3032 return 0;
ee78dc32 3033 case WM_PAINT:
ce6059da 3034 {
55dcfc15
AI
3035 PAINTSTRUCT paintStruct;
3036 RECT update_rect;
aa35b6ad 3037 bzero (&update_rect, sizeof (update_rect));
55dcfc15 3038
18f0b342
AI
3039 f = x_window_to_frame (dpyinfo, hwnd);
3040 if (f == 0)
3041 {
3042 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
3043 return 0;
3044 }
3045
55dcfc15
AI
3046 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
3047 fails. Apparently this can happen under some
3048 circumstances. */
aa35b6ad 3049 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
55dcfc15
AI
3050 {
3051 enter_crit ();
3052 BeginPaint (hwnd, &paintStruct);
3053
aa35b6ad
JR
3054 /* The rectangles returned by GetUpdateRect and BeginPaint
3055 do not always match. Play it safe by assuming both areas
3056 are invalid. */
3057 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
55dcfc15
AI
3058
3059#if defined (W32_DEBUG_DISPLAY)
18f0b342
AI
3060 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
3061 f,
3062 wmsg.rect.left, wmsg.rect.top,
3063 wmsg.rect.right, wmsg.rect.bottom));
3064 DebPrint ((" [update region is %d,%d-%d,%d]\n",
55dcfc15
AI
3065 update_rect.left, update_rect.top,
3066 update_rect.right, update_rect.bottom));
3067#endif
3068 EndPaint (hwnd, &paintStruct);
3069 leave_crit ();
3070
3071 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
7d0393cf 3072
55dcfc15
AI
3073 return 0;
3074 }
c0611964
AI
3075
3076 /* If GetUpdateRect returns 0 (meaning there is no update
3077 region), assume the whole window needs to be repainted. */
3078 GetClientRect(hwnd, &wmsg.rect);
3079 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3080 return 0;
ee78dc32 3081 }
a1a80b40 3082
ccc2d29c
GV
3083 case WM_INPUTLANGCHANGE:
3084 /* Inform lisp thread of keyboard layout changes. */
3085 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3086
3087 /* Clear dead keys in the keyboard state; for simplicity only
3088 preserve modifier key states. */
3089 {
3090 int i;
3091 BYTE keystate[256];
3092
3093 GetKeyboardState (keystate);
3094 for (i = 0; i < 256; i++)
3095 if (1
3096 && i != VK_SHIFT
3097 && i != VK_LSHIFT
3098 && i != VK_RSHIFT
3099 && i != VK_CAPITAL
3100 && i != VK_NUMLOCK
3101 && i != VK_SCROLL
3102 && i != VK_CONTROL
3103 && i != VK_LCONTROL
3104 && i != VK_RCONTROL
3105 && i != VK_MENU
3106 && i != VK_LMENU
3107 && i != VK_RMENU
3108 && i != VK_LWIN
3109 && i != VK_RWIN)
3110 keystate[i] = 0;
3111 SetKeyboardState (keystate);
3112 }
3113 goto dflt;
3114
3115 case WM_HOTKEY:
3116 /* Synchronize hot keys with normal input. */
3117 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3118 return (0);
3119
a1a80b40
GV
3120 case WM_KEYUP:
3121 case WM_SYSKEYUP:
3122 record_keyup (wParam, lParam);
3123 goto dflt;
3124
ee78dc32
GV
3125 case WM_KEYDOWN:
3126 case WM_SYSKEYDOWN:
ccc2d29c
GV
3127 /* Ignore keystrokes we fake ourself; see below. */
3128 if (dpyinfo->faked_key == wParam)
3129 {
3130 dpyinfo->faked_key = 0;
576ba81c
AI
3131 /* Make sure TranslateMessage sees them though (as long as
3132 they don't produce WM_CHAR messages). This ensures that
3133 indicator lights are toggled promptly on Windows 9x, for
3134 example. */
3135 if (lispy_function_keys[wParam] != 0)
3136 {
3137 windows_translate = 1;
3138 goto translate;
3139 }
3140 return 0;
ccc2d29c
GV
3141 }
3142
7830e24b
RS
3143 /* Synchronize modifiers with current keystroke. */
3144 sync_modifiers ();
a1a80b40 3145 record_keydown (wParam, lParam);
ccc2d29c 3146 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
84fb1139
KH
3147
3148 windows_translate = 0;
ccc2d29c
GV
3149
3150 switch (wParam)
3151 {
3152 case VK_LWIN:
3153 if (NILP (Vw32_pass_lwindow_to_system))
3154 {
3155 /* Prevent system from acting on keyup (which opens the
3156 Start menu if no other key was pressed) by simulating a
3157 press of Space which we will ignore. */
3158 if (GetAsyncKeyState (wParam) & 1)
3159 {
adcc3809 3160 if (NUMBERP (Vw32_phantom_key_code))
576ba81c 3161 key = XUINT (Vw32_phantom_key_code) & 255;
adcc3809 3162 else
576ba81c
AI
3163 key = VK_SPACE;
3164 dpyinfo->faked_key = key;
3165 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
ccc2d29c
GV
3166 }
3167 }
3168 if (!NILP (Vw32_lwindow_modifier))
3169 return 0;
3170 break;
3171 case VK_RWIN:
3172 if (NILP (Vw32_pass_rwindow_to_system))
3173 {
3174 if (GetAsyncKeyState (wParam) & 1)
3175 {
adcc3809 3176 if (NUMBERP (Vw32_phantom_key_code))
576ba81c 3177 key = XUINT (Vw32_phantom_key_code) & 255;
adcc3809 3178 else
576ba81c
AI
3179 key = VK_SPACE;
3180 dpyinfo->faked_key = key;
3181 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
ccc2d29c
GV
3182 }
3183 }
3184 if (!NILP (Vw32_rwindow_modifier))
3185 return 0;
3186 break;
576ba81c 3187 case VK_APPS:
ccc2d29c
GV
3188 if (!NILP (Vw32_apps_modifier))
3189 return 0;
3190 break;
3191 case VK_MENU:
7d0393cf 3192 if (NILP (Vw32_pass_alt_to_system))
adcc3809
GV
3193 /* Prevent DefWindowProc from activating the menu bar if an
3194 Alt key is pressed and released by itself. */
ccc2d29c 3195 return 0;
84fb1139 3196 windows_translate = 1;
ccc2d29c 3197 break;
7d0393cf 3198 case VK_CAPITAL:
ccc2d29c
GV
3199 /* Decide whether to treat as modifier or function key. */
3200 if (NILP (Vw32_enable_caps_lock))
3201 goto disable_lock_key;
adcc3809
GV
3202 windows_translate = 1;
3203 break;
ccc2d29c
GV
3204 case VK_NUMLOCK:
3205 /* Decide whether to treat as modifier or function key. */
3206 if (NILP (Vw32_enable_num_lock))
3207 goto disable_lock_key;
adcc3809
GV
3208 windows_translate = 1;
3209 break;
ccc2d29c
GV
3210 case VK_SCROLL:
3211 /* Decide whether to treat as modifier or function key. */
3212 if (NILP (Vw32_scroll_lock_modifier))
3213 goto disable_lock_key;
adcc3809
GV
3214 windows_translate = 1;
3215 break;
ccc2d29c 3216 disable_lock_key:
adcc3809
GV
3217 /* Ensure the appropriate lock key state (and indicator light)
3218 remains in the same state. We do this by faking another
3219 press of the relevant key. Apparently, this really is the
3220 only way to toggle the state of the indicator lights. */
3221 dpyinfo->faked_key = wParam;
3222 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3223 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3224 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3225 KEYEVENTF_EXTENDEDKEY | 0, 0);
3226 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3227 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3228 /* Ensure indicator lights are updated promptly on Windows 9x
3229 (TranslateMessage apparently does this), after forwarding
3230 input event. */
3231 post_character_message (hwnd, msg, wParam, lParam,
3232 w32_get_key_modifiers (wParam, lParam));
3233 windows_translate = 1;
ccc2d29c 3234 break;
7d0393cf 3235 case VK_CONTROL:
ccc2d29c
GV
3236 case VK_SHIFT:
3237 case VK_PROCESSKEY: /* Generated by IME. */
3238 windows_translate = 1;
3239 break;
adcc3809
GV
3240 case VK_CANCEL:
3241 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3242 which is confusing for purposes of key binding; convert
3243 VK_CANCEL events into VK_PAUSE events. */
3244 wParam = VK_PAUSE;
3245 break;
3246 case VK_PAUSE:
3247 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3248 for purposes of key binding; convert these back into
3249 VK_NUMLOCK events, at least when we want to see NumLock key
3250 presses. (Note that there is never any possibility that
3251 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3252 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3253 wParam = VK_NUMLOCK;
3254 break;
ccc2d29c
GV
3255 default:
3256 /* If not defined as a function key, change it to a WM_CHAR message. */
3257 if (lispy_function_keys[wParam] == 0)
3258 {
adcc3809
GV
3259 DWORD modifiers = construct_console_modifiers ();
3260
ccc2d29c
GV
3261 if (!NILP (Vw32_recognize_altgr)
3262 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3263 {
3264 /* Always let TranslateMessage handle AltGr key chords;
3265 for some reason, ToAscii doesn't always process AltGr
3266 chords correctly. */
3267 windows_translate = 1;
3268 }
adcc3809 3269 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
ccc2d29c 3270 {
adcc3809
GV
3271 /* Handle key chords including any modifiers other
3272 than shift directly, in order to preserve as much
3273 modifier information as possible. */
ccc2d29c
GV
3274 if ('A' <= wParam && wParam <= 'Z')
3275 {
3276 /* Don't translate modified alphabetic keystrokes,
3277 so the user doesn't need to constantly switch
3278 layout to type control or meta keystrokes when
3279 the normal layout translates alphabetic
3280 characters to non-ascii characters. */
3281 if (!modifier_set (VK_SHIFT))
3282 wParam += ('a' - 'A');
3283 msg = WM_CHAR;
3284 }
3285 else
3286 {
3287 /* Try to handle other keystrokes by determining the
3288 base character (ie. translating the base key plus
3289 shift modifier). */
3290 int add;
3291 int isdead = 0;
3292 KEY_EVENT_RECORD key;
7d0393cf 3293
ccc2d29c
GV
3294 key.bKeyDown = TRUE;
3295 key.wRepeatCount = 1;
3296 key.wVirtualKeyCode = wParam;
3297 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3298 key.uChar.AsciiChar = 0;
adcc3809 3299 key.dwControlKeyState = modifiers;
ccc2d29c
GV
3300
3301 add = w32_kbd_patch_key (&key);
3302 /* 0 means an unrecognised keycode, negative means
3303 dead key. Ignore both. */
3304 while (--add >= 0)
3305 {
3306 /* Forward asciified character sequence. */
3307 post_character_message
3308 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
3309 w32_get_key_modifiers (wParam, lParam));
3310 w32_kbd_patch_key (&key);
3311 }
3312 return 0;
3313 }
3314 }
3315 else
3316 {
3317 /* Let TranslateMessage handle everything else. */
3318 windows_translate = 1;
3319 }
3320 }
3321 }
a1a80b40 3322
adcc3809 3323 translate:
84fb1139
KH
3324 if (windows_translate)
3325 {
e9e23e23 3326 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
84fb1139 3327
e9e23e23
GV
3328 windows_msg.time = GetMessageTime ();
3329 TranslateMessage (&windows_msg);
84fb1139
KH
3330 goto dflt;
3331 }
3332
ee78dc32 3333 /* Fall through */
7d0393cf 3334
ee78dc32
GV
3335 case WM_SYSCHAR:
3336 case WM_CHAR:
ccc2d29c
GV
3337 post_character_message (hwnd, msg, wParam, lParam,
3338 w32_get_key_modifiers (wParam, lParam));
ee78dc32 3339 break;
da36a4d6 3340
5ac45f98
GV
3341 /* Simulate middle mouse button events when left and right buttons
3342 are used together, but only if user has two button mouse. */
ee78dc32 3343 case WM_LBUTTONDOWN:
5ac45f98 3344 case WM_RBUTTONDOWN:
7ce9aaca 3345 if (XINT (Vw32_num_mouse_buttons) > 2)
5ac45f98
GV
3346 goto handle_plain_button;
3347
3348 {
3349 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3350 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3351
3cb20f4a
RS
3352 if (button_state & this)
3353 return 0;
5ac45f98
GV
3354
3355 if (button_state == 0)
3356 SetCapture (hwnd);
3357
3358 button_state |= this;
3359
3360 if (button_state & other)
3361 {
84fb1139 3362 if (mouse_button_timer)
5ac45f98 3363 {
84fb1139
KH
3364 KillTimer (hwnd, mouse_button_timer);
3365 mouse_button_timer = 0;
5ac45f98
GV
3366
3367 /* Generate middle mouse event instead. */
3368 msg = WM_MBUTTONDOWN;
3369 button_state |= MMOUSE;
3370 }
3371 else if (button_state & MMOUSE)
3372 {
3373 /* Ignore button event if we've already generated a
3374 middle mouse down event. This happens if the
3375 user releases and press one of the two buttons
3376 after we've faked a middle mouse event. */
3377 return 0;
3378 }
3379 else
3380 {
3381 /* Flush out saved message. */
84fb1139 3382 post_msg (&saved_mouse_button_msg);
5ac45f98 3383 }
fbd6baed 3384 wmsg.dwModifiers = w32_get_modifiers ();
5ac45f98
GV
3385 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3386
3387 /* Clear message buffer. */
84fb1139 3388 saved_mouse_button_msg.msg.hwnd = 0;
5ac45f98
GV
3389 }
3390 else
3391 {
3392 /* Hold onto message for now. */
84fb1139 3393 mouse_button_timer =
adcc3809
GV
3394 SetTimer (hwnd, MOUSE_BUTTON_ID,
3395 XINT (Vw32_mouse_button_tolerance), NULL);
84fb1139
KH
3396 saved_mouse_button_msg.msg.hwnd = hwnd;
3397 saved_mouse_button_msg.msg.message = msg;
3398 saved_mouse_button_msg.msg.wParam = wParam;
3399 saved_mouse_button_msg.msg.lParam = lParam;
3400 saved_mouse_button_msg.msg.time = GetMessageTime ();
fbd6baed 3401 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
5ac45f98
GV
3402 }
3403 }
3404 return 0;
3405
ee78dc32 3406 case WM_LBUTTONUP:
5ac45f98 3407 case WM_RBUTTONUP:
7ce9aaca 3408 if (XINT (Vw32_num_mouse_buttons) > 2)
5ac45f98
GV
3409 goto handle_plain_button;
3410
3411 {
3412 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3413 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3414
3cb20f4a
RS
3415 if ((button_state & this) == 0)
3416 return 0;
5ac45f98
GV
3417
3418 button_state &= ~this;
3419
3420 if (button_state & MMOUSE)
3421 {
3422 /* Only generate event when second button is released. */
3423 if ((button_state & other) == 0)
3424 {
3425 msg = WM_MBUTTONUP;
3426 button_state &= ~MMOUSE;
3427
3428 if (button_state) abort ();
3429 }
3430 else
3431 return 0;
3432 }
3433 else
3434 {
3435 /* Flush out saved message if necessary. */
84fb1139 3436 if (saved_mouse_button_msg.msg.hwnd)
5ac45f98 3437 {
84fb1139 3438 post_msg (&saved_mouse_button_msg);
5ac45f98
GV
3439 }
3440 }
fbd6baed 3441 wmsg.dwModifiers = w32_get_modifiers ();
5ac45f98
GV
3442 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3443
3444 /* Always clear message buffer and cancel timer. */
84fb1139
KH
3445 saved_mouse_button_msg.msg.hwnd = 0;
3446 KillTimer (hwnd, mouse_button_timer);
3447 mouse_button_timer = 0;
5ac45f98
GV
3448
3449 if (button_state == 0)
3450 ReleaseCapture ();
3451 }
3452 return 0;
3453
74214547
JR
3454 case WM_XBUTTONDOWN:
3455 case WM_XBUTTONUP:
3456 if (w32_pass_extra_mouse_buttons_to_system)
3457 goto dflt;
3458 /* else fall through and process them. */
ee78dc32
GV
3459 case WM_MBUTTONDOWN:
3460 case WM_MBUTTONUP:
5ac45f98 3461 handle_plain_button:
ee78dc32
GV
3462 {
3463 BOOL up;
1edf84e7 3464 int button;
ee78dc32 3465
74214547 3466 if (parse_button (msg, HIWORD (wParam), &button, &up))
ee78dc32
GV
3467 {
3468 if (up) ReleaseCapture ();
3469 else SetCapture (hwnd);
7d0393cf 3470 button = (button == 0) ? LMOUSE :
1edf84e7
GV
3471 ((button == 1) ? MMOUSE : RMOUSE);
3472 if (up)
3473 button_state &= ~button;
3474 else
3475 button_state |= button;
ee78dc32
GV
3476 }
3477 }
7d0393cf 3478
fbd6baed 3479 wmsg.dwModifiers = w32_get_modifiers ();
ee78dc32 3480 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
74214547
JR
3481
3482 /* Need to return true for XBUTTON messages, false for others,
3483 to indicate that we processed the message. */
3484 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
5ac45f98 3485
5ac45f98 3486 case WM_MOUSEMOVE:
9eb16b62
JR
3487 /* If the mouse has just moved into the frame, start tracking
3488 it, so we will be notified when it leaves the frame. Mouse
3489 tracking only works under W98 and NT4 and later. On earlier
3490 versions, there is no way of telling when the mouse leaves the
3491 frame, so we just have to put up with help-echo and mouse
3492 highlighting remaining while the frame is not active. */
3493 if (track_mouse_event_fn && !track_mouse_window)
3494 {
3495 TRACKMOUSEEVENT tme;
3496 tme.cbSize = sizeof (tme);
3497 tme.dwFlags = TME_LEAVE;
3498 tme.hwndTrack = hwnd;
3499
3500 track_mouse_event_fn (&tme);
3501 track_mouse_window = hwnd;
3502 }
3503 case WM_VSCROLL:
fbd6baed 3504 if (XINT (Vw32_mouse_move_interval) <= 0
84fb1139
KH
3505 || (msg == WM_MOUSEMOVE && button_state == 0))
3506 {
fbd6baed 3507 wmsg.dwModifiers = w32_get_modifiers ();
84fb1139
KH
3508 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3509 return 0;
3510 }
7d0393cf 3511
84fb1139
KH
3512 /* Hang onto mouse move and scroll messages for a bit, to avoid
3513 sending such events to Emacs faster than it can process them.
3514 If we get more events before the timer from the first message
3515 expires, we just replace the first message. */
3516
3517 if (saved_mouse_move_msg.msg.hwnd == 0)
3518 mouse_move_timer =
adcc3809
GV
3519 SetTimer (hwnd, MOUSE_MOVE_ID,
3520 XINT (Vw32_mouse_move_interval), NULL);
84fb1139
KH
3521
3522 /* Hold onto message for now. */
3523 saved_mouse_move_msg.msg.hwnd = hwnd;
3524 saved_mouse_move_msg.msg.message = msg;
3525 saved_mouse_move_msg.msg.wParam = wParam;
3526 saved_mouse_move_msg.msg.lParam = lParam;
3527 saved_mouse_move_msg.msg.time = GetMessageTime ();
fbd6baed 3528 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
7d0393cf 3529
84fb1139
KH
3530 return 0;
3531
1edf84e7
GV
3532 case WM_MOUSEWHEEL:
3533 wmsg.dwModifiers = w32_get_modifiers ();
3534 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3535 return 0;
3536
cb9e33d4
RS
3537 case WM_DROPFILES:
3538 wmsg.dwModifiers = w32_get_modifiers ();
3539 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3540 return 0;
3541
84fb1139
KH
3542 case WM_TIMER:
3543 /* Flush out saved messages if necessary. */
3544 if (wParam == mouse_button_timer)
5ac45f98 3545 {
84fb1139
KH
3546 if (saved_mouse_button_msg.msg.hwnd)
3547 {
3548 post_msg (&saved_mouse_button_msg);
3549 saved_mouse_button_msg.msg.hwnd = 0;
3550 }
3551 KillTimer (hwnd, mouse_button_timer);
3552 mouse_button_timer = 0;
3553 }
3554 else if (wParam == mouse_move_timer)
3555 {
3556 if (saved_mouse_move_msg.msg.hwnd)
3557 {
3558 post_msg (&saved_mouse_move_msg);
3559 saved_mouse_move_msg.msg.hwnd = 0;
3560 }
3561 KillTimer (hwnd, mouse_move_timer);
3562 mouse_move_timer = 0;
5ac45f98 3563 }
48094ace
JR
3564 else if (wParam == menu_free_timer)
3565 {
3566 KillTimer (hwnd, menu_free_timer);
3567 menu_free_timer = 0;
27605fa7 3568 f = x_window_to_frame (dpyinfo, hwnd);
48094ace
JR
3569 if (!f->output_data.w32->menu_command_in_progress)
3570 {
3571 /* Free memory used by owner-drawn and help-echo strings. */
3572 w32_free_menu_strings (hwnd);
3573 f->output_data.w32->menubar_active = 0;
3574 }
3575 }
5ac45f98 3576 return 0;
7d0393cf 3577
84fb1139
KH
3578 case WM_NCACTIVATE:
3579 /* Windows doesn't send us focus messages when putting up and
e9e23e23 3580 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
84fb1139
KH
3581 The only indication we get that something happened is receiving
3582 this message afterwards. So this is a good time to reset our
3583 keyboard modifiers' state. */
3584 reset_modifiers ();
3585 goto dflt;
da36a4d6 3586
1edf84e7 3587 case WM_INITMENU:
487163ac
AI
3588 button_state = 0;
3589 ReleaseCapture ();
1edf84e7
GV
3590 /* We must ensure menu bar is fully constructed and up to date
3591 before allowing user interaction with it. To achieve this
3592 we send this message to the lisp thread and wait for a
3593 reply (whose value is not actually needed) to indicate that
3594 the menu bar is now ready for use, so we can now return.
3595
3596 To remain responsive in the meantime, we enter a nested message
3597 loop that can process all other messages.
3598
3599 However, we skip all this if the message results from calling
3600 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3601 thread a message because it is blocked on us at this point. We
3602 set menubar_active before calling TrackPopupMenu to indicate
3603 this (there is no possibility of confusion with real menubar
3604 being active). */
3605
3606 f = x_window_to_frame (dpyinfo, hwnd);
3607 if (f
3608 && (f->output_data.w32->menubar_active
3609 /* We can receive this message even in the absence of a
3610 menubar (ie. when the system menu is activated) - in this
3611 case we do NOT want to forward the message, otherwise it
3612 will cause the menubar to suddenly appear when the user
3613 had requested it to be turned off! */
3614 || f->output_data.w32->menubar_widget == NULL))
3615 return 0;
3616
3617 {
3618 deferred_msg msg_buf;
3619
3620 /* Detect if message has already been deferred; in this case
3621 we cannot return any sensible value to ignore this. */
3622 if (find_deferred_msg (hwnd, msg) != NULL)
3623 abort ();
3624
3625 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3626 }
3627
3628 case WM_EXITMENULOOP:
3629 f = x_window_to_frame (dpyinfo, hwnd);
3630
48094ace
JR
3631 /* If a menu command is not already in progress, check again
3632 after a short delay, since Windows often (always?) sends the
3633 WM_EXITMENULOOP before the corresponding WM_COMMAND message. */
3634 if (f && !f->output_data.w32->menu_command_in_progress)
3635 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
1edf84e7
GV
3636 goto dflt;
3637
126f2e35 3638 case WM_MENUSELECT:
4e3a1c61
JR
3639 /* Direct handling of help_echo in menus. Should be safe now
3640 that we generate the help_echo by placing a help event in the
3641 keyboard buffer. */
ca56d953 3642 {
ca56d953
JR
3643 HMENU menu = (HMENU) lParam;
3644 UINT menu_item = (UINT) LOWORD (wParam);
3645 UINT flags = (UINT) HIWORD (wParam);
3646
4e3a1c61 3647 w32_menu_display_help (hwnd, menu, menu_item, flags);
ca56d953 3648 }
126f2e35
JR
3649 return 0;
3650
87996783
GV
3651 case WM_MEASUREITEM:
3652 f = x_window_to_frame (dpyinfo, hwnd);
3653 if (f)
3654 {
3655 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3656
3657 if (pMis->CtlType == ODT_MENU)
3658 {
3659 /* Work out dimensions for popup menu titles. */
3660 char * title = (char *) pMis->itemData;
3661 HDC hdc = GetDC (hwnd);
3662 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3663 LOGFONT menu_logfont;
3664 HFONT old_font;
3665 SIZE size;
3666
3667 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3668 menu_logfont.lfWeight = FW_BOLD;
3669 menu_font = CreateFontIndirect (&menu_logfont);
3670 old_font = SelectObject (hdc, menu_font);
3671
dfff8a69
JR
3672 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3673 if (title)
3674 {
3675 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3676 pMis->itemWidth = size.cx;
3677 if (pMis->itemHeight < size.cy)
3678 pMis->itemHeight = size.cy;
3679 }
3680 else
3681 pMis->itemWidth = 0;
87996783
GV
3682
3683 SelectObject (hdc, old_font);
3684 DeleteObject (menu_font);
3685 ReleaseDC (hwnd, hdc);
3686 return TRUE;
3687 }
3688 }
3689 return 0;
3690
3691 case WM_DRAWITEM:
3692 f = x_window_to_frame (dpyinfo, hwnd);
3693 if (f)
3694 {
3695 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3696
3697 if (pDis->CtlType == ODT_MENU)
3698 {
3699 /* Draw popup menu title. */
3700 char * title = (char *) pDis->itemData;
212da13b
JR
3701 if (title)
3702 {
3703 HDC hdc = pDis->hDC;
3704 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3705 LOGFONT menu_logfont;
3706 HFONT old_font;
3707
3708 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3709 menu_logfont.lfWeight = FW_BOLD;
3710 menu_font = CreateFontIndirect (&menu_logfont);
3711 old_font = SelectObject (hdc, menu_font);
3712
3713 /* Always draw title as if not selected. */
3714 ExtTextOut (hdc,
3715 pDis->rcItem.left
3716 + GetSystemMetrics (SM_CXMENUCHECK),
3717 pDis->rcItem.top,
3718 ETO_OPAQUE, &pDis->rcItem,
3719 title, strlen (title), NULL);
3720
3721 SelectObject (hdc, old_font);
3722 DeleteObject (menu_font);
3723 }
87996783
GV
3724 return TRUE;
3725 }
3726 }
3727 return 0;
3728
1edf84e7
GV
3729#if 0
3730 /* Still not right - can't distinguish between clicks in the
3731 client area of the frame from clicks forwarded from the scroll
3732 bars - may have to hook WM_NCHITTEST to remember the mouse
3733 position and then check if it is in the client area ourselves. */
3734 case WM_MOUSEACTIVATE:
3735 /* Discard the mouse click that activates a frame, allowing the
3736 user to click anywhere without changing point (or worse!).
3737 Don't eat mouse clicks on scrollbars though!! */
3738 if (LOWORD (lParam) == HTCLIENT )
3739 return MA_ACTIVATEANDEAT;
3740 goto dflt;
3741#endif
3742
9eb16b62
JR
3743 case WM_MOUSELEAVE:
3744 /* No longer tracking mouse. */
3745 track_mouse_window = NULL;
3746
1edf84e7 3747 case WM_ACTIVATEAPP:
ccc2d29c 3748 case WM_ACTIVATE:
1edf84e7
GV
3749 case WM_WINDOWPOSCHANGED:
3750 case WM_SHOWWINDOW:
3751 /* Inform lisp thread that a frame might have just been obscured
3752 or exposed, so should recheck visibility of all frames. */
3753 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3754 goto dflt;
3755
da36a4d6 3756 case WM_SETFOCUS:
adcc3809
GV
3757 dpyinfo->faked_key = 0;
3758 reset_modifiers ();
ccc2d29c
GV
3759 register_hot_keys (hwnd);
3760 goto command;
8681157a 3761 case WM_KILLFOCUS:
ccc2d29c 3762 unregister_hot_keys (hwnd);
487163ac
AI
3763 button_state = 0;
3764 ReleaseCapture ();
65906840
JR
3765 /* Relinquish the system caret. */
3766 if (w32_system_caret_hwnd)
3767 {
93f2ca61 3768 w32_visible_system_caret_hwnd = NULL;
d285988b
JR
3769 w32_system_caret_hwnd = NULL;
3770 DestroyCaret ();
65906840 3771 }
48094ace
JR
3772 goto command;
3773 case WM_COMMAND:
3774 f = x_window_to_frame (dpyinfo, hwnd);
3775 if (f && HIWORD (wParam) == 0)
3776 {
3777 f->output_data.w32->menu_command_in_progress = 1;
3778 if (menu_free_timer)
3779 {
3780 KillTimer (hwnd, menu_free_timer);
7d0393cf 3781 menu_free_timer = 0;
48094ace
JR
3782 }
3783 }
ee78dc32
GV
3784 case WM_MOVE:
3785 case WM_SIZE:
ccc2d29c 3786 command:
fbd6baed 3787 wmsg.dwModifiers = w32_get_modifiers ();
ee78dc32
GV
3788 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3789 goto dflt;
8847d890
RS
3790
3791 case WM_CLOSE:
fbd6baed 3792 wmsg.dwModifiers = w32_get_modifiers ();
8847d890
RS
3793 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3794 return 0;
3795
ee78dc32 3796 case WM_WINDOWPOSCHANGING:
bfd6edcc
JR
3797 /* Don't restrict the sizing of tip frames. */
3798 if (hwnd == tip_window)
3799 return 0;
ee78dc32
GV
3800 {
3801 WINDOWPLACEMENT wp;
3802 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
1edf84e7
GV
3803
3804 wp.length = sizeof (WINDOWPLACEMENT);
ee78dc32 3805 GetWindowPlacement (hwnd, &wp);
7d0393cf 3806
1edf84e7 3807 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
ee78dc32
GV
3808 {
3809 RECT rect;
3810 int wdiff;
3811 int hdiff;
1edf84e7
GV
3812 DWORD font_width;
3813 DWORD line_height;
3814 DWORD internal_border;
3815 DWORD scrollbar_extra;
ee78dc32 3816 RECT wr;
7d0393cf 3817
5ac45f98 3818 wp.length = sizeof(wp);
ee78dc32 3819 GetWindowRect (hwnd, &wr);
7d0393cf 3820
3c190163 3821 enter_crit ();
7d0393cf 3822
1edf84e7
GV
3823 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3824 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3825 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3826 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
7d0393cf 3827
3c190163 3828 leave_crit ();
7d0393cf 3829
ee78dc32 3830 memset (&rect, 0, sizeof (rect));
7d0393cf 3831 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
ee78dc32
GV
3832 GetMenu (hwnd) != NULL);
3833
1edf84e7
GV
3834 /* Force width and height of client area to be exact
3835 multiples of the character cell dimensions. */
3836 wdiff = (lppos->cx - (rect.right - rect.left)
3837 - 2 * internal_border - scrollbar_extra)
3838 % font_width;
3839 hdiff = (lppos->cy - (rect.bottom - rect.top)
3840 - 2 * internal_border)
3841 % line_height;
7d0393cf 3842
ee78dc32
GV
3843 if (wdiff || hdiff)
3844 {
7d0393cf
JB
3845 /* For right/bottom sizing we can just fix the sizes.
3846 However for top/left sizing we will need to fix the X
ee78dc32 3847 and Y positions as well. */
7d0393cf 3848
ee78dc32
GV
3849 lppos->cx -= wdiff;
3850 lppos->cy -= hdiff;
7d0393cf
JB
3851
3852 if (wp.showCmd != SW_SHOWMAXIMIZED
1edf84e7 3853 && (lppos->flags & SWP_NOMOVE) == 0)
ee78dc32
GV
3854 {
3855 if (lppos->x != wr.left || lppos->y != wr.top)
3856 {
3857 lppos->x += wdiff;
3858 lppos->y += hdiff;
3859 }
3860 else
3861 {
3862 lppos->flags |= SWP_NOMOVE;
3863 }
3864 }
7d0393cf 3865
1edf84e7 3866 return 0;
ee78dc32
GV
3867 }
3868 }
3869 }
7d0393cf 3870
ee78dc32 3871 goto dflt;
1edf84e7 3872
b1f918f8
GV
3873 case WM_GETMINMAXINFO:
3874 /* Hack to correct bug that allows Emacs frames to be resized
3875 below the Minimum Tracking Size. */
3876 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
bf853fee
AI
3877 /* Hack to allow resizing the Emacs frame above the screen size.
3878 Note that Windows 9x limits coordinates to 16-bits. */
3879 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3880 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
b1f918f8
GV
3881 return 0;
3882
c9b2104d
JR
3883 case WM_SETCURSOR:
3884 if (LOWORD (lParam) == HTCLIENT)
3885 return 0;
3886
3887 goto dflt;
c922a224 3888
c9b2104d
JR
3889 case WM_EMACS_SETCURSOR:
3890 {
3891 Cursor cursor = (Cursor) wParam;
3892 if (cursor)
3893 SetCursor (cursor);
3894 return 0;
3895 }
c922a224 3896
1edf84e7
GV
3897 case WM_EMACS_CREATESCROLLBAR:
3898 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3899 (struct scroll_bar *) lParam);
3900
5ac45f98 3901 case WM_EMACS_SHOWWINDOW:
1edf84e7
GV
3902 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3903
dfdb4047 3904 case WM_EMACS_SETFOREGROUND:
ce6059da
AI
3905 {
3906 HWND foreground_window;
3907 DWORD foreground_thread, retval;
3908
3909 /* On NT 5.0, and apparently Windows 98, it is necessary to
3910 attach to the thread that currently has focus in order to
3911 pull the focus away from it. */
3912 foreground_window = GetForegroundWindow ();
3913 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3914 if (!foreground_window
3915 || foreground_thread == GetCurrentThreadId ()
3916 || !AttachThreadInput (GetCurrentThreadId (),
3917 foreground_thread, TRUE))
3918 foreground_thread = 0;
3919
3920 retval = SetForegroundWindow ((HWND) wParam);
3921
3922 /* Detach from the previous foreground thread. */
3923 if (foreground_thread)
3924 AttachThreadInput (GetCurrentThreadId (),
3925 foreground_thread, FALSE);
3926
3927 return retval;
3928 }
dfdb4047 3929
5ac45f98
GV
3930 case WM_EMACS_SETWINDOWPOS:
3931 {
1edf84e7
GV
3932 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3933 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5ac45f98
GV
3934 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3935 }
1edf84e7 3936
ee78dc32 3937 case WM_EMACS_DESTROYWINDOW:
cb9e33d4 3938 DragAcceptFiles ((HWND) wParam, FALSE);
1edf84e7
GV
3939 return DestroyWindow ((HWND) wParam);
3940
93f2ca61
JR
3941 case WM_EMACS_HIDE_CARET:
3942 return HideCaret (hwnd);
3943
3944 case WM_EMACS_SHOW_CARET:
3945 return ShowCaret (hwnd);
3946
65906840
JR
3947 case WM_EMACS_DESTROY_CARET:
3948 w32_system_caret_hwnd = NULL;
93f2ca61 3949 w32_visible_system_caret_hwnd = NULL;
65906840
JR
3950 return DestroyCaret ();
3951
3952 case WM_EMACS_TRACK_CARET:
3953 /* If there is currently no system caret, create one. */
3954 if (w32_system_caret_hwnd == NULL)
3955 {
93f2ca61
JR
3956 /* Use the default caret width, and avoid changing it
3957 unneccesarily, as it confuses screen reader software. */
65906840 3958 w32_system_caret_hwnd = hwnd;
93f2ca61 3959 CreateCaret (hwnd, NULL, 0,
65906840
JR
3960 w32_system_caret_height);
3961 }
7d0393cf 3962
93f2ca61
JR
3963 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3964 return 0;
3965 /* Ensure visible caret gets turned on when requested. */
3966 else if (w32_use_visible_system_caret
3967 && w32_visible_system_caret_hwnd != hwnd)
3968 {
3969 w32_visible_system_caret_hwnd = hwnd;
3970 return ShowCaret (hwnd);
3971 }
3972 /* Ensure visible caret gets turned off when requested. */
3973 else if (!w32_use_visible_system_caret
3974 && w32_visible_system_caret_hwnd)
3975 {
3976 w32_visible_system_caret_hwnd = NULL;
3977 return HideCaret (hwnd);
3978 }
3979 else
3980 return 1;
65906840 3981
1edf84e7
GV
3982 case WM_EMACS_TRACKPOPUPMENU:
3983 {
3984 UINT flags;
3985 POINT *pos;
3986 int retval;
3987 pos = (POINT *)lParam;
3988 flags = TPM_CENTERALIGN;
3989 if (button_state & LMOUSE)
3990 flags |= TPM_LEFTBUTTON;
3991 else if (button_state & RMOUSE)
3992 flags |= TPM_RIGHTBUTTON;
7d0393cf 3993
87996783
GV
3994 /* Remember we did a SetCapture on the initial mouse down event,
3995 so for safety, we make sure the capture is cancelled now. */
3996 ReleaseCapture ();
490822ff 3997 button_state = 0;
87996783 3998
1edf84e7
GV
3999 /* Use menubar_active to indicate that WM_INITMENU is from
4000 TrackPopupMenu below, and should be ignored. */
4001 f = x_window_to_frame (dpyinfo, hwnd);
4002 if (f)
4003 f->output_data.w32->menubar_active = 1;
7d0393cf
JB
4004
4005 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
1edf84e7
GV
4006 0, hwnd, NULL))
4007 {
4008 MSG amsg;
4009 /* Eat any mouse messages during popupmenu */
4010 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4011 PM_REMOVE));
4012 /* Get the menu selection, if any */
4013 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4014 {
4015 retval = LOWORD (amsg.wParam);
4016 }
4017 else
4018 {
4019 retval = 0;
4020 }
1edf84e7
GV
4021 }
4022 else
4023 {
4024 retval = -1;
4025 }
4026
4027 return retval;
4028 }
4029
ee78dc32 4030 default:
93fbe8b7
GV
4031 /* Check for messages registered at runtime. */
4032 if (msg == msh_mousewheel)
4033 {
4034 wmsg.dwModifiers = w32_get_modifiers ();
4035 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4036 return 0;
4037 }
7d0393cf 4038
ee78dc32
GV
4039 dflt:
4040 return DefWindowProc (hwnd, msg, wParam, lParam);
4041 }
7d0393cf 4042
1edf84e7
GV
4043
4044 /* The most common default return code for handled messages is 0. */
4045 return 0;
ee78dc32
GV
4046}
4047
7d0393cf 4048void
ee78dc32
GV
4049my_create_window (f)
4050 struct frame * f;
4051{
4052 MSG msg;
4053
1edf84e7
GV
4054 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4055 abort ();
ee78dc32
GV
4056 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4057}
4058
ca56d953
JR
4059
4060/* Create a tooltip window. Unlike my_create_window, we do not do this
4061 indirectly via the Window thread, as we do not need to process Window
4062 messages for the tooltip. Creating tooltips indirectly also creates
4063 deadlocks when tooltips are created for menu items. */
7d0393cf 4064void
ca56d953
JR
4065my_create_tip_window (f)
4066 struct frame *f;
4067{
bfd6edcc 4068 RECT rect;
ca56d953 4069
bfd6edcc 4070 rect.left = rect.top = 0;
be786000
KS
4071 rect.right = FRAME_PIXEL_WIDTH (f);
4072 rect.bottom = FRAME_PIXEL_HEIGHT (f);
bfd6edcc
JR
4073
4074 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4075 FRAME_EXTERNAL_MENU_BAR (f));
4076
4077 tip_window = FRAME_W32_WINDOW (f)
ca56d953
JR
4078 = CreateWindow (EMACS_CLASS,
4079 f->namebuf,
4080 f->output_data.w32->dwStyle,
be786000
KS
4081 f->left_pos,
4082 f->top_pos,
bfd6edcc
JR
4083 rect.right - rect.left,
4084 rect.bottom - rect.top,
ca56d953
JR
4085 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4086 NULL,
4087 hinst,
4088 NULL);
4089
bfd6edcc 4090 if (tip_window)
ca56d953 4091 {
be786000
KS
4092 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4093 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4094 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
bfd6edcc
JR
4095 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4096
4097 /* Tip frames have no scrollbars. */
4098 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
ca56d953
JR
4099
4100 /* Do this to discard the default setting specified by our parent. */
bfd6edcc 4101 ShowWindow (tip_window, SW_HIDE);
ca56d953
JR
4102 }
4103}
4104
4105
fbd6baed 4106/* Create and set up the w32 window for frame F. */
ee78dc32
GV
4107
4108static void
fbd6baed 4109w32_window (f, window_prompting, minibuffer_only)
ee78dc32
GV
4110 struct frame *f;
4111 long window_prompting;
4112 int minibuffer_only;
4113{
4114 BLOCK_INPUT;
4115
4116 /* Use the resource name as the top-level window name
4117 for looking up resources. Make a non-Lisp copy
4118 for the window manager, so GC relocation won't bother it.
4119
4120 Elsewhere we specify the window name for the window manager. */
7d0393cf 4121
ee78dc32 4122 {
d5db4077 4123 char *str = (char *) SDATA (Vx_resource_name);
ee78dc32
GV
4124 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4125 strcpy (f->namebuf, str);
4126 }
4127
4128 my_create_window (f);
4129
4130 validate_x_resource_name ();
4131
4132 /* x_set_name normally ignores requests to set the name if the
4133 requested name is the same as the current name. This is the one
4134 place where that assumption isn't correct; f->name is set, but
4135 the server hasn't been told. */
4136 {
4137 Lisp_Object name;
4138 int explicit = f->explicit_name;
4139
4140 f->explicit_name = 0;
4141 name = f->name;
4142 f->name = Qnil;
4143 x_set_name (f, name, explicit);
4144 }
4145
4146 UNBLOCK_INPUT;
4147
4148 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4149 initialize_frame_menubar (f);
4150
fbd6baed 4151 if (FRAME_W32_WINDOW (f) == 0)
ee78dc32
GV
4152 error ("Unable to create window");
4153}
4154
4155/* Handle the icon stuff for this window. Perhaps later we might
4156 want an x_set_icon_position which can be called interactively as
4157 well. */
4158
4159static void
4160x_icon (f, parms)
4161 struct frame *f;
4162 Lisp_Object parms;
4163{
4164 Lisp_Object icon_x, icon_y;
4165
e9e23e23 4166 /* Set the position of the icon. Note that Windows 95 groups all
ee78dc32 4167 icons in the tray. */
6fc2811b
JR
4168 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4169 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
ee78dc32
GV
4170 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4171 {
b7826503
PJ
4172 CHECK_NUMBER (icon_x);
4173 CHECK_NUMBER (icon_y);
ee78dc32
GV
4174 }
4175 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4176 error ("Both left and top icon corners of icon must be specified");
4177
4178 BLOCK_INPUT;
4179
4180 if (! EQ (icon_x, Qunbound))
4181 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4182
1edf84e7
GV
4183#if 0 /* TODO */
4184 /* Start up iconic or window? */
4185 x_wm_set_window_state
6fc2811b 4186 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
1edf84e7
GV
4187 ? IconicState
4188 : NormalState));
4189
d5db4077 4190 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
1edf84e7 4191 ? f->icon_name
d5db4077 4192 : f->name)));
1edf84e7
GV
4193#endif
4194
ee78dc32
GV
4195 UNBLOCK_INPUT;
4196}
4197
6fc2811b
JR
4198
4199static void
4200x_make_gc (f)
4201 struct frame *f;
4202{
4203 XGCValues gc_values;
4204
4205 BLOCK_INPUT;
4206
4207 /* Create the GC's of this frame.
4208 Note that many default values are used. */
4209
4210 /* Normal video */
be786000 4211 gc_values.font = FRAME_FONT (f);
6fc2811b
JR
4212
4213 /* Cursor has cursor-color background, background-color foreground. */
4214 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4215 gc_values.background = f->output_data.w32->cursor_pixel;
4216 f->output_data.w32->cursor_gc
4217 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4218 (GCFont | GCForeground | GCBackground),
4219 &gc_values);
4220
4221 /* Reliefs. */
4222 f->output_data.w32->white_relief.gc = 0;
4223 f->output_data.w32->black_relief.gc = 0;
4224
4225 UNBLOCK_INPUT;
4226}
4227
4228
937e601e
AI
4229/* Handler for signals raised during x_create_frame and
4230 x_create_top_frame. FRAME is the frame which is partially
4231 constructed. */
4232
4233static Lisp_Object
4234unwind_create_frame (frame)
4235 Lisp_Object frame;
4236{
4237 struct frame *f = XFRAME (frame);
4238
4239 /* If frame is ``official'', nothing to do. */
4240 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
4241 {
4242#ifdef GLYPH_DEBUG
4243 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4244#endif
7d0393cf 4245
937e601e
AI
4246 x_free_frame_resources (f);
4247
4248 /* Check that reference counts are indeed correct. */
4249 xassert (dpyinfo->reference_count == dpyinfo_refcount);
4250 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
c844a81a
GM
4251
4252 return Qt;
937e601e 4253 }
7d0393cf 4254
937e601e
AI
4255 return Qnil;
4256}
4257
4258
ee78dc32
GV
4259DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4260 1, 1, 0,
74e1aeec
JR
4261 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4262Returns an Emacs frame object.
4263ALIST is an alist of frame parameters.
4264If the parameters specify that the frame should not have a minibuffer,
4265and do not specify a specific minibuffer window to use,
4266then `default-minibuffer-frame' must be a frame whose minibuffer can
4267be shared by the new frame.
4268
4269This function is an internal primitive--use `make-frame' instead. */)
ee78dc32
GV
4270 (parms)
4271 Lisp_Object parms;
4272{
4273 struct frame *f;
4274 Lisp_Object frame, tem;
4275 Lisp_Object name;
4276 int minibuffer_only = 0;
4277 long window_prompting = 0;
4278 int width, height;
331379bf 4279 int count = SPECPDL_INDEX ();
1edf84e7 4280 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
ee78dc32 4281 Lisp_Object display;
6fc2811b 4282 struct w32_display_info *dpyinfo = NULL;
ee78dc32
GV
4283 Lisp_Object parent;
4284 struct kboard *kb;
4285
4587b026
GV
4286 check_w32 ();
4287
ee78dc32
GV
4288 /* Use this general default value to start with
4289 until we know if this frame has a specified name. */
4290 Vx_resource_name = Vinvocation_name;
4291
6fc2811b 4292 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
ee78dc32
GV
4293 if (EQ (display, Qunbound))
4294 display = Qnil;
4295 dpyinfo = check_x_display_info (display);
4296#ifdef MULTI_KBOARD
4297 kb = dpyinfo->kboard;
4298#else
4299 kb = &the_only_kboard;
4300#endif
4301
6fc2811b 4302 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
ee78dc32
GV
4303 if (!STRINGP (name)
4304 && ! EQ (name, Qunbound)
4305 && ! NILP (name))
4306 error ("Invalid frame name--not a string or nil");
4307
4308 if (STRINGP (name))
4309 Vx_resource_name = name;
4310
4311 /* See if parent window is specified. */
6fc2811b 4312 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
ee78dc32
GV
4313 if (EQ (parent, Qunbound))
4314 parent = Qnil;
4315 if (! NILP (parent))
b7826503 4316 CHECK_NUMBER (parent);
ee78dc32 4317
1edf84e7
GV
4318 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4319 /* No need to protect DISPLAY because that's not used after passing
4320 it to make_frame_without_minibuffer. */
4321 frame = Qnil;
4322 GCPRO4 (parms, parent, name, frame);
1660f34a
JR
4323 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
4324 RES_TYPE_SYMBOL);
ee78dc32
GV
4325 if (EQ (tem, Qnone) || NILP (tem))
4326 f = make_frame_without_minibuffer (Qnil, kb, display);
4327 else if (EQ (tem, Qonly))
4328 {
4329 f = make_minibuffer_frame ();
4330 minibuffer_only = 1;
4331 }
4332 else if (WINDOWP (tem))
4333 f = make_frame_without_minibuffer (tem, kb, display);
4334 else
4335 f = make_frame (1);
4336
1edf84e7
GV
4337 XSETFRAME (frame, f);
4338
ee78dc32
GV
4339 /* Note that Windows does support scroll bars. */
4340 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
6d906347 4341
5ac45f98 4342 /* By default, make scrollbars the system standard width. */
be786000 4343 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
ee78dc32 4344
fbd6baed 4345 f->output_method = output_w32;
6fc2811b
JR
4346 f->output_data.w32 =
4347 (struct w32_output *) xmalloc (sizeof (struct w32_output));
fbd6baed 4348 bzero (f->output_data.w32, sizeof (struct w32_output));
4587b026 4349 FRAME_FONTSET (f) = -1;
937e601e 4350 record_unwind_protect (unwind_create_frame, frame);
4587b026 4351
1edf84e7 4352 f->icon_name
6fc2811b 4353 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
1edf84e7
GV
4354 if (! STRINGP (f->icon_name))
4355 f->icon_name = Qnil;
4356
fbd6baed 4357/* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
ee78dc32
GV
4358#ifdef MULTI_KBOARD
4359 FRAME_KBOARD (f) = kb;
4360#endif
4361
4362 /* Specify the parent under which to make this window. */
4363
4364 if (!NILP (parent))
4365 {
1660f34a 4366 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
fbd6baed 4367 f->output_data.w32->explicit_parent = 1;
ee78dc32
GV
4368 }
4369 else
4370 {
fbd6baed
GV
4371 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4372 f->output_data.w32->explicit_parent = 0;
ee78dc32
GV
4373 }
4374
ee78dc32
GV
4375 /* Set the name; the functions to which we pass f expect the name to
4376 be set. */
4377 if (EQ (name, Qunbound) || NILP (name))
4378 {
fbd6baed 4379 f->name = build_string (dpyinfo->w32_id_name);
ee78dc32
GV
4380 f->explicit_name = 0;
4381 }
4382 else
4383 {
4384 f->name = name;
4385 f->explicit_name = 1;
4386 /* use the frame's title when getting resources for this frame. */
4387 specbind (Qx_resource_name, name);
4388 }
4389
4390 /* Extract the window parameters from the supplied values
4391 that are needed to determine window geometry. */
4392 {
4393 Lisp_Object font;
4394
6fc2811b
JR
4395 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
4396
ee78dc32
GV
4397 BLOCK_INPUT;
4398 /* First, try whatever font the caller has specified. */
4399 if (STRINGP (font))
4587b026
GV
4400 {
4401 tem = Fquery_fontset (font, Qnil);
4402 if (STRINGP (tem))
10b4bc33 4403 font = x_new_fontset (f, tem);
4587b026 4404 else
d5db4077 4405 font = x_new_font (f, SDATA (font));
4587b026 4406 }
ee78dc32
GV
4407 /* Try out a font which we hope has bold and italic variations. */
4408 if (!STRINGP (font))
e39649be 4409 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
ee78dc32 4410 if (! STRINGP (font))
6fc2811b 4411 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
ee78dc32
GV
4412 /* If those didn't work, look for something which will at least work. */
4413 if (! STRINGP (font))
6fc2811b 4414 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
ee78dc32
GV
4415 UNBLOCK_INPUT;
4416 if (! STRINGP (font))
1edf84e7 4417 font = build_string ("Fixedsys");
ee78dc32 4418
7d0393cf 4419 x_default_parameter (f, parms, Qfont, font,
6fc2811b 4420 "font", "Font", RES_TYPE_STRING);
ee78dc32
GV
4421 }
4422
4423 x_default_parameter (f, parms, Qborder_width, make_number (2),
1660f34a 4424 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
ee78dc32
GV
4425 /* This defaults to 2 in order to match xterm. We recognize either
4426 internalBorderWidth or internalBorder (which is what xterm calls
4427 it). */
4428 if (NILP (Fassq (Qinternal_border_width, parms)))
4429 {
4430 Lisp_Object value;
4431
6fc2811b 4432 value = w32_get_arg (parms, Qinternal_border_width,
1660f34a 4433 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
ee78dc32
GV
4434 if (! EQ (value, Qunbound))
4435 parms = Fcons (Fcons (Qinternal_border_width, value),
4436 parms);
4437 }
1edf84e7 4438 /* Default internalBorderWidth to 0 on Windows to match other programs. */
ee78dc32 4439 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
1660f34a
JR
4440 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4441 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
4442 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
ee78dc32
GV
4443
4444 /* Also do the stuff which must be set before the window exists. */
4445 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6fc2811b 4446 "foreground", "Foreground", RES_TYPE_STRING);
ee78dc32 4447 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6fc2811b 4448 "background", "Background", RES_TYPE_STRING);
ee78dc32 4449 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6fc2811b 4450 "pointerColor", "Foreground", RES_TYPE_STRING);
ee78dc32 4451 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6fc2811b 4452 "cursorColor", "Foreground", RES_TYPE_STRING);
ee78dc32 4453 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6fc2811b
JR
4454 "borderColor", "BorderColor", RES_TYPE_STRING);
4455 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
4456 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
dfff8a69
JR
4457 x_default_parameter (f, parms, Qline_spacing, Qnil,
4458 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
41c1bdd9
KS
4459 x_default_parameter (f, parms, Qleft_fringe, Qnil,
4460 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4461 x_default_parameter (f, parms, Qright_fringe, Qnil,
4462 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
6fc2811b 4463
ee78dc32 4464
6fc2811b
JR
4465 /* Init faces before x_default_parameter is called for scroll-bar
4466 parameters because that function calls x_set_scroll_bar_width,
4467 which calls change_frame_size, which calls Fset_window_buffer,
4468 which runs hooks, which call Fvertical_motion. At the end, we
4469 end up in init_iterator with a null face cache, which should not
4470 happen. */
4471 init_frame_faces (f);
7d0393cf 4472
ee78dc32 4473 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
6fc2811b 4474 "menuBar", "MenuBar", RES_TYPE_NUMBER);
d3109773 4475 x_default_parameter (f, parms, Qtool_bar_lines, make_number (1),
6fc2811b 4476 "toolBar", "ToolBar", RES_TYPE_NUMBER);
919f1e88 4477
1edf84e7 4478 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
6fc2811b 4479 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
1edf84e7 4480 x_default_parameter (f, parms, Qtitle, Qnil,
6fc2811b 4481 "title", "Title", RES_TYPE_STRING);
f7b9d4d1
JR
4482 x_default_parameter (f, parms, Qfullscreen, Qnil,
4483 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
ee78dc32 4484
fbd6baed
GV
4485 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4486 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
3cf3436e 4487
c9b2104d
JR
4488 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4489 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4490 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
7d63e5e3 4491 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
c9b2104d
JR
4492 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4493 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
c9b2104d 4494
6d906347 4495 window_prompting = x_figure_window_size (f, parms, 1);
ee78dc32 4496
6fc2811b
JR
4497 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4498 f->no_split = minibuffer_only || EQ (tem, Qt);
4499
fbd6baed 4500 w32_window (f, window_prompting, minibuffer_only);
ee78dc32 4501 x_icon (f, parms);
6fc2811b
JR
4502
4503 x_make_gc (f);
4504
4505 /* Now consider the frame official. */
4506 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
4507 Vframe_list = Fcons (frame, Vframe_list);
ee78dc32
GV
4508
4509 /* We need to do this after creating the window, so that the
4510 icon-creation functions can say whose icon they're describing. */
4511 x_default_parameter (f, parms, Qicon_type, Qnil,
6fc2811b 4512 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
ee78dc32
GV
4513
4514 x_default_parameter (f, parms, Qauto_raise, Qnil,
6fc2811b 4515 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
ee78dc32 4516 x_default_parameter (f, parms, Qauto_lower, Qnil,
6fc2811b 4517 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
ee78dc32 4518 x_default_parameter (f, parms, Qcursor_type, Qbox,
6fc2811b
JR
4519 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4520 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
4521 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
ee78dc32 4522
be786000 4523 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
ee78dc32 4524 Change will not be effected unless different from the current
be786000
KS
4525 FRAME_LINES (f). */
4526 width = FRAME_COLS (f);
4527 height = FRAME_LINES (f);
dc220243 4528
be786000
KS
4529 FRAME_LINES (f) = 0;
4530 SET_FRAME_COLS (f, 0);
6fc2811b
JR
4531 change_frame_size (f, height, width, 1, 0, 0);
4532
6fc2811b
JR
4533 /* Tell the server what size and position, etc, we want, and how
4534 badly we want them. This should be done after we have the menu
4535 bar so that its size can be taken into account. */
ee78dc32
GV
4536 BLOCK_INPUT;
4537 x_wm_set_size_hint (f, window_prompting, 0);
4538 UNBLOCK_INPUT;
4539
815d969e
JR
4540 /* Avoid a bug that causes the new frame to never become visible if
4541 an echo area message is displayed during the following call1. */
4542 specbind(Qredisplay_dont_pause, Qt);
4543
4694d762
JR
4544 /* Set up faces after all frame parameters are known. This call
4545 also merges in face attributes specified for new frames. If we
4546 don't do this, the `menu' face for instance won't have the right
4547 colors, and the menu bar won't appear in the specified colors for
4548 new frames. */
4549 call1 (Qface_set_after_frame_default, frame);
4550
6fc2811b
JR
4551 /* Make the window appear on the frame and enable display, unless
4552 the caller says not to. However, with explicit parent, Emacs
4553 cannot control visibility, so don't try. */
fbd6baed 4554 if (! f->output_data.w32->explicit_parent)
ee78dc32
GV
4555 {
4556 Lisp_Object visibility;
4557
6fc2811b 4558 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
ee78dc32
GV
4559 if (EQ (visibility, Qunbound))
4560 visibility = Qt;
4561
4562 if (EQ (visibility, Qicon))
4563 x_iconify_frame (f);
4564 else if (! NILP (visibility))
4565 x_make_frame_visible (f);
4566 else
4567 /* Must have been Qnil. */
4568 ;
4569 }
6fc2811b 4570 UNGCPRO;
7d0393cf 4571
9e57df62
GM
4572 /* Make sure windows on this frame appear in calls to next-window
4573 and similar functions. */
4574 Vwindow_list = Qnil;
7d0393cf 4575
ee78dc32
GV
4576 return unbind_to (count, frame);
4577}
4578
4579/* FRAME is used only to get a handle on the X display. We don't pass the
4580 display info directly because we're called from frame.c, which doesn't
4581 know about that structure. */
4582Lisp_Object
4583x_get_focus_frame (frame)
4584 struct frame *frame;
4585{
fbd6baed 4586 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
ee78dc32 4587 Lisp_Object xfocus;
fbd6baed 4588 if (! dpyinfo->w32_focus_frame)
ee78dc32
GV
4589 return Qnil;
4590
fbd6baed 4591 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
ee78dc32
GV
4592 return xfocus;
4593}
1edf84e7
GV
4594
4595DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
74e1aeec 4596 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
1edf84e7
GV
4597 (frame)
4598 Lisp_Object frame;
4599{
4600 x_focus_on_frame (check_x_frame (frame));
4601 return Qnil;
4602}
4603
ee78dc32 4604\f
767b1ff0
JR
4605/* Return the charset portion of a font name. */
4606char * xlfd_charset_of_font (char * fontname)
4607{
4608 char *charset, *encoding;
4609
4610 encoding = strrchr(fontname, '-');
ceb12877 4611 if (!encoding || encoding == fontname)
767b1ff0
JR
4612 return NULL;
4613
478ea067
AI
4614 for (charset = encoding - 1; charset >= fontname; charset--)
4615 if (*charset == '-')
4616 break;
767b1ff0 4617
478ea067 4618 if (charset == fontname || strcmp(charset, "-*-*") == 0)
767b1ff0
JR
4619 return NULL;
4620
4621 return charset + 1;
4622}
4623
33d52f9c
GV
4624struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
4625 int size, char* filename);
8edb0a6f 4626static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
c7501041
EZ
4627static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
4628 char * charset);
4629static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
33d52f9c 4630
8edb0a6f 4631static struct font_info *
33d52f9c 4632w32_load_system_font (f,fontname,size)
55dcfc15
AI
4633 struct frame *f;
4634 char * fontname;
4635 int size;
ee78dc32 4636{
4587b026
GV
4637 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4638 Lisp_Object font_names;
4639
4587b026
GV
4640 /* Get a list of all the fonts that match this name. Once we
4641 have a list of matching fonts, we compare them against the fonts
4642 we already have loaded by comparing names. */
4643 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
4644
4645 if (!NILP (font_names))
3c190163 4646 {
4587b026
GV
4647 Lisp_Object tail;
4648 int i;
4587b026
GV
4649
4650 /* First check if any are already loaded, as that is cheaper
4651 than loading another one. */
4652 for (i = 0; i < dpyinfo->n_fonts; i++)
8e713be6 4653 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
6fc2811b
JR
4654 if (dpyinfo->font_table[i].name
4655 && (!strcmp (dpyinfo->font_table[i].name,
d5db4077 4656 SDATA (XCAR (tail)))
6fc2811b 4657 || !strcmp (dpyinfo->font_table[i].full_name,
d5db4077 4658 SDATA (XCAR (tail)))))
4587b026 4659 return (dpyinfo->font_table + i);
6fc2811b 4660
d5db4077 4661 fontname = (char *) SDATA (XCAR (font_names));
4587b026 4662 }
1075afa9 4663 else if (w32_strict_fontnames)
5ca0cd71
GV
4664 {
4665 /* If EnumFontFamiliesEx was available, we got a full list of
4666 fonts back so stop now to avoid the possibility of loading a
4667 random font. If we had to fall back to EnumFontFamilies, the
4668 list is incomplete, so continue whether the font we want was
4669 listed or not. */
4670 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
4671 FARPROC enum_font_families_ex
1075afa9 4672 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5ca0cd71
GV
4673 if (enum_font_families_ex)
4674 return NULL;
4675 }
4587b026
GV
4676
4677 /* Load the font and add it to the table. */
4678 {
767b1ff0 4679 char *full_name, *encoding, *charset;
4587b026
GV
4680 XFontStruct *font;
4681 struct font_info *fontp;
3c190163 4682 LOGFONT lf;
4587b026 4683 BOOL ok;
19c291d3 4684 int codepage;
6fc2811b 4685 int i;
5ac45f98 4686
4587b026 4687 if (!fontname || !x_to_w32_font (fontname, &lf))
3c190163 4688 return (NULL);
5ac45f98 4689
4587b026
GV
4690 if (!*lf.lfFaceName)
4691 /* If no name was specified for the font, we get a random font
4692 from CreateFontIndirect - this is not particularly
4693 desirable, especially since CreateFontIndirect does not
4694 fill out the missing name in lf, so we never know what we
4695 ended up with. */
4696 return NULL;
4697
c8d88d08 4698 lf.lfQuality = DEFAULT_QUALITY;
d65a9cdc 4699
3c190163 4700 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
c6be3860 4701 bzero (font, sizeof (*font));
5ac45f98 4702
33d52f9c
GV
4703 /* Set bdf to NULL to indicate that this is a Windows font. */
4704 font->bdf = NULL;
5ac45f98 4705
3c190163 4706 BLOCK_INPUT;
5ac45f98
GV
4707
4708 font->hfont = CreateFontIndirect (&lf);
ee78dc32 4709
7d0393cf 4710 if (font->hfont == NULL)
1a292d24
AI
4711 {
4712 ok = FALSE;
7d0393cf
JB
4713 }
4714 else
1a292d24
AI
4715 {
4716 HDC hdc;
4717 HANDLE oldobj;
19c291d3
AI
4718
4719 codepage = w32_codepage_for_font (fontname);
1a292d24
AI
4720
4721 hdc = GetDC (dpyinfo->root_window);
4722 oldobj = SelectObject (hdc, font->hfont);
5c6682be 4723
1a292d24 4724 ok = GetTextMetrics (hdc, &font->tm);
5c6682be
JR
4725 if (codepage == CP_UNICODE)
4726 font->double_byte_p = 1;
4727 else
8b77111c
AI
4728 {
4729 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
4730 don't report themselves as double byte fonts, when
4731 patently they are. So instead of trusting
4732 GetFontLanguageInfo, we check the properties of the
4733 codepage directly, since that is ultimately what we are
4734 working from anyway. */
4735 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
4736 CPINFO cpi = {0};
4737 GetCPInfo (codepage, &cpi);
4738 font->double_byte_p = cpi.MaxCharSize > 1;
4739 }
5c6682be 4740
1a292d24
AI
4741 SelectObject (hdc, oldobj);
4742 ReleaseDC (dpyinfo->root_window, hdc);
6fc2811b
JR
4743 /* Fill out details in lf according to the font that was
4744 actually loaded. */
4745 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
4746 lf.lfWidth = font->tm.tmAveCharWidth;
4747 lf.lfWeight = font->tm.tmWeight;
4748 lf.lfItalic = font->tm.tmItalic;
4749 lf.lfCharSet = font->tm.tmCharSet;
4750 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
d88c567c 4751 ? VARIABLE_PITCH : FIXED_PITCH);
6fc2811b
JR
4752 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
4753 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
c6be3860
AI
4754
4755 w32_cache_char_metrics (font);
1a292d24 4756 }
5ac45f98 4757
1a292d24 4758 UNBLOCK_INPUT;
5ac45f98 4759
4587b026
GV
4760 if (!ok)
4761 {
1a292d24
AI
4762 w32_unload_font (dpyinfo, font);
4763 return (NULL);
4764 }
ee78dc32 4765
6fc2811b
JR
4766 /* Find a free slot in the font table. */
4767 for (i = 0; i < dpyinfo->n_fonts; ++i)
4768 if (dpyinfo->font_table[i].name == NULL)
4769 break;
4770
4771 /* If no free slot found, maybe enlarge the font table. */
4772 if (i == dpyinfo->n_fonts
4773 && dpyinfo->n_fonts == dpyinfo->font_table_size)
4587b026 4774 {
6fc2811b
JR
4775 int sz;
4776 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
4777 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
4587b026 4778 dpyinfo->font_table
6fc2811b 4779 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
4587b026
GV
4780 }
4781
6fc2811b
JR
4782 fontp = dpyinfo->font_table + i;
4783 if (i == dpyinfo->n_fonts)
4784 ++dpyinfo->n_fonts;
4587b026
GV
4785
4786 /* Now fill in the slots of *FONTP. */
4787 BLOCK_INPUT;
10b4bc33 4788 bzero (fontp, sizeof (*fontp));
4587b026 4789 fontp->font = font;
6fc2811b 4790 fontp->font_idx = i;
4587b026
GV
4791 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
4792 bcopy (fontname, fontp->name, strlen (fontname) + 1);
4793
10b4bc33 4794 fontp->charset = charset_unicode;
767b1ff0
JR
4795 charset = xlfd_charset_of_font (fontname);
4796
19c291d3
AI
4797 /* Cache the W32 codepage for a font. This makes w32_encode_char
4798 (called for every glyph during redisplay) much faster. */
4799 fontp->codepage = codepage;
4800
4587b026
GV
4801 /* Work out the font's full name. */
4802 full_name = (char *)xmalloc (100);
767b1ff0 4803 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
4587b026
GV
4804 fontp->full_name = full_name;
4805 else
4806 {
4807 /* If all else fails - just use the name we used to load it. */
4808 xfree (full_name);
4809 fontp->full_name = fontp->name;
4810 }
4811
4812 fontp->size = FONT_WIDTH (font);
4813 fontp->height = FONT_HEIGHT (font);
4814
4815 /* The slot `encoding' specifies how to map a character
4816 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
126f2e35
JR
4817 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
4818 (0:0x20..0x7F, 1:0xA0..0xFF,
4819 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
4587b026 4820 2:0xA020..0xFF7F). For the moment, we don't know which charset
10b4bc33 4821 uses this font. So, we set information in fontp->encoding_type
4587b026
GV
4822 which is never used by any charset. If mapping can't be
4823 decided, set FONT_ENCODING_NOT_DECIDED. */
33d52f9c
GV
4824
4825 /* SJIS fonts need to be set to type 4, all others seem to work as
4826 type FONT_ENCODING_NOT_DECIDED. */
4827 encoding = strrchr (fontp->name, '-');
d84b082d 4828 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
10b4bc33 4829 fontp->encoding_type = 4;
33d52f9c 4830 else
10b4bc33 4831 fontp->encoding_type = FONT_ENCODING_NOT_DECIDED;
4587b026
GV
4832
4833 /* The following three values are set to 0 under W32, which is
4834 what they get set to if XGetFontProperty fails under X. */
4835 fontp->baseline_offset = 0;
4836 fontp->relative_compose = 0;
33d52f9c 4837 fontp->default_ascent = 0;
4587b026 4838
6fc2811b
JR
4839 /* Set global flag fonts_changed_p to non-zero if the font loaded
4840 has a character with a smaller width than any other character
f7b9d4d1 4841 before, or if the font loaded has a smaller height than any
6fc2811b
JR
4842 other font loaded before. If this happens, it will make a
4843 glyph matrix reallocation necessary. */
f7b9d4d1 4844 fonts_changed_p |= x_compute_min_glyph_bounds (f);
4587b026 4845 UNBLOCK_INPUT;
4587b026
GV
4846 return fontp;
4847 }
4848}
4849
33d52f9c
GV
4850/* Load font named FONTNAME of size SIZE for frame F, and return a
4851 pointer to the structure font_info while allocating it dynamically.
4852 If loading fails, return NULL. */
4853struct font_info *
4854w32_load_font (f,fontname,size)
4855struct frame *f;
4856char * fontname;
4857int size;
4858{
4859 Lisp_Object bdf_fonts;
4860 struct font_info *retval = NULL;
4861
8edb0a6f 4862 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
33d52f9c
GV
4863
4864 while (!retval && CONSP (bdf_fonts))
4865 {
4866 char *bdf_name, *bdf_file;
4867 Lisp_Object bdf_pair;
4868
d5db4077 4869 bdf_name = SDATA (XCAR (bdf_fonts));
8e713be6 4870 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
d5db4077 4871 bdf_file = SDATA (XCDR (bdf_pair));
33d52f9c
GV
4872
4873 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
4874
8e713be6 4875 bdf_fonts = XCDR (bdf_fonts);
33d52f9c
GV
4876 }
4877
4878 if (retval)
4879 return retval;
4880
4881 return w32_load_system_font(f, fontname, size);
4882}
4883
4884
7d0393cf 4885void
fbd6baed
GV
4886w32_unload_font (dpyinfo, font)
4887 struct w32_display_info *dpyinfo;
ee78dc32
GV
4888 XFontStruct * font;
4889{
7d0393cf 4890 if (font)
ee78dc32 4891 {
c6be3860 4892 if (font->per_char) xfree (font->per_char);
33d52f9c
GV
4893 if (font->bdf) w32_free_bdf_font (font->bdf);
4894
3c190163 4895 if (font->hfont) DeleteObject(font->hfont);
ee78dc32
GV
4896 xfree (font);
4897 }
4898}
4899
fbd6baed 4900/* The font conversion stuff between x and w32 */
ee78dc32
GV
4901
4902/* X font string is as follows (from faces.el)
4903 * (let ((- "[-?]")
4904 * (foundry "[^-]+")
4905 * (family "[^-]+")
4906 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
4907 * (weight\? "\\([^-]*\\)") ; 1
4908 * (slant "\\([ior]\\)") ; 2
4909 * (slant\? "\\([^-]?\\)") ; 2
4910 * (swidth "\\([^-]*\\)") ; 3
4911 * (adstyle "[^-]*") ; 4
4912 * (pixelsize "[0-9]+")
4913 * (pointsize "[0-9][0-9]+")
4914 * (resx "[0-9][0-9]+")
4915 * (resy "[0-9][0-9]+")
4916 * (spacing "[cmp?*]")
4917 * (avgwidth "[0-9]+")
4918 * (registry "[^-]+")
4919 * (encoding "[^-]+")
4920 * )
ee78dc32 4921 */
ee78dc32 4922
7d0393cf 4923static LONG
fbd6baed 4924x_to_w32_weight (lpw)
ee78dc32
GV
4925 char * lpw;
4926{
4927 if (!lpw) return (FW_DONTCARE);
5ac45f98
GV
4928
4929 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
4930 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
4931 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
4932 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
1edf84e7 4933 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5ac45f98
GV
4934 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
4935 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
4936 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
4937 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
4938 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
ee78dc32 4939 else
5ac45f98 4940 return FW_DONTCARE;
ee78dc32
GV
4941}
4942
5ac45f98 4943
7d0393cf 4944static char *
fbd6baed 4945w32_to_x_weight (fnweight)
ee78dc32
GV
4946 int fnweight;
4947{
5ac45f98
GV
4948 if (fnweight >= FW_HEAVY) return "heavy";
4949 if (fnweight >= FW_EXTRABOLD) return "extrabold";
4950 if (fnweight >= FW_BOLD) return "bold";
03f8fb34 4951 if (fnweight >= FW_SEMIBOLD) return "demibold";
5ac45f98
GV
4952 if (fnweight >= FW_MEDIUM) return "medium";
4953 if (fnweight >= FW_NORMAL) return "normal";
4954 if (fnweight >= FW_LIGHT) return "light";
4955 if (fnweight >= FW_EXTRALIGHT) return "extralight";
4956 if (fnweight >= FW_THIN) return "thin";
4957 else
4958 return "*";
4959}
4960
8edb0a6f 4961static LONG
fbd6baed 4962x_to_w32_charset (lpcs)
5ac45f98
GV
4963 char * lpcs;
4964{
767b1ff0 4965 Lisp_Object this_entry, w32_charset;
8b77111c
AI
4966 char *charset;
4967 int len = strlen (lpcs);
4968
4969 /* Support "*-#nnn" format for unknown charsets. */
4970 if (strncmp (lpcs, "*-#", 3) == 0)
4971 return atoi (lpcs + 3);
4972
4973 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
4974 charset = alloca (len + 1);
4975 strcpy (charset, lpcs);
4976 lpcs = strchr (charset, '*');
4977 if (lpcs)
4978 *lpcs = 0;
4587b026 4979
dfff8a69
JR
4980 /* Look through w32-charset-info-alist for the character set.
4981 Format of each entry is
4982 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
4983 */
8b77111c 4984 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
4587b026 4985
767b1ff0
JR
4986 if (NILP(this_entry))
4987 {
4988 /* At startup, we want iso8859-1 fonts to come up properly. */
8b77111c 4989 if (stricmp(charset, "iso8859-1") == 0)
767b1ff0
JR
4990 return ANSI_CHARSET;
4991 else
4992 return DEFAULT_CHARSET;
4993 }
4994
4995 w32_charset = Fcar (Fcdr (this_entry));
4996
d84b082d 4997 /* Translate Lisp symbol to number. */
767b1ff0
JR
4998 if (w32_charset == Qw32_charset_ansi)
4999 return ANSI_CHARSET;
5000 if (w32_charset == Qw32_charset_symbol)
5001 return SYMBOL_CHARSET;
5002 if (w32_charset == Qw32_charset_shiftjis)
5003 return SHIFTJIS_CHARSET;
5004 if (w32_charset == Qw32_charset_hangeul)
5005 return HANGEUL_CHARSET;
5006 if (w32_charset == Qw32_charset_chinesebig5)
5007 return CHINESEBIG5_CHARSET;
5008 if (w32_charset == Qw32_charset_gb2312)
5009 return GB2312_CHARSET;
5010 if (w32_charset == Qw32_charset_oem)
5011 return OEM_CHARSET;
dfff8a69 5012#ifdef JOHAB_CHARSET
767b1ff0
JR
5013 if (w32_charset == Qw32_charset_johab)
5014 return JOHAB_CHARSET;
5015 if (w32_charset == Qw32_charset_easteurope)
5016 return EASTEUROPE_CHARSET;
5017 if (w32_charset == Qw32_charset_turkish)
5018 return TURKISH_CHARSET;
5019 if (w32_charset == Qw32_charset_baltic)
5020 return BALTIC_CHARSET;
5021 if (w32_charset == Qw32_charset_russian)
5022 return RUSSIAN_CHARSET;
5023 if (w32_charset == Qw32_charset_arabic)
5024 return ARABIC_CHARSET;
5025 if (w32_charset == Qw32_charset_greek)
5026 return GREEK_CHARSET;
5027 if (w32_charset == Qw32_charset_hebrew)
5028 return HEBREW_CHARSET;
5029 if (w32_charset == Qw32_charset_vietnamese)
5030 return VIETNAMESE_CHARSET;
5031 if (w32_charset == Qw32_charset_thai)
5032 return THAI_CHARSET;
5033 if (w32_charset == Qw32_charset_mac)
5034 return MAC_CHARSET;
dfff8a69 5035#endif /* JOHAB_CHARSET */
5ac45f98 5036#ifdef UNICODE_CHARSET
767b1ff0
JR
5037 if (w32_charset == Qw32_charset_unicode)
5038 return UNICODE_CHARSET;
5ac45f98 5039#endif
dfff8a69
JR
5040
5041 return DEFAULT_CHARSET;
5ac45f98
GV
5042}
5043
dfff8a69 5044
8edb0a6f 5045static char *
fbd6baed 5046w32_to_x_charset (fncharset)
5ac45f98
GV
5047 int fncharset;
5048{
5e905a57 5049 static char buf[32];
767b1ff0 5050 Lisp_Object charset_type;
1edf84e7 5051
5ac45f98
GV
5052 switch (fncharset)
5053 {
767b1ff0
JR
5054 case ANSI_CHARSET:
5055 /* Handle startup case of w32-charset-info-alist not
5056 being set up yet. */
5057 if (NILP(Vw32_charset_info_alist))
5058 return "iso8859-1";
5059 charset_type = Qw32_charset_ansi;
5060 break;
5061 case DEFAULT_CHARSET:
5062 charset_type = Qw32_charset_default;
5063 break;
5064 case SYMBOL_CHARSET:
5065 charset_type = Qw32_charset_symbol;
5066 break;
5067 case SHIFTJIS_CHARSET:
5068 charset_type = Qw32_charset_shiftjis;
5069 break;
5070 case HANGEUL_CHARSET:
5071 charset_type = Qw32_charset_hangeul;
5072 break;
5073 case GB2312_CHARSET:
5074 charset_type = Qw32_charset_gb2312;
5075 break;
5076 case CHINESEBIG5_CHARSET:
5077 charset_type = Qw32_charset_chinesebig5;
5078 break;
5079 case OEM_CHARSET:
5080 charset_type = Qw32_charset_oem;
5081 break;
4587b026
GV
5082
5083 /* More recent versions of Windows (95 and NT4.0) define more
5084 character sets. */
5085#ifdef EASTEUROPE_CHARSET
767b1ff0
JR
5086 case EASTEUROPE_CHARSET:
5087 charset_type = Qw32_charset_easteurope;
5088 break;
5089 case TURKISH_CHARSET:
5090 charset_type = Qw32_charset_turkish;
5091 break;
5092 case BALTIC_CHARSET:
5093 charset_type = Qw32_charset_baltic;
5094 break;
33d52f9c 5095 case RUSSIAN_CHARSET:
767b1ff0
JR
5096 charset_type = Qw32_charset_russian;
5097 break;
5098 case ARABIC_CHARSET:
5099 charset_type = Qw32_charset_arabic;
5100 break;
5101 case GREEK_CHARSET:
5102 charset_type = Qw32_charset_greek;
5103 break;
5104 case HEBREW_CHARSET:
5105 charset_type = Qw32_charset_hebrew;
5106 break;
5107 case VIETNAMESE_CHARSET:
5108 charset_type = Qw32_charset_vietnamese;
5109 break;
5110 case THAI_CHARSET:
5111 charset_type = Qw32_charset_thai;
5112 break;
5113 case MAC_CHARSET:
5114 charset_type = Qw32_charset_mac;
5115 break;
5116 case JOHAB_CHARSET:
5117 charset_type = Qw32_charset_johab;
5118 break;
4587b026
GV
5119#endif
5120
5ac45f98 5121#ifdef UNICODE_CHARSET
767b1ff0
JR
5122 case UNICODE_CHARSET:
5123 charset_type = Qw32_charset_unicode;
5124 break;
5ac45f98 5125#endif
767b1ff0
JR
5126 default:
5127 /* Encode numerical value of unknown charset. */
5128 sprintf (buf, "*-#%u", fncharset);
5129 return buf;
5ac45f98 5130 }
7d0393cf 5131
767b1ff0
JR
5132 {
5133 Lisp_Object rest;
5134 char * best_match = NULL;
5135
5136 /* Look through w32-charset-info-alist for the character set.
5137 Prefer ISO codepages, and prefer lower numbers in the ISO
5138 range. Only return charsets for codepages which are installed.
5139
5140 Format of each entry is
5141 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5142 */
5143 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5144 {
5145 char * x_charset;
5146 Lisp_Object w32_charset;
5147 Lisp_Object codepage;
5148
5149 Lisp_Object this_entry = XCAR (rest);
5150
5151 /* Skip invalid entries in alist. */
5152 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5153 || !CONSP (XCDR (this_entry))
5154 || !SYMBOLP (XCAR (XCDR (this_entry))))
5155 continue;
5156
d5db4077 5157 x_charset = SDATA (XCAR (this_entry));
767b1ff0
JR
5158 w32_charset = XCAR (XCDR (this_entry));
5159 codepage = XCDR (XCDR (this_entry));
5160
5161 /* Look for Same charset and a valid codepage (or non-int
5162 which means ignore). */
5163 if (w32_charset == charset_type
5164 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5165 || IsValidCodePage (XINT (codepage))))
5166 {
5167 /* If we don't have a match already, then this is the
5168 best. */
5169 if (!best_match)
5170 best_match = x_charset;
5171 /* If this is an ISO codepage, and the best so far isn't,
5172 then this is better. */
d84b082d
JR
5173 else if (strnicmp (best_match, "iso", 3) != 0
5174 && strnicmp (x_charset, "iso", 3) == 0)
767b1ff0
JR
5175 best_match = x_charset;
5176 /* If both are ISO8859 codepages, choose the one with the
5177 lowest number in the encoding field. */
d84b082d
JR
5178 else if (strnicmp (best_match, "iso8859-", 8) == 0
5179 && strnicmp (x_charset, "iso8859-", 8) == 0)
767b1ff0
JR
5180 {
5181 int best_enc = atoi (best_match + 8);
5182 int this_enc = atoi (x_charset + 8);
5183 if (this_enc > 0 && this_enc < best_enc)
5184 best_match = x_charset;
7d0393cf 5185 }
767b1ff0
JR
5186 }
5187 }
5188
5189 /* If no match, encode the numeric value. */
5190 if (!best_match)
5191 {
5192 sprintf (buf, "*-#%u", fncharset);
5193 return buf;
5194 }
5195
5e905a57
JR
5196 strncpy(buf, best_match, 31);
5197 buf[31] = '\0';
767b1ff0
JR
5198 return buf;
5199 }
ee78dc32
GV
5200}
5201
dfff8a69 5202
d84b082d
JR
5203/* Return all the X charsets that map to a font. */
5204static Lisp_Object
5205w32_to_all_x_charsets (fncharset)
5206 int fncharset;
5207{
5208 static char buf[32];
5209 Lisp_Object charset_type;
5210 Lisp_Object retval = Qnil;
5211
5212 switch (fncharset)
5213 {
5214 case ANSI_CHARSET:
5215 /* Handle startup case of w32-charset-info-alist not
5216 being set up yet. */
5217 if (NILP(Vw32_charset_info_alist))
d86c35ee
JR
5218 return Fcons (build_string ("iso8859-1"), Qnil);
5219
d84b082d
JR
5220 charset_type = Qw32_charset_ansi;
5221 break;
5222 case DEFAULT_CHARSET:
5223 charset_type = Qw32_charset_default;
5224 break;
5225 case SYMBOL_CHARSET:
5226 charset_type = Qw32_charset_symbol;
5227 break;
5228 case SHIFTJIS_CHARSET:
5229 charset_type = Qw32_charset_shiftjis;
5230 break;
5231 case HANGEUL_CHARSET:
5232 charset_type = Qw32_charset_hangeul;
5233 break;
5234 case GB2312_CHARSET:
5235 charset_type = Qw32_charset_gb2312;
5236 break;
5237 case CHINESEBIG5_CHARSET:
5238 charset_type = Qw32_charset_chinesebig5;
5239 break;
5240 case OEM_CHARSET:
5241 charset_type = Qw32_charset_oem;
5242 break;
5243
5244 /* More recent versions of Windows (95 and NT4.0) define more
5245 character sets. */
5246#ifdef EASTEUROPE_CHARSET
5247 case EASTEUROPE_CHARSET:
5248 charset_type = Qw32_charset_easteurope;
5249 break;
5250 case TURKISH_CHARSET:
5251 charset_type = Qw32_charset_turkish;
5252 break;
5253 case BALTIC_CHARSET:
5254 charset_type = Qw32_charset_baltic;
5255 break;
5256 case RUSSIAN_CHARSET:
5257 charset_type = Qw32_charset_russian;
5258 break;
5259 case ARABIC_CHARSET:
5260 charset_type = Qw32_charset_arabic;
5261 break;
5262 case GREEK_CHARSET:
5263 charset_type = Qw32_charset_greek;
5264 break;
5265 case HEBREW_CHARSET:
5266 charset_type = Qw32_charset_hebrew;
5267 break;
5268 case VIETNAMESE_CHARSET:
5269 charset_type = Qw32_charset_vietnamese;
5270 break;
5271 case THAI_CHARSET:
5272 charset_type = Qw32_charset_thai;
5273 break;
5274 case MAC_CHARSET:
5275 charset_type = Qw32_charset_mac;
5276 break;
5277 case JOHAB_CHARSET:
5278 charset_type = Qw32_charset_johab;
5279 break;
5280#endif
5281
5282#ifdef UNICODE_CHARSET
5283 case UNICODE_CHARSET:
5284 charset_type = Qw32_charset_unicode;
5285 break;
5286#endif
5287 default:
5288 /* Encode numerical value of unknown charset. */
5289 sprintf (buf, "*-#%u", fncharset);
5290 return Fcons (build_string (buf), Qnil);
5291 }
7d0393cf 5292
d84b082d
JR
5293 {
5294 Lisp_Object rest;
5295 /* Look through w32-charset-info-alist for the character set.
5296 Only return charsets for codepages which are installed.
5297
5298 Format of each entry in Vw32_charset_info_alist is
5299 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5300 */
5301 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5302 {
5303 Lisp_Object x_charset;
5304 Lisp_Object w32_charset;
5305 Lisp_Object codepage;
5306
5307 Lisp_Object this_entry = XCAR (rest);
5308
5309 /* Skip invalid entries in alist. */
5310 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5311 || !CONSP (XCDR (this_entry))
5312 || !SYMBOLP (XCAR (XCDR (this_entry))))
5313 continue;
5314
5315 x_charset = XCAR (this_entry);
5316 w32_charset = XCAR (XCDR (this_entry));
5317 codepage = XCDR (XCDR (this_entry));
5318
5319 /* Look for Same charset and a valid codepage (or non-int
5320 which means ignore). */
5321 if (w32_charset == charset_type
5322 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5323 || IsValidCodePage (XINT (codepage))))
5324 {
5325 retval = Fcons (x_charset, retval);
5326 }
5327 }
5328
5329 /* If no match, encode the numeric value. */
5330 if (NILP (retval))
5331 {
5332 sprintf (buf, "*-#%u", fncharset);
5333 return Fcons (build_string (buf), Qnil);
5334 }
5335
5336 return retval;
5337 }
5338}
5339
dfff8a69
JR
5340/* Get the Windows codepage corresponding to the specified font. The
5341 charset info in the font name is used to look up
5342 w32-charset-to-codepage-alist. */
7d0393cf 5343int
dfff8a69
JR
5344w32_codepage_for_font (char *fontname)
5345{
767b1ff0
JR
5346 Lisp_Object codepage, entry;
5347 char *charset_str, *charset, *end;
dfff8a69 5348
767b1ff0 5349 if (NILP (Vw32_charset_info_alist))
dfff8a69
JR
5350 return CP_DEFAULT;
5351
767b1ff0
JR
5352 /* Extract charset part of font string. */
5353 charset = xlfd_charset_of_font (fontname);
5354
5355 if (!charset)
ceb12877 5356 return CP_UNKNOWN;
767b1ff0 5357
8b77111c 5358 charset_str = (char *) alloca (strlen (charset) + 1);
767b1ff0
JR
5359 strcpy (charset_str, charset);
5360
8b77111c 5361#if 0
dfff8a69
JR
5362 /* Remove leading "*-". */
5363 if (strncmp ("*-", charset_str, 2) == 0)
5364 charset = charset_str + 2;
5365 else
8b77111c 5366#endif
dfff8a69
JR
5367 charset = charset_str;
5368
5369 /* Stop match at wildcard (including preceding '-'). */
5370 if (end = strchr (charset, '*'))
5371 {
5372 if (end > charset && *(end-1) == '-')
5373 end--;
5374 *end = '\0';
5375 }
5376
767b1ff0
JR
5377 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
5378 if (NILP (entry))
ceb12877 5379 return CP_UNKNOWN;
767b1ff0
JR
5380
5381 codepage = Fcdr (Fcdr (entry));
5382
5383 if (NILP (codepage))
5384 return CP_8BIT;
5385 else if (XFASTINT (codepage) == XFASTINT (Qt))
5386 return CP_UNICODE;
5387 else if (INTEGERP (codepage))
dfff8a69
JR
5388 return XINT (codepage);
5389 else
ceb12877 5390 return CP_UNKNOWN;
dfff8a69
JR
5391}
5392
5393
7d0393cf 5394static BOOL
767b1ff0 5395w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
ee78dc32
GV
5396 LOGFONT * lplogfont;
5397 char * lpxstr;
5398 int len;
767b1ff0 5399 char * specific_charset;
ee78dc32 5400{
6fc2811b 5401 char* fonttype;
f46e6225 5402 char *fontname;
3cb20f4a
RS
5403 char height_pixels[8];
5404 char height_dpi[8];
5405 char width_pixels[8];
4587b026 5406 char *fontname_dash;
ac849ba4
JR
5407 int display_resy = (int) one_w32_display_info.resy;
5408 int display_resx = (int) one_w32_display_info.resx;
f46e6225 5409 struct coding_system coding;
3cb20f4a
RS
5410
5411 if (!lpxstr) abort ();
ee78dc32 5412
3cb20f4a
RS
5413 if (!lplogfont)
5414 return FALSE;
5415
6fc2811b
JR
5416 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5417 fonttype = "raster";
5418 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5419 fonttype = "outline";
5420 else
5421 fonttype = "unknown";
5422
1fa3a200 5423 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
f46e6225 5424 &coding);
aab5ac44
KH
5425 coding.src_multibyte = 0;
5426 coding.dst_multibyte = 1;
f46e6225 5427 coding.mode |= CODING_MODE_LAST_BLOCK;
65413122
KH
5428 /* We explicitely disable composition handling because selection
5429 data should not contain any composition sequence. */
10b4bc33
JR
5430 coding.common_flags &= ~CODING_ANNOTATION_MASK;
5431
5432 coding.dst_bytes = LF_FACESIZE * 2;
5433 coding.destination = (unsigned char *) xmalloc (coding.dst_bytes + 1);
5434 decode_coding_c_string (&coding, lplogfont->lfFaceName,
5435 strlen(lplogfont->lfFaceName), Qnil);
5436 fontname = coding.destination;
f46e6225 5437
f46e6225 5438 *(fontname + coding.produced) = '\0';
4587b026
GV
5439
5440 /* Replace dashes with underscores so the dashes are not
f46e6225 5441 misinterpreted. */
4587b026
GV
5442 fontname_dash = fontname;
5443 while (fontname_dash = strchr (fontname_dash, '-'))
5444 *fontname_dash = '_';
5445
3cb20f4a 5446 if (lplogfont->lfHeight)
ee78dc32 5447 {
3cb20f4a
RS
5448 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
5449 sprintf (height_dpi, "%u",
33d52f9c 5450 abs (lplogfont->lfHeight) * 720 / display_resy);
5ac45f98
GV
5451 }
5452 else
ee78dc32 5453 {
3cb20f4a
RS
5454 strcpy (height_pixels, "*");
5455 strcpy (height_dpi, "*");
ee78dc32 5456 }
3cb20f4a
RS
5457 if (lplogfont->lfWidth)
5458 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5459 else
5460 strcpy (width_pixels, "*");
5461
5462 _snprintf (lpxstr, len - 1,
6fc2811b
JR
5463 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5464 fonttype, /* foundry */
4587b026
GV
5465 fontname, /* family */
5466 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5467 lplogfont->lfItalic?'i':'r', /* slant */
5468 /* setwidth name */
5469 /* add style name */
5470 height_pixels, /* pixel size */
5471 height_dpi, /* point size */
33d52f9c
GV
5472 display_resx, /* resx */
5473 display_resy, /* resy */
4587b026
GV
5474 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5475 ? 'p' : 'c', /* spacing */
5476 width_pixels, /* avg width */
767b1ff0 5477 specific_charset ? specific_charset
7d0393cf 5478 : w32_to_x_charset (lplogfont->lfCharSet)
767b1ff0 5479 /* charset registry and encoding */
3cb20f4a
RS
5480 );
5481
ee78dc32
GV
5482 lpxstr[len - 1] = 0; /* just to be sure */
5483 return (TRUE);
5484}
5485
7d0393cf 5486static BOOL
fbd6baed 5487x_to_w32_font (lpxstr, lplogfont)
ee78dc32
GV
5488 char * lpxstr;
5489 LOGFONT * lplogfont;
5490{
f46e6225
GV
5491 struct coding_system coding;
5492
ee78dc32 5493 if (!lplogfont) return (FALSE);
f46e6225 5494
ee78dc32 5495 memset (lplogfont, 0, sizeof (*lplogfont));
5ac45f98 5496
1a292d24 5497 /* Set default value for each field. */
771c47d5 5498#if 1
ee78dc32
GV
5499 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5500 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5501 lplogfont->lfQuality = DEFAULT_QUALITY;
5ac45f98
GV
5502#else
5503 /* go for maximum quality */
5504 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5505 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5506 lplogfont->lfQuality = PROOF_QUALITY;
5507#endif
5508
1a292d24
AI
5509 lplogfont->lfCharSet = DEFAULT_CHARSET;
5510 lplogfont->lfWeight = FW_DONTCARE;
5511 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5512
5ac45f98
GV
5513 if (!lpxstr)
5514 return FALSE;
5515
5516 /* Provide a simple escape mechanism for specifying Windows font names
5517 * directly -- if font spec does not beginning with '-', assume this
5518 * format:
5519 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5520 */
7d0393cf 5521
5ac45f98
GV
5522 if (*lpxstr == '-')
5523 {
33d52f9c
GV
5524 int fields, tem;
5525 char name[50], weight[20], slant, pitch, pixels[10], height[10],
8b77111c 5526 width[10], resy[10], remainder[50];
5ac45f98 5527 char * encoding;
ac849ba4 5528 int dpi = (int) one_w32_display_info.resy;
5ac45f98
GV
5529
5530 fields = sscanf (lpxstr,
8b77111c 5531 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
33d52f9c 5532 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
8b77111c
AI
5533 if (fields == EOF)
5534 return (FALSE);
5535
5536 /* In the general case when wildcards cover more than one field,
5537 we don't know which field is which, so don't fill any in.
5538 However, we need to cope with this particular form, which is
5539 generated by font_list_1 (invoked by try_font_list):
5540 "-raster-6x10-*-gb2312*-*"
5541 and make sure to correctly parse the charset field. */
5542 if (fields == 3)
5543 {
5544 fields = sscanf (lpxstr,
5545 "-%*[^-]-%49[^-]-*-%49s",
5546 name, remainder);
5547 }
5548 else if (fields < 9)
5549 {
5550 fields = 0;
5551 remainder[0] = 0;
5552 }
6fc2811b 5553
5ac45f98
GV
5554 if (fields > 0 && name[0] != '*')
5555 {
f46e6225 5556 setup_coding_system
1fa3a200 5557 (Fcheck_coding_system (Vlocale_coding_system), &coding);
aab5ac44
KH
5558 coding.src_multibyte = 1;
5559 coding.dst_multibyte = 1;
10b4bc33
JR
5560 coding.dst_bytes = strlen (name) * 2;
5561 coding.destination = (unsigned char *) xmalloc (coding.dst_bytes);
f46e6225 5562 coding.mode |= CODING_MODE_LAST_BLOCK;
10b4bc33
JR
5563 encode_coding_object (&coding, build_string (name), 0, 0,
5564 strlen (name), coding.dst_bytes, Qnil);
8ea3e054
RS
5565 if (coding.produced >= LF_FACESIZE)
5566 coding.produced = LF_FACESIZE - 1;
10b4bc33
JR
5567
5568 coding.destination[coding.produced] = '\0';
5569
5570 strcpy (lplogfont->lfFaceName, coding.destination);
5571 xfree (coding.destination);
5ac45f98
GV
5572 }
5573 else
5574 {
6fc2811b 5575 lplogfont->lfFaceName[0] = '\0';
5ac45f98
GV
5576 }
5577
5578 fields--;
5579
fbd6baed 5580 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5ac45f98
GV
5581
5582 fields--;
5583
c8874f14 5584 lplogfont->lfItalic = (fields > 0 && slant == 'i');
5ac45f98
GV
5585
5586 fields--;
5587
5588 if (fields > 0 && pixels[0] != '*')
5589 lplogfont->lfHeight = atoi (pixels);
5590
5591 fields--;
5ac45f98 5592 fields--;
33d52f9c
GV
5593 if (fields > 0 && resy[0] != '*')
5594 {
6fc2811b 5595 tem = atoi (resy);
33d52f9c
GV
5596 if (tem > 0) dpi = tem;
5597 }
5ac45f98 5598
33d52f9c
GV
5599 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
5600 lplogfont->lfHeight = atoi (height) * dpi / 720;
5601
5602 if (fields > 0)
5ac45f98
GV
5603 lplogfont->lfPitchAndFamily =
5604 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
5605
5606 fields--;
5607
5608 if (fields > 0 && width[0] != '*')
5609 lplogfont->lfWidth = atoi (width) / 10;
5610
5611 fields--;
5612
4587b026 5613 /* Strip the trailing '-' if present. (it shouldn't be, as it
d88c567c 5614 fails the test against xlfd-tight-regexp in fontset.el). */
3c190163 5615 {
5ac45f98
GV
5616 int len = strlen (remainder);
5617 if (len > 0 && remainder[len-1] == '-')
5618 remainder[len-1] = 0;
ee78dc32 5619 }
5ac45f98 5620 encoding = remainder;
8b77111c 5621#if 0
5ac45f98
GV
5622 if (strncmp (encoding, "*-", 2) == 0)
5623 encoding += 2;
8b77111c
AI
5624#endif
5625 lplogfont->lfCharSet = x_to_w32_charset (encoding);
5ac45f98
GV
5626 }
5627 else
5628 {
5629 int fields;
5630 char name[100], height[10], width[10], weight[20];
a1a80b40 5631
5ac45f98
GV
5632 fields = sscanf (lpxstr,
5633 "%99[^:]:%9[^:]:%9[^:]:%19s",
5634 name, height, width, weight);
5635
5636 if (fields == EOF) return (FALSE);
5637
5638 if (fields > 0)
5639 {
5640 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
5641 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
5642 }
5643 else
5644 {
5645 lplogfont->lfFaceName[0] = 0;
5646 }
5647
5648 fields--;
5649
5650 if (fields > 0)
5651 lplogfont->lfHeight = atoi (height);
5652
5653 fields--;
5654
5655 if (fields > 0)
5656 lplogfont->lfWidth = atoi (width);
5657
5658 fields--;
5659
fbd6baed 5660 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5ac45f98
GV
5661 }
5662
5663 /* This makes TrueType fonts work better. */
5664 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6fc2811b 5665
ee78dc32
GV
5666 return (TRUE);
5667}
5668
d88c567c
JR
5669/* Strip the pixel height and point height from the given xlfd, and
5670 return the pixel height. If no pixel height is specified, calculate
5671 one from the point height, or if that isn't defined either, return
5672 0 (which usually signifies a scalable font).
5673*/
8edb0a6f
JR
5674static int
5675xlfd_strip_height (char *fontname)
d88c567c 5676{
8edb0a6f 5677 int pixel_height, field_number;
d88c567c
JR
5678 char *read_from, *write_to;
5679
5680 xassert (fontname);
5681
5682 pixel_height = field_number = 0;
5683 write_to = NULL;
5684
5685 /* Look for height fields. */
5686 for (read_from = fontname; *read_from; read_from++)
5687 {
5688 if (*read_from == '-')
5689 {
5690 field_number++;
5691 if (field_number == 7) /* Pixel height. */
5692 {
5693 read_from++;
5694 write_to = read_from;
5695
5696 /* Find end of field. */
5697 for (;*read_from && *read_from != '-'; read_from++)
5698 ;
5699
5700 /* Split the fontname at end of field. */
5701 if (*read_from)
5702 {
5703 *read_from = '\0';
5704 read_from++;
5705 }
5706 pixel_height = atoi (write_to);
5707 /* Blank out field. */
5708 if (read_from > write_to)
5709 {
5710 *write_to = '-';
5711 write_to++;
5712 }
767b1ff0 5713 /* If the pixel height field is at the end (partial xlfd),
d88c567c
JR
5714 return now. */
5715 else
5716 return pixel_height;
5717
5718 /* If we got a pixel height, the point height can be
5719 ignored. Just blank it out and break now. */
5720 if (pixel_height)
5721 {
5722 /* Find end of point size field. */
5723 for (; *read_from && *read_from != '-'; read_from++)
5724 ;
5725
5726 if (*read_from)
5727 read_from++;
5728
5729 /* Blank out the point size field. */
5730 if (read_from > write_to)
5731 {
5732 *write_to = '-';
5733 write_to++;
5734 }
5735 else
5736 return pixel_height;
5737
5738 break;
5739 }
5740 /* If the point height is already blank, break now. */
5741 if (*read_from == '-')
5742 {
5743 read_from++;
5744 break;
5745 }
5746 }
5747 else if (field_number == 8)
5748 {
5749 /* If we didn't get a pixel height, try to get the point
5750 height and convert that. */
5751 int point_size;
5752 char *point_size_start = read_from++;
5753
5754 /* Find end of field. */
5755 for (; *read_from && *read_from != '-'; read_from++)
5756 ;
5757
5758 if (*read_from)
5759 {
5760 *read_from = '\0';
5761 read_from++;
5762 }
5763
5764 point_size = atoi (point_size_start);
5765
5766 /* Convert to pixel height. */
5767 pixel_height = point_size
5768 * one_w32_display_info.height_in / 720;
5769
5770 /* Blank out this field and break. */
5771 *write_to = '-';
5772 write_to++;
5773 break;
5774 }
5775 }
5776 }
5777
5778 /* Shift the rest of the font spec into place. */
5779 if (write_to && read_from > write_to)
5780 {
5781 for (; *read_from; read_from++, write_to++)
5782 *write_to = *read_from;
5783 *write_to = '\0';
5784 }
5785
5786 return pixel_height;
5787}
5788
6fc2811b 5789/* Assume parameter 1 is fully qualified, no wildcards. */
7d0393cf 5790static BOOL
6fc2811b
JR
5791w32_font_match (fontname, pattern)
5792 char * fontname;
5793 char * pattern;
ee78dc32 5794{
e7c72122 5795 char *regex = alloca (strlen (pattern) * 2 + 3);
d88c567c 5796 char *font_name_copy = alloca (strlen (fontname) + 1);
6fc2811b 5797 char *ptr;
ee78dc32 5798
d88c567c
JR
5799 /* Copy fontname so we can modify it during comparison. */
5800 strcpy (font_name_copy, fontname);
5801
6fc2811b
JR
5802 ptr = regex;
5803 *ptr++ = '^';
ee78dc32 5804
6fc2811b
JR
5805 /* Turn pattern into a regexp and do a regexp match. */
5806 for (; *pattern; pattern++)
5807 {
5808 if (*pattern == '?')
5809 *ptr++ = '.';
5810 else if (*pattern == '*')
5811 {
5812 *ptr++ = '.';
5813 *ptr++ = '*';
5814 }
33d52f9c 5815 else
6fc2811b 5816 *ptr++ = *pattern;
ee78dc32 5817 }
6fc2811b
JR
5818 *ptr = '$';
5819 *(ptr + 1) = '\0';
5820
d88c567c
JR
5821 /* Strip out font heights and compare them seperately, since
5822 rounding error can cause mismatches. This also allows a
5823 comparison between a font that declares only a pixel height and a
5824 pattern that declares the point height.
5825 */
5826 {
5827 int font_height, pattern_height;
5828
5829 font_height = xlfd_strip_height (font_name_copy);
5830 pattern_height = xlfd_strip_height (regex);
5831
5832 /* Compare now, and don't bother doing expensive regexp matching
5833 if the heights differ. */
5834 if (font_height && pattern_height && (font_height != pattern_height))
5835 return FALSE;
5836 }
5837
6fc2811b 5838 return (fast_c_string_match_ignore_case (build_string (regex),
d88c567c 5839 font_name_copy) >= 0);
ee78dc32
GV
5840}
5841
5ca0cd71
GV
5842/* Callback functions, and a structure holding info they need, for
5843 listing system fonts on W32. We need one set of functions to do the
5844 job properly, but these don't work on NT 3.51 and earlier, so we
5845 have a second set which don't handle character sets properly to
5846 fall back on.
5847
5848 In both cases, there are two passes made. The first pass gets one
5849 font from each family, the second pass lists all the fonts from
5850 each family. */
5851
7d0393cf 5852typedef struct enumfont_t
ee78dc32
GV
5853{
5854 HDC hdc;
5855 int numFonts;
3cb20f4a 5856 LOGFONT logfont;
ee78dc32 5857 XFontStruct *size_ref;
23afac8f 5858 Lisp_Object pattern;
d84b082d 5859 Lisp_Object list;
ee78dc32
GV
5860} enumfont_t;
5861
d84b082d
JR
5862
5863static void
5864enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
5865
5866
7d0393cf 5867static int CALLBACK
ee78dc32
GV
5868enum_font_cb2 (lplf, lptm, FontType, lpef)
5869 ENUMLOGFONT * lplf;
5870 NEWTEXTMETRIC * lptm;
5871 int FontType;
5872 enumfont_t * lpef;
5873{
66895301
JR
5874 /* Ignore struck out and underlined versions of fonts. */
5875 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
5876 return 1;
5877
5878 /* Only return fonts with names starting with @ if they were
5879 explicitly specified, since Microsoft uses an initial @ to
5880 denote fonts for vertical writing, without providing a more
5881 convenient way of identifying them. */
5882 if (lplf->elfLogFont.lfFaceName[0] == '@'
5883 && lpef->logfont.lfFaceName[0] != '@')
5e905a57
JR
5884 return 1;
5885
4587b026
GV
5886 /* Check that the character set matches if it was specified */
5887 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
5888 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
5e905a57 5889 return 1;
4587b026 5890
6358474d
JR
5891 if (FontType == RASTER_FONTTYPE)
5892 {
5893 /* DBCS raster fonts have problems displaying, so skip them. */
5894 int charset = lplf->elfLogFont.lfCharSet;
5895 if (charset == SHIFTJIS_CHARSET
5896 || charset == HANGEUL_CHARSET
5897 || charset == CHINESEBIG5_CHARSET
5898 || charset == GB2312_CHARSET
5899#ifdef JOHAB_CHARSET
5900 || charset == JOHAB_CHARSET
5901#endif
5902 )
5903 return 1;
5904 }
5905
ee78dc32
GV
5906 {
5907 char buf[100];
4587b026 5908 Lisp_Object width = Qnil;
d84b082d 5909 Lisp_Object charset_list = Qnil;
767b1ff0 5910 char *charset = NULL;
ee78dc32 5911
6fc2811b
JR
5912 /* Truetype fonts do not report their true metrics until loaded */
5913 if (FontType != RASTER_FONTTYPE)
3cb20f4a 5914 {
23afac8f 5915 if (!NILP (lpef->pattern))
6fc2811b
JR
5916 {
5917 /* Scalable fonts are as big as you want them to be. */
5918 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
5919 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
5920 width = make_number (lpef->logfont.lfWidth);
5921 }
5922 else
5923 {
5924 lplf->elfLogFont.lfHeight = 0;
5925 lplf->elfLogFont.lfWidth = 0;
5926 }
3cb20f4a 5927 }
6fc2811b 5928
f46e6225
GV
5929 /* Make sure the height used here is the same as everywhere
5930 else (ie character height, not cell height). */
6fc2811b
JR
5931 if (lplf->elfLogFont.lfHeight > 0)
5932 {
5933 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
5934 if (FontType == RASTER_FONTTYPE)
5935 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
5936 else
5937 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
5938 }
4587b026 5939
23afac8f 5940 if (!NILP (lpef->pattern))
767b1ff0 5941 {
d5db4077 5942 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
767b1ff0 5943
644cefdf
JR
5944 /* We already checked charsets above, but DEFAULT_CHARSET
5945 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
5946 if (charset
5947 && strncmp (charset, "*-*", 3) != 0
5948 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
5949 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
5950 return 1;
767b1ff0
JR
5951 }
5952
d84b082d
JR
5953 if (charset)
5954 charset_list = Fcons (build_string (charset), Qnil);
5955 else
5956 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
ee78dc32 5957
d84b082d
JR
5958 /* Loop through the charsets. */
5959 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
ee78dc32 5960 {
d84b082d 5961 Lisp_Object this_charset = Fcar (charset_list);
d5db4077 5962 charset = SDATA (this_charset);
d84b082d
JR
5963
5964 /* List bold and italic variations if w32-enable-synthesized-fonts
5965 is non-nil and this is a plain font. */
5966 if (w32_enable_synthesized_fonts
5967 && lplf->elfLogFont.lfWeight == FW_NORMAL
5968 && lplf->elfLogFont.lfItalic == FALSE)
5969 {
5970 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5971 charset, width);
5972 /* bold. */
5973 lplf->elfLogFont.lfWeight = FW_BOLD;
5974 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5975 charset, width);
5976 /* bold italic. */
5977 lplf->elfLogFont.lfItalic = TRUE;
5978 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5979 charset, width);
5980 /* italic. */
5981 lplf->elfLogFont.lfWeight = FW_NORMAL;
5982 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5983 charset, width);
5984 }
5985 else
5986 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5987 charset, width);
ee78dc32
GV
5988 }
5989 }
6fc2811b 5990
5e905a57 5991 return 1;
ee78dc32
GV
5992}
5993
d84b082d
JR
5994static void
5995enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
5996 enumfont_t * lpef;
5997 LOGFONT * logfont;
5998 char * match_charset;
5999 Lisp_Object width;
6000{
6001 char buf[100];
6002
6003 if (!w32_to_x_font (logfont, buf, 100, match_charset))
6004 return;
6005
23afac8f 6006 if (NILP (lpef->pattern)
d5db4077 6007 || w32_font_match (buf, SDATA (lpef->pattern)))
d84b082d
JR
6008 {
6009 /* Check if we already listed this font. This may happen if
6010 w32_enable_synthesized_fonts is non-nil, and there are real
6011 bold and italic versions of the font. */
6012 Lisp_Object font_name = build_string (buf);
6013 if (NILP (Fmember (font_name, lpef->list)))
6014 {
23afac8f
JR
6015 Lisp_Object entry = Fcons (font_name, width);
6016 lpef->list = Fcons (entry, lpef->list);
d84b082d
JR
6017 lpef->numFonts++;
6018 }
6019 }
6020}
6021
6022
7d0393cf 6023static int CALLBACK
ee78dc32
GV
6024enum_font_cb1 (lplf, lptm, FontType, lpef)
6025 ENUMLOGFONT * lplf;
6026 NEWTEXTMETRIC * lptm;
6027 int FontType;
6028 enumfont_t * lpef;
6029{
6030 return EnumFontFamilies (lpef->hdc,
6031 lplf->elfLogFont.lfFaceName,
6032 (FONTENUMPROC) enum_font_cb2,
6033 (LPARAM) lpef);
6034}
6035
6036
8edb0a6f 6037static int CALLBACK
5ca0cd71
GV
6038enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6039 ENUMLOGFONTEX * lplf;
6040 NEWTEXTMETRICEX * lptm;
6041 int font_type;
6042 enumfont_t * lpef;
6043{
6044 /* We are not interested in the extra info we get back from the 'Ex
6045 version - only the fact that we get character set variations
6046 enumerated seperately. */
6047 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6048 font_type, lpef);
6049}
6050
8edb0a6f 6051static int CALLBACK
5ca0cd71
GV
6052enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6053 ENUMLOGFONTEX * lplf;
6054 NEWTEXTMETRICEX * lptm;
6055 int font_type;
6056 enumfont_t * lpef;
6057{
6058 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6059 FARPROC enum_font_families_ex
6060 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6061 /* We don't really expect EnumFontFamiliesEx to disappear once we
6062 get here, so don't bother handling it gracefully. */
6063 if (enum_font_families_ex == NULL)
6064 error ("gdi32.dll has disappeared!");
6065 return enum_font_families_ex (lpef->hdc,
6066 &lplf->elfLogFont,
6067 (FONTENUMPROC) enum_fontex_cb2,
6068 (LPARAM) lpef, 0);
6069}
6070
4587b026
GV
6071/* Interface to fontset handler. (adapted from mw32font.c in Meadow
6072 and xterm.c in Emacs 20.3) */
6073
8edb0a6f 6074static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
33d52f9c
GV
6075{
6076 char *fontname, *ptnstr;
6077 Lisp_Object list, tem, newlist = Qnil;
55dcfc15 6078 int n_fonts = 0;
33d52f9c
GV
6079
6080 list = Vw32_bdf_filename_alist;
d5db4077 6081 ptnstr = SDATA (pattern);
33d52f9c 6082
8e713be6 6083 for ( ; CONSP (list); list = XCDR (list))
33d52f9c 6084 {
8e713be6 6085 tem = XCAR (list);
33d52f9c 6086 if (CONSP (tem))
d5db4077 6087 fontname = SDATA (XCAR (tem));
33d52f9c 6088 else if (STRINGP (tem))
d5db4077 6089 fontname = SDATA (tem);
33d52f9c
GV
6090 else
6091 continue;
6092
6093 if (w32_font_match (fontname, ptnstr))
5ca0cd71 6094 {
8e713be6 6095 newlist = Fcons (XCAR (tem), newlist);
5ca0cd71 6096 n_fonts++;
bd11cc09 6097 if (max_names >= 0 && n_fonts >= max_names)
5ca0cd71
GV
6098 break;
6099 }
33d52f9c
GV
6100 }
6101
6102 return newlist;
6103}
6104
5ca0cd71 6105
4587b026
GV
6106/* Return a list of names of available fonts matching PATTERN on frame
6107 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6108 to be listed. Frame F NULL means we have not yet created any
6109 frame, which means we can't get proper size info, as we don't have
6110 a device context to use for GetTextMetrics.
bd11cc09
JR
6111 MAXNAMES sets a limit on how many fonts to match. If MAXNAMES is
6112 negative, then all matching fonts are returned. */
4587b026
GV
6113
6114Lisp_Object
dc220243
JR
6115w32_list_fonts (f, pattern, size, maxnames)
6116 struct frame *f;
6117 Lisp_Object pattern;
6118 int size;
6119 int maxnames;
4587b026 6120{
6fc2811b 6121 Lisp_Object patterns, key = Qnil, tem, tpat;
4587b026 6122 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
33d52f9c 6123 struct w32_display_info *dpyinfo = &one_w32_display_info;
5ca0cd71 6124 int n_fonts = 0;
396594fe 6125
4587b026
GV
6126 patterns = Fassoc (pattern, Valternate_fontname_alist);
6127 if (NILP (patterns))
6128 patterns = Fcons (pattern, Qnil);
6129
8e713be6 6130 for (; CONSP (patterns); patterns = XCDR (patterns))
4587b026
GV
6131 {
6132 enumfont_t ef;
767b1ff0 6133 int codepage;
4587b026 6134
8e713be6 6135 tpat = XCAR (patterns);
4587b026 6136
767b1ff0
JR
6137 if (!STRINGP (tpat))
6138 continue;
6139
6140 /* Avoid expensive EnumFontFamilies functions if we are not
6141 going to be able to output one of these anyway. */
d5db4077 6142 codepage = w32_codepage_for_font (SDATA (tpat));
767b1ff0 6143 if (codepage != CP_8BIT && codepage != CP_UNICODE
ceb12877
AI
6144 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6145 && !IsValidCodePage(codepage))
767b1ff0
JR
6146 continue;
6147
4587b026
GV
6148 /* See if we cached the result for this particular query.
6149 The cache is an alist of the form:
6150 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6151 */
8e713be6 6152 if (tem = XCDR (dpyinfo->name_list_element),
33d52f9c 6153 !NILP (list = Fassoc (tpat, tem)))
4587b026
GV
6154 {
6155 list = Fcdr_safe (list);
6156 /* We have a cached list. Don't have to get the list again. */
6157 goto label_cached;
6158 }
6159
6160 BLOCK_INPUT;
6161 /* At first, put PATTERN in the cache. */
23afac8f
JR
6162 ef.pattern = tpat;
6163 ef.list = Qnil;
4587b026 6164 ef.numFonts = 0;
33d52f9c 6165
5ca0cd71
GV
6166 /* Use EnumFontFamiliesEx where it is available, as it knows
6167 about character sets. Fall back to EnumFontFamilies for
6168 older versions of NT that don't support the 'Ex function. */
d5db4077 6169 x_to_w32_font (SDATA (tpat), &ef.logfont);
4587b026 6170 {
5ca0cd71
GV
6171 LOGFONT font_match_pattern;
6172 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6173 FARPROC enum_font_families_ex
6174 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6175
6176 /* We do our own pattern matching so we can handle wildcards. */
6177 font_match_pattern.lfFaceName[0] = 0;
6178 font_match_pattern.lfPitchAndFamily = 0;
6179 /* We can use the charset, because if it is a wildcard it will
6180 be DEFAULT_CHARSET anyway. */
6181 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6182
33d52f9c 6183 ef.hdc = GetDC (dpyinfo->root_window);
4587b026 6184
5ca0cd71
GV
6185 if (enum_font_families_ex)
6186 enum_font_families_ex (ef.hdc,
6187 &font_match_pattern,
6188 (FONTENUMPROC) enum_fontex_cb1,
6189 (LPARAM) &ef, 0);
6190 else
6191 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6192 (LPARAM)&ef);
4587b026 6193
33d52f9c 6194 ReleaseDC (dpyinfo->root_window, ef.hdc);
4587b026
GV
6195 }
6196
6197 UNBLOCK_INPUT;
23afac8f 6198 list = ef.list;
4587b026
GV
6199
6200 /* Make a list of the fonts we got back.
6201 Store that in the font cache for the display. */
f3fbd155
KR
6202 XSETCDR (dpyinfo->name_list_element,
6203 Fcons (Fcons (tpat, list),
6204 XCDR (dpyinfo->name_list_element)));
4587b026
GV
6205
6206 label_cached:
6207 if (NILP (list)) continue; /* Try the remaining alternatives. */
6208
6209 newlist = second_best = Qnil;
6210
7d0393cf 6211 /* Make a list of the fonts that have the right width. */
8e713be6 6212 for (; CONSP (list); list = XCDR (list))
4587b026
GV
6213 {
6214 int found_size;
8e713be6 6215 tem = XCAR (list);
4587b026
GV
6216
6217 if (!CONSP (tem))
6218 continue;
8e713be6 6219 if (NILP (XCAR (tem)))
4587b026
GV
6220 continue;
6221 if (!size)
6222 {
8e713be6 6223 newlist = Fcons (XCAR (tem), newlist);
5ca0cd71 6224 n_fonts++;
bd11cc09 6225 if (maxnames >= 0 && n_fonts >= maxnames)
5ca0cd71
GV
6226 break;
6227 else
6228 continue;
4587b026 6229 }
8e713be6 6230 if (!INTEGERP (XCDR (tem)))
4587b026
GV
6231 {
6232 /* Since we don't yet know the size of the font, we must
6233 load it and try GetTextMetrics. */
4587b026
GV
6234 W32FontStruct thisinfo;
6235 LOGFONT lf;
6236 HDC hdc;
6237 HANDLE oldobj;
6238
d5db4077 6239 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
4587b026
GV
6240 continue;
6241
6242 BLOCK_INPUT;
33d52f9c 6243 thisinfo.bdf = NULL;
4587b026
GV
6244 thisinfo.hfont = CreateFontIndirect (&lf);
6245 if (thisinfo.hfont == NULL)
6246 continue;
6247
6248 hdc = GetDC (dpyinfo->root_window);
6249 oldobj = SelectObject (hdc, thisinfo.hfont);
6250 if (GetTextMetrics (hdc, &thisinfo.tm))
f3fbd155 6251 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
4587b026 6252 else
f3fbd155 6253 XSETCDR (tem, make_number (0));
4587b026
GV
6254 SelectObject (hdc, oldobj);
6255 ReleaseDC (dpyinfo->root_window, hdc);
6256 DeleteObject(thisinfo.hfont);
6257 UNBLOCK_INPUT;
6258 }
8e713be6 6259 found_size = XINT (XCDR (tem));
4587b026 6260 if (found_size == size)
5ca0cd71 6261 {
8e713be6 6262 newlist = Fcons (XCAR (tem), newlist);
5ca0cd71 6263 n_fonts++;
bd11cc09 6264 if (maxnames >= 0 && n_fonts >= maxnames)
5ca0cd71
GV
6265 break;
6266 }
4587b026
GV
6267 /* keep track of the closest matching size in case
6268 no exact match is found. */
6269 else if (found_size > 0)
6270 {
6271 if (NILP (second_best))
6272 second_best = tem;
7d0393cf 6273
4587b026
GV
6274 else if (found_size < size)
6275 {
8e713be6
KR
6276 if (XINT (XCDR (second_best)) > size
6277 || XINT (XCDR (second_best)) < found_size)
4587b026
GV
6278 second_best = tem;
6279 }
6280 else
6281 {
8e713be6
KR
6282 if (XINT (XCDR (second_best)) > size
6283 && XINT (XCDR (second_best)) >
4587b026
GV
6284 found_size)
6285 second_best = tem;
6286 }
6287 }
6288 }
6289
6290 if (!NILP (newlist))
6291 break;
6292 else if (!NILP (second_best))
6293 {
8e713be6 6294 newlist = Fcons (XCAR (second_best), Qnil);
4587b026
GV
6295 break;
6296 }
6297 }
6298
33d52f9c 6299 /* Include any bdf fonts. */
bd11cc09 6300 if (n_fonts < maxnames || maxnames < 0)
33d52f9c
GV
6301 {
6302 Lisp_Object combined[2];
5ca0cd71 6303 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
33d52f9c
GV
6304 combined[1] = newlist;
6305 newlist = Fnconc(2, combined);
6306 }
6307
4587b026
GV
6308 return newlist;
6309}
6310
5ca0cd71 6311
4587b026
GV
6312/* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6313struct font_info *
6314w32_get_font_info (f, font_idx)
6315 FRAME_PTR f;
6316 int font_idx;
6317{
6318 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6319}
6320
6321
6322struct font_info*
6323w32_query_font (struct frame *f, char *fontname)
6324{
6325 int i;
6326 struct font_info *pfi;
6327
6328 pfi = FRAME_W32_FONT_TABLE (f);
6329
6330 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6331 {
6332 if (strcmp(pfi->name, fontname) == 0) return pfi;
6333 }
6334
6335 return NULL;
6336}
6337
6338/* Find a CCL program for a font specified by FONTP, and set the member
6339 `encoder' of the structure. */
6340
6341void
6342w32_find_ccl_program (fontp)
6343 struct font_info *fontp;
6344{
3545439c 6345 Lisp_Object list, elt;
4587b026 6346
8e713be6 6347 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
4587b026 6348 {
8e713be6 6349 elt = XCAR (list);
4587b026 6350 if (CONSP (elt)
8e713be6
KR
6351 && STRINGP (XCAR (elt))
6352 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
4587b026 6353 >= 0))
3545439c
KH
6354 break;
6355 }
6356 if (! NILP (list))
6357 {
17eedd00
KH
6358 struct ccl_program *ccl
6359 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
3545439c 6360
8e713be6 6361 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
3545439c
KH
6362 xfree (ccl);
6363 else
6364 fontp->font_encoder = ccl;
4587b026
GV
6365 }
6366}
6367
6368\f
8edb0a6f
JR
6369/* Find BDF files in a specified directory. (use GCPRO when calling,
6370 as this calls lisp to get a directory listing). */
6371static Lisp_Object
6372w32_find_bdf_fonts_in_dir (Lisp_Object directory)
6373{
6374 Lisp_Object filelist, list = Qnil;
6375 char fontname[100];
6376
6377 if (!STRINGP(directory))
6378 return Qnil;
6379
6380 filelist = Fdirectory_files (directory, Qt,
6381 build_string (".*\\.[bB][dD][fF]"), Qt);
6382
6383 for ( ; CONSP(filelist); filelist = XCDR (filelist))
6384 {
6385 Lisp_Object filename = XCAR (filelist);
d5db4077 6386 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
8edb0a6f
JR
6387 store_in_alist (&list, build_string (fontname), filename);
6388 }
6389 return list;
6390}
6391
6fc2811b
JR
6392DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6393 1, 1, 0,
b3700ae7
JR
6394 doc: /* Return a list of BDF fonts in DIR.
6395The list is suitable for appending to w32-bdf-filename-alist. Fonts
6396which do not contain an xlfd description will not be included in the
6397list. DIR may be a list of directories. */)
6fc2811b
JR
6398 (directory)
6399 Lisp_Object directory;
6400{
6401 Lisp_Object list = Qnil;
6402 struct gcpro gcpro1, gcpro2;
ee78dc32 6403
6fc2811b
JR
6404 if (!CONSP (directory))
6405 return w32_find_bdf_fonts_in_dir (directory);
ee78dc32 6406
6fc2811b 6407 for ( ; CONSP (directory); directory = XCDR (directory))
ee78dc32 6408 {
6fc2811b
JR
6409 Lisp_Object pair[2];
6410 pair[0] = list;
6411 pair[1] = Qnil;
6412 GCPRO2 (directory, list);
6413 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
6414 list = Fnconc( 2, pair );
6415 UNGCPRO;
6416 }
6417 return list;
6418}
ee78dc32 6419
6fc2811b
JR
6420\f
6421DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
74e1aeec 6422 doc: /* Internal function called by `color-defined-p', which see. */)
6fc2811b
JR
6423 (color, frame)
6424 Lisp_Object color, frame;
6425{
6426 XColor foo;
6427 FRAME_PTR f = check_x_frame (frame);
ee78dc32 6428
b7826503 6429 CHECK_STRING (color);
ee78dc32 6430
d5db4077 6431 if (w32_defined_color (f, SDATA (color), &foo, 0))
6fc2811b
JR
6432 return Qt;
6433 else
6434 return Qnil;
6435}
ee78dc32 6436
2d764c78 6437DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
74e1aeec 6438 doc: /* Internal function called by `color-values', which see. */)
ee78dc32
GV
6439 (color, frame)
6440 Lisp_Object color, frame;
6441{
6fc2811b 6442 XColor foo;
ee78dc32
GV
6443 FRAME_PTR f = check_x_frame (frame);
6444
b7826503 6445 CHECK_STRING (color);
ee78dc32 6446
d5db4077 6447 if (w32_defined_color (f, SDATA (color), &foo, 0))
ee78dc32
GV
6448 {
6449 Lisp_Object rgb[3];
6450
6fc2811b
JR
6451 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
6452 | GetRValue (foo.pixel));
6453 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
6454 | GetGValue (foo.pixel));
6455 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
6456 | GetBValue (foo.pixel));
ee78dc32
GV
6457 return Flist (3, rgb);
6458 }
6459 else
6460 return Qnil;
6461}
6462
2d764c78 6463DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
74e1aeec 6464 doc: /* Internal function called by `display-color-p', which see. */)
ee78dc32
GV
6465 (display)
6466 Lisp_Object display;
6467{
fbd6baed 6468 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6469
6470 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6471 return Qnil;
6472
6473 return Qt;
6474}
6475
74e1aeec
JR
6476DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6477 Sx_display_grayscale_p, 0, 1, 0,
6478 doc: /* Return t if the X display supports shades of gray.
6479Note that color displays do support shades of gray.
6480The optional argument DISPLAY specifies which display to ask about.
6481DISPLAY should be either a frame or a display name (a string).
6482If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6483 (display)
6484 Lisp_Object display;
6485{
fbd6baed 6486 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6487
6488 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6489 return Qnil;
6490
6491 return Qt;
6492}
6493
74e1aeec
JR
6494DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6495 Sx_display_pixel_width, 0, 1, 0,
6496 doc: /* Returns the width in pixels of DISPLAY.
6497The optional argument DISPLAY specifies which display to ask about.
6498DISPLAY should be either a frame or a display name (a string).
6499If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6500 (display)
6501 Lisp_Object display;
6502{
fbd6baed 6503 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6504
6505 return make_number (dpyinfo->width);
6506}
6507
6508DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
74e1aeec
JR
6509 Sx_display_pixel_height, 0, 1, 0,
6510 doc: /* Returns the height in pixels of DISPLAY.
6511The optional argument DISPLAY specifies which display to ask about.
6512DISPLAY should be either a frame or a display name (a string).
6513If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6514 (display)
6515 Lisp_Object display;
6516{
fbd6baed 6517 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6518
6519 return make_number (dpyinfo->height);
6520}
6521
6522DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
74e1aeec
JR
6523 0, 1, 0,
6524 doc: /* Returns the number of bitplanes of DISPLAY.
6525The optional argument DISPLAY specifies which display to ask about.
6526DISPLAY should be either a frame or a display name (a string).
6527If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6528 (display)
6529 Lisp_Object display;
6530{
fbd6baed 6531 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6532
6533 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6534}
6535
6536DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
74e1aeec
JR
6537 0, 1, 0,
6538 doc: /* Returns the number of color cells of DISPLAY.
6539The optional argument DISPLAY specifies which display to ask about.
6540DISPLAY should be either a frame or a display name (a string).
6541If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6542 (display)
6543 Lisp_Object display;
6544{
fbd6baed 6545 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6546 HDC hdc;
6547 int cap;
6548
5ac45f98
GV
6549 hdc = GetDC (dpyinfo->root_window);
6550 if (dpyinfo->has_palette)
6551 cap = GetDeviceCaps (hdc,SIZEPALETTE);
6552 else
6553 cap = GetDeviceCaps (hdc,NUMCOLORS);
abf8c61b 6554
007776bc
JB
6555 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
6556 and because probably is more meaningful on Windows anyway */
abf8c61b 6557 if (cap < 0)
007776bc 6558 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
7d0393cf 6559
ee78dc32 6560 ReleaseDC (dpyinfo->root_window, hdc);
7d0393cf 6561
ee78dc32
GV
6562 return make_number (cap);
6563}
6564
6565DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6566 Sx_server_max_request_size,
74e1aeec
JR
6567 0, 1, 0,
6568 doc: /* Returns the maximum request size of the server of DISPLAY.
6569The optional argument DISPLAY specifies which display to ask about.
6570DISPLAY should be either a frame or a display name (a string).
6571If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6572 (display)
6573 Lisp_Object display;
6574{
fbd6baed 6575 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6576
6577 return make_number (1);
6578}
6579
6580DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
74e1aeec
JR
6581 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
6582The optional argument DISPLAY specifies which display to ask about.
6583DISPLAY should be either a frame or a display name (a string).
6584If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6585 (display)
6586 Lisp_Object display;
6587{
dfff8a69 6588 return build_string ("Microsoft Corp.");
ee78dc32
GV
6589}
6590
6591DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
74e1aeec
JR
6592 doc: /* Returns the version numbers of the server of DISPLAY.
6593The value is a list of three integers: the major and minor
6594version numbers, and the vendor-specific release
6595number. See also the function `x-server-vendor'.
6596
6597The optional argument DISPLAY specifies which display to ask about.
6598DISPLAY should be either a frame or a display name (a string).
6599If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6600 (display)
6601 Lisp_Object display;
6602{
fbd6baed 6603 return Fcons (make_number (w32_major_version),
58e0f0e4
AI
6604 Fcons (make_number (w32_minor_version),
6605 Fcons (make_number (w32_build_number), Qnil)));
ee78dc32
GV
6606}
6607
6608DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
74e1aeec
JR
6609 doc: /* Returns the number of screens on the server of DISPLAY.
6610The optional argument DISPLAY specifies which display to ask about.
6611DISPLAY should be either a frame or a display name (a string).
6612If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6613 (display)
6614 Lisp_Object display;
6615{
ee78dc32
GV
6616 return make_number (1);
6617}
6618
74e1aeec
JR
6619DEFUN ("x-display-mm-height", Fx_display_mm_height,
6620 Sx_display_mm_height, 0, 1, 0,
6621 doc: /* Returns the height in millimeters of DISPLAY.
6622The optional argument DISPLAY specifies which display to ask about.
6623DISPLAY should be either a frame or a display name (a string).
6624If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6625 (display)
6626 Lisp_Object display;
6627{
fbd6baed 6628 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6629 HDC hdc;
6630 int cap;
6631
5ac45f98 6632 hdc = GetDC (dpyinfo->root_window);
7d0393cf 6633
ee78dc32 6634 cap = GetDeviceCaps (hdc, VERTSIZE);
7d0393cf 6635
ee78dc32 6636 ReleaseDC (dpyinfo->root_window, hdc);
7d0393cf 6637
ee78dc32
GV
6638 return make_number (cap);
6639}
6640
6641DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
74e1aeec
JR
6642 doc: /* Returns the width in millimeters of DISPLAY.
6643The optional argument DISPLAY specifies which display to ask about.
6644DISPLAY should be either a frame or a display name (a string).
6645If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6646 (display)
6647 Lisp_Object display;
6648{
fbd6baed 6649 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6650
6651 HDC hdc;
6652 int cap;
6653
5ac45f98 6654 hdc = GetDC (dpyinfo->root_window);
7d0393cf 6655
ee78dc32 6656 cap = GetDeviceCaps (hdc, HORZSIZE);
7d0393cf 6657
ee78dc32 6658 ReleaseDC (dpyinfo->root_window, hdc);
7d0393cf 6659
ee78dc32
GV
6660 return make_number (cap);
6661}
6662
6663DEFUN ("x-display-backing-store", Fx_display_backing_store,
74e1aeec
JR
6664 Sx_display_backing_store, 0, 1, 0,
6665 doc: /* Returns an indication of whether DISPLAY does backing store.
6666The value may be `always', `when-mapped', or `not-useful'.
6667The optional argument DISPLAY specifies which display to ask about.
6668DISPLAY should be either a frame or a display name (a string).
6669If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6670 (display)
6671 Lisp_Object display;
6672{
6673 return intern ("not-useful");
6674}
6675
6676DEFUN ("x-display-visual-class", Fx_display_visual_class,
74e1aeec
JR
6677 Sx_display_visual_class, 0, 1, 0,
6678 doc: /* Returns the visual class of DISPLAY.
6679The value is one of the symbols `static-gray', `gray-scale',
6680`static-color', `pseudo-color', `true-color', or `direct-color'.
6681
6682The optional argument DISPLAY specifies which display to ask about.
6683DISPLAY should be either a frame or a display name (a string).
6684If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6685 (display)
6686 Lisp_Object display;
6687{
fbd6baed 6688 struct w32_display_info *dpyinfo = check_x_display_info (display);
abf8c61b 6689 Lisp_Object result = Qnil;
ee78dc32 6690
abf8c61b
AI
6691 if (dpyinfo->has_palette)
6692 result = intern ("pseudo-color");
6693 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6694 result = intern ("static-grey");
6695 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6696 result = intern ("static-color");
6697 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6698 result = intern ("true-color");
ee78dc32 6699
abf8c61b 6700 return result;
ee78dc32
GV
6701}
6702
6703DEFUN ("x-display-save-under", Fx_display_save_under,
74e1aeec
JR
6704 Sx_display_save_under, 0, 1, 0,
6705 doc: /* Returns t if DISPLAY supports the save-under feature.
6706The optional argument DISPLAY specifies which display to ask about.
6707DISPLAY should be either a frame or a display name (a string).
6708If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6709 (display)
6710 Lisp_Object display;
6711{
6fc2811b
JR
6712 return Qnil;
6713}
6714\f
6715int
6716x_pixel_width (f)
6717 register struct frame *f;
6718{
be786000 6719 return FRAME_PIXEL_WIDTH (f);
6fc2811b
JR
6720}
6721
6722int
6723x_pixel_height (f)
6724 register struct frame *f;
6725{
be786000 6726 return FRAME_PIXEL_HEIGHT (f);
6fc2811b
JR
6727}
6728
6729int
6730x_char_width (f)
6731 register struct frame *f;
6732{
be786000 6733 return FRAME_COLUMN_WIDTH (f);
6fc2811b
JR
6734}
6735
6736int
6737x_char_height (f)
6738 register struct frame *f;
6739{
be786000 6740 return FRAME_LINE_HEIGHT (f);
6fc2811b
JR
6741}
6742
6743int
6744x_screen_planes (f)
6745 register struct frame *f;
6746{
6747 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
6748}
6749\f
6750/* Return the display structure for the display named NAME.
6751 Open a new connection if necessary. */
6752
6753struct w32_display_info *
6754x_display_info_for_name (name)
6755 Lisp_Object name;
6756{
6757 Lisp_Object names;
6758 struct w32_display_info *dpyinfo;
6759
b7826503 6760 CHECK_STRING (name);
6fc2811b
JR
6761
6762 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
6763 dpyinfo;
6764 dpyinfo = dpyinfo->next, names = XCDR (names))
6765 {
6766 Lisp_Object tem;
6767 tem = Fstring_equal (XCAR (XCAR (names)), name);
6768 if (!NILP (tem))
6769 return dpyinfo;
6770 }
6771
6772 /* Use this general default value to start with. */
6773 Vx_resource_name = Vinvocation_name;
6774
6775 validate_x_resource_name ();
6776
6777 dpyinfo = w32_term_init (name, (unsigned char *)0,
d5db4077 6778 (char *) SDATA (Vx_resource_name));
6fc2811b
JR
6779
6780 if (dpyinfo == 0)
d5db4077 6781 error ("Cannot connect to server %s", SDATA (name));
6fc2811b
JR
6782
6783 w32_in_use = 1;
6784 XSETFASTINT (Vwindow_system_version, 3);
6785
6786 return dpyinfo;
6787}
6788
6789DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
74e1aeec
JR
6790 1, 3, 0, doc: /* Open a connection to a server.
6791DISPLAY is the name of the display to connect to.
6792Optional second arg XRM-STRING is a string of resources in xrdb format.
6793If the optional third arg MUST-SUCCEED is non-nil,
6794terminate Emacs if we can't open the connection. */)
6fc2811b
JR
6795 (display, xrm_string, must_succeed)
6796 Lisp_Object display, xrm_string, must_succeed;
6797{
6798 unsigned char *xrm_option;
6799 struct w32_display_info *dpyinfo;
6800
74e1aeec
JR
6801 /* If initialization has already been done, return now to avoid
6802 overwriting critical parts of one_w32_display_info. */
6803 if (w32_in_use)
6804 return Qnil;
6805
b7826503 6806 CHECK_STRING (display);
6fc2811b 6807 if (! NILP (xrm_string))
b7826503 6808 CHECK_STRING (xrm_string);
6fc2811b
JR
6809
6810 if (! EQ (Vwindow_system, intern ("w32")))
6811 error ("Not using Microsoft Windows");
6812
6813 /* Allow color mapping to be defined externally; first look in user's
6814 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6815 {
6816 Lisp_Object color_file;
6817 struct gcpro gcpro1;
6818
6819 color_file = build_string("~/rgb.txt");
6820
6821 GCPRO1 (color_file);
6822
6823 if (NILP (Ffile_readable_p (color_file)))
6824 color_file =
6825 Fexpand_file_name (build_string ("rgb.txt"),
6826 Fsymbol_value (intern ("data-directory")));
6827
6828 Vw32_color_map = Fw32_load_color_file (color_file);
6829
6830 UNGCPRO;
6831 }
6832 if (NILP (Vw32_color_map))
6833 Vw32_color_map = Fw32_default_color_map ();
6834
5a8a15ec
JR
6835 /* Merge in system logical colors. */
6836 add_system_logical_colors_to_map (&Vw32_color_map);
6837
6fc2811b 6838 if (! NILP (xrm_string))
d5db4077 6839 xrm_option = (unsigned char *) SDATA (xrm_string);
6fc2811b
JR
6840 else
6841 xrm_option = (unsigned char *) 0;
6842
6843 /* Use this general default value to start with. */
6844 /* First remove .exe suffix from invocation-name - it looks ugly. */
6845 {
6846 char basename[ MAX_PATH ], *str;
6847
d5db4077 6848 strcpy (basename, SDATA (Vinvocation_name));
6fc2811b
JR
6849 str = strrchr (basename, '.');
6850 if (str) *str = 0;
6851 Vinvocation_name = build_string (basename);
6852 }
6853 Vx_resource_name = Vinvocation_name;
6854
6855 validate_x_resource_name ();
6856
6857 /* This is what opens the connection and sets x_current_display.
6858 This also initializes many symbols, such as those used for input. */
6859 dpyinfo = w32_term_init (display, xrm_option,
d5db4077 6860 (char *) SDATA (Vx_resource_name));
6fc2811b
JR
6861
6862 if (dpyinfo == 0)
6863 {
6864 if (!NILP (must_succeed))
6865 fatal ("Cannot connect to server %s.\n",
d5db4077 6866 SDATA (display));
6fc2811b 6867 else
d5db4077 6868 error ("Cannot connect to server %s", SDATA (display));
6fc2811b
JR
6869 }
6870
6871 w32_in_use = 1;
6872
6873 XSETFASTINT (Vwindow_system_version, 3);
6874 return Qnil;
6875}
6876
6877DEFUN ("x-close-connection", Fx_close_connection,
6878 Sx_close_connection, 1, 1, 0,
74e1aeec
JR
6879 doc: /* Close the connection to DISPLAY's server.
6880For DISPLAY, specify either a frame or a display name (a string).
6881If DISPLAY is nil, that stands for the selected frame's display. */)
6fc2811b
JR
6882 (display)
6883 Lisp_Object display;
6884{
6885 struct w32_display_info *dpyinfo = check_x_display_info (display);
6886 int i;
6887
6888 if (dpyinfo->reference_count > 0)
6889 error ("Display still has frames on it");
6890
6891 BLOCK_INPUT;
6892 /* Free the fonts in the font table. */
6893 for (i = 0; i < dpyinfo->n_fonts; i++)
6894 if (dpyinfo->font_table[i].name)
6895 {
126f2e35
JR
6896 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
6897 xfree (dpyinfo->font_table[i].full_name);
6fc2811b 6898 xfree (dpyinfo->font_table[i].name);
6fc2811b
JR
6899 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
6900 }
6901 x_destroy_all_bitmaps (dpyinfo);
6902
6903 x_delete_display (dpyinfo);
6904 UNBLOCK_INPUT;
6905
6906 return Qnil;
6907}
6908
6909DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
74e1aeec 6910 doc: /* Return the list of display names that Emacs has connections to. */)
6fc2811b
JR
6911 ()
6912{
6913 Lisp_Object tail, result;
6914
6915 result = Qnil;
6916 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
6917 result = Fcons (XCAR (XCAR (tail)), result);
6918
6919 return result;
6920}
6921
6922DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
0a332240
PJ
6923 doc: /* This is a noop on W32 systems. */)
6924 (on, display)
6925 Lisp_Object display, on;
6fc2811b 6926{
6fc2811b
JR
6927 return Qnil;
6928}
6929
6930\f
6fc2811b
JR
6931/***********************************************************************
6932 Image types
6933 ***********************************************************************/
6934
6935/* Value is the number of elements of vector VECTOR. */
6936
6937#define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
6938
6939/* List of supported image types. Use define_image_type to add new
6940 types. Use lookup_image_type to find a type for a given symbol. */
6941
6942static struct image_type *image_types;
6943
6fc2811b
JR
6944/* The symbol `image' which is the car of the lists used to represent
6945 images in Lisp. */
6946
6947extern Lisp_Object Qimage;
6948
6949/* The symbol `xbm' which is used as the type symbol for XBM images. */
6950
6951Lisp_Object Qxbm;
6952
6953/* Keywords. */
6954
6fc2811b 6955extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
77814035
KS
6956extern Lisp_Object QCdata, QCtype;
6957Lisp_Object QCascent, QCmargin, QCrelief;
a93f4566 6958Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
3cf3436e 6959Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
6fc2811b
JR
6960
6961/* Other symbols. */
6962
3cf3436e 6963Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
6fc2811b
JR
6964
6965/* Time in seconds after which images should be removed from the cache
6966 if not displayed. */
6967
6968Lisp_Object Vimage_cache_eviction_delay;
6969
6970/* Function prototypes. */
6971
6972static void define_image_type P_ ((struct image_type *type));
6973static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
6974static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
6975static void x_laplace P_ ((struct frame *, struct image *));
3cf3436e 6976static void x_emboss P_ ((struct frame *, struct image *));
6fc2811b
JR
6977static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
6978 Lisp_Object));
6979
dfff8a69 6980
6fc2811b
JR
6981/* Define a new image type from TYPE. This adds a copy of TYPE to
6982 image_types and adds the symbol *TYPE->type to Vimage_types. */
6983
6984static void
6985define_image_type (type)
6986 struct image_type *type;
6987{
6988 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
6989 The initialized data segment is read-only. */
6990 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
6991 bcopy (type, p, sizeof *p);
6992 p->next = image_types;
6993 image_types = p;
6994 Vimage_types = Fcons (*p->type, Vimage_types);
6995}
6996
6997
6998/* Look up image type SYMBOL, and return a pointer to its image_type
6999 structure. Value is null if SYMBOL is not a known image type. */
7000
7001static INLINE struct image_type *
7002lookup_image_type (symbol)
7003 Lisp_Object symbol;
7004{
7005 struct image_type *type;
7006
7007 for (type = image_types; type; type = type->next)
7008 if (EQ (symbol, *type->type))
7009 break;
7010
7011 return type;
7012}
7013
7014
7015/* Value is non-zero if OBJECT is a valid Lisp image specification. A
7016 valid image specification is a list whose car is the symbol
7017 `image', and whose rest is a property list. The property list must
7018 contain a value for key `:type'. That value must be the name of a
7019 supported image type. The rest of the property list depends on the
7020 image type. */
7021
7022int
7023valid_image_p (object)
7024 Lisp_Object object;
7025{
7026 int valid_p = 0;
7d0393cf 7027
6fc2811b
JR
7028 if (CONSP (object) && EQ (XCAR (object), Qimage))
7029 {
3cf3436e
JR
7030 Lisp_Object tem;
7031
7032 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
7033 if (EQ (XCAR (tem), QCtype))
7034 {
7035 tem = XCDR (tem);
7036 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
7037 {
7038 struct image_type *type;
7039 type = lookup_image_type (XCAR (tem));
7040 if (type)
7041 valid_p = type->valid_p (object);
7042 }
7043
7044 break;
7045 }
6fc2811b
JR
7046 }
7047
7048 return valid_p;
7049}
7050
7051
7052/* Log error message with format string FORMAT and argument ARG.
7053 Signaling an error, e.g. when an image cannot be loaded, is not a
7054 good idea because this would interrupt redisplay, and the error
7055 message display would lead to another redisplay. This function
7056 therefore simply displays a message. */
7057
7058static void
7059image_error (format, arg1, arg2)
7060 char *format;
7061 Lisp_Object arg1, arg2;
7062{
7063 add_to_log (format, arg1, arg2);
7064}
7065
7066
7067\f
7068/***********************************************************************
7069 Image specifications
7070 ***********************************************************************/
7071
7072enum image_value_type
7073{
7074 IMAGE_DONT_CHECK_VALUE_TYPE,
7075 IMAGE_STRING_VALUE,
3cf3436e 7076 IMAGE_STRING_OR_NIL_VALUE,
6fc2811b
JR
7077 IMAGE_SYMBOL_VALUE,
7078 IMAGE_POSITIVE_INTEGER_VALUE,
8edb0a6f 7079 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
6fc2811b 7080 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
dfff8a69 7081 IMAGE_ASCENT_VALUE,
6fc2811b
JR
7082 IMAGE_INTEGER_VALUE,
7083 IMAGE_FUNCTION_VALUE,
7084 IMAGE_NUMBER_VALUE,
7085 IMAGE_BOOL_VALUE
7086};
7087
7088/* Structure used when parsing image specifications. */
7089
7090struct image_keyword
7091{
7092 /* Name of keyword. */
7093 char *name;
7094
7095 /* The type of value allowed. */
7096 enum image_value_type type;
7097
7098 /* Non-zero means key must be present. */
7099 int mandatory_p;
7100
7101 /* Used to recognize duplicate keywords in a property list. */
7102 int count;
7103
7104 /* The value that was found. */
7105 Lisp_Object value;
7106};
7107
7108
7109static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7110 int, Lisp_Object));
7111static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7112
7113
7114/* Parse image spec SPEC according to KEYWORDS. A valid image spec
7115 has the format (image KEYWORD VALUE ...). One of the keyword/
7116 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7117 image_keywords structures of size NKEYWORDS describing other
7118 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7119
7120static int
7121parse_image_spec (spec, keywords, nkeywords, type)
7122 Lisp_Object spec;
7123 struct image_keyword *keywords;
7124 int nkeywords;
7125 Lisp_Object type;
7126{
7127 int i;
7128 Lisp_Object plist;
7129
7130 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7131 return 0;
7132
7133 plist = XCDR (spec);
7134 while (CONSP (plist))
7135 {
7136 Lisp_Object key, value;
7137
7138 /* First element of a pair must be a symbol. */
7139 key = XCAR (plist);
7140 plist = XCDR (plist);
7141 if (!SYMBOLP (key))
7142 return 0;
7143
7144 /* There must follow a value. */
7145 if (!CONSP (plist))
7146 return 0;
7147 value = XCAR (plist);
7148 plist = XCDR (plist);
7149
7150 /* Find key in KEYWORDS. Error if not found. */
7151 for (i = 0; i < nkeywords; ++i)
d5db4077 7152 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
6fc2811b
JR
7153 break;
7154
7155 if (i == nkeywords)
7156 continue;
7157
7158 /* Record that we recognized the keyword. If a keywords
7159 was found more than once, it's an error. */
7160 keywords[i].value = value;
7161 ++keywords[i].count;
7d0393cf 7162
6fc2811b
JR
7163 if (keywords[i].count > 1)
7164 return 0;
7165
7166 /* Check type of value against allowed type. */
7167 switch (keywords[i].type)
7168 {
7169 case IMAGE_STRING_VALUE:
7170 if (!STRINGP (value))
7171 return 0;
7172 break;
7173
3cf3436e
JR
7174 case IMAGE_STRING_OR_NIL_VALUE:
7175 if (!STRINGP (value) && !NILP (value))
7176 return 0;
7177 break;
7178
6fc2811b
JR
7179 case IMAGE_SYMBOL_VALUE:
7180 if (!SYMBOLP (value))
7181 return 0;
7182 break;
7183
7184 case IMAGE_POSITIVE_INTEGER_VALUE:
7185 if (!INTEGERP (value) || XINT (value) <= 0)
7186 return 0;
7187 break;
7188
8edb0a6f
JR
7189 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
7190 if (INTEGERP (value) && XINT (value) >= 0)
7191 break;
7192 if (CONSP (value)
7193 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
7194 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
7195 break;
7196 return 0;
7197
dfff8a69
JR
7198 case IMAGE_ASCENT_VALUE:
7199 if (SYMBOLP (value) && EQ (value, Qcenter))
7200 break;
7201 else if (INTEGERP (value)
7202 && XINT (value) >= 0
7203 && XINT (value) <= 100)
7204 break;
7205 return 0;
7206
6fc2811b
JR
7207 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7208 if (!INTEGERP (value) || XINT (value) < 0)
7209 return 0;
7210 break;
7211
7212 case IMAGE_DONT_CHECK_VALUE_TYPE:
7213 break;
7214
7215 case IMAGE_FUNCTION_VALUE:
7216 value = indirect_function (value);
7d0393cf 7217 if (SUBRP (value)
6fc2811b
JR
7218 || COMPILEDP (value)
7219 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7220 break;
7221 return 0;
7222
7223 case IMAGE_NUMBER_VALUE:
7224 if (!INTEGERP (value) && !FLOATP (value))
7225 return 0;
7226 break;
7227
7228 case IMAGE_INTEGER_VALUE:
7229 if (!INTEGERP (value))
7230 return 0;
7231 break;
7232
7233 case IMAGE_BOOL_VALUE:
7234 if (!NILP (value) && !EQ (value, Qt))
7235 return 0;
7236 break;
7237
7238 default:
7239 abort ();
7240 break;
7241 }
7242
7243 if (EQ (key, QCtype) && !EQ (type, value))
7244 return 0;
7245 }
7246
7247 /* Check that all mandatory fields are present. */
7248 for (i = 0; i < nkeywords; ++i)
7249 if (keywords[i].mandatory_p && keywords[i].count == 0)
7250 return 0;
7251
7252 return NILP (plist);
7253}
7254
7255
7256/* Return the value of KEY in image specification SPEC. Value is nil
7257 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7258 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7259
7260static Lisp_Object
7261image_spec_value (spec, key, found)
7262 Lisp_Object spec, key;
7263 int *found;
7264{
7265 Lisp_Object tail;
7d0393cf 7266
6fc2811b
JR
7267 xassert (valid_image_p (spec));
7268
7269 for (tail = XCDR (spec);
7270 CONSP (tail) && CONSP (XCDR (tail));
7271 tail = XCDR (XCDR (tail)))
7272 {
7273 if (EQ (XCAR (tail), key))
7274 {
7275 if (found)
7276 *found = 1;
7277 return XCAR (XCDR (tail));
7278 }
7279 }
7d0393cf 7280
6fc2811b
JR
7281 if (found)
7282 *found = 0;
7283 return Qnil;
7284}
7d0393cf 7285
6fc2811b 7286
ac849ba4
JR
7287DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
7288 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
7289PIXELS non-nil means return the size in pixels, otherwise return the
7290size in canonical character units.
7291FRAME is the frame on which the image will be displayed. FRAME nil
7292or omitted means use the selected frame. */)
7293 (spec, pixels, frame)
7294 Lisp_Object spec, pixels, frame;
7295{
7296 Lisp_Object size;
7297
7298 size = Qnil;
7299 if (valid_image_p (spec))
7300 {
7301 struct frame *f = check_x_frame (frame);
7302 int id = lookup_image (f, spec);
7303 struct image *img = IMAGE_FROM_ID (f, id);
7304 int width = img->width + 2 * img->hmargin;
7305 int height = img->height + 2 * img->vmargin;
7d0393cf 7306
ac849ba4 7307 if (NILP (pixels))
be786000
KS
7308 size = Fcons (make_float ((double) width / FRAME_COLUMN_WIDTH (f)),
7309 make_float ((double) height / FRAME_LINE_HEIGHT (f)));
ac849ba4
JR
7310 else
7311 size = Fcons (make_number (width), make_number (height));
7312 }
7313 else
7314 error ("Invalid image specification");
7315
7316 return size;
7317}
7318
7319
7320DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
7321 doc: /* Return t if image SPEC has a mask bitmap.
7322FRAME is the frame on which the image will be displayed. FRAME nil
7323or omitted means use the selected frame. */)
7324 (spec, frame)
7325 Lisp_Object spec, frame;
7326{
7327 Lisp_Object mask;
7328
7329 mask = Qnil;
7330 if (valid_image_p (spec))
7331 {
7332 struct frame *f = check_x_frame (frame);
7333 int id = lookup_image (f, spec);
7334 struct image *img = IMAGE_FROM_ID (f, id);
7335 if (img->mask)
7336 mask = Qt;
7337 }
7338 else
7339 error ("Invalid image specification");
7340
7341 return mask;
7342}
6fc2811b
JR
7343
7344\f
7345/***********************************************************************
7346 Image type independent image structures
7347 ***********************************************************************/
7348
7349static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7350static void free_image P_ ((struct frame *f, struct image *img));
197edd35 7351static void x_destroy_x_image P_ ((XImage *));
6fc2811b
JR
7352
7353
7354/* Allocate and return a new image structure for image specification
7355 SPEC. SPEC has a hash value of HASH. */
7356
7357static struct image *
7358make_image (spec, hash)
7359 Lisp_Object spec;
7360 unsigned hash;
7361{
7362 struct image *img = (struct image *) xmalloc (sizeof *img);
7d0393cf 7363
6fc2811b
JR
7364 xassert (valid_image_p (spec));
7365 bzero (img, sizeof *img);
7366 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7367 xassert (img->type != NULL);
7368 img->spec = spec;
7369 img->data.lisp_val = Qnil;
7370 img->ascent = DEFAULT_IMAGE_ASCENT;
7371 img->hash = hash;
7372 return img;
7373}
7374
7375
7376/* Free image IMG which was used on frame F, including its resources. */
7377
7378static void
7379free_image (f, img)
7380 struct frame *f;
7381 struct image *img;
7382{
7383 if (img)
7384 {
7385 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7386
7387 /* Remove IMG from the hash table of its cache. */
7388 if (img->prev)
7389 img->prev->next = img->next;
7390 else
7391 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7392
7393 if (img->next)
7394 img->next->prev = img->prev;
7395
7396 c->images[img->id] = NULL;
7397
7398 /* Free resources, then free IMG. */
7399 img->type->free (f, img);
7400 xfree (img);
7401 }
7402}
7403
7404
7405/* Prepare image IMG for display on frame F. Must be called before
7406 drawing an image. */
7407
7408void
7409prepare_image_for_display (f, img)
7410 struct frame *f;
7411 struct image *img;
7412{
7413 EMACS_TIME t;
7414
7415 /* We're about to display IMG, so set its timestamp to `now'. */
7416 EMACS_GET_TIME (t);
7417 img->timestamp = EMACS_SECS (t);
7418
7419 /* If IMG doesn't have a pixmap yet, load it now, using the image
7420 type dependent loader function. */
7421 if (img->pixmap == 0 && !img->load_failed_p)
7422 img->load_failed_p = img->type->load (f, img) == 0;
7423}
7d0393cf 7424
6fc2811b 7425
dfff8a69
JR
7426/* Value is the number of pixels for the ascent of image IMG when
7427 drawn in face FACE. */
7428
7429int
7430image_ascent (img, face)
7431 struct image *img;
7432 struct face *face;
7433{
8edb0a6f 7434 int height = img->height + img->vmargin;
dfff8a69
JR
7435 int ascent;
7436
7437 if (img->ascent == CENTERED_IMAGE_ASCENT)
7438 {
7439 if (face->font)
7440 ascent = height / 2 - (FONT_DESCENT(face->font)
7441 - FONT_BASE(face->font)) / 2;
7442 else
7443 ascent = height / 2;
7444 }
7445 else
ac849ba4 7446 ascent = (int) (height * img->ascent / 100.0);
dfff8a69
JR
7447
7448 return ascent;
7449}
7450
7451
6fc2811b 7452\f
a05e2bae
JR
7453/* Image background colors. */
7454
ac849ba4
JR
7455/* Find the "best" corner color of a bitmap. XIMG is assumed to a device
7456 context with the bitmap selected. */
7457static COLORREF
197edd35
JR
7458four_corners_best (img_dc, width, height)
7459 HDC img_dc;
a05e2bae
JR
7460 unsigned long width, height;
7461{
ac849ba4 7462 COLORREF corners[4], best;
a05e2bae
JR
7463 int i, best_count;
7464
197edd35
JR
7465 /* Get the colors at the corners of img_dc. */
7466 corners[0] = GetPixel (img_dc, 0, 0);
7467 corners[1] = GetPixel (img_dc, width - 1, 0);
7468 corners[2] = GetPixel (img_dc, width - 1, height - 1);
7469 corners[3] = GetPixel (img_dc, 0, height - 1);
a05e2bae
JR
7470
7471 /* Choose the most frequently found color as background. */
7472 for (i = best_count = 0; i < 4; ++i)
7473 {
7474 int j, n;
7d0393cf 7475
a05e2bae
JR
7476 for (j = n = 0; j < 4; ++j)
7477 if (corners[i] == corners[j])
7478 ++n;
7479
7480 if (n > best_count)
7481 best = corners[i], best_count = n;
7482 }
7483
7484 return best;
a05e2bae
JR
7485}
7486
7487/* Return the `background' field of IMG. If IMG doesn't have one yet,
197edd35
JR
7488 it is guessed heuristically. If non-zero, IMG_DC is an existing
7489 device context with the image selected to use for the heuristic. */
a05e2bae
JR
7490
7491unsigned long
197edd35 7492image_background (img, f, img_dc)
a05e2bae
JR
7493 struct image *img;
7494 struct frame *f;
197edd35 7495 HDC img_dc;
a05e2bae
JR
7496{
7497 if (! img->background_valid)
7498 /* IMG doesn't have a background yet, try to guess a reasonable value. */
7499 {
197edd35
JR
7500 int free_ximg = !img_dc;
7501 HGDIOBJ prev;
7502
7503 if (free_ximg)
7504 {
7505 HDC frame_dc = get_frame_dc (f);
7506 img_dc = CreateCompatibleDC (frame_dc);
7507 release_frame_dc (f, frame_dc);
a05e2bae 7508
197edd35
JR
7509 prev = SelectObject (img_dc, img->pixmap);
7510 }
a05e2bae 7511
197edd35 7512 img->background = four_corners_best (img_dc, img->width, img->height);
a05e2bae
JR
7513
7514 if (free_ximg)
197edd35
JR
7515 {
7516 SelectObject (img_dc, prev);
7517 DeleteDC (img_dc);
7518 }
a05e2bae
JR
7519
7520 img->background_valid = 1;
a05e2bae
JR
7521 }
7522
7523 return img->background;
7524}
7525
7526/* Return the `background_transparent' field of IMG. If IMG doesn't
7527 have one yet, it is guessed heuristically. If non-zero, MASK is an
7528 existing XImage object to use for the heuristic. */
7529
7530int
7531image_background_transparent (img, f, mask)
7532 struct image *img;
7533 struct frame *f;
197edd35 7534 HDC mask;
a05e2bae
JR
7535{
7536 if (! img->background_transparent_valid)
7537 /* IMG doesn't have a background yet, try to guess a reasonable value. */
7538 {
a05e2bae
JR
7539 if (img->mask)
7540 {
7541 int free_mask = !mask;
197edd35 7542 HGDIOBJ prev;
a05e2bae 7543
197edd35
JR
7544 if (free_mask)
7545 {
7546 HDC frame_dc = get_frame_dc (f);
7547 mask = CreateCompatibleDC (frame_dc);
7548 release_frame_dc (f, frame_dc);
7549
c922a224 7550 prev = SelectObject (mask, img->mask);
197edd35 7551 }
a05e2bae
JR
7552
7553 img->background_transparent
7554 = !four_corners_best (mask, img->width, img->height);
7555
7556 if (free_mask)
197edd35
JR
7557 {
7558 SelectObject (mask, prev);
7559 DeleteDC (mask);
7560 }
a05e2bae
JR
7561 }
7562 else
a05e2bae
JR
7563 img->background_transparent = 0;
7564
7565 img->background_transparent_valid = 1;
7566 }
7567
7568 return img->background_transparent;
7569}
7570
7571\f
6fc2811b
JR
7572/***********************************************************************
7573 Helper functions for X image types
7574 ***********************************************************************/
7575
a05e2bae
JR
7576static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
7577 int, int));
6fc2811b
JR
7578static void x_clear_image P_ ((struct frame *f, struct image *img));
7579static unsigned long x_alloc_image_color P_ ((struct frame *f,
7580 struct image *img,
7581 Lisp_Object color_name,
7582 unsigned long dflt));
7583
a05e2bae
JR
7584
7585/* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
7586 free the pixmap if any. MASK_P non-zero means clear the mask
7587 pixmap if any. COLORS_P non-zero means free colors allocated for
7588 the image, if any. */
7589
7590static void
7591x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
7592 struct frame *f;
7593 struct image *img;
7594 int pixmap_p, mask_p, colors_p;
7595{
a05e2bae
JR
7596 if (pixmap_p && img->pixmap)
7597 {
ac849ba4
JR
7598 DeleteObject (img->pixmap);
7599 img->pixmap = NULL;
a05e2bae
JR
7600 img->background_valid = 0;
7601 }
7602
7603 if (mask_p && img->mask)
7604 {
ac849ba4
JR
7605 DeleteObject (img->mask);
7606 img->mask = NULL;
a05e2bae
JR
7607 img->background_transparent_valid = 0;
7608 }
7d0393cf 7609
a05e2bae
JR
7610 if (colors_p && img->ncolors)
7611 {
bf76fe9c 7612#if 0 /* TODO: color table support. */
a05e2bae 7613 x_free_colors (f, img->colors, img->ncolors);
bf76fe9c 7614#endif
a05e2bae
JR
7615 xfree (img->colors);
7616 img->colors = NULL;
7617 img->ncolors = 0;
7618 }
a05e2bae
JR
7619}
7620
6fc2811b
JR
7621/* Free X resources of image IMG which is used on frame F. */
7622
7623static void
7624x_clear_image (f, img)
7625 struct frame *f;
7626 struct image *img;
7627{
6fc2811b
JR
7628 if (img->pixmap)
7629 {
7630 BLOCK_INPUT;
ac849ba4 7631 DeleteObject (img->pixmap);
6fc2811b
JR
7632 img->pixmap = 0;
7633 UNBLOCK_INPUT;
7634 }
7635
7636 if (img->ncolors)
7637 {
ac849ba4
JR
7638#if 0 /* TODO: color table support */
7639
6fc2811b 7640 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
7d0393cf 7641
6fc2811b
JR
7642 /* If display has an immutable color map, freeing colors is not
7643 necessary and some servers don't allow it. So don't do it. */
7644 if (class != StaticColor
7645 && class != StaticGray
7646 && class != TrueColor)
7647 {
7648 Colormap cmap;
7649 BLOCK_INPUT;
7650 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
7651 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
7652 img->ncolors, 0);
7653 UNBLOCK_INPUT;
7654 }
ac849ba4 7655#endif
7d0393cf 7656
6fc2811b
JR
7657 xfree (img->colors);
7658 img->colors = NULL;
7659 img->ncolors = 0;
7660 }
6fc2811b
JR
7661}
7662
7663
7664/* Allocate color COLOR_NAME for image IMG on frame F. If color
7665 cannot be allocated, use DFLT. Add a newly allocated color to
7666 IMG->colors, so that it can be freed again. Value is the pixel
7667 color. */
7668
7669static unsigned long
7670x_alloc_image_color (f, img, color_name, dflt)
7671 struct frame *f;
7672 struct image *img;
7673 Lisp_Object color_name;
7674 unsigned long dflt;
7675{
6fc2811b
JR
7676 XColor color;
7677 unsigned long result;
7678
7679 xassert (STRINGP (color_name));
7680
d5db4077 7681 if (w32_defined_color (f, SDATA (color_name), &color, 1))
6fc2811b
JR
7682 {
7683 /* This isn't called frequently so we get away with simply
7684 reallocating the color vector to the needed size, here. */
7685 ++img->ncolors;
7686 img->colors =
7687 (unsigned long *) xrealloc (img->colors,
7688 img->ncolors * sizeof *img->colors);
7689 img->colors[img->ncolors - 1] = color.pixel;
7690 result = color.pixel;
7691 }
7692 else
7693 result = dflt;
7694 return result;
6fc2811b
JR
7695}
7696
7697
7698\f
7699/***********************************************************************
7700 Image Cache
7701 ***********************************************************************/
7702
7703static void cache_image P_ ((struct frame *f, struct image *img));
3cf3436e 7704static void postprocess_image P_ ((struct frame *, struct image *));
197edd35 7705static void x_disable_image P_ ((struct frame *, struct image *));
6fc2811b
JR
7706
7707
7708/* Return a new, initialized image cache that is allocated from the
7709 heap. Call free_image_cache to free an image cache. */
7710
7711struct image_cache *
7712make_image_cache ()
7713{
7714 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
7715 int size;
7d0393cf 7716
6fc2811b
JR
7717 bzero (c, sizeof *c);
7718 c->size = 50;
7719 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
7720 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
7721 c->buckets = (struct image **) xmalloc (size);
7722 bzero (c->buckets, size);
7723 return c;
7724}
7725
7726
7727/* Free image cache of frame F. Be aware that X frames share images
7728 caches. */
7729
7730void
7731free_image_cache (f)
7732 struct frame *f;
7733{
7734 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7735 if (c)
7736 {
7737 int i;
7738
7739 /* Cache should not be referenced by any frame when freed. */
7740 xassert (c->refcount == 0);
7d0393cf 7741
6fc2811b
JR
7742 for (i = 0; i < c->used; ++i)
7743 free_image (f, c->images[i]);
7744 xfree (c->images);
7745 xfree (c);
7746 xfree (c->buckets);
7747 FRAME_X_IMAGE_CACHE (f) = NULL;
7748 }
7749}
7750
7751
7752/* Clear image cache of frame F. FORCE_P non-zero means free all
7753 images. FORCE_P zero means clear only images that haven't been
7754 displayed for some time. Should be called from time to time to
dfff8a69
JR
7755 reduce the number of loaded images. If image-eviction-seconds is
7756 non-nil, this frees images in the cache which weren't displayed for
6fc2811b
JR
7757 at least that many seconds. */
7758
7759void
7760clear_image_cache (f, force_p)
7761 struct frame *f;
7762 int force_p;
7763{
7764 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7765
7766 if (c && INTEGERP (Vimage_cache_eviction_delay))
7767 {
7768 EMACS_TIME t;
7769 unsigned long old;
0327b4cc 7770 int i, nfreed;
6fc2811b
JR
7771
7772 EMACS_GET_TIME (t);
7773 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
7d0393cf 7774
0327b4cc
JR
7775 /* Block input so that we won't be interrupted by a SIGIO
7776 while being in an inconsistent state. */
7777 BLOCK_INPUT;
7d0393cf 7778
0327b4cc 7779 for (i = nfreed = 0; i < c->used; ++i)
6fc2811b
JR
7780 {
7781 struct image *img = c->images[i];
7782 if (img != NULL
0327b4cc 7783 && (force_p || (img->timestamp < old)))
6fc2811b
JR
7784 {
7785 free_image (f, img);
0327b4cc 7786 ++nfreed;
6fc2811b
JR
7787 }
7788 }
7789
7790 /* We may be clearing the image cache because, for example,
7791 Emacs was iconified for a longer period of time. In that
7792 case, current matrices may still contain references to
7793 images freed above. So, clear these matrices. */
0327b4cc 7794 if (nfreed)
6fc2811b 7795 {
0327b4cc 7796 Lisp_Object tail, frame;
7d0393cf 7797
0327b4cc
JR
7798 FOR_EACH_FRAME (tail, frame)
7799 {
7800 struct frame *f = XFRAME (frame);
7801 if (FRAME_W32_P (f)
7802 && FRAME_X_IMAGE_CACHE (f) == c)
7803 clear_current_matrices (f);
7804 }
7805
6fc2811b
JR
7806 ++windows_or_buffers_changed;
7807 }
0327b4cc
JR
7808
7809 UNBLOCK_INPUT;
6fc2811b
JR
7810 }
7811}
7812
7813
7814DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
7815 0, 1, 0,
74e1aeec
JR
7816 doc: /* Clear the image cache of FRAME.
7817FRAME nil or omitted means use the selected frame.
7818FRAME t means clear the image caches of all frames. */)
6fc2811b
JR
7819 (frame)
7820 Lisp_Object frame;
7821{
7822 if (EQ (frame, Qt))
7823 {
7824 Lisp_Object tail;
7d0393cf 7825
6fc2811b
JR
7826 FOR_EACH_FRAME (tail, frame)
7827 if (FRAME_W32_P (XFRAME (frame)))
7828 clear_image_cache (XFRAME (frame), 1);
7829 }
7830 else
7831 clear_image_cache (check_x_frame (frame), 1);
7832
7833 return Qnil;
7834}
7835
7836
3cf3436e
JR
7837/* Compute masks and transform image IMG on frame F, as specified
7838 by the image's specification, */
7839
7840static void
7841postprocess_image (f, img)
7842 struct frame *f;
7843 struct image *img;
7844{
3cf3436e
JR
7845 /* Manipulation of the image's mask. */
7846 if (img->pixmap)
7847 {
7848 Lisp_Object conversion, spec;
7849 Lisp_Object mask;
7850
7851 spec = img->spec;
7d0393cf 7852
3cf3436e
JR
7853 /* `:heuristic-mask t'
7854 `:mask heuristic'
7855 means build a mask heuristically.
7856 `:heuristic-mask (R G B)'
7857 `:mask (heuristic (R G B))'
7858 means build a mask from color (R G B) in the
7859 image.
7860 `:mask nil'
7861 means remove a mask, if any. */
7d0393cf 7862
3cf3436e
JR
7863 mask = image_spec_value (spec, QCheuristic_mask, NULL);
7864 if (!NILP (mask))
7865 x_build_heuristic_mask (f, img, mask);
7866 else
7867 {
7868 int found_p;
7d0393cf 7869
3cf3436e 7870 mask = image_spec_value (spec, QCmask, &found_p);
7d0393cf 7871
3cf3436e
JR
7872 if (EQ (mask, Qheuristic))
7873 x_build_heuristic_mask (f, img, Qt);
7874 else if (CONSP (mask)
7875 && EQ (XCAR (mask), Qheuristic))
7876 {
7877 if (CONSP (XCDR (mask)))
7878 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
7879 else
7880 x_build_heuristic_mask (f, img, XCDR (mask));
7881 }
7882 else if (NILP (mask) && found_p && img->mask)
7883 {
ac849ba4 7884 DeleteObject (img->mask);
3cf3436e
JR
7885 img->mask = NULL;
7886 }
7887 }
7d0393cf
JB
7888
7889
3cf3436e
JR
7890 /* Should we apply an image transformation algorithm? */
7891 conversion = image_spec_value (spec, QCconversion, NULL);
7892 if (EQ (conversion, Qdisabled))
7893 x_disable_image (f, img);
7894 else if (EQ (conversion, Qlaplace))
7895 x_laplace (f, img);
7896 else if (EQ (conversion, Qemboss))
7897 x_emboss (f, img);
7898 else if (CONSP (conversion)
7899 && EQ (XCAR (conversion), Qedge_detection))
7900 {
7901 Lisp_Object tem;
7902 tem = XCDR (conversion);
7903 if (CONSP (tem))
7904 x_edge_detection (f, img,
7905 Fplist_get (tem, QCmatrix),
7906 Fplist_get (tem, QCcolor_adjustment));
7907 }
7908 }
3cf3436e
JR
7909}
7910
7911
6fc2811b
JR
7912/* Return the id of image with Lisp specification SPEC on frame F.
7913 SPEC must be a valid Lisp image specification (see valid_image_p). */
7914
7915int
7916lookup_image (f, spec)
7917 struct frame *f;
7918 Lisp_Object spec;
7919{
7920 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7921 struct image *img;
7922 int i;
7923 unsigned hash;
7924 struct gcpro gcpro1;
7925 EMACS_TIME now;
7926
7927 /* F must be a window-system frame, and SPEC must be a valid image
7928 specification. */
7929 xassert (FRAME_WINDOW_P (f));
7930 xassert (valid_image_p (spec));
7d0393cf 7931
6fc2811b
JR
7932 GCPRO1 (spec);
7933
7934 /* Look up SPEC in the hash table of the image cache. */
7935 hash = sxhash (spec, 0);
7936 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
7937
7938 for (img = c->buckets[i]; img; img = img->next)
7939 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
7940 break;
7941
7942 /* If not found, create a new image and cache it. */
7943 if (img == NULL)
7944 {
3cf3436e
JR
7945 extern Lisp_Object Qpostscript;
7946
8edb0a6f 7947 BLOCK_INPUT;
6fc2811b
JR
7948 img = make_image (spec, hash);
7949 cache_image (f, img);
7950 img->load_failed_p = img->type->load (f, img) == 0;
6fc2811b
JR
7951
7952 /* If we can't load the image, and we don't have a width and
7953 height, use some arbitrary width and height so that we can
7954 draw a rectangle for it. */
7955 if (img->load_failed_p)
7956 {
7957 Lisp_Object value;
7958
7959 value = image_spec_value (spec, QCwidth, NULL);
7960 img->width = (INTEGERP (value)
7961 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
7962 value = image_spec_value (spec, QCheight, NULL);
7963 img->height = (INTEGERP (value)
7964 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
7965 }
7966 else
7967 {
7968 /* Handle image type independent image attributes
8f92c555 7969 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
a05e2bae
JR
7970 `:background COLOR'. */
7971 Lisp_Object ascent, margin, relief, bg;
6fc2811b
JR
7972
7973 ascent = image_spec_value (spec, QCascent, NULL);
7974 if (INTEGERP (ascent))
7975 img->ascent = XFASTINT (ascent);
dfff8a69
JR
7976 else if (EQ (ascent, Qcenter))
7977 img->ascent = CENTERED_IMAGE_ASCENT;
7978
6fc2811b
JR
7979 margin = image_spec_value (spec, QCmargin, NULL);
7980 if (INTEGERP (margin) && XINT (margin) >= 0)
8edb0a6f
JR
7981 img->vmargin = img->hmargin = XFASTINT (margin);
7982 else if (CONSP (margin) && INTEGERP (XCAR (margin))
7983 && INTEGERP (XCDR (margin)))
7984 {
7985 if (XINT (XCAR (margin)) > 0)
7986 img->hmargin = XFASTINT (XCAR (margin));
7987 if (XINT (XCDR (margin)) > 0)
7988 img->vmargin = XFASTINT (XCDR (margin));
7989 }
7d0393cf 7990
6fc2811b
JR
7991 relief = image_spec_value (spec, QCrelief, NULL);
7992 if (INTEGERP (relief))
7993 {
7994 img->relief = XINT (relief);
8edb0a6f
JR
7995 img->hmargin += abs (img->relief);
7996 img->vmargin += abs (img->relief);
6fc2811b
JR
7997 }
7998
a05e2bae
JR
7999 if (! img->background_valid)
8000 {
8001 bg = image_spec_value (img->spec, QCbackground, NULL);
8002 if (!NILP (bg))
8003 {
8004 img->background
8005 = x_alloc_image_color (f, img, bg,
8006 FRAME_BACKGROUND_PIXEL (f));
8007 img->background_valid = 1;
8008 }
8009 }
8010
3cf3436e
JR
8011 /* Do image transformations and compute masks, unless we
8012 don't have the image yet. */
8013 if (!EQ (*img->type->type, Qpostscript))
8014 postprocess_image (f, img);
6fc2811b 8015 }
3cf3436e 8016
8edb0a6f
JR
8017 UNBLOCK_INPUT;
8018 xassert (!interrupt_input_blocked);
6fc2811b
JR
8019 }
8020
8021 /* We're using IMG, so set its timestamp to `now'. */
8022 EMACS_GET_TIME (now);
8023 img->timestamp = EMACS_SECS (now);
7d0393cf 8024
6fc2811b 8025 UNGCPRO;
7d0393cf 8026
6fc2811b
JR
8027 /* Value is the image id. */
8028 return img->id;
8029}
8030
8031
8032/* Cache image IMG in the image cache of frame F. */
8033
8034static void
8035cache_image (f, img)
8036 struct frame *f;
8037 struct image *img;
8038{
8039 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8040 int i;
8041
8042 /* Find a free slot in c->images. */
8043 for (i = 0; i < c->used; ++i)
8044 if (c->images[i] == NULL)
8045 break;
8046
8047 /* If no free slot found, maybe enlarge c->images. */
8048 if (i == c->used && c->used == c->size)
8049 {
8050 c->size *= 2;
8051 c->images = (struct image **) xrealloc (c->images,
8052 c->size * sizeof *c->images);
8053 }
8054
8055 /* Add IMG to c->images, and assign IMG an id. */
8056 c->images[i] = img;
8057 img->id = i;
8058 if (i == c->used)
8059 ++c->used;
8060
8061 /* Add IMG to the cache's hash table. */
8062 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8063 img->next = c->buckets[i];
8064 if (img->next)
8065 img->next->prev = img;
8066 img->prev = NULL;
8067 c->buckets[i] = img;
8068}
8069
8070
8071/* Call FN on every image in the image cache of frame F. Used to mark
8072 Lisp Objects in the image cache. */
8073
8074void
8075forall_images_in_image_cache (f, fn)
8076 struct frame *f;
8077 void (*fn) P_ ((struct image *img));
8078{
8079 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8080 {
8081 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8082 if (c)
8083 {
8084 int i;
8085 for (i = 0; i < c->used; ++i)
8086 if (c->images[i])
8087 fn (c->images[i]);
8088 }
8089 }
8090}
8091
8092
8093\f
8094/***********************************************************************
8095 W32 support code
8096 ***********************************************************************/
8097
839b1909
JR
8098/* Macro for defining functions that will be loaded from image DLLs. */
8099#define DEF_IMGLIB_FN(func) FARPROC fn_##func
c922a224 8100
839b1909
JR
8101/* Macro for loading those image functions from the library. */
8102#define LOAD_IMGLIB_FN(lib,func) { \
8103 fn_##func = (void *) GetProcAddress (lib, #func); \
8104 if (!fn_##func) return 0; \
c922a224 8105 }
839b1909 8106
6fc2811b
JR
8107static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8108 XImage **, Pixmap *));
6fc2811b
JR
8109static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8110
8111
8112/* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8113 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8114 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
ac849ba4
JR
8115 via xmalloc. DEPTH of zero signifies a 24 bit image, otherwise
8116 DEPTH should indicate the bit depth of the image. Print error
8117 messages via image_error if an error occurs. Value is non-zero if
8118 successful. */
6fc2811b
JR
8119
8120static int
8121x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8122 struct frame *f;
8123 int width, height, depth;
8124 XImage **ximg;
8125 Pixmap *pixmap;
8126{
ac849ba4
JR
8127 BITMAPINFOHEADER *header;
8128 HDC hdc;
8129 int scanline_width_bits;
8130 int remainder;
8131 int palette_colors = 0;
6fc2811b 8132
ac849ba4
JR
8133 if (depth == 0)
8134 depth = 24;
6fc2811b 8135
ac849ba4
JR
8136 if (depth != 1 && depth != 4 && depth != 8
8137 && depth != 16 && depth != 24 && depth != 32)
8138 {
8139 image_error ("Invalid image bit depth specified", Qnil, Qnil);
8140 return 0;
8141 }
8142
8143 scanline_width_bits = width * depth;
8144 remainder = scanline_width_bits % 32;
8145
8146 if (remainder)
8147 scanline_width_bits += 32 - remainder;
8148
8149 /* Bitmaps with a depth less than 16 need a palette. */
8150 /* BITMAPINFO structure already contains the first RGBQUAD. */
8151 if (depth < 16)
8152 palette_colors = 1 << depth - 1;
8153
8154 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
6fc2811b
JR
8155 if (*ximg == NULL)
8156 {
ac849ba4 8157 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
6fc2811b
JR
8158 return 0;
8159 }
8160
ac849ba4
JR
8161 header = &((*ximg)->info.bmiHeader);
8162 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
8163 header->biSize = sizeof (*header);
8164 header->biWidth = width;
8165 header->biHeight = -height; /* negative indicates a top-down bitmap. */
8166 header->biPlanes = 1;
8167 header->biBitCount = depth;
8168 header->biCompression = BI_RGB;
8169 header->biClrUsed = palette_colors;
6fc2811b 8170
197edd35 8171 /* TODO: fill in palette. */
35624c03
JR
8172 if (depth == 1)
8173 {
8174 (*ximg)->info.bmiColors[0].rgbBlue = 0;
8175 (*ximg)->info.bmiColors[0].rgbGreen = 0;
8176 (*ximg)->info.bmiColors[0].rgbRed = 0;
8177 (*ximg)->info.bmiColors[0].rgbReserved = 0;
8178 (*ximg)->info.bmiColors[1].rgbBlue = 255;
8179 (*ximg)->info.bmiColors[1].rgbGreen = 255;
8180 (*ximg)->info.bmiColors[1].rgbRed = 255;
8181 (*ximg)->info.bmiColors[1].rgbReserved = 0;
8182 }
197edd35 8183
ac849ba4
JR
8184 hdc = get_frame_dc (f);
8185
8186 /* Create a DIBSection and raster array for the bitmap,
8187 and store its handle in *pixmap. */
197edd35
JR
8188 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
8189 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
ac849ba4
JR
8190 &((*ximg)->data), NULL, 0);
8191
8192 /* Realize display palette and garbage all frames. */
8193 release_frame_dc (f, hdc);
8194
8195 if (*pixmap == NULL)
6fc2811b 8196 {
ac849ba4
JR
8197 DWORD err = GetLastError();
8198 Lisp_Object errcode;
8199 /* All system errors are < 10000, so the following is safe. */
8200 XSETINT (errcode, (int) err);
8201 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
6fc2811b 8202 x_destroy_x_image (*ximg);
6fc2811b
JR
8203 return 0;
8204 }
ac849ba4 8205
6fc2811b
JR
8206 return 1;
8207}
8208
8209
8210/* Destroy XImage XIMG. Free XIMG->data. */
8211
8212static void
8213x_destroy_x_image (ximg)
8214 XImage *ximg;
8215{
8216 xassert (interrupt_input_blocked);
8217 if (ximg)
8218 {
ac849ba4 8219 /* Data will be freed by DestroyObject. */
6fc2811b 8220 ximg->data = NULL;
ac849ba4 8221 xfree (ximg);
6fc2811b
JR
8222 }
8223}
8224
8225
8226/* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8227 are width and height of both the image and pixmap. */
8228
8229static void
8230x_put_x_image (f, ximg, pixmap, width, height)
8231 struct frame *f;
8232 XImage *ximg;
8233 Pixmap pixmap;
c9b2104d 8234 int width, height;
6fc2811b 8235{
197edd35
JR
8236#if 0 /* I don't think this is necessary looking at where it is used. */
8237 HDC hdc = get_frame_dc (f);
8238 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
8239 release_frame_dc (f, hdc);
6fc2811b 8240#endif
ac849ba4 8241}
6fc2811b
JR
8242
8243\f
8244/***********************************************************************
3cf3436e 8245 File Handling
6fc2811b
JR
8246 ***********************************************************************/
8247
8248static Lisp_Object x_find_image_file P_ ((Lisp_Object));
3cf3436e
JR
8249static char *slurp_file P_ ((char *, int *));
8250
6fc2811b
JR
8251
8252/* Find image file FILE. Look in data-directory, then
8253 x-bitmap-file-path. Value is the full name of the file found, or
8254 nil if not found. */
8255
8256static Lisp_Object
8257x_find_image_file (file)
8258 Lisp_Object file;
8259{
8260 Lisp_Object file_found, search_path;
8261 struct gcpro gcpro1, gcpro2;
8262 int fd;
8263
8264 file_found = Qnil;
8265 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8266 GCPRO2 (file_found, search_path);
8267
8268 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
de2413e9 8269 fd = openp (search_path, file, Qnil, &file_found, Qnil);
7d0393cf 8270
939d6465 8271 if (fd == -1)
6fc2811b
JR
8272 file_found = Qnil;
8273 else
8274 close (fd);
8275
8276 UNGCPRO;
8277 return file_found;
8278}
8279
8280
3cf3436e
JR
8281/* Read FILE into memory. Value is a pointer to a buffer allocated
8282 with xmalloc holding FILE's contents. Value is null if an error
8283 occurred. *SIZE is set to the size of the file. */
8284
8285static char *
8286slurp_file (file, size)
8287 char *file;
8288 int *size;
8289{
8290 FILE *fp = NULL;
8291 char *buf = NULL;
8292 struct stat st;
8293
8294 if (stat (file, &st) == 0
c45bb3b2 8295 && (fp = fopen (file, "rb")) != NULL
3cf3436e
JR
8296 && (buf = (char *) xmalloc (st.st_size),
8297 fread (buf, 1, st.st_size, fp) == st.st_size))
8298 {
8299 *size = st.st_size;
8300 fclose (fp);
8301 }
8302 else
8303 {
8304 if (fp)
8305 fclose (fp);
8306 if (buf)
8307 {
8308 xfree (buf);
8309 buf = NULL;
8310 }
8311 }
7d0393cf 8312
3cf3436e
JR
8313 return buf;
8314}
8315
8316
6fc2811b
JR
8317\f
8318/***********************************************************************
8319 XBM images
8320 ***********************************************************************/
8321
217e5be0 8322static int xbm_scan P_ ((char **, char *, char *, int *));
6fc2811b 8323static int xbm_load P_ ((struct frame *f, struct image *img));
217e5be0
JR
8324static int xbm_load_image P_ ((struct frame *f, struct image *img,
8325 char *, char *));
6fc2811b 8326static int xbm_image_p P_ ((Lisp_Object object));
217e5be0
JR
8327static int xbm_read_bitmap_data P_ ((char *, char *, int *, int *,
8328 unsigned char **));
8329static int xbm_file_p P_ ((Lisp_Object));
6fc2811b
JR
8330
8331
8332/* Indices of image specification fields in xbm_format, below. */
8333
8334enum xbm_keyword_index
8335{
8336 XBM_TYPE,
8337 XBM_FILE,
8338 XBM_WIDTH,
8339 XBM_HEIGHT,
8340 XBM_DATA,
8341 XBM_FOREGROUND,
8342 XBM_BACKGROUND,
8343 XBM_ASCENT,
8344 XBM_MARGIN,
8345 XBM_RELIEF,
8346 XBM_ALGORITHM,
8347 XBM_HEURISTIC_MASK,
a05e2bae 8348 XBM_MASK,
6fc2811b
JR
8349 XBM_LAST
8350};
8351
8352/* Vector of image_keyword structures describing the format
8353 of valid XBM image specifications. */
8354
8355static struct image_keyword xbm_format[XBM_LAST] =
8356{
8357 {":type", IMAGE_SYMBOL_VALUE, 1},
8358 {":file", IMAGE_STRING_VALUE, 0},
8359 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8360 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8361 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
217e5be0
JR
8362 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
8363 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8364 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 8365 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 8366 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 8367 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
217e5be0
JR
8368 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8369 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
6fc2811b
JR
8370};
8371
8372/* Structure describing the image type XBM. */
8373
8374static struct image_type xbm_type =
8375{
8376 &Qxbm,
8377 xbm_image_p,
8378 xbm_load,
8379 x_clear_image,
8380 NULL
8381};
8382
8383/* Tokens returned from xbm_scan. */
8384
8385enum xbm_token
8386{
8387 XBM_TK_IDENT = 256,
8388 XBM_TK_NUMBER
8389};
8390
7d0393cf 8391
6fc2811b
JR
8392/* Return non-zero if OBJECT is a valid XBM-type image specification.
8393 A valid specification is a list starting with the symbol `image'
8394 The rest of the list is a property list which must contain an
8395 entry `:type xbm..
8396
8397 If the specification specifies a file to load, it must contain
8398 an entry `:file FILENAME' where FILENAME is a string.
8399
8400 If the specification is for a bitmap loaded from memory it must
8401 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8402 WIDTH and HEIGHT are integers > 0. DATA may be:
8403
8404 1. a string large enough to hold the bitmap data, i.e. it must
8405 have a size >= (WIDTH + 7) / 8 * HEIGHT
8406
8407 2. a bool-vector of size >= WIDTH * HEIGHT
8408
8409 3. a vector of strings or bool-vectors, one for each line of the
8410 bitmap.
8411
217e5be0
JR
8412 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
8413 may not be specified in this case because they are defined in the
8414 XBM file.
8415
6fc2811b
JR
8416 Both the file and data forms may contain the additional entries
8417 `:background COLOR' and `:foreground COLOR'. If not present,
8418 foreground and background of the frame on which the image is
217e5be0 8419 displayed is used. */
6fc2811b
JR
8420
8421static int
8422xbm_image_p (object)
8423 Lisp_Object object;
8424{
8425 struct image_keyword kw[XBM_LAST];
7d0393cf 8426
6fc2811b
JR
8427 bcopy (xbm_format, kw, sizeof kw);
8428 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8429 return 0;
8430
8431 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8432
8433 if (kw[XBM_FILE].count)
8434 {
8435 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8436 return 0;
8437 }
217e5be0
JR
8438 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
8439 {
8440 /* In-memory XBM file. */
8441 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
8442 return 0;
8443 }
6fc2811b
JR
8444 else
8445 {
8446 Lisp_Object data;
8447 int width, height;
8448
8449 /* Entries for `:width', `:height' and `:data' must be present. */
8450 if (!kw[XBM_WIDTH].count
8451 || !kw[XBM_HEIGHT].count
8452 || !kw[XBM_DATA].count)
8453 return 0;
8454
8455 data = kw[XBM_DATA].value;
8456 width = XFASTINT (kw[XBM_WIDTH].value);
8457 height = XFASTINT (kw[XBM_HEIGHT].value);
7d0393cf 8458
6fc2811b
JR
8459 /* Check type of data, and width and height against contents of
8460 data. */
8461 if (VECTORP (data))
8462 {
8463 int i;
7d0393cf 8464
6fc2811b
JR
8465 /* Number of elements of the vector must be >= height. */
8466 if (XVECTOR (data)->size < height)
8467 return 0;
8468
8469 /* Each string or bool-vector in data must be large enough
8470 for one line of the image. */
8471 for (i = 0; i < height; ++i)
8472 {
8473 Lisp_Object elt = XVECTOR (data)->contents[i];
8474
8475 if (STRINGP (elt))
8476 {
d5db4077 8477 if (SCHARS (elt)
6fc2811b
JR
8478 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8479 return 0;
8480 }
8481 else if (BOOL_VECTOR_P (elt))
8482 {
8483 if (XBOOL_VECTOR (elt)->size < width)
8484 return 0;
8485 }
8486 else
8487 return 0;
8488 }
8489 }
8490 else if (STRINGP (data))
8491 {
d5db4077 8492 if (SCHARS (data)
6fc2811b
JR
8493 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8494 return 0;
8495 }
8496 else if (BOOL_VECTOR_P (data))
8497 {
8498 if (XBOOL_VECTOR (data)->size < width * height)
8499 return 0;
8500 }
8501 else
8502 return 0;
8503 }
8504
6fc2811b
JR
8505 return 1;
8506}
8507
8508
8509/* Scan a bitmap file. FP is the stream to read from. Value is
8510 either an enumerator from enum xbm_token, or a character for a
8511 single-character token, or 0 at end of file. If scanning an
8512 identifier, store the lexeme of the identifier in SVAL. If
8513 scanning a number, store its value in *IVAL. */
8514
8515static int
3cf3436e
JR
8516xbm_scan (s, end, sval, ival)
8517 char **s, *end;
6fc2811b
JR
8518 char *sval;
8519 int *ival;
8520{
8521 int c;
3cf3436e
JR
8522
8523 loop:
8524
6fc2811b 8525 /* Skip white space. */
af3f7be7 8526 while (*s < end && (c = *(*s)++, isspace (c)))
6fc2811b
JR
8527 ;
8528
3cf3436e 8529 if (*s >= end)
6fc2811b
JR
8530 c = 0;
8531 else if (isdigit (c))
8532 {
8533 int value = 0, digit;
7d0393cf 8534
3cf3436e 8535 if (c == '0' && *s < end)
6fc2811b 8536 {
3cf3436e 8537 c = *(*s)++;
6fc2811b
JR
8538 if (c == 'x' || c == 'X')
8539 {
3cf3436e 8540 while (*s < end)
6fc2811b 8541 {
3cf3436e 8542 c = *(*s)++;
6fc2811b
JR
8543 if (isdigit (c))
8544 digit = c - '0';
8545 else if (c >= 'a' && c <= 'f')
8546 digit = c - 'a' + 10;
8547 else if (c >= 'A' && c <= 'F')
8548 digit = c - 'A' + 10;
8549 else
8550 break;
8551 value = 16 * value + digit;
8552 }
8553 }
8554 else if (isdigit (c))
8555 {
8556 value = c - '0';
3cf3436e
JR
8557 while (*s < end
8558 && (c = *(*s)++, isdigit (c)))
6fc2811b
JR
8559 value = 8 * value + c - '0';
8560 }
8561 }
8562 else
8563 {
8564 value = c - '0';
3cf3436e
JR
8565 while (*s < end
8566 && (c = *(*s)++, isdigit (c)))
6fc2811b
JR
8567 value = 10 * value + c - '0';
8568 }
8569
3cf3436e
JR
8570 if (*s < end)
8571 *s = *s - 1;
6fc2811b
JR
8572 *ival = value;
8573 c = XBM_TK_NUMBER;
8574 }
8575 else if (isalpha (c) || c == '_')
8576 {
8577 *sval++ = c;
3cf3436e
JR
8578 while (*s < end
8579 && (c = *(*s)++, (isalnum (c) || c == '_')))
6fc2811b
JR
8580 *sval++ = c;
8581 *sval = 0;
3cf3436e
JR
8582 if (*s < end)
8583 *s = *s - 1;
6fc2811b
JR
8584 c = XBM_TK_IDENT;
8585 }
3cf3436e
JR
8586 else if (c == '/' && **s == '*')
8587 {
8588 /* C-style comment. */
8589 ++*s;
8590 while (**s && (**s != '*' || *(*s + 1) != '/'))
8591 ++*s;
8592 if (**s)
8593 {
8594 *s += 2;
8595 goto loop;
8596 }
8597 }
6fc2811b
JR
8598
8599 return c;
8600}
8601
8602
217e5be0
JR
8603/* XBM bits seem to be backward within bytes compared with how
8604 Windows does things. */
8605static unsigned char reflect_byte (unsigned char orig)
8606{
8607 int i;
8608 unsigned char reflected = 0x00;
8609 for (i = 0; i < 8; i++)
8610 {
8611 if (orig & (0x01 << i))
8612 reflected |= 0x80 >> i;
8613 }
8614 return reflected;
8615}
8616
8617
af3f7be7
JR
8618/* Create a Windows bitmap from X bitmap data. */
8619static HBITMAP
8620w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
8621{
8622 int i, j, w1, w2;
8623 char *bits, *p;
8624 HBITMAP bmp;
8625
8626 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
8627 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
c736ffda 8628 bits = (char *) alloca (height * w2);
af3f7be7
JR
8629 bzero (bits, height * w2);
8630 for (i = 0; i < height; i++)
8631 {
8632 p = bits + i*w2;
8633 for (j = 0; j < w1; j++)
8634 *p++ = reflect_byte(*data++);
8635 }
8636 bmp = CreateBitmap (width, height, 1, 1, bits);
af3f7be7
JR
8637
8638 return bmp;
8639}
8640
8641
6fc2811b 8642/* Replacement for XReadBitmapFileData which isn't available under old
3cf3436e
JR
8643 X versions. CONTENTS is a pointer to a buffer to parse; END is the
8644 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
8645 the image. Return in *DATA the bitmap data allocated with xmalloc.
8646 Value is non-zero if successful. DATA null means just test if
8647 CONTENTS looks like an in-memory XBM file. */
6fc2811b
JR
8648
8649static int
3cf3436e
JR
8650xbm_read_bitmap_data (contents, end, width, height, data)
8651 char *contents, *end;
6fc2811b
JR
8652 int *width, *height;
8653 unsigned char **data;
8654{
3cf3436e 8655 char *s = contents;
6fc2811b
JR
8656 char buffer[BUFSIZ];
8657 int padding_p = 0;
8658 int v10 = 0;
af3f7be7 8659 int bytes_per_line, i, nbytes;
6fc2811b
JR
8660 unsigned char *p;
8661 int value;
8662 int LA1;
8663
8664#define match() \
217e5be0 8665 LA1 = xbm_scan (&s, end, buffer, &value)
6fc2811b
JR
8666
8667#define expect(TOKEN) \
8668 if (LA1 != (TOKEN)) \
8669 goto failure; \
8670 else \
7d0393cf 8671 match ()
6fc2811b
JR
8672
8673#define expect_ident(IDENT) \
8674 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8675 match (); \
8676 else \
8677 goto failure
8678
6fc2811b 8679 *width = *height = -1;
3cf3436e
JR
8680 if (data)
8681 *data = NULL;
8682 LA1 = xbm_scan (&s, end, buffer, &value);
6fc2811b
JR
8683
8684 /* Parse defines for width, height and hot-spots. */
8685 while (LA1 == '#')
8686 {
8687 match ();
8688 expect_ident ("define");
8689 expect (XBM_TK_IDENT);
8690
8691 if (LA1 == XBM_TK_NUMBER);
8692 {
8693 char *p = strrchr (buffer, '_');
8694 p = p ? p + 1 : buffer;
8695 if (strcmp (p, "width") == 0)
8696 *width = value;
8697 else if (strcmp (p, "height") == 0)
8698 *height = value;
8699 }
8700 expect (XBM_TK_NUMBER);
8701 }
8702
8703 if (*width < 0 || *height < 0)
8704 goto failure;
3cf3436e
JR
8705 else if (data == NULL)
8706 goto success;
6fc2811b
JR
8707
8708 /* Parse bits. Must start with `static'. */
8709 expect_ident ("static");
8710 if (LA1 == XBM_TK_IDENT)
8711 {
8712 if (strcmp (buffer, "unsigned") == 0)
8713 {
7d0393cf 8714 match ();
6fc2811b
JR
8715 expect_ident ("char");
8716 }
8717 else if (strcmp (buffer, "short") == 0)
8718 {
8719 match ();
8720 v10 = 1;
af3f7be7
JR
8721 if (*width % 16 && *width % 16 < 9)
8722 padding_p = 1;
6fc2811b
JR
8723 }
8724 else if (strcmp (buffer, "char") == 0)
8725 match ();
8726 else
8727 goto failure;
8728 }
7d0393cf 8729 else
6fc2811b
JR
8730 goto failure;
8731
8732 expect (XBM_TK_IDENT);
8733 expect ('[');
8734 expect (']');
8735 expect ('=');
8736 expect ('{');
8737
af3f7be7
JR
8738 bytes_per_line = (*width + 7) / 8 + padding_p;
8739 nbytes = bytes_per_line * *height;
8740 p = *data = (char *) xmalloc (nbytes);
6fc2811b
JR
8741
8742 if (v10)
8743 {
6fc2811b
JR
8744 for (i = 0; i < nbytes; i += 2)
8745 {
8746 int val = value;
8747 expect (XBM_TK_NUMBER);
8748
35624c03 8749 *p++ = ~ val;
af3f7be7 8750 if (!padding_p || ((i + 2) % bytes_per_line))
35624c03 8751 *p++ = ~ (value >> 8);
7d0393cf 8752
6fc2811b
JR
8753 if (LA1 == ',' || LA1 == '}')
8754 match ();
8755 else
8756 goto failure;
8757 }
8758 }
8759 else
8760 {
8761 for (i = 0; i < nbytes; ++i)
8762 {
8763 int val = value;
8764 expect (XBM_TK_NUMBER);
7d0393cf 8765
35624c03 8766 *p++ = ~ val;
217e5be0 8767
6fc2811b
JR
8768 if (LA1 == ',' || LA1 == '}')
8769 match ();
8770 else
8771 goto failure;
8772 }
8773 }
8774
3cf3436e 8775 success:
6fc2811b
JR
8776 return 1;
8777
8778 failure:
3cf3436e
JR
8779
8780 if (data && *data)
6fc2811b
JR
8781 {
8782 xfree (*data);
8783 *data = NULL;
8784 }
8785 return 0;
8786
8787#undef match
8788#undef expect
8789#undef expect_ident
8790}
8791
516eea8e
JR
8792static void convert_mono_to_color_image (f, img, foreground, background)
8793 struct frame *f;
8794 struct image *img;
8795 COLORREF foreground, background;
8796{
8797 HDC hdc, old_img_dc, new_img_dc;
8798 HGDIOBJ old_prev, new_prev;
8799 HBITMAP new_pixmap;
8800
8801 hdc = get_frame_dc (f);
8802 old_img_dc = CreateCompatibleDC (hdc);
8803 new_img_dc = CreateCompatibleDC (hdc);
8804 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
8805 release_frame_dc (f, hdc);
8806 old_prev = SelectObject (old_img_dc, img->pixmap);
8807 new_prev = SelectObject (new_img_dc, new_pixmap);
8808 SetTextColor (new_img_dc, foreground);
8809 SetBkColor (new_img_dc, background);
8810
8811 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
8812 0, 0, SRCCOPY);
8813
8814 SelectObject (old_img_dc, old_prev);
c922a224 8815 SelectObject (new_img_dc, new_prev);
516eea8e
JR
8816 DeleteDC (old_img_dc);
8817 DeleteDC (new_img_dc);
8818 DeleteObject (img->pixmap);
8819 if (new_pixmap == 0)
8820 fprintf (stderr, "Failed to convert image to color.\n");
8821 else
8822 img->pixmap = new_pixmap;
8823}
6fc2811b 8824
3cf3436e
JR
8825/* Load XBM image IMG which will be displayed on frame F from buffer
8826 CONTENTS. END is the end of the buffer. Value is non-zero if
8827 successful. */
6fc2811b
JR
8828
8829static int
3cf3436e 8830xbm_load_image (f, img, contents, end)
6fc2811b
JR
8831 struct frame *f;
8832 struct image *img;
3cf3436e 8833 char *contents, *end;
6fc2811b
JR
8834{
8835 int rc;
8836 unsigned char *data;
8837 int success_p = 0;
7d0393cf 8838
3cf3436e 8839 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
6fc2811b
JR
8840 if (rc)
8841 {
6fc2811b
JR
8842 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8843 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
516eea8e 8844 int non_default_colors = 0;
6fc2811b 8845 Lisp_Object value;
7d0393cf 8846
6fc2811b
JR
8847 xassert (img->width > 0 && img->height > 0);
8848
8849 /* Get foreground and background colors, maybe allocate colors. */
8850 value = image_spec_value (img->spec, QCforeground, NULL);
8851 if (!NILP (value))
516eea8e
JR
8852 {
8853 foreground = x_alloc_image_color (f, img, value, foreground);
8854 non_default_colors = 1;
8855 }
6fc2811b
JR
8856 value = image_spec_value (img->spec, QCbackground, NULL);
8857 if (!NILP (value))
a05e2bae
JR
8858 {
8859 background = x_alloc_image_color (f, img, value, background);
8860 img->background = background;
8861 img->background_valid = 1;
516eea8e 8862 non_default_colors = 1;
a05e2bae 8863 }
6fc2811b 8864 img->pixmap
af3f7be7 8865 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
ac849ba4 8866
516eea8e
JR
8867 /* If colors were specified, transfer the bitmap to a color one. */
8868 if (non_default_colors)
8869 convert_mono_to_color_image (f, img, foreground, background);
8870
6fc2811b
JR
8871 xfree (data);
8872
8873 if (img->pixmap == 0)
8874 {
8875 x_clear_image (f, img);
3cf3436e 8876 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
6fc2811b
JR
8877 }
8878 else
8879 success_p = 1;
6fc2811b
JR
8880 }
8881 else
8882 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8883
6fc2811b
JR
8884 return success_p;
8885}
8886
8887
3cf3436e
JR
8888/* Value is non-zero if DATA looks like an in-memory XBM file. */
8889
8890static int
8891xbm_file_p (data)
8892 Lisp_Object data;
8893{
8894 int w, h;
8895 return (STRINGP (data)
d5db4077
KR
8896 && xbm_read_bitmap_data (SDATA (data),
8897 (SDATA (data)
8898 + SBYTES (data)),
3cf3436e
JR
8899 &w, &h, NULL));
8900}
8901
7d0393cf 8902
6fc2811b
JR
8903/* Fill image IMG which is used on frame F with pixmap data. Value is
8904 non-zero if successful. */
8905
8906static int
8907xbm_load (f, img)
8908 struct frame *f;
8909 struct image *img;
8910{
8911 int success_p = 0;
8912 Lisp_Object file_name;
8913
8914 xassert (xbm_image_p (img->spec));
8915
8916 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8917 file_name = image_spec_value (img->spec, QCfile, NULL);
8918 if (STRINGP (file_name))
3cf3436e
JR
8919 {
8920 Lisp_Object file;
8921 char *contents;
8922 int size;
8923 struct gcpro gcpro1;
8924
8925 file = x_find_image_file (file_name);
8926 GCPRO1 (file);
8927 if (!STRINGP (file))
8928 {
8929 image_error ("Cannot find image file `%s'", file_name, Qnil);
8930 UNGCPRO;
8931 return 0;
8932 }
8933
d5db4077 8934 contents = slurp_file (SDATA (file), &size);
3cf3436e
JR
8935 if (contents == NULL)
8936 {
8937 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8938 UNGCPRO;
8939 return 0;
8940 }
8941
8942 success_p = xbm_load_image (f, img, contents, contents + size);
8943 UNGCPRO;
8944 }
6fc2811b
JR
8945 else
8946 {
8947 struct image_keyword fmt[XBM_LAST];
8948 Lisp_Object data;
6fc2811b
JR
8949 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8950 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
516eea8e 8951 int non_default_colors = 0;
6fc2811b
JR
8952 char *bits;
8953 int parsed_p;
3cf3436e
JR
8954 int in_memory_file_p = 0;
8955
8956 /* See if data looks like an in-memory XBM file. */
8957 data = image_spec_value (img->spec, QCdata, NULL);
8958 in_memory_file_p = xbm_file_p (data);
6fc2811b 8959
217e5be0 8960 /* Parse the image specification. */
6fc2811b
JR
8961 bcopy (xbm_format, fmt, sizeof fmt);
8962 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
8963 xassert (parsed_p);
8964
8965 /* Get specified width, and height. */
3cf3436e
JR
8966 if (!in_memory_file_p)
8967 {
8968 img->width = XFASTINT (fmt[XBM_WIDTH].value);
8969 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
8970 xassert (img->width > 0 && img->height > 0);
8971 }
217e5be0 8972
6fc2811b 8973 /* Get foreground and background colors, maybe allocate colors. */
3cf3436e
JR
8974 if (fmt[XBM_FOREGROUND].count
8975 && STRINGP (fmt[XBM_FOREGROUND].value))
516eea8e
JR
8976 {
8977 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
8978 foreground);
8979 non_default_colors = 1;
8980 }
8981
3cf3436e
JR
8982 if (fmt[XBM_BACKGROUND].count
8983 && STRINGP (fmt[XBM_BACKGROUND].value))
516eea8e
JR
8984 {
8985 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
8986 background);
8987 non_default_colors = 1;
8988 }
6fc2811b 8989
3cf3436e 8990 if (in_memory_file_p)
d5db4077
KR
8991 success_p = xbm_load_image (f, img, SDATA (data),
8992 (SDATA (data)
8993 + SBYTES (data)));
3cf3436e 8994 else
6fc2811b 8995 {
3cf3436e
JR
8996 if (VECTORP (data))
8997 {
8998 int i;
8999 char *p;
9000 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
7d0393cf 9001
3cf3436e
JR
9002 p = bits = (char *) alloca (nbytes * img->height);
9003 for (i = 0; i < img->height; ++i, p += nbytes)
9004 {
9005 Lisp_Object line = XVECTOR (data)->contents[i];
9006 if (STRINGP (line))
d5db4077 9007 bcopy (SDATA (line), p, nbytes);
3cf3436e
JR
9008 else
9009 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
9010 }
9011 }
9012 else if (STRINGP (data))
d5db4077 9013 bits = SDATA (data);
3cf3436e
JR
9014 else
9015 bits = XBOOL_VECTOR (data)->data;
af3f7be7 9016
3cf3436e 9017 /* Create the pixmap. */
3cf3436e 9018 img->pixmap
af3f7be7
JR
9019 = w32_create_pixmap_from_bitmap_data (img->width, img->height,
9020 bits);
9021
516eea8e
JR
9022 /* If colors were specified, transfer the bitmap to a color one. */
9023 if (non_default_colors)
9024 convert_mono_to_color_image (f, img, foreground, background);
9025
3cf3436e
JR
9026 if (img->pixmap)
9027 success_p = 1;
9028 else
6fc2811b 9029 {
3cf3436e
JR
9030 image_error ("Unable to create pixmap for XBM image `%s'",
9031 img->spec, Qnil);
9032 x_clear_image (f, img);
6fc2811b
JR
9033 }
9034 }
6fc2811b
JR
9035 }
9036
9037 return success_p;
9038}
7d0393cf 9039
6fc2811b
JR
9040
9041\f
9042/***********************************************************************
9043 XPM images
9044 ***********************************************************************/
9045
7d0393cf 9046#if HAVE_XPM
6fc2811b
JR
9047
9048static int xpm_image_p P_ ((Lisp_Object object));
9049static int xpm_load P_ ((struct frame *f, struct image *img));
9050static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
9051
c736ffda
JR
9052/* Indicate to xpm.h that we don't have Xlib. */
9053#define FOR_MSW
9054/* simx.h in xpm defines XColor and XImage differently than Emacs. */
9055#define XColor xpm_XColor
9056#define XImage xpm_XImage
9057#define PIXEL_ALREADY_TYPEDEFED
6fc2811b 9058#include "X11/xpm.h"
c736ffda
JR
9059#undef FOR_MSW
9060#undef XColor
9061#undef XImage
9062#undef PIXEL_ALREADY_TYPEDEFED
6fc2811b
JR
9063
9064/* The symbol `xpm' identifying XPM-format images. */
9065
9066Lisp_Object Qxpm;
9067
9068/* Indices of image specification fields in xpm_format, below. */
9069
9070enum xpm_keyword_index
9071{
9072 XPM_TYPE,
9073 XPM_FILE,
9074 XPM_DATA,
9075 XPM_ASCENT,
9076 XPM_MARGIN,
9077 XPM_RELIEF,
9078 XPM_ALGORITHM,
9079 XPM_HEURISTIC_MASK,
a05e2bae 9080 XPM_MASK,
6fc2811b 9081 XPM_COLOR_SYMBOLS,
a05e2bae 9082 XPM_BACKGROUND,
6fc2811b
JR
9083 XPM_LAST
9084};
9085
9086/* Vector of image_keyword structures describing the format
9087 of valid XPM image specifications. */
9088
9089static struct image_keyword xpm_format[XPM_LAST] =
9090{
9091 {":type", IMAGE_SYMBOL_VALUE, 1},
9092 {":file", IMAGE_STRING_VALUE, 0},
9093 {":data", IMAGE_STRING_VALUE, 0},
8f92c555 9094 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 9095 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 9096 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 9097 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6fc2811b 9098 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
9099 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9100 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9101 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
9102};
9103
197edd35 9104/* Structure describing the image type XPM. */
6fc2811b
JR
9105
9106static struct image_type xpm_type =
9107{
9108 &Qxpm,
9109 xpm_image_p,
9110 xpm_load,
9111 x_clear_image,
9112 NULL
9113};
9114
9115
c736ffda
JR
9116/* XPM library details. */
9117
9118DEF_IMGLIB_FN (XpmFreeAttributes);
9119DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
9120DEF_IMGLIB_FN (XpmReadFileToImage);
9121DEF_IMGLIB_FN (XImageFree);
9122
9123
9124static int
9125init_xpm_functions (library)
9126 HMODULE library;
9127{
9128 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
9129 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
9130 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
9131 LOAD_IMGLIB_FN (library, XImageFree);
9132
9133 return 1;
9134}
9135
6fc2811b
JR
9136/* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9137 for XPM images. Such a list must consist of conses whose car and
9138 cdr are strings. */
9139
9140static int
9141xpm_valid_color_symbols_p (color_symbols)
9142 Lisp_Object color_symbols;
9143{
9144 while (CONSP (color_symbols))
9145 {
9146 Lisp_Object sym = XCAR (color_symbols);
9147 if (!CONSP (sym)
9148 || !STRINGP (XCAR (sym))
9149 || !STRINGP (XCDR (sym)))
9150 break;
9151 color_symbols = XCDR (color_symbols);
9152 }
9153
9154 return NILP (color_symbols);
9155}
9156
9157
9158/* Value is non-zero if OBJECT is a valid XPM image specification. */
9159
9160static int
9161xpm_image_p (object)
9162 Lisp_Object object;
9163{
9164 struct image_keyword fmt[XPM_LAST];
9165 bcopy (xpm_format, fmt, sizeof fmt);
9166 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9167 /* Either `:file' or `:data' must be present. */
9168 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9169 /* Either no `:color-symbols' or it's a list of conses
9170 whose car and cdr are strings. */
9171 && (fmt[XPM_COLOR_SYMBOLS].count == 0
8f92c555 9172 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
6fc2811b
JR
9173}
9174
9175
9176/* Load image IMG which will be displayed on frame F. Value is
9177 non-zero if successful. */
9178
9179static int
9180xpm_load (f, img)
9181 struct frame *f;
9182 struct image *img;
9183{
c736ffda
JR
9184 HDC hdc;
9185 int rc;
6fc2811b
JR
9186 XpmAttributes attrs;
9187 Lisp_Object specified_file, color_symbols;
c736ffda 9188 xpm_XImage * xpm_image, * xpm_mask;
6fc2811b
JR
9189
9190 /* Configure the XPM lib. Use the visual of frame F. Allocate
9191 close colors. Return colors allocated. */
9192 bzero (&attrs, sizeof attrs);
c736ffda
JR
9193 xpm_image = xpm_mask = NULL;
9194
9195#if 0
dfff8a69
JR
9196 attrs.visual = FRAME_X_VISUAL (f);
9197 attrs.colormap = FRAME_X_COLORMAP (f);
6fc2811b 9198 attrs.valuemask |= XpmVisual;
dfff8a69 9199 attrs.valuemask |= XpmColormap;
c736ffda 9200#endif
6fc2811b 9201 attrs.valuemask |= XpmReturnAllocPixels;
dfff8a69 9202#ifdef XpmAllocCloseColors
6fc2811b
JR
9203 attrs.alloc_close_colors = 1;
9204 attrs.valuemask |= XpmAllocCloseColors;
dfff8a69
JR
9205#else
9206 attrs.closeness = 600;
9207 attrs.valuemask |= XpmCloseness;
9208#endif
6fc2811b
JR
9209
9210 /* If image specification contains symbolic color definitions, add
9211 these to `attrs'. */
9212 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
9213 if (CONSP (color_symbols))
9214 {
9215 Lisp_Object tail;
9216 XpmColorSymbol *xpm_syms;
9217 int i, size;
7d0393cf 9218
6fc2811b
JR
9219 attrs.valuemask |= XpmColorSymbols;
9220
9221 /* Count number of symbols. */
9222 attrs.numsymbols = 0;
9223 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
9224 ++attrs.numsymbols;
9225
9226 /* Allocate an XpmColorSymbol array. */
9227 size = attrs.numsymbols * sizeof *xpm_syms;
9228 xpm_syms = (XpmColorSymbol *) alloca (size);
9229 bzero (xpm_syms, size);
9230 attrs.colorsymbols = xpm_syms;
9231
9232 /* Fill the color symbol array. */
9233 for (tail = color_symbols, i = 0;
9234 CONSP (tail);
9235 ++i, tail = XCDR (tail))
9236 {
9237 Lisp_Object name = XCAR (XCAR (tail));
9238 Lisp_Object color = XCDR (XCAR (tail));
d5db4077
KR
9239 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
9240 strcpy (xpm_syms[i].name, SDATA (name));
9241 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
9242 strcpy (xpm_syms[i].value, SDATA (color));
6fc2811b
JR
9243 }
9244 }
9245
9246 /* Create a pixmap for the image, either from a file, or from a
9247 string buffer containing data in the same format as an XPM file. */
c736ffda 9248
6fc2811b 9249 specified_file = image_spec_value (img->spec, QCfile, NULL);
177c0ea7 9250
c736ffda
JR
9251 {
9252 HDC frame_dc = get_frame_dc (f);
9253 hdc = CreateCompatibleDC (frame_dc);
9254 release_frame_dc (f, frame_dc);
9255 }
9256
6fc2811b
JR
9257 if (STRINGP (specified_file))
9258 {
9259 Lisp_Object file = x_find_image_file (specified_file);
9260 if (!STRINGP (file))
9261 {
9262 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6fc2811b
JR
9263 return 0;
9264 }
7d0393cf 9265
c736ffda
JR
9266 /* XpmReadFileToPixmap is not available in the Windows port of
9267 libxpm. But XpmReadFileToImage almost does what we want. */
9268 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
9269 &xpm_image, &xpm_mask,
9270 &attrs);
6fc2811b
JR
9271 }
9272 else
9273 {
9274 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
c736ffda
JR
9275 /* XpmCreatePixmapFromBuffer is not available in the Windows port
9276 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
9277 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
9278 &xpm_image, &xpm_mask,
9279 &attrs);
6fc2811b 9280 }
6fc2811b
JR
9281
9282 if (rc == XpmSuccess)
9283 {
c736ffda
JR
9284 int i;
9285
9286 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
9287 plus some duplicate attributes. */
9288 if (xpm_image && xpm_image->bitmap)
9289 {
9290 img->pixmap = xpm_image->bitmap;
9291 /* XImageFree in libXpm frees XImage struct without destroying
9292 the bitmap, which is what we want. */
9293 fn_XImageFree (xpm_image);
9294 }
9295 if (xpm_mask && xpm_mask->bitmap)
177c0ea7 9296 {
c736ffda
JR
9297 /* The mask appears to be inverted compared with what we expect.
9298 TODO: invert our expectations. See other places where we
9299 have to invert bits because our idea of masks is backwards. */
9300 HGDIOBJ old_obj;
9301 old_obj = SelectObject (hdc, xpm_mask->bitmap);
9302
9303 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
9304 SelectObject (hdc, old_obj);
9305
9306 img->mask = xpm_mask->bitmap;
177c0ea7 9307 fn_XImageFree (xpm_mask);
c736ffda
JR
9308 DeleteDC (hdc);
9309 }
9310
9311 DeleteDC (hdc);
9312
6fc2811b
JR
9313 /* Remember allocated colors. */
9314 img->ncolors = attrs.nalloc_pixels;
9315 img->colors = (unsigned long *) xmalloc (img->ncolors
9316 * sizeof *img->colors);
9317 for (i = 0; i < attrs.nalloc_pixels; ++i)
9318 img->colors[i] = attrs.alloc_pixels[i];
9319
9320 img->width = attrs.width;
9321 img->height = attrs.height;
9322 xassert (img->width > 0 && img->height > 0);
9323
9324 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
c736ffda 9325 fn_XpmFreeAttributes (&attrs);
6fc2811b
JR
9326 }
9327 else
9328 {
c736ffda
JR
9329 DeleteDC (hdc);
9330
6fc2811b
JR
9331 switch (rc)
9332 {
9333 case XpmOpenFailed:
9334 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9335 break;
7d0393cf 9336
6fc2811b
JR
9337 case XpmFileInvalid:
9338 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9339 break;
7d0393cf 9340
6fc2811b
JR
9341 case XpmNoMemory:
9342 image_error ("Out of memory (%s)", img->spec, Qnil);
9343 break;
7d0393cf 9344
6fc2811b
JR
9345 case XpmColorFailed:
9346 image_error ("Color allocation error (%s)", img->spec, Qnil);
9347 break;
7d0393cf 9348
6fc2811b
JR
9349 default:
9350 image_error ("Unknown error (%s)", img->spec, Qnil);
9351 break;
9352 }
9353 }
9354
9355 return rc == XpmSuccess;
9356}
9357
9358#endif /* HAVE_XPM != 0 */
9359
9360\f
767b1ff0 9361#if 0 /* TODO : Color tables on W32. */
6fc2811b
JR
9362/***********************************************************************
9363 Color table
9364 ***********************************************************************/
9365
9366/* An entry in the color table mapping an RGB color to a pixel color. */
9367
9368struct ct_color
9369{
9370 int r, g, b;
9371 unsigned long pixel;
9372
9373 /* Next in color table collision list. */
9374 struct ct_color *next;
9375};
9376
9377/* The bucket vector size to use. Must be prime. */
9378
9379#define CT_SIZE 101
9380
9381/* Value is a hash of the RGB color given by R, G, and B. */
9382
9383#define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9384
9385/* The color hash table. */
9386
9387struct ct_color **ct_table;
9388
9389/* Number of entries in the color table. */
9390
9391int ct_colors_allocated;
9392
9393/* Function prototypes. */
9394
9395static void init_color_table P_ ((void));
9396static void free_color_table P_ ((void));
9397static unsigned long *colors_in_color_table P_ ((int *n));
9398static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9399static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9400
9401
9402/* Initialize the color table. */
9403
9404static void
9405init_color_table ()
9406{
9407 int size = CT_SIZE * sizeof (*ct_table);
9408 ct_table = (struct ct_color **) xmalloc (size);
9409 bzero (ct_table, size);
9410 ct_colors_allocated = 0;
9411}
9412
9413
9414/* Free memory associated with the color table. */
9415
9416static void
9417free_color_table ()
9418{
9419 int i;
9420 struct ct_color *p, *next;
9421
9422 for (i = 0; i < CT_SIZE; ++i)
9423 for (p = ct_table[i]; p; p = next)
9424 {
9425 next = p->next;
9426 xfree (p);
9427 }
9428
9429 xfree (ct_table);
9430 ct_table = NULL;
9431}
9432
9433
9434/* Value is a pixel color for RGB color R, G, B on frame F. If an
9435 entry for that color already is in the color table, return the
9436 pixel color of that entry. Otherwise, allocate a new color for R,
9437 G, B, and make an entry in the color table. */
9438
9439static unsigned long
9440lookup_rgb_color (f, r, g, b)
9441 struct frame *f;
9442 int r, g, b;
9443{
9444 unsigned hash = CT_HASH_RGB (r, g, b);
9445 int i = hash % CT_SIZE;
9446 struct ct_color *p;
9447
9448 for (p = ct_table[i]; p; p = p->next)
9449 if (p->r == r && p->g == g && p->b == b)
9450 break;
9451
9452 if (p == NULL)
9453 {
9454 COLORREF color;
9455 Colormap cmap;
9456 int rc;
9457
9458 color = PALETTERGB (r, g, b);
9459
9460 ++ct_colors_allocated;
9461
9462 p = (struct ct_color *) xmalloc (sizeof *p);
9463 p->r = r;
9464 p->g = g;
9465 p->b = b;
9466 p->pixel = color;
9467 p->next = ct_table[i];
9468 ct_table[i] = p;
9469 }
9470
9471 return p->pixel;
9472}
9473
9474
9475/* Look up pixel color PIXEL which is used on frame F in the color
9476 table. If not already present, allocate it. Value is PIXEL. */
9477
9478static unsigned long
9479lookup_pixel_color (f, pixel)
9480 struct frame *f;
9481 unsigned long pixel;
9482{
9483 int i = pixel % CT_SIZE;
9484 struct ct_color *p;
9485
9486 for (p = ct_table[i]; p; p = p->next)
9487 if (p->pixel == pixel)
9488 break;
9489
9490 if (p == NULL)
9491 {
9492 XColor color;
9493 Colormap cmap;
9494 int rc;
9495
9496 BLOCK_INPUT;
7d0393cf 9497
6fc2811b
JR
9498 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9499 color.pixel = pixel;
9500 XQueryColor (NULL, cmap, &color);
9501 rc = x_alloc_nearest_color (f, cmap, &color);
9502 UNBLOCK_INPUT;
9503
9504 if (rc)
9505 {
9506 ++ct_colors_allocated;
7d0393cf 9507
6fc2811b
JR
9508 p = (struct ct_color *) xmalloc (sizeof *p);
9509 p->r = color.red;
9510 p->g = color.green;
9511 p->b = color.blue;
9512 p->pixel = pixel;
9513 p->next = ct_table[i];
9514 ct_table[i] = p;
9515 }
9516 else
9517 return FRAME_FOREGROUND_PIXEL (f);
9518 }
9519 return p->pixel;
9520}
9521
9522
9523/* Value is a vector of all pixel colors contained in the color table,
9524 allocated via xmalloc. Set *N to the number of colors. */
9525
9526static unsigned long *
9527colors_in_color_table (n)
9528 int *n;
9529{
9530 int i, j;
9531 struct ct_color *p;
9532 unsigned long *colors;
9533
9534 if (ct_colors_allocated == 0)
9535 {
9536 *n = 0;
9537 colors = NULL;
9538 }
9539 else
9540 {
9541 colors = (unsigned long *) xmalloc (ct_colors_allocated
9542 * sizeof *colors);
9543 *n = ct_colors_allocated;
7d0393cf 9544
6fc2811b
JR
9545 for (i = j = 0; i < CT_SIZE; ++i)
9546 for (p = ct_table[i]; p; p = p->next)
9547 colors[j++] = p->pixel;
9548 }
9549
9550 return colors;
9551}
9552
767b1ff0 9553#endif /* TODO */
6fc2811b
JR
9554
9555\f
9556/***********************************************************************
9557 Algorithms
9558 ***********************************************************************/
3cf3436e
JR
9559static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
9560static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
9561static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
ac849ba4 9562static void XPutPixel (XImage *, int, int, COLORREF);
3cf3436e
JR
9563
9564/* Non-zero means draw a cross on images having `:conversion
9565 disabled'. */
6fc2811b 9566
3cf3436e 9567int cross_disabled_images;
6fc2811b 9568
3cf3436e
JR
9569/* Edge detection matrices for different edge-detection
9570 strategies. */
6fc2811b 9571
3cf3436e
JR
9572static int emboss_matrix[9] = {
9573 /* x - 1 x x + 1 */
9574 2, -1, 0, /* y - 1 */
9575 -1, 0, 1, /* y */
9576 0, 1, -2 /* y + 1 */
9577};
9578
9579static int laplace_matrix[9] = {
9580 /* x - 1 x x + 1 */
9581 1, 0, 0, /* y - 1 */
9582 0, 0, 0, /* y */
9583 0, 0, -1 /* y + 1 */
9584};
9585
9586/* Value is the intensity of the color whose red/green/blue values
9587 are R, G, and B. */
9588
9589#define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
9590
9591
9592/* On frame F, return an array of XColor structures describing image
9593 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
9594 non-zero means also fill the red/green/blue members of the XColor
9595 structures. Value is a pointer to the array of XColors structures,
9596 allocated with xmalloc; it must be freed by the caller. */
9597
9598static XColor *
9599x_to_xcolors (f, img, rgb_p)
9600 struct frame *f;
9601 struct image *img;
9602 int rgb_p;
9603{
9604 int x, y;
9605 XColor *colors, *p;
197edd35
JR
9606 HDC hdc, bmpdc;
9607 HGDIOBJ prev;
3cf3436e
JR
9608
9609 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
197edd35
JR
9610
9611 /* Load the image into a memory device context. */
9612 hdc = get_frame_dc (f);
9613 bmpdc = CreateCompatibleDC (hdc);
9614 release_frame_dc (f, hdc);
9615 prev = SelectObject (bmpdc, img->pixmap);
3cf3436e
JR
9616
9617 /* Fill the `pixel' members of the XColor array. I wished there
9618 were an easy and portable way to circumvent XGetPixel. */
9619 p = colors;
9620 for (y = 0; y < img->height; ++y)
9621 {
9622 XColor *row = p;
7d0393cf 9623
3cf3436e 9624 for (x = 0; x < img->width; ++x, ++p)
197edd35
JR
9625 {
9626 /* TODO: palette support needed here? */
9627 p->pixel = GetPixel (bmpdc, x, y);
3cf3436e 9628
197edd35
JR
9629 if (rgb_p)
9630 {
9631 p->red = 256 * GetRValue (p->pixel);
9632 p->green = 256 * GetGValue (p->pixel);
9633 p->blue = 256 * GetBValue (p->pixel);
9634 }
9635 }
3cf3436e
JR
9636 }
9637
197edd35
JR
9638 SelectObject (bmpdc, prev);
9639 DeleteDC (bmpdc);
9640
3cf3436e
JR
9641 return colors;
9642}
9643
ac849ba4
JR
9644/* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
9645 created with CreateDIBSection, with the pointer to the bit values
9646 stored in ximg->data. */
9647
9648static void XPutPixel (ximg, x, y, color)
9649 XImage * ximg;
9650 int x, y;
9651 COLORREF color;
9652{
9653 int width = ximg->info.bmiHeader.biWidth;
9654 int height = ximg->info.bmiHeader.biHeight;
ac849ba4
JR
9655 unsigned char * pixel;
9656
54eefef1
JR
9657 /* True color images. */
9658 if (ximg->info.bmiHeader.biBitCount == 24)
9659 {
9660 int rowbytes = width * 3;
9661 /* Ensure scanlines are aligned on 4 byte boundaries. */
9662 if (rowbytes % 4)
9663 rowbytes += 4 - (rowbytes % 4);
9664
9665 pixel = ximg->data + y * rowbytes + x * 3;
9666 /* Windows bitmaps are in BGR order. */
9667 *pixel = GetBValue (color);
9668 *(pixel + 1) = GetGValue (color);
9669 *(pixel + 2) = GetRValue (color);
9670 }
9671 /* Monochrome images. */
9672 else if (ximg->info.bmiHeader.biBitCount == 1)
9673 {
9674 int rowbytes = width / 8;
9675 /* Ensure scanlines are aligned on 4 byte boundaries. */
9676 if (rowbytes % 4)
9677 rowbytes += 4 - (rowbytes % 4);
9678 pixel = ximg->data + y * rowbytes + x / 8;
9679 /* Filter out palette info. */
9680 if (color & 0x00ffffff)
9681 *pixel = *pixel | (1 << x % 8);
9682 else
9683 *pixel = *pixel & ~(1 << x % 8);
9684 }
9685 else
839b1909 9686 image_error ("XPutPixel: palette image not supported.", Qnil, Qnil);
ac849ba4
JR
9687}
9688
3cf3436e
JR
9689/* Create IMG->pixmap from an array COLORS of XColor structures, whose
9690 RGB members are set. F is the frame on which this all happens.
9691 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
6fc2811b
JR
9692
9693static void
3cf3436e 9694x_from_xcolors (f, img, colors)
6fc2811b 9695 struct frame *f;
3cf3436e 9696 struct image *img;
6fc2811b 9697 XColor *colors;
6fc2811b 9698{
3cf3436e
JR
9699 int x, y;
9700 XImage *oimg;
9701 Pixmap pixmap;
9702 XColor *p;
ac849ba4 9703#if 0 /* TODO: color tables. */
3cf3436e 9704 init_color_table ();
ac849ba4 9705#endif
3cf3436e
JR
9706 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9707 &oimg, &pixmap);
9708 p = colors;
9709 for (y = 0; y < img->height; ++y)
9710 for (x = 0; x < img->width; ++x, ++p)
9711 {
9712 unsigned long pixel;
ac849ba4 9713#if 0 /* TODO: color tables. */
3cf3436e 9714 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
ac849ba4 9715#else
197edd35 9716 pixel = PALETTERGB (p->red / 256, p->green / 256, p->blue / 256);
ac849ba4 9717#endif
3cf3436e
JR
9718 XPutPixel (oimg, x, y, pixel);
9719 }
6fc2811b 9720
3cf3436e
JR
9721 xfree (colors);
9722 x_clear_image_1 (f, img, 1, 0, 1);
6fc2811b 9723
3cf3436e
JR
9724 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9725 x_destroy_x_image (oimg);
9726 img->pixmap = pixmap;
ac849ba4 9727#if 0 /* TODO: color tables. */
3cf3436e
JR
9728 img->colors = colors_in_color_table (&img->ncolors);
9729 free_color_table ();
ac849ba4 9730#endif
6fc2811b
JR
9731}
9732
9733
3cf3436e
JR
9734/* On frame F, perform edge-detection on image IMG.
9735
9736 MATRIX is a nine-element array specifying the transformation
9737 matrix. See emboss_matrix for an example.
7d0393cf 9738
3cf3436e
JR
9739 COLOR_ADJUST is a color adjustment added to each pixel of the
9740 outgoing image. */
6fc2811b
JR
9741
9742static void
3cf3436e 9743x_detect_edges (f, img, matrix, color_adjust)
6fc2811b 9744 struct frame *f;
3cf3436e
JR
9745 struct image *img;
9746 int matrix[9], color_adjust;
6fc2811b 9747{
3cf3436e
JR
9748 XColor *colors = x_to_xcolors (f, img, 1);
9749 XColor *new, *p;
9750 int x, y, i, sum;
9751
9752 for (i = sum = 0; i < 9; ++i)
9753 sum += abs (matrix[i]);
9754
9755#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
9756
9757 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
9758
9759 for (y = 0; y < img->height; ++y)
9760 {
9761 p = COLOR (new, 0, y);
9762 p->red = p->green = p->blue = 0xffff/2;
9763 p = COLOR (new, img->width - 1, y);
9764 p->red = p->green = p->blue = 0xffff/2;
9765 }
7d0393cf 9766
3cf3436e
JR
9767 for (x = 1; x < img->width - 1; ++x)
9768 {
9769 p = COLOR (new, x, 0);
9770 p->red = p->green = p->blue = 0xffff/2;
9771 p = COLOR (new, x, img->height - 1);
9772 p->red = p->green = p->blue = 0xffff/2;
9773 }
9774
9775 for (y = 1; y < img->height - 1; ++y)
9776 {
9777 p = COLOR (new, 1, y);
7d0393cf 9778
3cf3436e
JR
9779 for (x = 1; x < img->width - 1; ++x, ++p)
9780 {
9781 int r, g, b, y1, x1;
9782
9783 r = g = b = i = 0;
9784 for (y1 = y - 1; y1 < y + 2; ++y1)
9785 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
9786 if (matrix[i])
9787 {
9788 XColor *t = COLOR (colors, x1, y1);
9789 r += matrix[i] * t->red;
9790 g += matrix[i] * t->green;
9791 b += matrix[i] * t->blue;
9792 }
9793
9794 r = (r / sum + color_adjust) & 0xffff;
9795 g = (g / sum + color_adjust) & 0xffff;
9796 b = (b / sum + color_adjust) & 0xffff;
9797 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
9798 }
9799 }
9800
9801 xfree (colors);
9802 x_from_xcolors (f, img, new);
9803
9804#undef COLOR
9805}
9806
9807
9808/* Perform the pre-defined `emboss' edge-detection on image IMG
9809 on frame F. */
9810
9811static void
9812x_emboss (f, img)
9813 struct frame *f;
9814 struct image *img;
9815{
9816 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
6fc2811b 9817}
3cf3436e 9818
6fc2811b
JR
9819
9820/* Transform image IMG which is used on frame F with a Laplace
9821 edge-detection algorithm. The result is an image that can be used
9822 to draw disabled buttons, for example. */
9823
9824static void
9825x_laplace (f, img)
9826 struct frame *f;
9827 struct image *img;
9828{
3cf3436e
JR
9829 x_detect_edges (f, img, laplace_matrix, 45000);
9830}
6fc2811b 9831
6fc2811b 9832
3cf3436e
JR
9833/* Perform edge-detection on image IMG on frame F, with specified
9834 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
6fc2811b 9835
3cf3436e 9836 MATRIX must be either
6fc2811b 9837
3cf3436e
JR
9838 - a list of at least 9 numbers in row-major form
9839 - a vector of at least 9 numbers
6fc2811b 9840
3cf3436e
JR
9841 COLOR_ADJUST nil means use a default; otherwise it must be a
9842 number. */
6fc2811b 9843
3cf3436e
JR
9844static void
9845x_edge_detection (f, img, matrix, color_adjust)
9846 struct frame *f;
9847 struct image *img;
9848 Lisp_Object matrix, color_adjust;
9849{
9850 int i = 0;
9851 int trans[9];
7d0393cf 9852
3cf3436e 9853 if (CONSP (matrix))
6fc2811b 9854 {
3cf3436e
JR
9855 for (i = 0;
9856 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
9857 ++i, matrix = XCDR (matrix))
9858 trans[i] = XFLOATINT (XCAR (matrix));
9859 }
9860 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
9861 {
9862 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
9863 trans[i] = XFLOATINT (AREF (matrix, i));
9864 }
9865
9866 if (NILP (color_adjust))
9867 color_adjust = make_number (0xffff / 2);
9868
9869 if (i == 9 && NUMBERP (color_adjust))
9870 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
9871}
9872
6fc2811b 9873
3cf3436e 9874/* Transform image IMG on frame F so that it looks disabled. */
6fc2811b 9875
3cf3436e
JR
9876static void
9877x_disable_image (f, img)
9878 struct frame *f;
9879 struct image *img;
9880{
ac849ba4 9881 struct w32_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3cf3436e 9882
ac849ba4 9883 if (dpyinfo->n_planes * dpyinfo->n_cbits >= 2)
3cf3436e
JR
9884 {
9885 /* Color (or grayscale). Convert to gray, and equalize. Just
9886 drawing such images with a stipple can look very odd, so
9887 we're using this method instead. */
9888 XColor *colors = x_to_xcolors (f, img, 1);
9889 XColor *p, *end;
9890 const int h = 15000;
9891 const int l = 30000;
9892
9893 for (p = colors, end = colors + img->width * img->height;
9894 p < end;
9895 ++p)
6fc2811b 9896 {
3cf3436e
JR
9897 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
9898 int i2 = (0xffff - h - l) * i / 0xffff + l;
9899 p->red = p->green = p->blue = i2;
6fc2811b
JR
9900 }
9901
3cf3436e 9902 x_from_xcolors (f, img, colors);
6fc2811b
JR
9903 }
9904
3cf3436e
JR
9905 /* Draw a cross over the disabled image, if we must or if we
9906 should. */
ac849ba4 9907 if (dpyinfo->n_planes * dpyinfo->n_cbits < 2 || cross_disabled_images)
3cf3436e 9908 {
197edd35
JR
9909 HDC hdc, bmpdc;
9910 HGDIOBJ prev;
9911
9912 hdc = get_frame_dc (f);
9913 bmpdc = CreateCompatibleDC (hdc);
9914 release_frame_dc (f, hdc);
9915
9916 prev = SelectObject (bmpdc, img->pixmap);
6fc2811b 9917
197edd35
JR
9918 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
9919 MoveToEx (bmpdc, 0, 0, NULL);
9920 LineTo (bmpdc, img->width - 1, img->height - 1);
9921 MoveToEx (bmpdc, 0, img->height - 1, NULL);
9922 LineTo (bmpdc, img->width - 1, 0);
6fc2811b 9923
3cf3436e
JR
9924 if (img->mask)
9925 {
197edd35
JR
9926 SelectObject (bmpdc, img->mask);
9927 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
9928 MoveToEx (bmpdc, 0, 0, NULL);
9929 LineTo (bmpdc, img->width - 1, img->height - 1);
9930 MoveToEx (bmpdc, 0, img->height - 1, NULL);
9931 LineTo (bmpdc, img->width - 1, 0);
3cf3436e 9932 }
197edd35
JR
9933 SelectObject (bmpdc, prev);
9934 DeleteDC (bmpdc);
3cf3436e 9935 }
6fc2811b
JR
9936}
9937
9938
9939/* Build a mask for image IMG which is used on frame F. FILE is the
9940 name of an image file, for error messages. HOW determines how to
9941 determine the background color of IMG. If it is a list '(R G B)',
9942 with R, G, and B being integers >= 0, take that as the color of the
9943 background. Otherwise, determine the background color of IMG
9944 heuristically. Value is non-zero if successful. */
9945
9946static int
9947x_build_heuristic_mask (f, img, how)
9948 struct frame *f;
9949 struct image *img;
9950 Lisp_Object how;
9951{
197edd35
JR
9952 HDC img_dc, frame_dc;
9953 HGDIOBJ prev;
9954 char *mask_img;
a05e2bae
JR
9955 int x, y, rc, use_img_background;
9956 unsigned long bg = 0;
197edd35 9957 int row_width;
a05e2bae
JR
9958
9959 if (img->mask)
9960 {
197edd35
JR
9961 DeleteObject (img->mask);
9962 img->mask = NULL;
a05e2bae
JR
9963 img->background_transparent_valid = 0;
9964 }
6fc2811b 9965
197edd35
JR
9966 /* Create the bit array serving as mask. */
9967 row_width = (img->width + 7) / 8;
9968 mask_img = xmalloc (row_width * img->height);
9969 bzero (mask_img, row_width * img->height);
6fc2811b 9970
197edd35
JR
9971 /* Create a memory device context for IMG->pixmap. */
9972 frame_dc = get_frame_dc (f);
9973 img_dc = CreateCompatibleDC (frame_dc);
9974 release_frame_dc (f, frame_dc);
9975 prev = SelectObject (img_dc, img->pixmap);
6fc2811b 9976
197edd35 9977 /* Determine the background color of img_dc. If HOW is `(R G B)'
a05e2bae
JR
9978 take that as color. Otherwise, use the image's background color. */
9979 use_img_background = 1;
7d0393cf 9980
6fc2811b
JR
9981 if (CONSP (how))
9982 {
a05e2bae 9983 int rgb[3], i;
6fc2811b 9984
a05e2bae 9985 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
6fc2811b
JR
9986 {
9987 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9988 how = XCDR (how);
9989 }
9990
9991 if (i == 3 && NILP (how))
9992 {
9993 char color_name[30];
6fc2811b 9994 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
0040b876 9995 bg = x_alloc_image_color (f, img, build_string (color_name), 0)
8f92c555 9996 & 0x00ffffff; /* Filter out palette info. */
a05e2bae 9997 use_img_background = 0;
6fc2811b
JR
9998 }
9999 }
7d0393cf 10000
a05e2bae 10001 if (use_img_background)
197edd35 10002 bg = four_corners_best (img_dc, img->width, img->height);
6fc2811b
JR
10003
10004 /* Set all bits in mask_img to 1 whose color in ximg is different
10005 from the background color bg. */
10006 for (y = 0; y < img->height; ++y)
10007 for (x = 0; x < img->width; ++x)
197edd35
JR
10008 {
10009 COLORREF p = GetPixel (img_dc, x, y);
10010 if (p != bg)
10011 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
10012 }
10013
10014 /* Create the mask image. */
10015 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
10016 mask_img);
6fc2811b 10017
a05e2bae 10018 /* Fill in the background_transparent field while we have the mask handy. */
197edd35
JR
10019 SelectObject (img_dc, img->mask);
10020
10021 image_background_transparent (img, f, img_dc);
a05e2bae 10022
6fc2811b 10023 /* Put mask_img into img->mask. */
54eefef1 10024 x_destroy_x_image ((XImage *)mask_img);
197edd35
JR
10025 SelectObject (img_dc, prev);
10026 DeleteDC (img_dc);
6fc2811b
JR
10027
10028 return 1;
10029}
217e5be0 10030
6fc2811b
JR
10031\f
10032/***********************************************************************
10033 PBM (mono, gray, color)
10034 ***********************************************************************/
6fc2811b
JR
10035
10036static int pbm_image_p P_ ((Lisp_Object object));
10037static int pbm_load P_ ((struct frame *f, struct image *img));
10038static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
10039
10040/* The symbol `pbm' identifying images of this type. */
10041
10042Lisp_Object Qpbm;
10043
10044/* Indices of image specification fields in gs_format, below. */
10045
10046enum pbm_keyword_index
10047{
10048 PBM_TYPE,
10049 PBM_FILE,
10050 PBM_DATA,
10051 PBM_ASCENT,
10052 PBM_MARGIN,
10053 PBM_RELIEF,
10054 PBM_ALGORITHM,
10055 PBM_HEURISTIC_MASK,
a05e2bae
JR
10056 PBM_MASK,
10057 PBM_FOREGROUND,
10058 PBM_BACKGROUND,
6fc2811b
JR
10059 PBM_LAST
10060};
10061
10062/* Vector of image_keyword structures describing the format
10063 of valid user-defined image specifications. */
10064
10065static struct image_keyword pbm_format[PBM_LAST] =
10066{
10067 {":type", IMAGE_SYMBOL_VALUE, 1},
10068 {":file", IMAGE_STRING_VALUE, 0},
10069 {":data", IMAGE_STRING_VALUE, 0},
8f92c555 10070 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 10071 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 10072 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 10073 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3cf3436e
JR
10074 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10075 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10076 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
10077 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
10078};
10079
10080/* Structure describing the image type `pbm'. */
10081
10082static struct image_type pbm_type =
10083{
10084 &Qpbm,
10085 pbm_image_p,
10086 pbm_load,
10087 x_clear_image,
10088 NULL
10089};
10090
10091
10092/* Return non-zero if OBJECT is a valid PBM image specification. */
10093
10094static int
10095pbm_image_p (object)
10096 Lisp_Object object;
10097{
10098 struct image_keyword fmt[PBM_LAST];
7d0393cf 10099
6fc2811b 10100 bcopy (pbm_format, fmt, sizeof fmt);
7d0393cf 10101
8f92c555 10102 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
6fc2811b
JR
10103 return 0;
10104
10105 /* Must specify either :data or :file. */
10106 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
10107}
10108
10109
10110/* Scan a decimal number from *S and return it. Advance *S while
10111 reading the number. END is the end of the string. Value is -1 at
10112 end of input. */
10113
10114static int
10115pbm_scan_number (s, end)
10116 unsigned char **s, *end;
10117{
10118 int c, val = -1;
10119
10120 while (*s < end)
10121 {
10122 /* Skip white-space. */
10123 while (*s < end && (c = *(*s)++, isspace (c)))
10124 ;
10125
10126 if (c == '#')
10127 {
10128 /* Skip comment to end of line. */
10129 while (*s < end && (c = *(*s)++, c != '\n'))
10130 ;
10131 }
10132 else if (isdigit (c))
10133 {
10134 /* Read decimal number. */
10135 val = c - '0';
10136 while (*s < end && (c = *(*s)++, isdigit (c)))
10137 val = 10 * val + c - '0';
10138 break;
10139 }
10140 else
10141 break;
10142 }
10143
10144 return val;
10145}
10146
10147
10148/* Read FILE into memory. Value is a pointer to a buffer allocated
10149 with xmalloc holding FILE's contents. Value is null if an error
6f826971 10150 occurred. *SIZE is set to the size of the file. */
6fc2811b
JR
10151
10152static char *
10153pbm_read_file (file, size)
10154 Lisp_Object file;
10155 int *size;
10156{
10157 FILE *fp = NULL;
10158 char *buf = NULL;
10159 struct stat st;
10160
d5db4077 10161 if (stat (SDATA (file), &st) == 0
c45bb3b2 10162 && (fp = fopen (SDATA (file), "rb")) != NULL
6fc2811b
JR
10163 && (buf = (char *) xmalloc (st.st_size),
10164 fread (buf, 1, st.st_size, fp) == st.st_size))
10165 {
10166 *size = st.st_size;
10167 fclose (fp);
10168 }
10169 else
10170 {
10171 if (fp)
10172 fclose (fp);
10173 if (buf)
10174 {
10175 xfree (buf);
10176 buf = NULL;
10177 }
10178 }
7d0393cf 10179
6fc2811b
JR
10180 return buf;
10181}
10182
10183
10184/* Load PBM image IMG for use on frame F. */
10185
7d0393cf 10186static int
6fc2811b
JR
10187pbm_load (f, img)
10188 struct frame *f;
10189 struct image *img;
10190{
10191 int raw_p, x, y;
10192 int width, height, max_color_idx = 0;
10193 XImage *ximg;
10194 Lisp_Object file, specified_file;
10195 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
10196 struct gcpro gcpro1;
10197 unsigned char *contents = NULL;
10198 unsigned char *end, *p;
10199 int size;
10200
10201 specified_file = image_spec_value (img->spec, QCfile, NULL);
10202 file = Qnil;
10203 GCPRO1 (file);
10204
10205 if (STRINGP (specified_file))
10206 {
10207 file = x_find_image_file (specified_file);
10208 if (!STRINGP (file))
10209 {
10210 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10211 UNGCPRO;
10212 return 0;
10213 }
10214
d5db4077 10215 contents = slurp_file (SDATA (file), &size);
6fc2811b
JR
10216 if (contents == NULL)
10217 {
10218 image_error ("Error reading `%s'", file, Qnil);
10219 UNGCPRO;
10220 return 0;
10221 }
10222
10223 p = contents;
10224 end = contents + size;
10225 }
10226 else
10227 {
10228 Lisp_Object data;
10229 data = image_spec_value (img->spec, QCdata, NULL);
d5db4077
KR
10230 p = SDATA (data);
10231 end = p + SBYTES (data);
6fc2811b
JR
10232 }
10233
10234 /* Check magic number. */
10235 if (end - p < 2 || *p++ != 'P')
10236 {
10237 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10238 error:
10239 xfree (contents);
10240 UNGCPRO;
10241 return 0;
10242 }
10243
6fc2811b
JR
10244 switch (*p++)
10245 {
10246 case '1':
10247 raw_p = 0, type = PBM_MONO;
10248 break;
7d0393cf 10249
6fc2811b
JR
10250 case '2':
10251 raw_p = 0, type = PBM_GRAY;
10252 break;
10253
10254 case '3':
10255 raw_p = 0, type = PBM_COLOR;
10256 break;
10257
10258 case '4':
10259 raw_p = 1, type = PBM_MONO;
10260 break;
7d0393cf 10261
6fc2811b
JR
10262 case '5':
10263 raw_p = 1, type = PBM_GRAY;
10264 break;
7d0393cf 10265
6fc2811b
JR
10266 case '6':
10267 raw_p = 1, type = PBM_COLOR;
10268 break;
10269
10270 default:
10271 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10272 goto error;
10273 }
10274
10275 /* Read width, height, maximum color-component. Characters
10276 starting with `#' up to the end of a line are ignored. */
10277 width = pbm_scan_number (&p, end);
10278 height = pbm_scan_number (&p, end);
10279
10280 if (type != PBM_MONO)
10281 {
10282 max_color_idx = pbm_scan_number (&p, end);
10283 if (raw_p && max_color_idx > 255)
10284 max_color_idx = 255;
10285 }
7d0393cf 10286
6fc2811b
JR
10287 if (width < 0
10288 || height < 0
10289 || (type != PBM_MONO && max_color_idx < 0))
10290 goto error;
10291
ac849ba4 10292 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
3cf3436e
JR
10293 goto error;
10294
ac849ba4 10295#if 0 /* TODO: color tables. */
6fc2811b
JR
10296 /* Initialize the color hash table. */
10297 init_color_table ();
ac849ba4 10298#endif
6fc2811b
JR
10299
10300 if (type == PBM_MONO)
10301 {
10302 int c = 0, g;
3cf3436e
JR
10303 struct image_keyword fmt[PBM_LAST];
10304 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
10305 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
10306
10307 /* Parse the image specification. */
10308 bcopy (pbm_format, fmt, sizeof fmt);
10309 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
7d0393cf 10310
3cf3436e
JR
10311 /* Get foreground and background colors, maybe allocate colors. */
10312 if (fmt[PBM_FOREGROUND].count
10313 && STRINGP (fmt[PBM_FOREGROUND].value))
10314 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
10315 if (fmt[PBM_BACKGROUND].count
10316 && STRINGP (fmt[PBM_BACKGROUND].value))
a05e2bae
JR
10317 {
10318 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
10319 img->background = bg;
10320 img->background_valid = 1;
10321 }
10322
6fc2811b
JR
10323 for (y = 0; y < height; ++y)
10324 for (x = 0; x < width; ++x)
10325 {
10326 if (raw_p)
10327 {
10328 if ((x & 7) == 0)
10329 c = *p++;
10330 g = c & 0x80;
10331 c <<= 1;
10332 }
10333 else
10334 g = pbm_scan_number (&p, end);
10335
3cf3436e 10336 XPutPixel (ximg, x, y, g ? fg : bg);
6fc2811b
JR
10337 }
10338 }
10339 else
10340 {
10341 for (y = 0; y < height; ++y)
10342 for (x = 0; x < width; ++x)
10343 {
10344 int r, g, b;
7d0393cf 10345
6fc2811b
JR
10346 if (type == PBM_GRAY)
10347 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
10348 else if (raw_p)
10349 {
10350 r = *p++;
10351 g = *p++;
10352 b = *p++;
10353 }
10354 else
10355 {
10356 r = pbm_scan_number (&p, end);
10357 g = pbm_scan_number (&p, end);
10358 b = pbm_scan_number (&p, end);
10359 }
7d0393cf 10360
6fc2811b
JR
10361 if (r < 0 || g < 0 || b < 0)
10362 {
ac849ba4 10363 x_destroy_x_image (ximg);
6fc2811b
JR
10364 image_error ("Invalid pixel value in image `%s'",
10365 img->spec, Qnil);
10366 goto error;
10367 }
7d0393cf 10368
6fc2811b 10369 /* RGB values are now in the range 0..max_color_idx.
ac849ba4
JR
10370 Scale this to the range 0..0xff supported by W32. */
10371 r = (int) ((double) r * 255 / max_color_idx);
10372 g = (int) ((double) g * 255 / max_color_idx);
10373 b = (int) ((double) b * 255 / max_color_idx);
10374 XPutPixel (ximg, x, y,
10375#if 0 /* TODO: color tables. */
10376 lookup_rgb_color (f, r, g, b));
10377#else
10378 PALETTERGB (r, g, b));
10379#endif
6fc2811b
JR
10380 }
10381 }
ac849ba4
JR
10382
10383#if 0 /* TODO: color tables. */
6fc2811b
JR
10384 /* Store in IMG->colors the colors allocated for the image, and
10385 free the color table. */
10386 img->colors = colors_in_color_table (&img->ncolors);
10387 free_color_table ();
ac849ba4 10388#endif
a05e2bae
JR
10389 /* Maybe fill in the background field while we have ximg handy. */
10390 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
10391 IMAGE_BACKGROUND (img, f, ximg);
7d0393cf 10392
6fc2811b
JR
10393 /* Put the image into a pixmap. */
10394 x_put_x_image (f, ximg, img->pixmap, width, height);
10395 x_destroy_x_image (ximg);
7d0393cf 10396
6fc2811b
JR
10397 img->width = width;
10398 img->height = height;
10399
10400 UNGCPRO;
10401 xfree (contents);
10402 return 1;
10403}
6fc2811b
JR
10404
10405\f
10406/***********************************************************************
10407 PNG
10408 ***********************************************************************/
10409
10410#if HAVE_PNG
10411
10412#include <png.h>
10413
10414/* Function prototypes. */
10415
10416static int png_image_p P_ ((Lisp_Object object));
10417static int png_load P_ ((struct frame *f, struct image *img));
10418
10419/* The symbol `png' identifying images of this type. */
10420
10421Lisp_Object Qpng;
10422
10423/* Indices of image specification fields in png_format, below. */
10424
10425enum png_keyword_index
10426{
10427 PNG_TYPE,
10428 PNG_DATA,
10429 PNG_FILE,
10430 PNG_ASCENT,
10431 PNG_MARGIN,
10432 PNG_RELIEF,
10433 PNG_ALGORITHM,
10434 PNG_HEURISTIC_MASK,
a05e2bae
JR
10435 PNG_MASK,
10436 PNG_BACKGROUND,
6fc2811b
JR
10437 PNG_LAST
10438};
10439
10440/* Vector of image_keyword structures describing the format
10441 of valid user-defined image specifications. */
10442
10443static struct image_keyword png_format[PNG_LAST] =
10444{
10445 {":type", IMAGE_SYMBOL_VALUE, 1},
10446 {":data", IMAGE_STRING_VALUE, 0},
10447 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 10448 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 10449 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 10450 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 10451 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
10452 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10453 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10454 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
10455};
10456
10457/* Structure describing the image type `png'. */
10458
10459static struct image_type png_type =
10460{
10461 &Qpng,
10462 png_image_p,
10463 png_load,
10464 x_clear_image,
10465 NULL
10466};
10467
839b1909
JR
10468/* PNG library details. */
10469
10470DEF_IMGLIB_FN (png_get_io_ptr);
10471DEF_IMGLIB_FN (png_check_sig);
10472DEF_IMGLIB_FN (png_create_read_struct);
10473DEF_IMGLIB_FN (png_create_info_struct);
10474DEF_IMGLIB_FN (png_destroy_read_struct);
10475DEF_IMGLIB_FN (png_set_read_fn);
c922a224 10476DEF_IMGLIB_FN (png_init_io);
839b1909
JR
10477DEF_IMGLIB_FN (png_set_sig_bytes);
10478DEF_IMGLIB_FN (png_read_info);
10479DEF_IMGLIB_FN (png_get_IHDR);
10480DEF_IMGLIB_FN (png_get_valid);
10481DEF_IMGLIB_FN (png_set_strip_16);
10482DEF_IMGLIB_FN (png_set_expand);
10483DEF_IMGLIB_FN (png_set_gray_to_rgb);
10484DEF_IMGLIB_FN (png_set_background);
10485DEF_IMGLIB_FN (png_get_bKGD);
10486DEF_IMGLIB_FN (png_read_update_info);
10487DEF_IMGLIB_FN (png_get_channels);
10488DEF_IMGLIB_FN (png_get_rowbytes);
10489DEF_IMGLIB_FN (png_read_image);
10490DEF_IMGLIB_FN (png_read_end);
10491DEF_IMGLIB_FN (png_error);
10492
10493static int
10494init_png_functions (library)
10495 HMODULE library;
10496{
10497 LOAD_IMGLIB_FN (library, png_get_io_ptr);
10498 LOAD_IMGLIB_FN (library, png_check_sig);
10499 LOAD_IMGLIB_FN (library, png_create_read_struct);
10500 LOAD_IMGLIB_FN (library, png_create_info_struct);
10501 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
10502 LOAD_IMGLIB_FN (library, png_set_read_fn);
c922a224 10503 LOAD_IMGLIB_FN (library, png_init_io);
839b1909
JR
10504 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
10505 LOAD_IMGLIB_FN (library, png_read_info);
10506 LOAD_IMGLIB_FN (library, png_get_IHDR);
10507 LOAD_IMGLIB_FN (library, png_get_valid);
10508 LOAD_IMGLIB_FN (library, png_set_strip_16);
10509 LOAD_IMGLIB_FN (library, png_set_expand);
10510 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
10511 LOAD_IMGLIB_FN (library, png_set_background);
10512 LOAD_IMGLIB_FN (library, png_get_bKGD);
10513 LOAD_IMGLIB_FN (library, png_read_update_info);
10514 LOAD_IMGLIB_FN (library, png_get_channels);
10515 LOAD_IMGLIB_FN (library, png_get_rowbytes);
10516 LOAD_IMGLIB_FN (library, png_read_image);
10517 LOAD_IMGLIB_FN (library, png_read_end);
10518 LOAD_IMGLIB_FN (library, png_error);
10519 return 1;
10520}
6fc2811b
JR
10521
10522/* Return non-zero if OBJECT is a valid PNG image specification. */
10523
10524static int
10525png_image_p (object)
10526 Lisp_Object object;
10527{
10528 struct image_keyword fmt[PNG_LAST];
10529 bcopy (png_format, fmt, sizeof fmt);
c922a224 10530
8f92c555 10531 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
6fc2811b
JR
10532 return 0;
10533
10534 /* Must specify either the :data or :file keyword. */
10535 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
10536}
10537
10538
10539/* Error and warning handlers installed when the PNG library
10540 is initialized. */
10541
10542static void
10543my_png_error (png_ptr, msg)
10544 png_struct *png_ptr;
10545 char *msg;
10546{
10547 xassert (png_ptr != NULL);
10548 image_error ("PNG error: %s", build_string (msg), Qnil);
10549 longjmp (png_ptr->jmpbuf, 1);
10550}
10551
10552
10553static void
10554my_png_warning (png_ptr, msg)
10555 png_struct *png_ptr;
10556 char *msg;
10557{
10558 xassert (png_ptr != NULL);
10559 image_error ("PNG warning: %s", build_string (msg), Qnil);
10560}
10561
6fc2811b
JR
10562/* Memory source for PNG decoding. */
10563
10564struct png_memory_storage
10565{
10566 unsigned char *bytes; /* The data */
10567 size_t len; /* How big is it? */
10568 int index; /* Where are we? */
10569};
10570
10571
10572/* Function set as reader function when reading PNG image from memory.
10573 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
10574 bytes from the input to DATA. */
10575
10576static void
10577png_read_from_memory (png_ptr, data, length)
10578 png_structp png_ptr;
10579 png_bytep data;
10580 png_size_t length;
10581{
10582 struct png_memory_storage *tbr
839b1909 10583 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
6fc2811b
JR
10584
10585 if (length > tbr->len - tbr->index)
839b1909 10586 fn_png_error (png_ptr, "Read error");
c922a224 10587
6fc2811b
JR
10588 bcopy (tbr->bytes + tbr->index, data, length);
10589 tbr->index = tbr->index + length;
10590}
10591
6fc2811b
JR
10592/* Load PNG image IMG for use on frame F. Value is non-zero if
10593 successful. */
10594
10595static int
10596png_load (f, img)
10597 struct frame *f;
10598 struct image *img;
10599{
10600 Lisp_Object file, specified_file;
10601 Lisp_Object specified_data;
10602 int x, y, i;
10603 XImage *ximg, *mask_img = NULL;
10604 struct gcpro gcpro1;
10605 png_struct *png_ptr = NULL;
10606 png_info *info_ptr = NULL, *end_info = NULL;
a05e2bae 10607 FILE *volatile fp = NULL;
6fc2811b 10608 png_byte sig[8];
54eefef1
JR
10609 png_byte * volatile pixels = NULL;
10610 png_byte ** volatile rows = NULL;
6fc2811b
JR
10611 png_uint_32 width, height;
10612 int bit_depth, color_type, interlace_type;
10613 png_byte channels;
10614 png_uint_32 row_bytes;
10615 int transparent_p;
6fc2811b
JR
10616 double screen_gamma, image_gamma;
10617 int intent;
10618 struct png_memory_storage tbr; /* Data to be read */
10619
10620 /* Find out what file to load. */
10621 specified_file = image_spec_value (img->spec, QCfile, NULL);
10622 specified_data = image_spec_value (img->spec, QCdata, NULL);
10623 file = Qnil;
10624 GCPRO1 (file);
10625
10626 if (NILP (specified_data))
10627 {
10628 file = x_find_image_file (specified_file);
10629 if (!STRINGP (file))
54eefef1
JR
10630 {
10631 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10632 UNGCPRO;
10633 return 0;
10634 }
6fc2811b
JR
10635
10636 /* Open the image file. */
d5db4077 10637 fp = fopen (SDATA (file), "rb");
6fc2811b 10638 if (!fp)
54eefef1
JR
10639 {
10640 image_error ("Cannot open image file `%s'", file, Qnil);
10641 UNGCPRO;
10642 fclose (fp);
10643 return 0;
10644 }
6fc2811b
JR
10645
10646 /* Check PNG signature. */
10647 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
839b1909 10648 || !fn_png_check_sig (sig, sizeof sig))
54eefef1
JR
10649 {
10650 image_error ("Not a PNG file: `%s'", file, Qnil);
10651 UNGCPRO;
10652 fclose (fp);
10653 return 0;
10654 }
6fc2811b
JR
10655 }
10656 else
10657 {
10658 /* Read from memory. */
d5db4077
KR
10659 tbr.bytes = SDATA (specified_data);
10660 tbr.len = SBYTES (specified_data);
6fc2811b
JR
10661 tbr.index = 0;
10662
10663 /* Check PNG signature. */
10664 if (tbr.len < sizeof sig
839b1909 10665 || !fn_png_check_sig (tbr.bytes, sizeof sig))
6fc2811b
JR
10666 {
10667 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10668 UNGCPRO;
10669 return 0;
10670 }
10671
10672 /* Need to skip past the signature. */
10673 tbr.bytes += sizeof (sig);
10674 }
10675
6fc2811b 10676 /* Initialize read and info structs for PNG lib. */
839b1909
JR
10677 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10678 my_png_error, my_png_warning);
6fc2811b
JR
10679 if (!png_ptr)
10680 {
10681 if (fp) fclose (fp);
10682 UNGCPRO;
10683 return 0;
10684 }
10685
839b1909 10686 info_ptr = fn_png_create_info_struct (png_ptr);
6fc2811b
JR
10687 if (!info_ptr)
10688 {
839b1909 10689 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
6fc2811b
JR
10690 if (fp) fclose (fp);
10691 UNGCPRO;
10692 return 0;
10693 }
10694
839b1909 10695 end_info = fn_png_create_info_struct (png_ptr);
6fc2811b
JR
10696 if (!end_info)
10697 {
839b1909 10698 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
6fc2811b
JR
10699 if (fp) fclose (fp);
10700 UNGCPRO;
10701 return 0;
10702 }
10703
10704 /* Set error jump-back. We come back here when the PNG library
10705 detects an error. */
10706 if (setjmp (png_ptr->jmpbuf))
10707 {
10708 error:
10709 if (png_ptr)
839b1909 10710 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6fc2811b
JR
10711 xfree (pixels);
10712 xfree (rows);
10713 if (fp) fclose (fp);
10714 UNGCPRO;
10715 return 0;
10716 }
10717
10718 /* Read image info. */
10719 if (!NILP (specified_data))
839b1909 10720 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
6fc2811b 10721 else
839b1909 10722 fn_png_init_io (png_ptr, fp);
6fc2811b 10723
839b1909
JR
10724 fn_png_set_sig_bytes (png_ptr, sizeof sig);
10725 fn_png_read_info (png_ptr, info_ptr);
10726 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10727 &interlace_type, NULL, NULL);
6fc2811b 10728
c922a224 10729 /* If image contains simply transparency data, we prefer to
6fc2811b 10730 construct a clipping mask. */
839b1909 10731 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6fc2811b
JR
10732 transparent_p = 1;
10733 else
10734 transparent_p = 0;
10735
c922a224 10736 /* This function is easier to write if we only have to handle
6fc2811b
JR
10737 one data format: RGB or RGBA with 8 bits per channel. Let's
10738 transform other formats into that format. */
10739
10740 /* Strip more than 8 bits per channel. */
10741 if (bit_depth == 16)
839b1909 10742 fn_png_set_strip_16 (png_ptr);
6fc2811b
JR
10743
10744 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10745 if available. */
839b1909 10746 fn_png_set_expand (png_ptr);
6fc2811b
JR
10747
10748 /* Convert grayscale images to RGB. */
c922a224 10749 if (color_type == PNG_COLOR_TYPE_GRAY
6fc2811b 10750 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
839b1909 10751 fn_png_set_gray_to_rgb (png_ptr);
6fc2811b 10752
54eefef1 10753 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
6fc2811b 10754
54eefef1 10755#if 0 /* Avoid double gamma correction for PNG images. */
6fc2811b 10756 /* Tell the PNG lib to handle gamma correction for us. */
6fc2811b
JR
10757#if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10758 if (png_get_sRGB (png_ptr, info_ptr, &intent))
54eefef1
JR
10759 /* The libpng documentation says this is right in this case. */
10760 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6fc2811b
JR
10761 else
10762#endif
10763 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10764 /* Image contains gamma information. */
10765 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10766 else
54eefef1
JR
10767 /* Use the standard default for the image gamma. */
10768 png_set_gamma (png_ptr, screen_gamma, 0.45455);
10769#endif /* if 0 */
6fc2811b
JR
10770
10771 /* Handle alpha channel by combining the image with a background
10772 color. Do this only if a real alpha channel is supplied. For
10773 simple transparency, we prefer a clipping mask. */
10774 if (!transparent_p)
10775 {
54eefef1 10776 png_color_16 *image_bg;
a05e2bae
JR
10777 Lisp_Object specified_bg
10778 = image_spec_value (img->spec, QCbackground, NULL);
10779
a05e2bae
JR
10780 if (STRINGP (specified_bg))
10781 /* The user specified `:background', use that. */
10782 {
10783 COLORREF color;
d5db4077 10784 if (w32_defined_color (f, SDATA (specified_bg), &color, 0))
a05e2bae
JR
10785 {
10786 png_color_16 user_bg;
10787
10788 bzero (&user_bg, sizeof user_bg);
54eefef1
JR
10789 user_bg.red = 256 * GetRValue (color);
10790 user_bg.green = 256 * GetGValue (color);
10791 user_bg.blue = 256 * GetBValue (color);
6fc2811b 10792
839b1909
JR
10793 fn_png_set_background (png_ptr, &user_bg,
10794 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
a05e2bae
JR
10795 }
10796 }
839b1909 10797 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
c922a224 10798 /* Image contains a background color with which to
6fc2811b 10799 combine the image. */
839b1909
JR
10800 fn_png_set_background (png_ptr, image_bg,
10801 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
6fc2811b
JR
10802 else
10803 {
10804 /* Image does not contain a background color with which
c922a224 10805 to combine the image data via an alpha channel. Use
6fc2811b 10806 the frame's background instead. */
54eefef1 10807 COLORREF color;
6fc2811b 10808 png_color_16 frame_background;
54eefef1
JR
10809 color = FRAME_BACKGROUND_PIXEL (f);
10810#if 0 /* TODO : Colormap support. */
10811 Colormap cmap;
6fc2811b 10812
a05e2bae 10813 cmap = FRAME_X_COLORMAP (f);
a05e2bae 10814 x_query_color (f, &color);
54eefef1 10815#endif
6fc2811b
JR
10816
10817 bzero (&frame_background, sizeof frame_background);
54eefef1
JR
10818 frame_background.red = 256 * GetRValue (color);
10819 frame_background.green = 256 * GetGValue (color);
10820 frame_background.blue = 256 * GetBValue (color);
6fc2811b 10821
839b1909
JR
10822 fn_png_set_background (png_ptr, &frame_background,
10823 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6fc2811b
JR
10824 }
10825 }
10826
10827 /* Update info structure. */
839b1909 10828 fn_png_read_update_info (png_ptr, info_ptr);
6fc2811b
JR
10829
10830 /* Get number of channels. Valid values are 1 for grayscale images
10831 and images with a palette, 2 for grayscale images with transparency
10832 information (alpha channel), 3 for RGB images, and 4 for RGB
10833 images with alpha channel, i.e. RGBA. If conversions above were
10834 sufficient we should only have 3 or 4 channels here. */
839b1909 10835 channels = fn_png_get_channels (png_ptr, info_ptr);
6fc2811b
JR
10836 xassert (channels == 3 || channels == 4);
10837
10838 /* Number of bytes needed for one row of the image. */
839b1909 10839 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6fc2811b
JR
10840
10841 /* Allocate memory for the image. */
10842 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10843 rows = (png_byte **) xmalloc (height * sizeof *rows);
10844 for (i = 0; i < height; ++i)
10845 rows[i] = pixels + i * row_bytes;
10846
10847 /* Read the entire image. */
839b1909
JR
10848 fn_png_read_image (png_ptr, rows);
10849 fn_png_read_end (png_ptr, info_ptr);
6fc2811b
JR
10850 if (fp)
10851 {
10852 fclose (fp);
10853 fp = NULL;
10854 }
c922a224 10855
6fc2811b
JR
10856 /* Create the X image and pixmap. */
10857 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10858 &img->pixmap))
a05e2bae 10859 goto error;
c922a224 10860
6fc2811b
JR
10861 /* Create an image and pixmap serving as mask if the PNG image
10862 contains an alpha channel. */
10863 if (channels == 4
10864 && !transparent_p
10865 && !x_create_x_image_and_pixmap (f, width, height, 1,
10866 &mask_img, &img->mask))
10867 {
10868 x_destroy_x_image (ximg);
54eefef1 10869 DeleteObject (img->pixmap);
6fc2811b 10870 img->pixmap = 0;
6fc2811b
JR
10871 goto error;
10872 }
6fc2811b 10873 /* Fill the X image and mask from PNG data. */
54eefef1 10874#if 0 /* TODO: Color tables. */
6fc2811b 10875 init_color_table ();
54eefef1 10876#endif
6fc2811b
JR
10877
10878 for (y = 0; y < height; ++y)
10879 {
10880 png_byte *p = rows[y];
10881
10882 for (x = 0; x < width; ++x)
10883 {
10884 unsigned r, g, b;
10885
54eefef1
JR
10886 r = *p++;
10887 g = *p++;
10888 b = *p++;
10889#if 0 /* TODO: Color tables. */
6fc2811b 10890 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
54eefef1
JR
10891#else
10892 XPutPixel (ximg, x, y, PALETTERGB (r, g, b));
10893#endif
6fc2811b 10894 /* An alpha channel, aka mask channel, associates variable
c922a224
JB
10895 transparency with an image. Where other image formats
10896 support binary transparency---fully transparent or fully
6fc2811b
JR
10897 opaque---PNG allows up to 254 levels of partial transparency.
10898 The PNG library implements partial transparency by combining
10899 the image with a specified background color.
10900
10901 I'm not sure how to handle this here nicely: because the
10902 background on which the image is displayed may change, for
c922a224
JB
10903 real alpha channel support, it would be necessary to create
10904 a new image for each possible background.
6fc2811b
JR
10905
10906 What I'm doing now is that a mask is created if we have
10907 boolean transparency information. Otherwise I'm using
10908 the frame's background color to combine the image with. */
10909
10910 if (channels == 4)
10911 {
10912 if (mask_img)
10913 XPutPixel (mask_img, x, y, *p > 0);
10914 ++p;
10915 }
10916 }
10917 }
10918
a05e2bae
JR
10919 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
10920 /* Set IMG's background color from the PNG image, unless the user
10921 overrode it. */
10922 {
10923 png_color_16 *bg;
839b1909 10924 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
a05e2bae 10925 {
54eefef1 10926#if 0 /* TODO: Color tables. */
a05e2bae 10927 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
54eefef1
JR
10928#else
10929 img->background = PALETTERGB (bg->red / 256, bg->green / 256,
10930 bg->blue / 256);
10931#endif
a05e2bae
JR
10932 img->background_valid = 1;
10933 }
10934 }
10935
54eefef1 10936#if 0 /* TODO: Color tables. */
6fc2811b
JR
10937 /* Remember colors allocated for this image. */
10938 img->colors = colors_in_color_table (&img->ncolors);
10939 free_color_table ();
54eefef1 10940#endif
6fc2811b
JR
10941
10942 /* Clean up. */
839b1909 10943 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6fc2811b
JR
10944 xfree (rows);
10945 xfree (pixels);
10946
10947 img->width = width;
10948 img->height = height;
10949
a05e2bae
JR
10950 /* Maybe fill in the background field while we have ximg handy. */
10951 IMAGE_BACKGROUND (img, f, ximg);
10952
6fc2811b
JR
10953 /* Put the image into the pixmap, then free the X image and its buffer. */
10954 x_put_x_image (f, ximg, img->pixmap, width, height);
10955 x_destroy_x_image (ximg);
10956
10957 /* Same for the mask. */
10958 if (mask_img)
10959 {
a05e2bae
JR
10960 /* Fill in the background_transparent field while we have the mask
10961 handy. */
10962 image_background_transparent (img, f, mask_img);
10963
6fc2811b
JR
10964 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10965 x_destroy_x_image (mask_img);
10966 }
10967
6fc2811b
JR
10968 UNGCPRO;
10969 return 1;
10970}
10971
10972#endif /* HAVE_PNG != 0 */
10973
10974
10975\f
10976/***********************************************************************
10977 JPEG
10978 ***********************************************************************/
10979
10980#if HAVE_JPEG
10981
10982/* Work around a warning about HAVE_STDLIB_H being redefined in
10983 jconfig.h. */
10984#ifdef HAVE_STDLIB_H
10985#define HAVE_STDLIB_H_1
10986#undef HAVE_STDLIB_H
10987#endif /* HAVE_STLIB_H */
10988
10989#include <jpeglib.h>
10990#include <jerror.h>
10991#include <setjmp.h>
10992
10993#ifdef HAVE_STLIB_H_1
10994#define HAVE_STDLIB_H 1
10995#endif
10996
10997static int jpeg_image_p P_ ((Lisp_Object object));
10998static int jpeg_load P_ ((struct frame *f, struct image *img));
10999
11000/* The symbol `jpeg' identifying images of this type. */
11001
11002Lisp_Object Qjpeg;
11003
11004/* Indices of image specification fields in gs_format, below. */
11005
11006enum jpeg_keyword_index
11007{
11008 JPEG_TYPE,
11009 JPEG_DATA,
11010 JPEG_FILE,
11011 JPEG_ASCENT,
11012 JPEG_MARGIN,
11013 JPEG_RELIEF,
11014 JPEG_ALGORITHM,
11015 JPEG_HEURISTIC_MASK,
a05e2bae
JR
11016 JPEG_MASK,
11017 JPEG_BACKGROUND,
6fc2811b
JR
11018 JPEG_LAST
11019};
11020
11021/* Vector of image_keyword structures describing the format
11022 of valid user-defined image specifications. */
11023
11024static struct image_keyword jpeg_format[JPEG_LAST] =
11025{
11026 {":type", IMAGE_SYMBOL_VALUE, 1},
11027 {":data", IMAGE_STRING_VALUE, 0},
11028 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 11029 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 11030 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 11031 {":relief", IMAGE_INTEGER_VALUE, 0},
a05e2bae
JR
11032 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11033 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11034 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11035 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
11036};
11037
11038/* Structure describing the image type `jpeg'. */
11039
11040static struct image_type jpeg_type =
11041{
11042 &Qjpeg,
11043 jpeg_image_p,
11044 jpeg_load,
11045 x_clear_image,
11046 NULL
11047};
11048
11049
afc390dc
JR
11050/* JPEG library details. */
11051DEF_IMGLIB_FN (jpeg_CreateDecompress);
11052DEF_IMGLIB_FN (jpeg_start_decompress);
11053DEF_IMGLIB_FN (jpeg_finish_decompress);
11054DEF_IMGLIB_FN (jpeg_destroy_decompress);
11055DEF_IMGLIB_FN (jpeg_read_header);
11056DEF_IMGLIB_FN (jpeg_read_scanlines);
11057DEF_IMGLIB_FN (jpeg_stdio_src);
11058DEF_IMGLIB_FN (jpeg_std_error);
11059DEF_IMGLIB_FN (jpeg_resync_to_restart);
11060
11061static int
11062init_jpeg_functions (library)
11063 HMODULE library;
11064{
11065 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
11066 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
11067 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
11068 LOAD_IMGLIB_FN (library, jpeg_read_header);
11069 LOAD_IMGLIB_FN (library, jpeg_stdio_src);
11070 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
11071 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
11072 LOAD_IMGLIB_FN (library, jpeg_std_error);
11073 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
11074 return 1;
11075}
11076
11077/* Wrapper since we can't directly assign the function pointer
11078 to another function pointer that was declared more completely easily. */
11079static boolean
11080jpeg_resync_to_restart_wrapper(cinfo, desired)
11081 j_decompress_ptr cinfo;
11082 int desired;
11083{
11084 return fn_jpeg_resync_to_restart (cinfo, desired);
11085}
11086
11087
6fc2811b
JR
11088/* Return non-zero if OBJECT is a valid JPEG image specification. */
11089
11090static int
11091jpeg_image_p (object)
11092 Lisp_Object object;
11093{
11094 struct image_keyword fmt[JPEG_LAST];
c922a224 11095
6fc2811b 11096 bcopy (jpeg_format, fmt, sizeof fmt);
c922a224 11097
8f92c555 11098 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6fc2811b
JR
11099 return 0;
11100
11101 /* Must specify either the :data or :file keyword. */
11102 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
11103}
11104
11105
11106struct my_jpeg_error_mgr
11107{
11108 struct jpeg_error_mgr pub;
11109 jmp_buf setjmp_buffer;
11110};
11111
afc390dc 11112
6fc2811b
JR
11113static void
11114my_error_exit (cinfo)
11115 j_common_ptr cinfo;
11116{
11117 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
11118 longjmp (mgr->setjmp_buffer, 1);
11119}
11120
afc390dc 11121
6fc2811b
JR
11122/* Init source method for JPEG data source manager. Called by
11123 jpeg_read_header() before any data is actually read. See
11124 libjpeg.doc from the JPEG lib distribution. */
11125
11126static void
11127our_init_source (cinfo)
11128 j_decompress_ptr cinfo;
11129{
11130}
11131
11132
11133/* Fill input buffer method for JPEG data source manager. Called
11134 whenever more data is needed. We read the whole image in one step,
11135 so this only adds a fake end of input marker at the end. */
11136
11137static boolean
11138our_fill_input_buffer (cinfo)
11139 j_decompress_ptr cinfo;
11140{
11141 /* Insert a fake EOI marker. */
11142 struct jpeg_source_mgr *src = cinfo->src;
11143 static JOCTET buffer[2];
11144
11145 buffer[0] = (JOCTET) 0xFF;
11146 buffer[1] = (JOCTET) JPEG_EOI;
11147
11148 src->next_input_byte = buffer;
11149 src->bytes_in_buffer = 2;
11150 return TRUE;
11151}
11152
11153
11154/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
11155 is the JPEG data source manager. */
11156
11157static void
11158our_skip_input_data (cinfo, num_bytes)
11159 j_decompress_ptr cinfo;
11160 long num_bytes;
11161{
11162 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
11163
11164 if (src)
11165 {
11166 if (num_bytes > src->bytes_in_buffer)
11167 ERREXIT (cinfo, JERR_INPUT_EOF);
c922a224 11168
6fc2811b
JR
11169 src->bytes_in_buffer -= num_bytes;
11170 src->next_input_byte += num_bytes;
11171 }
11172}
11173
11174
11175/* Method to terminate data source. Called by
11176 jpeg_finish_decompress() after all data has been processed. */
11177
11178static void
11179our_term_source (cinfo)
11180 j_decompress_ptr cinfo;
11181{
11182}
11183
11184
11185/* Set up the JPEG lib for reading an image from DATA which contains
11186 LEN bytes. CINFO is the decompression info structure created for
11187 reading the image. */
11188
11189static void
11190jpeg_memory_src (cinfo, data, len)
11191 j_decompress_ptr cinfo;
11192 JOCTET *data;
11193 unsigned int len;
11194{
11195 struct jpeg_source_mgr *src;
11196
11197 if (cinfo->src == NULL)
11198 {
11199 /* First time for this JPEG object? */
11200 cinfo->src = (struct jpeg_source_mgr *)
11201 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
11202 sizeof (struct jpeg_source_mgr));
11203 src = (struct jpeg_source_mgr *) cinfo->src;
11204 src->next_input_byte = data;
11205 }
c922a224 11206
6fc2811b
JR
11207 src = (struct jpeg_source_mgr *) cinfo->src;
11208 src->init_source = our_init_source;
11209 src->fill_input_buffer = our_fill_input_buffer;
11210 src->skip_input_data = our_skip_input_data;
afc390dc 11211 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6fc2811b
JR
11212 src->term_source = our_term_source;
11213 src->bytes_in_buffer = len;
11214 src->next_input_byte = data;
11215}
11216
11217
11218/* Load image IMG for use on frame F. Patterned after example.c
11219 from the JPEG lib. */
11220
c922a224 11221static int
6fc2811b
JR
11222jpeg_load (f, img)
11223 struct frame *f;
11224 struct image *img;
11225{
11226 struct jpeg_decompress_struct cinfo;
11227 struct my_jpeg_error_mgr mgr;
11228 Lisp_Object file, specified_file;
11229 Lisp_Object specified_data;
a05e2bae 11230 FILE * volatile fp = NULL;
6fc2811b
JR
11231 JSAMPARRAY buffer;
11232 int row_stride, x, y;
11233 XImage *ximg = NULL;
11234 int rc;
11235 unsigned long *colors;
11236 int width, height;
11237 struct gcpro gcpro1;
11238
11239 /* Open the JPEG file. */
11240 specified_file = image_spec_value (img->spec, QCfile, NULL);
11241 specified_data = image_spec_value (img->spec, QCdata, NULL);
11242 file = Qnil;
11243 GCPRO1 (file);
11244
6fc2811b
JR
11245 if (NILP (specified_data))
11246 {
11247 file = x_find_image_file (specified_file);
11248 if (!STRINGP (file))
afc390dc
JR
11249 {
11250 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11251 UNGCPRO;
11252 return 0;
11253 }
c922a224 11254
c45bb3b2 11255 fp = fopen (SDATA (file), "rb");
6fc2811b 11256 if (fp == NULL)
afc390dc
JR
11257 {
11258 image_error ("Cannot open `%s'", file, Qnil);
11259 UNGCPRO;
11260 return 0;
11261 }
6fc2811b 11262 }
7d0393cf 11263
6fc2811b 11264 /* Customize libjpeg's error handling to call my_error_exit when an
afc390dc
JR
11265 error is detected. This function will perform a longjmp. */
11266 cinfo.err = fn_jpeg_std_error (&mgr.pub);
a05e2bae 11267 mgr.pub.error_exit = my_error_exit;
c922a224 11268
6fc2811b
JR
11269 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
11270 {
11271 if (rc == 1)
11272 {
11273 /* Called from my_error_exit. Display a JPEG error. */
11274 char buffer[JMSG_LENGTH_MAX];
11275 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
11276 image_error ("Error reading JPEG image `%s': %s", img->spec,
11277 build_string (buffer));
11278 }
c922a224 11279
6fc2811b
JR
11280 /* Close the input file and destroy the JPEG object. */
11281 if (fp)
afc390dc
JR
11282 fclose ((FILE *) fp);
11283 fn_jpeg_destroy_decompress (&cinfo);
7d0393cf 11284
6fc2811b
JR
11285 /* If we already have an XImage, free that. */
11286 x_destroy_x_image (ximg);
11287
11288 /* Free pixmap and colors. */
11289 x_clear_image (f, img);
c922a224 11290
6fc2811b
JR
11291 UNGCPRO;
11292 return 0;
11293 }
11294
11295 /* Create the JPEG decompression object. Let it read from fp.
afc390dc
JR
11296 Read the JPEG image header. */
11297 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6fc2811b
JR
11298
11299 if (NILP (specified_data))
afc390dc 11300 fn_jpeg_stdio_src (&cinfo, (FILE *) fp);
6fc2811b 11301 else
d5db4077
KR
11302 jpeg_memory_src (&cinfo, SDATA (specified_data),
11303 SBYTES (specified_data));
6fc2811b 11304
afc390dc 11305 fn_jpeg_read_header (&cinfo, TRUE);
6fc2811b
JR
11306
11307 /* Customize decompression so that color quantization will be used.
afc390dc 11308 Start decompression. */
6fc2811b 11309 cinfo.quantize_colors = TRUE;
afc390dc 11310 fn_jpeg_start_decompress (&cinfo);
6fc2811b
JR
11311 width = img->width = cinfo.output_width;
11312 height = img->height = cinfo.output_height;
11313
6fc2811b 11314 /* Create X image and pixmap. */
afc390dc 11315 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
a05e2bae 11316 longjmp (mgr.setjmp_buffer, 2);
6fc2811b
JR
11317
11318 /* Allocate colors. When color quantization is used,
11319 cinfo.actual_number_of_colors has been set with the number of
11320 colors generated, and cinfo.colormap is a two-dimensional array
11321 of color indices in the range 0..cinfo.actual_number_of_colors.
11322 No more than 255 colors will be generated. */
11323 {
11324 int i, ir, ig, ib;
11325
11326 if (cinfo.out_color_components > 2)
11327 ir = 0, ig = 1, ib = 2;
11328 else if (cinfo.out_color_components > 1)
11329 ir = 0, ig = 1, ib = 0;
11330 else
11331 ir = 0, ig = 0, ib = 0;
11332
afc390dc 11333#if 0 /* TODO: Color tables. */
6fc2811b
JR
11334 /* Use the color table mechanism because it handles colors that
11335 cannot be allocated nicely. Such colors will be replaced with
11336 a default color, and we don't have to care about which colors
11337 can be freed safely, and which can't. */
11338 init_color_table ();
afc390dc 11339#endif
6fc2811b
JR
11340 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
11341 * sizeof *colors);
c922a224 11342
6fc2811b
JR
11343 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
11344 {
afc390dc
JR
11345 int r = cinfo.colormap[ir][i];
11346 int g = cinfo.colormap[ig][i];
11347 int b = cinfo.colormap[ib][i];
11348#if 0 /* TODO: Color tables. */
6fc2811b 11349 colors[i] = lookup_rgb_color (f, r, g, b);
afc390dc
JR
11350#else
11351 colors[i] = PALETTERGB (r, g, b);
11352#endif
6fc2811b
JR
11353 }
11354
afc390dc 11355#if 0 /* TODO: Color tables. */
6fc2811b
JR
11356 /* Remember those colors actually allocated. */
11357 img->colors = colors_in_color_table (&img->ncolors);
11358 free_color_table ();
afc390dc 11359#endif
6fc2811b
JR
11360 }
11361
11362 /* Read pixels. */
11363 row_stride = width * cinfo.output_components;
11364 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
11365 row_stride, 1);
11366 for (y = 0; y < height; ++y)
11367 {
afc390dc 11368 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6fc2811b
JR
11369 for (x = 0; x < cinfo.output_width; ++x)
11370 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
11371 }
11372
11373 /* Clean up. */
afc390dc
JR
11374 fn_jpeg_finish_decompress (&cinfo);
11375 fn_jpeg_destroy_decompress (&cinfo);
6fc2811b 11376 if (fp)
afc390dc 11377 fclose ((FILE *) fp);
7d0393cf 11378
a05e2bae
JR
11379 /* Maybe fill in the background field while we have ximg handy. */
11380 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11381 IMAGE_BACKGROUND (img, f, ximg);
c922a224 11382
6fc2811b
JR
11383 /* Put the image into the pixmap. */
11384 x_put_x_image (f, ximg, img->pixmap, width, height);
11385 x_destroy_x_image (ximg);
6fc2811b
JR
11386 UNGCPRO;
11387 return 1;
11388}
11389
11390#endif /* HAVE_JPEG */
11391
11392
11393\f
11394/***********************************************************************
11395 TIFF
11396 ***********************************************************************/
11397
11398#if HAVE_TIFF
11399
11400#include <tiffio.h>
11401
11402static int tiff_image_p P_ ((Lisp_Object object));
11403static int tiff_load P_ ((struct frame *f, struct image *img));
11404
11405/* The symbol `tiff' identifying images of this type. */
11406
11407Lisp_Object Qtiff;
11408
11409/* Indices of image specification fields in tiff_format, below. */
11410
11411enum tiff_keyword_index
11412{
11413 TIFF_TYPE,
11414 TIFF_DATA,
11415 TIFF_FILE,
11416 TIFF_ASCENT,
11417 TIFF_MARGIN,
11418 TIFF_RELIEF,
11419 TIFF_ALGORITHM,
11420 TIFF_HEURISTIC_MASK,
a05e2bae
JR
11421 TIFF_MASK,
11422 TIFF_BACKGROUND,
6fc2811b
JR
11423 TIFF_LAST
11424};
11425
11426/* Vector of image_keyword structures describing the format
11427 of valid user-defined image specifications. */
11428
11429static struct image_keyword tiff_format[TIFF_LAST] =
11430{
11431 {":type", IMAGE_SYMBOL_VALUE, 1},
11432 {":data", IMAGE_STRING_VALUE, 0},
11433 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 11434 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 11435 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 11436 {":relief", IMAGE_INTEGER_VALUE, 0},
a05e2bae
JR
11437 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11438 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11439 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11440 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
11441};
11442
11443/* Structure describing the image type `tiff'. */
11444
11445static struct image_type tiff_type =
11446{
11447 &Qtiff,
11448 tiff_image_p,
11449 tiff_load,
11450 x_clear_image,
11451 NULL
11452};
11453
12b918b2
JB
11454/* TIFF library details. */
11455DEF_IMGLIB_FN (TIFFSetErrorHandler);
11456DEF_IMGLIB_FN (TIFFSetWarningHandler);
11457DEF_IMGLIB_FN (TIFFOpen);
11458DEF_IMGLIB_FN (TIFFClientOpen);
11459DEF_IMGLIB_FN (TIFFGetField);
11460DEF_IMGLIB_FN (TIFFReadRGBAImage);
11461DEF_IMGLIB_FN (TIFFClose);
11462
11463static int
11464init_tiff_functions (library)
11465 HMODULE library;
11466{
11467 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
11468 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
11469 LOAD_IMGLIB_FN (library, TIFFOpen);
11470 LOAD_IMGLIB_FN (library, TIFFClientOpen);
11471 LOAD_IMGLIB_FN (library, TIFFGetField);
11472 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
11473 LOAD_IMGLIB_FN (library, TIFFClose);
11474 return 1;
11475}
6fc2811b
JR
11476
11477/* Return non-zero if OBJECT is a valid TIFF image specification. */
11478
11479static int
11480tiff_image_p (object)
11481 Lisp_Object object;
11482{
11483 struct image_keyword fmt[TIFF_LAST];
11484 bcopy (tiff_format, fmt, sizeof fmt);
7d0393cf 11485
8f92c555 11486 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6fc2811b 11487 return 0;
7d0393cf 11488
6fc2811b
JR
11489 /* Must specify either the :data or :file keyword. */
11490 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
11491}
11492
11493
11494/* Reading from a memory buffer for TIFF images Based on the PNG
11495 memory source, but we have to provide a lot of extra functions.
11496 Blah.
11497
11498 We really only need to implement read and seek, but I am not
11499 convinced that the TIFF library is smart enough not to destroy
11500 itself if we only hand it the function pointers we need to
11501 override. */
11502
11503typedef struct
11504{
11505 unsigned char *bytes;
11506 size_t len;
11507 int index;
11508}
11509tiff_memory_source;
11510
11511static size_t
11512tiff_read_from_memory (data, buf, size)
11513 thandle_t data;
11514 tdata_t buf;
11515 tsize_t size;
11516{
11517 tiff_memory_source *src = (tiff_memory_source *) data;
11518
11519 if (size > src->len - src->index)
11520 return (size_t) -1;
11521 bcopy (src->bytes + src->index, buf, size);
11522 src->index += size;
11523 return size;
11524}
11525
11526static size_t
11527tiff_write_from_memory (data, buf, size)
11528 thandle_t data;
11529 tdata_t buf;
11530 tsize_t size;
11531{
11532 return (size_t) -1;
11533}
11534
11535static toff_t
11536tiff_seek_in_memory (data, off, whence)
11537 thandle_t data;
11538 toff_t off;
11539 int whence;
11540{
11541 tiff_memory_source *src = (tiff_memory_source *) data;
11542 int idx;
11543
11544 switch (whence)
11545 {
11546 case SEEK_SET: /* Go from beginning of source. */
11547 idx = off;
11548 break;
7d0393cf 11549
6fc2811b
JR
11550 case SEEK_END: /* Go from end of source. */
11551 idx = src->len + off;
11552 break;
7d0393cf 11553
6fc2811b
JR
11554 case SEEK_CUR: /* Go from current position. */
11555 idx = src->index + off;
11556 break;
7d0393cf 11557
6fc2811b
JR
11558 default: /* Invalid `whence'. */
11559 return -1;
11560 }
7d0393cf 11561
6fc2811b
JR
11562 if (idx > src->len || idx < 0)
11563 return -1;
7d0393cf 11564
6fc2811b
JR
11565 src->index = idx;
11566 return src->index;
11567}
11568
11569static int
11570tiff_close_memory (data)
11571 thandle_t data;
11572{
11573 /* NOOP */
11574 return 0;
11575}
11576
11577static int
11578tiff_mmap_memory (data, pbase, psize)
11579 thandle_t data;
11580 tdata_t *pbase;
11581 toff_t *psize;
11582{
11583 /* It is already _IN_ memory. */
11584 return 0;
11585}
11586
11587static void
11588tiff_unmap_memory (data, base, size)
11589 thandle_t data;
11590 tdata_t base;
11591 toff_t size;
11592{
11593 /* We don't need to do this. */
11594}
11595
11596static toff_t
11597tiff_size_of_memory (data)
11598 thandle_t data;
11599{
11600 return ((tiff_memory_source *) data)->len;
11601}
11602
3cf3436e
JR
11603
11604static void
11605tiff_error_handler (title, format, ap)
11606 const char *title, *format;
11607 va_list ap;
11608{
11609 char buf[512];
11610 int len;
7d0393cf 11611
3cf3436e
JR
11612 len = sprintf (buf, "TIFF error: %s ", title);
11613 vsprintf (buf + len, format, ap);
11614 add_to_log (buf, Qnil, Qnil);
11615}
11616
11617
11618static void
11619tiff_warning_handler (title, format, ap)
11620 const char *title, *format;
11621 va_list ap;
11622{
11623 char buf[512];
11624 int len;
7d0393cf 11625
3cf3436e
JR
11626 len = sprintf (buf, "TIFF warning: %s ", title);
11627 vsprintf (buf + len, format, ap);
11628 add_to_log (buf, Qnil, Qnil);
11629}
11630
11631
6fc2811b
JR
11632/* Load TIFF image IMG for use on frame F. Value is non-zero if
11633 successful. */
11634
11635static int
11636tiff_load (f, img)
11637 struct frame *f;
11638 struct image *img;
11639{
11640 Lisp_Object file, specified_file;
11641 Lisp_Object specified_data;
11642 TIFF *tiff;
11643 int width, height, x, y;
11644 uint32 *buf;
11645 int rc;
11646 XImage *ximg;
11647 struct gcpro gcpro1;
11648 tiff_memory_source memsrc;
11649
11650 specified_file = image_spec_value (img->spec, QCfile, NULL);
11651 specified_data = image_spec_value (img->spec, QCdata, NULL);
11652 file = Qnil;
11653 GCPRO1 (file);
11654
12b918b2
JB
11655 fn_TIFFSetErrorHandler (tiff_error_handler);
11656 fn_TIFFSetWarningHandler (tiff_warning_handler);
3cf3436e 11657
6fc2811b
JR
11658 if (NILP (specified_data))
11659 {
11660 /* Read from a file */
11661 file = x_find_image_file (specified_file);
11662 if (!STRINGP (file))
3cf3436e
JR
11663 {
11664 image_error ("Cannot find image file `%s'", file, Qnil);
11665 UNGCPRO;
11666 return 0;
11667 }
7d0393cf 11668
6fc2811b 11669 /* Try to open the image file. */
12b918b2 11670 tiff = fn_TIFFOpen (SDATA (file), "r");
6fc2811b 11671 if (tiff == NULL)
3cf3436e
JR
11672 {
11673 image_error ("Cannot open `%s'", file, Qnil);
11674 UNGCPRO;
11675 return 0;
11676 }
6fc2811b
JR
11677 }
11678 else
11679 {
11680 /* Memory source! */
d5db4077
KR
11681 memsrc.bytes = SDATA (specified_data);
11682 memsrc.len = SBYTES (specified_data);
6fc2811b
JR
11683 memsrc.index = 0;
11684
12b918b2
JB
11685 tiff = fn_TIFFClientOpen ("memory_source", "r", &memsrc,
11686 (TIFFReadWriteProc) tiff_read_from_memory,
11687 (TIFFReadWriteProc) tiff_write_from_memory,
11688 tiff_seek_in_memory,
11689 tiff_close_memory,
11690 tiff_size_of_memory,
11691 tiff_mmap_memory,
11692 tiff_unmap_memory);
6fc2811b
JR
11693
11694 if (!tiff)
11695 {
11696 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
11697 UNGCPRO;
11698 return 0;
11699 }
11700 }
11701
11702 /* Get width and height of the image, and allocate a raster buffer
11703 of width x height 32-bit values. */
12b918b2
JB
11704 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
11705 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6fc2811b 11706 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7d0393cf 11707
12b918b2
JB
11708 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
11709 fn_TIFFClose (tiff);
6fc2811b
JR
11710 if (!rc)
11711 {
11712 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
11713 xfree (buf);
11714 UNGCPRO;
11715 return 0;
11716 }
11717
6fc2811b
JR
11718 /* Create the X image and pixmap. */
11719 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11720 {
6fc2811b
JR
11721 xfree (buf);
11722 UNGCPRO;
11723 return 0;
11724 }
11725
12b918b2 11726#if 0 /* TODO: Color tables. */
6fc2811b
JR
11727 /* Initialize the color table. */
11728 init_color_table ();
12b918b2 11729#endif
6fc2811b
JR
11730
11731 /* Process the pixel raster. Origin is in the lower-left corner. */
11732 for (y = 0; y < height; ++y)
11733 {
11734 uint32 *row = buf + y * width;
7d0393cf 11735
6fc2811b
JR
11736 for (x = 0; x < width; ++x)
11737 {
11738 uint32 abgr = row[x];
12b918b2
JB
11739 int r = TIFFGetR (abgr);
11740 int g = TIFFGetG (abgr);
11741 int b = TIFFGetB (abgr);
11742#if 0 /* TODO: Color tables. */
7d0393cf 11743 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
12b918b2
JB
11744#else
11745 XPutPixel (ximg, x, height - 1 - y, PALETTERGB (r, g, b));
11746#endif
6fc2811b
JR
11747 }
11748 }
11749
12b918b2 11750#if 0 /* TODO: Color tables. */
6fc2811b
JR
11751 /* Remember the colors allocated for the image. Free the color table. */
11752 img->colors = colors_in_color_table (&img->ncolors);
11753 free_color_table ();
12b918b2 11754#endif
6fc2811b 11755
a05e2bae
JR
11756 img->width = width;
11757 img->height = height;
11758
11759 /* Maybe fill in the background field while we have ximg handy. */
11760 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11761 IMAGE_BACKGROUND (img, f, ximg);
11762
6fc2811b
JR
11763 /* Put the image into the pixmap, then free the X image and its buffer. */
11764 x_put_x_image (f, ximg, img->pixmap, width, height);
11765 x_destroy_x_image (ximg);
11766 xfree (buf);
6fc2811b
JR
11767
11768 UNGCPRO;
11769 return 1;
11770}
11771
11772#endif /* HAVE_TIFF != 0 */
11773
11774
11775\f
11776/***********************************************************************
11777 GIF
11778 ***********************************************************************/
11779
11780#if HAVE_GIF
11781
1ffb278b 11782#define DrawText gif_DrawText
6fc2811b 11783#include <gif_lib.h>
1ffb278b 11784#undef DrawText
6fc2811b
JR
11785
11786static int gif_image_p P_ ((Lisp_Object object));
11787static int gif_load P_ ((struct frame *f, struct image *img));
11788
11789/* The symbol `gif' identifying images of this type. */
11790
11791Lisp_Object Qgif;
11792
11793/* Indices of image specification fields in gif_format, below. */
11794
11795enum gif_keyword_index
11796{
11797 GIF_TYPE,
11798 GIF_DATA,
11799 GIF_FILE,
11800 GIF_ASCENT,
11801 GIF_MARGIN,
11802 GIF_RELIEF,
11803 GIF_ALGORITHM,
11804 GIF_HEURISTIC_MASK,
a05e2bae 11805 GIF_MASK,
6fc2811b 11806 GIF_IMAGE,
a05e2bae 11807 GIF_BACKGROUND,
6fc2811b
JR
11808 GIF_LAST
11809};
11810
11811/* Vector of image_keyword structures describing the format
11812 of valid user-defined image specifications. */
11813
11814static struct image_keyword gif_format[GIF_LAST] =
11815{
11816 {":type", IMAGE_SYMBOL_VALUE, 1},
11817 {":data", IMAGE_STRING_VALUE, 0},
11818 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 11819 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 11820 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 11821 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 11822 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6fc2811b 11823 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
11824 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11825 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11826 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
11827};
11828
11829/* Structure describing the image type `gif'. */
11830
11831static struct image_type gif_type =
11832{
11833 &Qgif,
11834 gif_image_p,
11835 gif_load,
11836 x_clear_image,
11837 NULL
11838};
11839
1ffb278b
JB
11840
11841/* GIF library details. */
11842DEF_IMGLIB_FN (DGifCloseFile);
11843DEF_IMGLIB_FN (DGifSlurp);
11844DEF_IMGLIB_FN (DGifOpen);
11845DEF_IMGLIB_FN (DGifOpenFileName);
11846
11847static int
11848init_gif_functions (library)
11849 HMODULE library;
11850{
11851 LOAD_IMGLIB_FN (library, DGifCloseFile);
11852 LOAD_IMGLIB_FN (library, DGifSlurp);
11853 LOAD_IMGLIB_FN (library, DGifOpen);
11854 LOAD_IMGLIB_FN (library, DGifOpenFileName);
11855 return 1;
11856}
11857
11858
6fc2811b
JR
11859/* Return non-zero if OBJECT is a valid GIF image specification. */
11860
11861static int
11862gif_image_p (object)
11863 Lisp_Object object;
11864{
11865 struct image_keyword fmt[GIF_LAST];
11866 bcopy (gif_format, fmt, sizeof fmt);
7d0393cf 11867
8f92c555 11868 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
6fc2811b 11869 return 0;
7d0393cf 11870
6fc2811b
JR
11871 /* Must specify either the :data or :file keyword. */
11872 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11873}
11874
11875/* Reading a GIF image from memory
11876 Based on the PNG memory stuff to a certain extent. */
11877
11878typedef struct
11879{
11880 unsigned char *bytes;
11881 size_t len;
11882 int index;
11883}
11884gif_memory_source;
11885
11886/* Make the current memory source available to gif_read_from_memory.
11887 It's done this way because not all versions of libungif support
11888 a UserData field in the GifFileType structure. */
11889static gif_memory_source *current_gif_memory_src;
11890
11891static int
11892gif_read_from_memory (file, buf, len)
11893 GifFileType *file;
11894 GifByteType *buf;
11895 int len;
11896{
11897 gif_memory_source *src = current_gif_memory_src;
11898
11899 if (len > src->len - src->index)
11900 return -1;
11901
11902 bcopy (src->bytes + src->index, buf, len);
11903 src->index += len;
11904 return len;
11905}
11906
11907
11908/* Load GIF image IMG for use on frame F. Value is non-zero if
11909 successful. */
11910
11911static int
11912gif_load (f, img)
11913 struct frame *f;
11914 struct image *img;
11915{
11916 Lisp_Object file, specified_file;
11917 Lisp_Object specified_data;
11918 int rc, width, height, x, y, i;
11919 XImage *ximg;
11920 ColorMapObject *gif_color_map;
11921 unsigned long pixel_colors[256];
11922 GifFileType *gif;
11923 struct gcpro gcpro1;
11924 Lisp_Object image;
11925 int ino, image_left, image_top, image_width, image_height;
11926 gif_memory_source memsrc;
11927 unsigned char *raster;
11928
11929 specified_file = image_spec_value (img->spec, QCfile, NULL);
11930 specified_data = image_spec_value (img->spec, QCdata, NULL);
11931 file = Qnil;
dfff8a69 11932 GCPRO1 (file);
6fc2811b
JR
11933
11934 if (NILP (specified_data))
11935 {
11936 file = x_find_image_file (specified_file);
6fc2811b
JR
11937 if (!STRINGP (file))
11938 {
11939 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11940 UNGCPRO;
11941 return 0;
11942 }
7d0393cf 11943
6fc2811b 11944 /* Open the GIF file. */
1ffb278b 11945 gif = fn_DGifOpenFileName (SDATA (file));
6fc2811b
JR
11946 if (gif == NULL)
11947 {
11948 image_error ("Cannot open `%s'", file, Qnil);
11949 UNGCPRO;
11950 return 0;
11951 }
11952 }
11953 else
11954 {
11955 /* Read from memory! */
11956 current_gif_memory_src = &memsrc;
d5db4077
KR
11957 memsrc.bytes = SDATA (specified_data);
11958 memsrc.len = SBYTES (specified_data);
6fc2811b
JR
11959 memsrc.index = 0;
11960
1ffb278b 11961 gif = fn_DGifOpen(&memsrc, gif_read_from_memory);
6fc2811b
JR
11962 if (!gif)
11963 {
11964 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11965 UNGCPRO;
11966 return 0;
11967 }
11968 }
11969
11970 /* Read entire contents. */
1ffb278b 11971 rc = fn_DGifSlurp (gif);
6fc2811b
JR
11972 if (rc == GIF_ERROR)
11973 {
11974 image_error ("Error reading `%s'", img->spec, Qnil);
1ffb278b 11975 fn_DGifCloseFile (gif);
6fc2811b
JR
11976 UNGCPRO;
11977 return 0;
11978 }
11979
11980 image = image_spec_value (img->spec, QCindex, NULL);
11981 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11982 if (ino >= gif->ImageCount)
11983 {
11984 image_error ("Invalid image number `%s' in image `%s'",
11985 image, img->spec);
1ffb278b 11986 fn_DGifCloseFile (gif);
6fc2811b
JR
11987 UNGCPRO;
11988 return 0;
11989 }
11990
1ffb278b
JB
11991 width = img->width = max (gif->SWidth, gif->Image.Left + gif->Image.Width);
11992 height = img->height = max (gif->SHeight, gif->Image.Top + gif->Image.Height);
6fc2811b 11993
6fc2811b
JR
11994 /* Create the X image and pixmap. */
11995 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11996 {
1ffb278b 11997 fn_DGifCloseFile (gif);
6fc2811b
JR
11998 UNGCPRO;
11999 return 0;
12000 }
7d0393cf 12001
6fc2811b
JR
12002 /* Allocate colors. */
12003 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
12004 if (!gif_color_map)
12005 gif_color_map = gif->SColorMap;
1ffb278b 12006#if 0 /* TODO: Color tables */
6fc2811b 12007 init_color_table ();
1ffb278b 12008#endif
6fc2811b 12009 bzero (pixel_colors, sizeof pixel_colors);
7d0393cf 12010
6fc2811b
JR
12011 for (i = 0; i < gif_color_map->ColorCount; ++i)
12012 {
1ffb278b
JB
12013 int r = gif_color_map->Colors[i].Red;
12014 int g = gif_color_map->Colors[i].Green;
12015 int b = gif_color_map->Colors[i].Blue;
12016#if 0 /* TODO: Color tables */
6fc2811b 12017 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
1ffb278b
JB
12018#else
12019 pixel_colors[i] = PALETTERGB (r, g, b);
12020#endif
6fc2811b
JR
12021 }
12022
1ffb278b 12023#if 0 /* TODO: Color tables */
6fc2811b
JR
12024 img->colors = colors_in_color_table (&img->ncolors);
12025 free_color_table ();
1ffb278b 12026#endif
6fc2811b
JR
12027
12028 /* Clear the part of the screen image that are not covered by
7d0393cf 12029 the image from the GIF file. Full animated GIF support
6fc2811b
JR
12030 requires more than can be done here (see the gif89 spec,
12031 disposal methods). Let's simply assume that the part
12032 not covered by a sub-image is in the frame's background color. */
12033 image_top = gif->SavedImages[ino].ImageDesc.Top;
12034 image_left = gif->SavedImages[ino].ImageDesc.Left;
12035 image_width = gif->SavedImages[ino].ImageDesc.Width;
12036 image_height = gif->SavedImages[ino].ImageDesc.Height;
12037
12038 for (y = 0; y < image_top; ++y)
12039 for (x = 0; x < width; ++x)
12040 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12041
12042 for (y = image_top + image_height; y < height; ++y)
12043 for (x = 0; x < width; ++x)
12044 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12045
12046 for (y = image_top; y < image_top + image_height; ++y)
12047 {
12048 for (x = 0; x < image_left; ++x)
12049 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12050 for (x = image_left + image_width; x < width; ++x)
12051 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
12052 }
12053
12054 /* Read the GIF image into the X image. We use a local variable
12055 `raster' here because RasterBits below is a char *, and invites
12056 problems with bytes >= 0x80. */
12057 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
12058
12059 if (gif->SavedImages[ino].ImageDesc.Interlace)
12060 {
12061 static int interlace_start[] = {0, 4, 2, 1};
12062 static int interlace_increment[] = {8, 8, 4, 2};
a05e2bae 12063 int pass;
6fc2811b
JR
12064 int row = interlace_start[0];
12065
12066 pass = 0;
12067
12068 for (y = 0; y < image_height; y++)
12069 {
12070 if (row >= image_height)
12071 {
12072 row = interlace_start[++pass];
12073 while (row >= image_height)
12074 row = interlace_start[++pass];
12075 }
7d0393cf 12076
6fc2811b
JR
12077 for (x = 0; x < image_width; x++)
12078 {
12079 int i = raster[(y * image_width) + x];
12080 XPutPixel (ximg, x + image_left, row + image_top,
12081 pixel_colors[i]);
12082 }
7d0393cf 12083
6fc2811b
JR
12084 row += interlace_increment[pass];
12085 }
12086 }
12087 else
12088 {
12089 for (y = 0; y < image_height; ++y)
12090 for (x = 0; x < image_width; ++x)
12091 {
12092 int i = raster[y* image_width + x];
12093 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
12094 }
12095 }
7d0393cf 12096
1ffb278b 12097 fn_DGifCloseFile (gif);
a05e2bae
JR
12098
12099 /* Maybe fill in the background field while we have ximg handy. */
12100 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12101 IMAGE_BACKGROUND (img, f, ximg);
12102
6fc2811b
JR
12103 /* Put the image into the pixmap, then free the X image and its buffer. */
12104 x_put_x_image (f, ximg, img->pixmap, width, height);
12105 x_destroy_x_image (ximg);
7d0393cf 12106
6fc2811b
JR
12107 UNGCPRO;
12108 return 1;
12109}
12110
12111#endif /* HAVE_GIF != 0 */
12112
12113
12114\f
12115/***********************************************************************
12116 Ghostscript
12117 ***********************************************************************/
12118
3cf3436e
JR
12119Lisp_Object Qpostscript;
12120
839b1909
JR
12121/* Keyword symbols. */
12122
12123Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12124
6fc2811b
JR
12125#ifdef HAVE_GHOSTSCRIPT
12126static int gs_image_p P_ ((Lisp_Object object));
12127static int gs_load P_ ((struct frame *f, struct image *img));
12128static void gs_clear_image P_ ((struct frame *f, struct image *img));
12129
12130/* The symbol `postscript' identifying images of this type. */
12131
6fc2811b
JR
12132/* Keyword symbols. */
12133
12134Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12135
12136/* Indices of image specification fields in gs_format, below. */
12137
12138enum gs_keyword_index
12139{
12140 GS_TYPE,
12141 GS_PT_WIDTH,
12142 GS_PT_HEIGHT,
12143 GS_FILE,
12144 GS_LOADER,
12145 GS_BOUNDING_BOX,
12146 GS_ASCENT,
12147 GS_MARGIN,
12148 GS_RELIEF,
12149 GS_ALGORITHM,
12150 GS_HEURISTIC_MASK,
a05e2bae
JR
12151 GS_MASK,
12152 GS_BACKGROUND,
6fc2811b
JR
12153 GS_LAST
12154};
12155
12156/* Vector of image_keyword structures describing the format
12157 of valid user-defined image specifications. */
12158
12159static struct image_keyword gs_format[GS_LAST] =
12160{
12161 {":type", IMAGE_SYMBOL_VALUE, 1},
12162 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12163 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12164 {":file", IMAGE_STRING_VALUE, 1},
12165 {":loader", IMAGE_FUNCTION_VALUE, 0},
12166 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8f92c555 12167 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 12168 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 12169 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 12170 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
12171 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12172 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12173 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
12174};
12175
12176/* Structure describing the image type `ghostscript'. */
12177
12178static struct image_type gs_type =
12179{
12180 &Qpostscript,
12181 gs_image_p,
12182 gs_load,
12183 gs_clear_image,
12184 NULL
12185};
12186
12187
12188/* Free X resources of Ghostscript image IMG which is used on frame F. */
12189
12190static void
12191gs_clear_image (f, img)
12192 struct frame *f;
12193 struct image *img;
12194{
12195 /* IMG->data.ptr_val may contain a recorded colormap. */
12196 xfree (img->data.ptr_val);
12197 x_clear_image (f, img);
12198}
12199
12200
12201/* Return non-zero if OBJECT is a valid Ghostscript image
12202 specification. */
12203
12204static int
12205gs_image_p (object)
12206 Lisp_Object object;
12207{
12208 struct image_keyword fmt[GS_LAST];
12209 Lisp_Object tem;
12210 int i;
7d0393cf 12211
6fc2811b 12212 bcopy (gs_format, fmt, sizeof fmt);
7d0393cf 12213
8f92c555 12214 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
6fc2811b
JR
12215 return 0;
12216
12217 /* Bounding box must be a list or vector containing 4 integers. */
12218 tem = fmt[GS_BOUNDING_BOX].value;
12219 if (CONSP (tem))
12220 {
12221 for (i = 0; i < 4; ++i, tem = XCDR (tem))
12222 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
12223 return 0;
12224 if (!NILP (tem))
12225 return 0;
12226 }
12227 else if (VECTORP (tem))
12228 {
12229 if (XVECTOR (tem)->size != 4)
12230 return 0;
12231 for (i = 0; i < 4; ++i)
12232 if (!INTEGERP (XVECTOR (tem)->contents[i]))
12233 return 0;
12234 }
12235 else
12236 return 0;
12237
12238 return 1;
12239}
12240
12241
12242/* Load Ghostscript image IMG for use on frame F. Value is non-zero
12243 if successful. */
12244
12245static int
12246gs_load (f, img)
12247 struct frame *f;
12248 struct image *img;
12249{
12250 char buffer[100];
12251 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
12252 struct gcpro gcpro1, gcpro2;
12253 Lisp_Object frame;
12254 double in_width, in_height;
12255 Lisp_Object pixel_colors = Qnil;
12256
12257 /* Compute pixel size of pixmap needed from the given size in the
12258 image specification. Sizes in the specification are in pt. 1 pt
12259 = 1/72 in, xdpi and ydpi are stored in the frame's X display
12260 info. */
12261 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
12262 in_width = XFASTINT (pt_width) / 72.0;
12263 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
12264 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
12265 in_height = XFASTINT (pt_height) / 72.0;
12266 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
12267
12268 /* Create the pixmap. */
12269 BLOCK_INPUT;
12270 xassert (img->pixmap == 0);
12271 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12272 img->width, img->height,
a05e2bae 12273 one_w32_display_info.n_cbits);
6fc2811b
JR
12274 UNBLOCK_INPUT;
12275
12276 if (!img->pixmap)
12277 {
12278 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
12279 return 0;
12280 }
7d0393cf 12281
6fc2811b
JR
12282 /* Call the loader to fill the pixmap. It returns a process object
12283 if successful. We do not record_unwind_protect here because
12284 other places in redisplay like calling window scroll functions
12285 don't either. Let the Lisp loader use `unwind-protect' instead. */
12286 GCPRO2 (window_and_pixmap_id, pixel_colors);
12287
12288 sprintf (buffer, "%lu %lu",
12289 (unsigned long) FRAME_W32_WINDOW (f),
12290 (unsigned long) img->pixmap);
12291 window_and_pixmap_id = build_string (buffer);
7d0393cf 12292
6fc2811b
JR
12293 sprintf (buffer, "%lu %lu",
12294 FRAME_FOREGROUND_PIXEL (f),
12295 FRAME_BACKGROUND_PIXEL (f));
12296 pixel_colors = build_string (buffer);
7d0393cf 12297
6fc2811b
JR
12298 XSETFRAME (frame, f);
12299 loader = image_spec_value (img->spec, QCloader, NULL);
12300 if (NILP (loader))
12301 loader = intern ("gs-load-image");
12302
12303 img->data.lisp_val = call6 (loader, frame, img->spec,
12304 make_number (img->width),
12305 make_number (img->height),
12306 window_and_pixmap_id,
12307 pixel_colors);
12308 UNGCPRO;
12309 return PROCESSP (img->data.lisp_val);
12310}
12311
12312
12313/* Kill the Ghostscript process that was started to fill PIXMAP on
12314 frame F. Called from XTread_socket when receiving an event
12315 telling Emacs that Ghostscript has finished drawing. */
12316
12317void
12318x_kill_gs_process (pixmap, f)
12319 Pixmap pixmap;
12320 struct frame *f;
12321{
12322 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
12323 int class, i;
12324 struct image *img;
12325
12326 /* Find the image containing PIXMAP. */
12327 for (i = 0; i < c->used; ++i)
12328 if (c->images[i]->pixmap == pixmap)
12329 break;
12330
3cf3436e
JR
12331 /* Should someone in between have cleared the image cache, for
12332 instance, give up. */
12333 if (i == c->used)
12334 return;
12335
6fc2811b
JR
12336 /* Kill the GS process. We should have found PIXMAP in the image
12337 cache and its image should contain a process object. */
6fc2811b
JR
12338 img = c->images[i];
12339 xassert (PROCESSP (img->data.lisp_val));
12340 Fkill_process (img->data.lisp_val, Qnil);
12341 img->data.lisp_val = Qnil;
12342
12343 /* On displays with a mutable colormap, figure out the colors
12344 allocated for the image by looking at the pixels of an XImage for
12345 img->pixmap. */
12346 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
12347 if (class != StaticColor && class != StaticGray && class != TrueColor)
12348 {
12349 XImage *ximg;
12350
12351 BLOCK_INPUT;
12352
12353 /* Try to get an XImage for img->pixmep. */
12354 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
12355 0, 0, img->width, img->height, ~0, ZPixmap);
12356 if (ximg)
12357 {
12358 int x, y;
7d0393cf 12359
6fc2811b
JR
12360 /* Initialize the color table. */
12361 init_color_table ();
7d0393cf 12362
6fc2811b
JR
12363 /* For each pixel of the image, look its color up in the
12364 color table. After having done so, the color table will
12365 contain an entry for each color used by the image. */
12366 for (y = 0; y < img->height; ++y)
12367 for (x = 0; x < img->width; ++x)
12368 {
12369 unsigned long pixel = XGetPixel (ximg, x, y);
12370 lookup_pixel_color (f, pixel);
12371 }
12372
12373 /* Record colors in the image. Free color table and XImage. */
12374 img->colors = colors_in_color_table (&img->ncolors);
12375 free_color_table ();
12376 XDestroyImage (ximg);
12377
12378#if 0 /* This doesn't seem to be the case. If we free the colors
12379 here, we get a BadAccess later in x_clear_image when
12380 freeing the colors. */
12381 /* We have allocated colors once, but Ghostscript has also
12382 allocated colors on behalf of us. So, to get the
12383 reference counts right, free them once. */
12384 if (img->ncolors)
3cf3436e 12385 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
6fc2811b 12386 img->colors, img->ncolors, 0);
6fc2811b
JR
12387#endif
12388 }
12389 else
12390 image_error ("Cannot get X image of `%s'; colors will not be freed",
12391 img->spec, Qnil);
7d0393cf 12392
6fc2811b
JR
12393 UNBLOCK_INPUT;
12394 }
3cf3436e
JR
12395
12396 /* Now that we have the pixmap, compute mask and transform the
12397 image if requested. */
12398 BLOCK_INPUT;
12399 postprocess_image (f, img);
12400 UNBLOCK_INPUT;
6fc2811b
JR
12401}
12402
12403#endif /* HAVE_GHOSTSCRIPT */
12404
12405\f
12406/***********************************************************************
12407 Window properties
12408 ***********************************************************************/
12409
12410DEFUN ("x-change-window-property", Fx_change_window_property,
12411 Sx_change_window_property, 2, 3, 0,
74e1aeec
JR
12412 doc: /* Change window property PROP to VALUE on the X window of FRAME.
12413PROP and VALUE must be strings. FRAME nil or omitted means use the
12414selected frame. Value is VALUE. */)
6fc2811b
JR
12415 (prop, value, frame)
12416 Lisp_Object frame, prop, value;
12417{
767b1ff0 12418#if 0 /* TODO : port window properties to W32 */
6fc2811b
JR
12419 struct frame *f = check_x_frame (frame);
12420 Atom prop_atom;
12421
b7826503
PJ
12422 CHECK_STRING (prop);
12423 CHECK_STRING (value);
6fc2811b
JR
12424
12425 BLOCK_INPUT;
d5db4077 12426 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6fc2811b
JR
12427 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12428 prop_atom, XA_STRING, 8, PropModeReplace,
d5db4077 12429 SDATA (value), SCHARS (value));
6fc2811b
JR
12430
12431 /* Make sure the property is set when we return. */
12432 XFlush (FRAME_W32_DISPLAY (f));
12433 UNBLOCK_INPUT;
12434
767b1ff0 12435#endif /* TODO */
6fc2811b
JR
12436
12437 return value;
12438}
12439
12440
12441DEFUN ("x-delete-window-property", Fx_delete_window_property,
12442 Sx_delete_window_property, 1, 2, 0,
74e1aeec
JR
12443 doc: /* Remove window property PROP from X window of FRAME.
12444FRAME nil or omitted means use the selected frame. Value is PROP. */)
6fc2811b
JR
12445 (prop, frame)
12446 Lisp_Object prop, frame;
12447{
767b1ff0 12448#if 0 /* TODO : port window properties to W32 */
6fc2811b
JR
12449
12450 struct frame *f = check_x_frame (frame);
12451 Atom prop_atom;
12452
b7826503 12453 CHECK_STRING (prop);
6fc2811b 12454 BLOCK_INPUT;
d5db4077 12455 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6fc2811b
JR
12456 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
12457
12458 /* Make sure the property is removed when we return. */
12459 XFlush (FRAME_W32_DISPLAY (f));
12460 UNBLOCK_INPUT;
767b1ff0 12461#endif /* TODO */
6fc2811b
JR
12462
12463 return prop;
12464}
12465
12466
12467DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
12468 1, 2, 0,
74e1aeec
JR
12469 doc: /* Value is the value of window property PROP on FRAME.
12470If FRAME is nil or omitted, use the selected frame. Value is nil
12471if FRAME hasn't a property with name PROP or if PROP has no string
12472value. */)
6fc2811b
JR
12473 (prop, frame)
12474 Lisp_Object prop, frame;
12475{
767b1ff0 12476#if 0 /* TODO : port window properties to W32 */
6fc2811b
JR
12477
12478 struct frame *f = check_x_frame (frame);
12479 Atom prop_atom;
12480 int rc;
12481 Lisp_Object prop_value = Qnil;
12482 char *tmp_data = NULL;
12483 Atom actual_type;
12484 int actual_format;
12485 unsigned long actual_size, bytes_remaining;
12486
b7826503 12487 CHECK_STRING (prop);
6fc2811b 12488 BLOCK_INPUT;
d5db4077 12489 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6fc2811b
JR
12490 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12491 prop_atom, 0, 0, False, XA_STRING,
12492 &actual_type, &actual_format, &actual_size,
12493 &bytes_remaining, (unsigned char **) &tmp_data);
12494 if (rc == Success)
12495 {
12496 int size = bytes_remaining;
12497
12498 XFree (tmp_data);
12499 tmp_data = NULL;
12500
12501 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12502 prop_atom, 0, bytes_remaining,
12503 False, XA_STRING,
7d0393cf
JB
12504 &actual_type, &actual_format,
12505 &actual_size, &bytes_remaining,
6fc2811b
JR
12506 (unsigned char **) &tmp_data);
12507 if (rc == Success)
12508 prop_value = make_string (tmp_data, size);
12509
12510 XFree (tmp_data);
12511 }
12512
12513 UNBLOCK_INPUT;
12514
12515 return prop_value;
12516
767b1ff0 12517#endif /* TODO */
6fc2811b
JR
12518 return Qnil;
12519}
12520
12521
12522\f
12523/***********************************************************************
12524 Busy cursor
12525 ***********************************************************************/
12526
f79e6790 12527/* If non-null, an asynchronous timer that, when it expires, displays
0af913d7 12528 an hourglass cursor on all frames. */
6fc2811b 12529
0af913d7 12530static struct atimer *hourglass_atimer;
6fc2811b 12531
0af913d7 12532/* Non-zero means an hourglass cursor is currently shown. */
6fc2811b 12533
0af913d7 12534static int hourglass_shown_p;
6fc2811b 12535
0af913d7 12536/* Number of seconds to wait before displaying an hourglass cursor. */
6fc2811b 12537
0af913d7 12538static Lisp_Object Vhourglass_delay;
6fc2811b 12539
0af913d7 12540/* Default number of seconds to wait before displaying an hourglass
f79e6790
JR
12541 cursor. */
12542
0af913d7 12543#define DEFAULT_HOURGLASS_DELAY 1
f79e6790
JR
12544
12545/* Function prototypes. */
12546
0af913d7
GM
12547static void show_hourglass P_ ((struct atimer *));
12548static void hide_hourglass P_ ((void));
f79e6790
JR
12549
12550
0af913d7 12551/* Cancel a currently active hourglass timer, and start a new one. */
f79e6790
JR
12552
12553void
0af913d7 12554start_hourglass ()
f79e6790 12555{
767b1ff0 12556#if 0 /* TODO: cursor shape changes. */
f79e6790 12557 EMACS_TIME delay;
dfff8a69 12558 int secs, usecs = 0;
7d0393cf 12559
0af913d7 12560 cancel_hourglass ();
f79e6790 12561
0af913d7
GM
12562 if (INTEGERP (Vhourglass_delay)
12563 && XINT (Vhourglass_delay) > 0)
12564 secs = XFASTINT (Vhourglass_delay);
12565 else if (FLOATP (Vhourglass_delay)
12566 && XFLOAT_DATA (Vhourglass_delay) > 0)
dfff8a69
JR
12567 {
12568 Lisp_Object tem;
0af913d7 12569 tem = Ftruncate (Vhourglass_delay, Qnil);
dfff8a69 12570 secs = XFASTINT (tem);
0af913d7 12571 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
dfff8a69 12572 }
f79e6790 12573 else
0af913d7 12574 secs = DEFAULT_HOURGLASS_DELAY;
7d0393cf 12575
dfff8a69 12576 EMACS_SET_SECS_USECS (delay, secs, usecs);
0af913d7
GM
12577 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
12578 show_hourglass, NULL);
f79e6790
JR
12579#endif
12580}
12581
12582
0af913d7
GM
12583/* Cancel the hourglass cursor timer if active, hide an hourglass
12584 cursor if shown. */
f79e6790
JR
12585
12586void
0af913d7 12587cancel_hourglass ()
f79e6790 12588{
0af913d7 12589 if (hourglass_atimer)
dfff8a69 12590 {
0af913d7
GM
12591 cancel_atimer (hourglass_atimer);
12592 hourglass_atimer = NULL;
dfff8a69 12593 }
7d0393cf 12594
0af913d7
GM
12595 if (hourglass_shown_p)
12596 hide_hourglass ();
f79e6790
JR
12597}
12598
12599
0af913d7
GM
12600/* Timer function of hourglass_atimer. TIMER is equal to
12601 hourglass_atimer.
f79e6790 12602
0af913d7
GM
12603 Display an hourglass cursor on all frames by mapping the frames'
12604 hourglass_window. Set the hourglass_p flag in the frames'
12605 output_data.x structure to indicate that an hourglass cursor is
12606 shown on the frames. */
f79e6790
JR
12607
12608static void
0af913d7 12609show_hourglass (timer)
f79e6790 12610 struct atimer *timer;
6fc2811b 12611{
767b1ff0 12612#if 0 /* TODO: cursor shape changes. */
f79e6790 12613 /* The timer implementation will cancel this timer automatically
0af913d7 12614 after this function has run. Set hourglass_atimer to null
f79e6790 12615 so that we know the timer doesn't have to be canceled. */
0af913d7 12616 hourglass_atimer = NULL;
f79e6790 12617
0af913d7 12618 if (!hourglass_shown_p)
6fc2811b
JR
12619 {
12620 Lisp_Object rest, frame;
7d0393cf 12621
f79e6790 12622 BLOCK_INPUT;
7d0393cf 12623
6fc2811b 12624 FOR_EACH_FRAME (rest, frame)
dc220243 12625 if (FRAME_W32_P (XFRAME (frame)))
6fc2811b
JR
12626 {
12627 struct frame *f = XFRAME (frame);
7d0393cf 12628
0af913d7 12629 f->output_data.w32->hourglass_p = 1;
7d0393cf 12630
0af913d7 12631 if (!f->output_data.w32->hourglass_window)
6fc2811b
JR
12632 {
12633 unsigned long mask = CWCursor;
12634 XSetWindowAttributes attrs;
7d0393cf 12635
0af913d7 12636 attrs.cursor = f->output_data.w32->hourglass_cursor;
7d0393cf 12637
0af913d7 12638 f->output_data.w32->hourglass_window
f79e6790 12639 = XCreateWindow (FRAME_X_DISPLAY (f),
6fc2811b
JR
12640 FRAME_OUTER_WINDOW (f),
12641 0, 0, 32000, 32000, 0, 0,
f79e6790
JR
12642 InputOnly,
12643 CopyFromParent,
6fc2811b
JR
12644 mask, &attrs);
12645 }
7d0393cf 12646
0af913d7
GM
12647 XMapRaised (FRAME_X_DISPLAY (f),
12648 f->output_data.w32->hourglass_window);
f79e6790 12649 XFlush (FRAME_X_DISPLAY (f));
6fc2811b 12650 }
6fc2811b 12651
0af913d7 12652 hourglass_shown_p = 1;
f79e6790
JR
12653 UNBLOCK_INPUT;
12654 }
12655#endif
6fc2811b
JR
12656}
12657
12658
0af913d7 12659/* Hide the hourglass cursor on all frames, if it is currently shown. */
6fc2811b 12660
f79e6790 12661static void
0af913d7 12662hide_hourglass ()
f79e6790 12663{
767b1ff0 12664#if 0 /* TODO: cursor shape changes. */
0af913d7 12665 if (hourglass_shown_p)
6fc2811b 12666 {
f79e6790
JR
12667 Lisp_Object rest, frame;
12668
12669 BLOCK_INPUT;
12670 FOR_EACH_FRAME (rest, frame)
6fc2811b 12671 {
f79e6790 12672 struct frame *f = XFRAME (frame);
7d0393cf 12673
dc220243 12674 if (FRAME_W32_P (f)
f79e6790 12675 /* Watch out for newly created frames. */
0af913d7 12676 && f->output_data.x->hourglass_window)
f79e6790 12677 {
0af913d7
GM
12678 XUnmapWindow (FRAME_X_DISPLAY (f),
12679 f->output_data.x->hourglass_window);
12680 /* Sync here because XTread_socket looks at the
12681 hourglass_p flag that is reset to zero below. */
f79e6790 12682 XSync (FRAME_X_DISPLAY (f), False);
0af913d7 12683 f->output_data.x->hourglass_p = 0;
f79e6790 12684 }
6fc2811b 12685 }
6fc2811b 12686
0af913d7 12687 hourglass_shown_p = 0;
f79e6790
JR
12688 UNBLOCK_INPUT;
12689 }
12690#endif
6fc2811b
JR
12691}
12692
12693
12694\f
12695/***********************************************************************
12696 Tool tips
12697 ***********************************************************************/
12698
12699static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
3cf3436e
JR
12700 Lisp_Object, Lisp_Object));
12701static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
12702 Lisp_Object, int, int, int *, int *));
7d0393cf 12703
3cf3436e 12704/* The frame of a currently visible tooltip. */
6fc2811b 12705
937e601e 12706Lisp_Object tip_frame;
6fc2811b
JR
12707
12708/* If non-nil, a timer started that hides the last tooltip when it
12709 fires. */
12710
12711Lisp_Object tip_timer;
12712Window tip_window;
12713
3cf3436e
JR
12714/* If non-nil, a vector of 3 elements containing the last args
12715 with which x-show-tip was called. See there. */
12716
12717Lisp_Object last_show_tip_args;
12718
12719/* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
12720
12721Lisp_Object Vx_max_tooltip_size;
12722
12723
937e601e
AI
12724static Lisp_Object
12725unwind_create_tip_frame (frame)
12726 Lisp_Object frame;
12727{
c844a81a
GM
12728 Lisp_Object deleted;
12729
12730 deleted = unwind_create_frame (frame);
12731 if (EQ (deleted, Qt))
12732 {
12733 tip_window = NULL;
12734 tip_frame = Qnil;
12735 }
7d0393cf 12736
c844a81a 12737 return deleted;
937e601e
AI
12738}
12739
12740
6fc2811b 12741/* Create a frame for a tooltip on the display described by DPYINFO.
3cf3436e
JR
12742 PARMS is a list of frame parameters. TEXT is the string to
12743 display in the tip frame. Value is the frame.
937e601e
AI
12744
12745 Note that functions called here, esp. x_default_parameter can
12746 signal errors, for instance when a specified color name is
12747 undefined. We have to make sure that we're in a consistent state
12748 when this happens. */
6fc2811b
JR
12749
12750static Lisp_Object
3cf3436e 12751x_create_tip_frame (dpyinfo, parms, text)
6fc2811b 12752 struct w32_display_info *dpyinfo;
3cf3436e 12753 Lisp_Object parms, text;
6fc2811b 12754{
6fc2811b
JR
12755 struct frame *f;
12756 Lisp_Object frame, tem;
12757 Lisp_Object name;
12758 long window_prompting = 0;
12759 int width, height;
331379bf 12760 int count = SPECPDL_INDEX ();
6fc2811b
JR
12761 struct gcpro gcpro1, gcpro2, gcpro3;
12762 struct kboard *kb;
3cf3436e
JR
12763 int face_change_count_before = face_change_count;
12764 Lisp_Object buffer;
12765 struct buffer *old_buffer;
6fc2811b 12766
ca56d953 12767 check_w32 ();
6fc2811b
JR
12768
12769 /* Use this general default value to start with until we know if
12770 this frame has a specified name. */
12771 Vx_resource_name = Vinvocation_name;
12772
12773#ifdef MULTI_KBOARD
12774 kb = dpyinfo->kboard;
12775#else
12776 kb = &the_only_kboard;
12777#endif
12778
12779 /* Get the name of the frame to use for resource lookup. */
12780 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
12781 if (!STRINGP (name)
12782 && !EQ (name, Qunbound)
12783 && !NILP (name))
12784 error ("Invalid frame name--not a string or nil");
12785 Vx_resource_name = name;
12786
12787 frame = Qnil;
12788 GCPRO3 (parms, name, frame);
9eb16b62
JR
12789 /* Make a frame without minibuffer nor mode-line. */
12790 f = make_frame (0);
12791 f->wants_modeline = 0;
6fc2811b 12792 XSETFRAME (frame, f);
3cf3436e
JR
12793
12794 buffer = Fget_buffer_create (build_string (" *tip*"));
be786000 12795 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer, Qnil);
3cf3436e
JR
12796 old_buffer = current_buffer;
12797 set_buffer_internal_1 (XBUFFER (buffer));
12798 current_buffer->truncate_lines = Qnil;
12799 Ferase_buffer ();
12800 Finsert (1, &text);
12801 set_buffer_internal_1 (old_buffer);
7d0393cf 12802
6fc2811b 12803 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
937e601e 12804 record_unwind_protect (unwind_create_tip_frame, frame);
6fc2811b 12805
3cf3436e
JR
12806 /* By setting the output method, we're essentially saying that
12807 the frame is live, as per FRAME_LIVE_P. If we get a signal
12808 from this point on, x_destroy_window might screw up reference
12809 counts etc. */
d88c567c 12810 f->output_method = output_w32;
6fc2811b
JR
12811 f->output_data.w32 =
12812 (struct w32_output *) xmalloc (sizeof (struct w32_output));
12813 bzero (f->output_data.w32, sizeof (struct w32_output));
ca56d953
JR
12814
12815 FRAME_FONTSET (f) = -1;
6fc2811b
JR
12816 f->icon_name = Qnil;
12817
ca56d953 12818#if 0 /* GLYPH_DEBUG TODO: image support. */
937e601e
AI
12819 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
12820 dpyinfo_refcount = dpyinfo->reference_count;
12821#endif /* GLYPH_DEBUG */
6fc2811b
JR
12822#ifdef MULTI_KBOARD
12823 FRAME_KBOARD (f) = kb;
12824#endif
12825 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12826 f->output_data.w32->explicit_parent = 0;
12827
12828 /* Set the name; the functions to which we pass f expect the name to
12829 be set. */
12830 if (EQ (name, Qunbound) || NILP (name))
12831 {
ca56d953 12832 f->name = build_string (dpyinfo->w32_id_name);
6fc2811b
JR
12833 f->explicit_name = 0;
12834 }
12835 else
12836 {
12837 f->name = name;
12838 f->explicit_name = 1;
12839 /* use the frame's title when getting resources for this frame. */
12840 specbind (Qx_resource_name, name);
12841 }
12842
6fc2811b
JR
12843 /* Extract the window parameters from the supplied values
12844 that are needed to determine window geometry. */
12845 {
12846 Lisp_Object font;
12847
12848 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12849
12850 BLOCK_INPUT;
12851 /* First, try whatever font the caller has specified. */
12852 if (STRINGP (font))
12853 {
12854 tem = Fquery_fontset (font, Qnil);
12855 if (STRINGP (tem))
10b4bc33 12856 font = x_new_fontset (f, tem);
6fc2811b 12857 else
d5db4077 12858 font = x_new_font (f, SDATA (font));
6fc2811b 12859 }
7d0393cf 12860
6fc2811b
JR
12861 /* Try out a font which we hope has bold and italic variations. */
12862 if (!STRINGP (font))
ca56d953 12863 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
6fc2811b 12864 if (! STRINGP (font))
ca56d953 12865 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
6fc2811b
JR
12866 /* If those didn't work, look for something which will at least work. */
12867 if (! STRINGP (font))
ca56d953 12868 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
6fc2811b
JR
12869 UNBLOCK_INPUT;
12870 if (! STRINGP (font))
ca56d953 12871 font = build_string ("Fixedsys");
6fc2811b
JR
12872
12873 x_default_parameter (f, parms, Qfont, font,
12874 "font", "Font", RES_TYPE_STRING);
12875 }
12876
12877 x_default_parameter (f, parms, Qborder_width, make_number (2),
12878 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6fc2811b
JR
12879 /* This defaults to 2 in order to match xterm. We recognize either
12880 internalBorderWidth or internalBorder (which is what xterm calls
12881 it). */
12882 if (NILP (Fassq (Qinternal_border_width, parms)))
12883 {
12884 Lisp_Object value;
12885
12886 value = w32_get_arg (parms, Qinternal_border_width,
12887 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12888 if (! EQ (value, Qunbound))
12889 parms = Fcons (Fcons (Qinternal_border_width, value),
12890 parms);
12891 }
bfd6edcc 12892 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6fc2811b
JR
12893 "internalBorderWidth", "internalBorderWidth",
12894 RES_TYPE_NUMBER);
12895
12896 /* Also do the stuff which must be set before the window exists. */
12897 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12898 "foreground", "Foreground", RES_TYPE_STRING);
12899 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12900 "background", "Background", RES_TYPE_STRING);
12901 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12902 "pointerColor", "Foreground", RES_TYPE_STRING);
12903 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12904 "cursorColor", "Foreground", RES_TYPE_STRING);
12905 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12906 "borderColor", "BorderColor", RES_TYPE_STRING);
12907
12908 /* Init faces before x_default_parameter is called for scroll-bar
12909 parameters because that function calls x_set_scroll_bar_width,
12910 which calls change_frame_size, which calls Fset_window_buffer,
12911 which runs hooks, which call Fvertical_motion. At the end, we
12912 end up in init_iterator with a null face cache, which should not
12913 happen. */
12914 init_frame_faces (f);
ca56d953
JR
12915
12916 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6fc2811b 12917 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
9eb16b62 12918
6d906347 12919 window_prompting = x_figure_window_size (f, parms, 0);
6fc2811b 12920
9eb16b62 12921 /* No fringes on tip frame. */
be786000
KS
12922 f->fringe_cols = 0;
12923 f->left_fringe_width = 0;
12924 f->right_fringe_width = 0;
9eb16b62 12925
ca56d953
JR
12926 BLOCK_INPUT;
12927 my_create_tip_window (f);
12928 UNBLOCK_INPUT;
6fc2811b
JR
12929
12930 x_make_gc (f);
12931
12932 x_default_parameter (f, parms, Qauto_raise, Qnil,
12933 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12934 x_default_parameter (f, parms, Qauto_lower, Qnil,
12935 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12936 x_default_parameter (f, parms, Qcursor_type, Qbox,
12937 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12938
be786000 12939 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
6fc2811b 12940 Change will not be effected unless different from the current
be786000
KS
12941 FRAME_LINES (f). */
12942 width = FRAME_COLS (f);
12943 height = FRAME_LINES (f);
12944 FRAME_LINES (f) = 0;
12945 SET_FRAME_COLS (f, 0);
6fc2811b
JR
12946 change_frame_size (f, height, width, 1, 0, 0);
12947
cd1d850f
JPW
12948 /* Add `tooltip' frame parameter's default value. */
12949 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
12950 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
12951 Qnil));
7d0393cf 12952
3cf3436e
JR
12953 /* Set up faces after all frame parameters are known. This call
12954 also merges in face attributes specified for new frames.
12955
12956 Frame parameters may be changed if .Xdefaults contains
12957 specifications for the default font. For example, if there is an
12958 `Emacs.default.attributeBackground: pink', the `background-color'
12959 attribute of the frame get's set, which let's the internal border
12960 of the tooltip frame appear in pink. Prevent this. */
12961 {
12962 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
12963
12964 /* Set tip_frame here, so that */
12965 tip_frame = frame;
12966 call1 (Qface_set_after_frame_default, frame);
7d0393cf 12967
3cf3436e
JR
12968 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
12969 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
12970 Qnil));
12971 }
7d0393cf 12972
6fc2811b
JR
12973 f->no_split = 1;
12974
12975 UNGCPRO;
12976
12977 /* It is now ok to make the frame official even if we get an error
12978 below. And the frame needs to be on Vframe_list or making it
12979 visible won't work. */
12980 Vframe_list = Fcons (frame, Vframe_list);
12981
12982 /* Now that the frame is official, it counts as a reference to
12983 its display. */
12984 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
ee78dc32 12985
3cf3436e
JR
12986 /* Setting attributes of faces of the tooltip frame from resources
12987 and similar will increment face_change_count, which leads to the
12988 clearing of all current matrices. Since this isn't necessary
12989 here, avoid it by resetting face_change_count to the value it
12990 had before we created the tip frame. */
12991 face_change_count = face_change_count_before;
12992
12993 /* Discard the unwind_protect. */
6fc2811b 12994 return unbind_to (count, frame);
ee78dc32
GV
12995}
12996
3cf3436e
JR
12997
12998/* Compute where to display tip frame F. PARMS is the list of frame
12999 parameters for F. DX and DY are specified offsets from the current
13000 location of the mouse. WIDTH and HEIGHT are the width and height
13001 of the tooltip. Return coordinates relative to the root window of
13002 the display in *ROOT_X, and *ROOT_Y. */
13003
13004static void
13005compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
13006 struct frame *f;
13007 Lisp_Object parms, dx, dy;
13008 int width, height;
13009 int *root_x, *root_y;
13010{
3cf3436e 13011 Lisp_Object left, top;
7d0393cf 13012
3cf3436e
JR
13013 /* User-specified position? */
13014 left = Fcdr (Fassq (Qleft, parms));
13015 top = Fcdr (Fassq (Qtop, parms));
7d0393cf 13016
3cf3436e
JR
13017 /* Move the tooltip window where the mouse pointer is. Resize and
13018 show it. */
ca56d953 13019 if (!INTEGERP (left) || !INTEGERP (top))
3cf3436e 13020 {
ca56d953
JR
13021 POINT pt;
13022
3cf3436e 13023 BLOCK_INPUT;
ca56d953
JR
13024 GetCursorPos (&pt);
13025 *root_x = pt.x;
13026 *root_y = pt.y;
3cf3436e
JR
13027 UNBLOCK_INPUT;
13028 }
13029
13030 if (INTEGERP (top))
13031 *root_y = XINT (top);
13032 else if (*root_y + XINT (dy) - height < 0)
13033 *root_y -= XINT (dy);
13034 else
13035 {
13036 *root_y -= height;
13037 *root_y += XINT (dy);
13038 }
13039
13040 if (INTEGERP (left))
13041 *root_x = XINT (left);
72e4adef
JR
13042 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
13043 /* It fits to the right of the pointer. */
13044 *root_x += XINT (dx);
13045 else if (width + XINT (dx) <= *root_x)
13046 /* It fits to the left of the pointer. */
3cf3436e
JR
13047 *root_x -= width + XINT (dx);
13048 else
72e4adef
JR
13049 /* Put it left justified on the screen -- it ought to fit that way. */
13050 *root_x = 0;
3cf3436e
JR
13051}
13052
13053
71eab8d1 13054DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
74e1aeec
JR
13055 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
13056A tooltip window is a small window displaying a string.
13057
13058FRAME nil or omitted means use the selected frame.
13059
13060PARMS is an optional list of frame parameters which can be
13061used to change the tooltip's appearance.
13062
ca56d953
JR
13063Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
13064means use the default timeout of 5 seconds.
74e1aeec 13065
ca56d953 13066If the list of frame parameters PARAMS contains a `left' parameter,
74e1aeec
JR
13067the tooltip is displayed at that x-position. Otherwise it is
13068displayed at the mouse position, with offset DX added (default is 5 if
13069DX isn't specified). Likewise for the y-position; if a `top' frame
13070parameter is specified, it determines the y-position of the tooltip
13071window, otherwise it is displayed at the mouse position, with offset
13072DY added (default is -10).
13073
13074A tooltip's maximum size is specified by `x-max-tooltip-size'.
13075Text larger than the specified size is clipped. */)
71eab8d1
AI
13076 (string, frame, parms, timeout, dx, dy)
13077 Lisp_Object string, frame, parms, timeout, dx, dy;
ee78dc32 13078{
6fc2811b
JR
13079 struct frame *f;
13080 struct window *w;
3cf3436e 13081 int root_x, root_y;
6fc2811b
JR
13082 struct buffer *old_buffer;
13083 struct text_pos pos;
13084 int i, width, height;
6fc2811b
JR
13085 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
13086 int old_windows_or_buffers_changed = windows_or_buffers_changed;
331379bf 13087 int count = SPECPDL_INDEX ();
7d0393cf 13088
6fc2811b 13089 specbind (Qinhibit_redisplay, Qt);
ee78dc32 13090
dfff8a69 13091 GCPRO4 (string, parms, frame, timeout);
ee78dc32 13092
b7826503 13093 CHECK_STRING (string);
6fc2811b
JR
13094 f = check_x_frame (frame);
13095 if (NILP (timeout))
13096 timeout = make_number (5);
13097 else
b7826503 13098 CHECK_NATNUM (timeout);
ee78dc32 13099
71eab8d1
AI
13100 if (NILP (dx))
13101 dx = make_number (5);
13102 else
b7826503 13103 CHECK_NUMBER (dx);
7d0393cf 13104
71eab8d1 13105 if (NILP (dy))
dc220243 13106 dy = make_number (-10);
71eab8d1 13107 else
b7826503 13108 CHECK_NUMBER (dy);
71eab8d1 13109
dc220243
JR
13110 if (NILP (last_show_tip_args))
13111 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
13112
13113 if (!NILP (tip_frame))
13114 {
13115 Lisp_Object last_string = AREF (last_show_tip_args, 0);
13116 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
13117 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
13118
13119 if (EQ (frame, last_frame)
13120 && !NILP (Fequal (last_string, string))
13121 && !NILP (Fequal (last_parms, parms)))
13122 {
13123 struct frame *f = XFRAME (tip_frame);
7d0393cf 13124
dc220243
JR
13125 /* Only DX and DY have changed. */
13126 if (!NILP (tip_timer))
13127 {
13128 Lisp_Object timer = tip_timer;
13129 tip_timer = Qnil;
13130 call1 (Qcancel_timer, timer);
13131 }
13132
13133 BLOCK_INPUT;
be786000
KS
13134 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
13135 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
d65a9cdc
JR
13136
13137 /* Put tooltip in topmost group and in position. */
ca56d953
JR
13138 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13139 root_x, root_y, 0, 0,
13140 SWP_NOSIZE | SWP_NOACTIVATE);
d65a9cdc
JR
13141
13142 /* Ensure tooltip is on top of other topmost windows (eg menus). */
13143 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
13144 0, 0, 0, 0,
13145 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
13146
dc220243
JR
13147 UNBLOCK_INPUT;
13148 goto start_timer;
13149 }
13150 }
13151
6fc2811b
JR
13152 /* Hide a previous tip, if any. */
13153 Fx_hide_tip ();
ee78dc32 13154
dc220243
JR
13155 ASET (last_show_tip_args, 0, string);
13156 ASET (last_show_tip_args, 1, frame);
13157 ASET (last_show_tip_args, 2, parms);
13158
6fc2811b
JR
13159 /* Add default values to frame parameters. */
13160 if (NILP (Fassq (Qname, parms)))
13161 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
13162 if (NILP (Fassq (Qinternal_border_width, parms)))
13163 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
13164 if (NILP (Fassq (Qborder_width, parms)))
13165 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
13166 if (NILP (Fassq (Qborder_color, parms)))
13167 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
13168 if (NILP (Fassq (Qbackground_color, parms)))
13169 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
13170 parms);
13171
0e3fcdef
JR
13172 /* Block input until the tip has been fully drawn, to avoid crashes
13173 when drawing tips in menus. */
13174 BLOCK_INPUT;
13175
6fc2811b
JR
13176 /* Create a frame for the tooltip, and record it in the global
13177 variable tip_frame. */
ca56d953 13178 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
937e601e 13179 f = XFRAME (frame);
6fc2811b 13180
3cf3436e 13181 /* Set up the frame's root window. */
6fc2811b 13182 w = XWINDOW (FRAME_ROOT_WINDOW (f));
be786000 13183 w->left_col = w->top_line = make_number (0);
3cf3436e
JR
13184
13185 if (CONSP (Vx_max_tooltip_size)
13186 && INTEGERP (XCAR (Vx_max_tooltip_size))
13187 && XINT (XCAR (Vx_max_tooltip_size)) > 0
13188 && INTEGERP (XCDR (Vx_max_tooltip_size))
13189 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
13190 {
be786000
KS
13191 w->total_cols = XCAR (Vx_max_tooltip_size);
13192 w->total_lines = XCDR (Vx_max_tooltip_size);
3cf3436e
JR
13193 }
13194 else
13195 {
be786000
KS
13196 w->total_cols = make_number (80);
13197 w->total_lines = make_number (40);
3cf3436e 13198 }
7d0393cf 13199
be786000 13200 FRAME_TOTAL_COLS (f) = XINT (w->total_cols);
6fc2811b
JR
13201 adjust_glyphs (f);
13202 w->pseudo_window_p = 1;
13203
13204 /* Display the tooltip text in a temporary buffer. */
6fc2811b 13205 old_buffer = current_buffer;
3cf3436e
JR
13206 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
13207 current_buffer->truncate_lines = Qnil;
6fc2811b
JR
13208 clear_glyph_matrix (w->desired_matrix);
13209 clear_glyph_matrix (w->current_matrix);
13210 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
13211 try_window (FRAME_ROOT_WINDOW (f), pos);
13212
13213 /* Compute width and height of the tooltip. */
13214 width = height = 0;
13215 for (i = 0; i < w->desired_matrix->nrows; ++i)
ee78dc32 13216 {
6fc2811b
JR
13217 struct glyph_row *row = &w->desired_matrix->rows[i];
13218 struct glyph *last;
13219 int row_width;
13220
13221 /* Stop at the first empty row at the end. */
13222 if (!row->enabled_p || !row->displays_text_p)
13223 break;
13224
13225 /* Let the row go over the full width of the frame. */
13226 row->full_width_p = 1;
13227
4e3a1c61
JR
13228#ifdef TODO /* Investigate why some fonts need more width than is
13229 calculated for some tooltips. */
6fc2811b
JR
13230 /* There's a glyph at the end of rows that is use to place
13231 the cursor there. Don't include the width of this glyph. */
13232 if (row->used[TEXT_AREA])
13233 {
13234 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
13235 row_width = row->pixel_width - last->pixel_width;
13236 }
13237 else
4e3a1c61 13238#endif
6fc2811b 13239 row_width = row->pixel_width;
7d0393cf 13240
ca56d953 13241 /* TODO: find why tips do not draw along baseline as instructed. */
bfd6edcc 13242 height += row->height;
6fc2811b 13243 width = max (width, row_width);
ee78dc32
GV
13244 }
13245
6fc2811b
JR
13246 /* Add the frame's internal border to the width and height the X
13247 window should have. */
13248 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
13249 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
ee78dc32 13250
6fc2811b
JR
13251 /* Move the tooltip window where the mouse pointer is. Resize and
13252 show it. */
3cf3436e 13253 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
71eab8d1 13254
bfd6edcc
JR
13255 {
13256 /* Adjust Window size to take border into account. */
13257 RECT rect;
13258 rect.left = rect.top = 0;
13259 rect.right = width;
13260 rect.bottom = height;
13261 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
13262 FRAME_EXTERNAL_MENU_BAR (f));
13263
d65a9cdc 13264 /* Position and size tooltip, and put it in the topmost group. */
bfd6edcc
JR
13265 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13266 root_x, root_y, rect.right - rect.left,
13267 rect.bottom - rect.top, SWP_NOACTIVATE);
13268
d65a9cdc
JR
13269 /* Ensure tooltip is on top of other topmost windows (eg menus). */
13270 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
13271 0, 0, 0, 0,
13272 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
13273
bfd6edcc
JR
13274 /* Let redisplay know that we have made the frame visible already. */
13275 f->async_visible = 1;
13276
13277 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
13278 }
ee78dc32 13279
6fc2811b
JR
13280 /* Draw into the window. */
13281 w->must_be_updated_p = 1;
13282 update_single_window (w, 1);
ee78dc32 13283
0e3fcdef
JR
13284 UNBLOCK_INPUT;
13285
6fc2811b
JR
13286 /* Restore original current buffer. */
13287 set_buffer_internal_1 (old_buffer);
13288 windows_or_buffers_changed = old_windows_or_buffers_changed;
ee78dc32 13289
dc220243 13290 start_timer:
6fc2811b
JR
13291 /* Let the tip disappear after timeout seconds. */
13292 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
13293 intern ("x-hide-tip"));
ee78dc32 13294
dfff8a69 13295 UNGCPRO;
6fc2811b 13296 return unbind_to (count, Qnil);
ee78dc32
GV
13297}
13298
ee78dc32 13299
6fc2811b 13300DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
74e1aeec
JR
13301 doc: /* Hide the current tooltip window, if there is any.
13302Value is t if tooltip was open, nil otherwise. */)
6fc2811b
JR
13303 ()
13304{
937e601e
AI
13305 int count;
13306 Lisp_Object deleted, frame, timer;
13307 struct gcpro gcpro1, gcpro2;
13308
13309 /* Return quickly if nothing to do. */
13310 if (NILP (tip_timer) && NILP (tip_frame))
13311 return Qnil;
7d0393cf 13312
937e601e
AI
13313 frame = tip_frame;
13314 timer = tip_timer;
13315 GCPRO2 (frame, timer);
13316 tip_frame = tip_timer = deleted = Qnil;
7d0393cf 13317
331379bf 13318 count = SPECPDL_INDEX ();
6fc2811b 13319 specbind (Qinhibit_redisplay, Qt);
937e601e 13320 specbind (Qinhibit_quit, Qt);
7d0393cf 13321
937e601e 13322 if (!NILP (timer))
dc220243 13323 call1 (Qcancel_timer, timer);
ee78dc32 13324
937e601e 13325 if (FRAMEP (frame))
6fc2811b 13326 {
937e601e
AI
13327 Fdelete_frame (frame, Qnil);
13328 deleted = Qt;
6fc2811b 13329 }
1edf84e7 13330
937e601e
AI
13331 UNGCPRO;
13332 return unbind_to (count, deleted);
6fc2811b 13333}
5ac45f98 13334
5ac45f98 13335
6fc2811b
JR
13336\f
13337/***********************************************************************
13338 File selection dialog
13339 ***********************************************************************/
6fc2811b
JR
13340extern Lisp_Object Qfile_name_history;
13341
1030b26b
JR
13342/* Callback for altering the behaviour of the Open File dialog.
13343 Makes the Filename text field contain "Current Directory" and be
13344 read-only when "Directories" is selected in the filter. This
13345 allows us to work around the fact that the standard Open File
13346 dialog does not support directories. */
13347UINT CALLBACK
13348file_dialog_callback (hwnd, msg, wParam, lParam)
13349 HWND hwnd;
13350 UINT msg;
13351 WPARAM wParam;
13352 LPARAM lParam;
13353{
13354 if (msg == WM_NOTIFY)
13355 {
13356 OFNOTIFY * notify = (OFNOTIFY *)lParam;
13357 /* Detect when the Filter dropdown is changed. */
13358 if (notify->hdr.code == CDN_TYPECHANGE)
13359 {
13360 HWND dialog = GetParent (hwnd);
13361 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
13362
13363 /* Directories is in index 2. */
13364 if (notify->lpOFN->nFilterIndex == 2)
13365 {
13366 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
13367 "Current Directory");
13368 EnableWindow (edit_control, FALSE);
13369 }
13370 else
13371 {
13372 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
13373 "");
13374 EnableWindow (edit_control, TRUE);
13375 }
13376 }
13377 }
13378 return 0;
13379}
13380
6fc2811b 13381DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
74e1aeec
JR
13382 doc: /* Read file name, prompting with PROMPT in directory DIR.
13383Use a file selection dialog.
13384Select DEFAULT-FILENAME in the dialog's file selection box, if
13385specified. Ensure that file exists if MUSTMATCH is non-nil. */)
6fc2811b
JR
13386 (prompt, dir, default_filename, mustmatch)
13387 Lisp_Object prompt, dir, default_filename, mustmatch;
13388{
13389 struct frame *f = SELECTED_FRAME ();
13390 Lisp_Object file = Qnil;
aed13378 13391 int count = SPECPDL_INDEX ();
6fc2811b
JR
13392 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
13393 char filename[MAX_PATH + 1];
13394 char init_dir[MAX_PATH + 1];
6fc2811b
JR
13395
13396 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
b7826503
PJ
13397 CHECK_STRING (prompt);
13398 CHECK_STRING (dir);
6fc2811b
JR
13399
13400 /* Create the dialog with PROMPT as title, using DIR as initial
13401 directory and using "*" as pattern. */
13402 dir = Fexpand_file_name (dir, Qnil);
d5db4077 13403 strncpy (init_dir, SDATA (dir), MAX_PATH);
6fc2811b
JR
13404 init_dir[MAX_PATH] = '\0';
13405 unixtodos_filename (init_dir);
13406
13407 if (STRINGP (default_filename))
13408 {
13409 char *file_name_only;
d5db4077 13410 char *full_path_name = SDATA (default_filename);
5ac45f98 13411
6fc2811b 13412 unixtodos_filename (full_path_name);
5ac45f98 13413
6fc2811b
JR
13414 file_name_only = strrchr (full_path_name, '\\');
13415 if (!file_name_only)
13416 file_name_only = full_path_name;
13417 else
13418 {
13419 file_name_only++;
6fc2811b 13420 }
ee78dc32 13421
6fc2811b
JR
13422 strncpy (filename, file_name_only, MAX_PATH);
13423 filename[MAX_PATH] = '\0';
13424 }
ee78dc32 13425 else
6fc2811b 13426 filename[0] = '\0';
ee78dc32 13427
1030b26b
JR
13428 {
13429 OPENFILENAME file_details;
5ac45f98 13430
1030b26b
JR
13431 /* Prevent redisplay. */
13432 specbind (Qinhibit_redisplay, Qt);
13433 BLOCK_INPUT;
ee78dc32 13434
1030b26b
JR
13435 bzero (&file_details, sizeof (file_details));
13436 file_details.lStructSize = sizeof (file_details);
13437 file_details.hwndOwner = FRAME_W32_WINDOW (f);
13438 /* Undocumented Bug in Common File Dialog:
13439 If a filter is not specified, shell links are not resolved. */
13440 file_details.lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
13441 file_details.lpstrFile = filename;
13442 file_details.nMaxFile = sizeof (filename);
13443 file_details.lpstrInitialDir = init_dir;
d5db4077 13444 file_details.lpstrTitle = SDATA (prompt);
1030b26b
JR
13445 file_details.Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
13446 | OFN_EXPLORER | OFN_ENABLEHOOK);
13447 if (!NILP (mustmatch))
13448 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
13449
13450 file_details.lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
13451
13452 if (GetOpenFileName (&file_details))
13453 {
13454 dostounix_filename (filename);
13455 if (file_details.nFilterIndex == 2)
13456 {
13457 /* "Folder Only" selected - strip dummy file name. */
13458 char * last = strrchr (filename, '/');
13459 *last = '\0';
13460 }
6fc2811b 13461
1030b26b
JR
13462 file = DECODE_FILE(build_string (filename));
13463 }
13464 /* User cancelled the dialog without making a selection. */
13465 else if (!CommDlgExtendedError ())
13466 file = Qnil;
13467 /* An error occurred, fallback on reading from the mini-buffer. */
13468 else
13469 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
13470 dir, mustmatch, dir, Qfile_name_history,
13471 default_filename, Qnil);
13472
13473 UNBLOCK_INPUT;
13474 file = unbind_to (count, file);
13475 }
ee78dc32 13476
6fc2811b 13477 UNGCPRO;
1edf84e7 13478
6fc2811b
JR
13479 /* Make "Cancel" equivalent to C-g. */
13480 if (NILP (file))
13481 Fsignal (Qquit, Qnil);
ee78dc32 13482
dfff8a69 13483 return unbind_to (count, file);
6fc2811b 13484}
ee78dc32 13485
ee78dc32 13486
6fc2811b 13487\f
6fc2811b
JR
13488/***********************************************************************
13489 w32 specialized functions
13490 ***********************************************************************/
ee78dc32 13491
d84b082d 13492DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
74e1aeec
JR
13493 doc: /* Select a font using the W32 font dialog.
13494Returns an X font string corresponding to the selection. */)
d84b082d
JR
13495 (frame, include_proportional)
13496 Lisp_Object frame, include_proportional;
ee78dc32
GV
13497{
13498 FRAME_PTR f = check_x_frame (frame);
13499 CHOOSEFONT cf;
13500 LOGFONT lf;
f46e6225
GV
13501 TEXTMETRIC tm;
13502 HDC hdc;
13503 HANDLE oldobj;
ee78dc32
GV
13504 char buf[100];
13505
13506 bzero (&cf, sizeof (cf));
f46e6225 13507 bzero (&lf, sizeof (lf));
ee78dc32
GV
13508
13509 cf.lStructSize = sizeof (cf);
fbd6baed 13510 cf.hwndOwner = FRAME_W32_WINDOW (f);
d84b082d
JR
13511 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
13512
13513 /* Unless include_proportional is non-nil, limit the selection to
13514 monospaced fonts. */
13515 if (NILP (include_proportional))
13516 cf.Flags |= CF_FIXEDPITCHONLY;
13517
ee78dc32
GV
13518 cf.lpLogFont = &lf;
13519
f46e6225
GV
13520 /* Initialize as much of the font details as we can from the current
13521 default font. */
13522 hdc = GetDC (FRAME_W32_WINDOW (f));
13523 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
13524 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
13525 if (GetTextMetrics (hdc, &tm))
13526 {
13527 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
13528 lf.lfWeight = tm.tmWeight;
13529 lf.lfItalic = tm.tmItalic;
13530 lf.lfUnderline = tm.tmUnderlined;
13531 lf.lfStrikeOut = tm.tmStruckOut;
f46e6225
GV
13532 lf.lfCharSet = tm.tmCharSet;
13533 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
13534 }
13535 SelectObject (hdc, oldobj);
6fc2811b 13536 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
f46e6225 13537
767b1ff0 13538 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
3c190163 13539 return Qnil;
ee78dc32
GV
13540
13541 return build_string (buf);
13542}
13543
74e1aeec
JR
13544DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
13545 Sw32_send_sys_command, 1, 2, 0,
13546 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
d84b082d
JR
13547Some useful values for command are #xf030 to maximise frame (#xf020
13548to minimize), #xf120 to restore frame to original size, and #xf100
13549to activate the menubar for keyboard access. #xf140 activates the
74e1aeec
JR
13550screen saver if defined.
13551
13552If optional parameter FRAME is not specified, use selected frame. */)
1edf84e7
GV
13553 (command, frame)
13554 Lisp_Object command, frame;
13555{
1edf84e7
GV
13556 FRAME_PTR f = check_x_frame (frame);
13557
b7826503 13558 CHECK_NUMBER (command);
1edf84e7 13559
ce6059da 13560 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
1edf84e7
GV
13561
13562 return Qnil;
13563}
13564
55dcfc15 13565DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
74e1aeec
JR
13566 doc: /* Get Windows to perform OPERATION on DOCUMENT.
13567This is a wrapper around the ShellExecute system function, which
13568invokes the application registered to handle OPERATION for DOCUMENT.
13569OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
13570nil for the default action), and DOCUMENT is typically the name of a
13571document file or URL, but can also be a program executable to run or
13572a directory to open in the Windows Explorer.
13573
13574If DOCUMENT is a program executable, PARAMETERS can be a string
13575containing command line parameters, but otherwise should be nil.
13576
13577SHOW-FLAG can be used to control whether the invoked application is hidden
13578or minimized. If SHOW-FLAG is nil, the application is displayed normally,
13579otherwise it is an integer representing a ShowWindow flag:
13580
13581 0 - start hidden
13582 1 - start normally
13583 3 - start maximized
13584 6 - start minimized */)
55dcfc15
AI
13585 (operation, document, parameters, show_flag)
13586 Lisp_Object operation, document, parameters, show_flag;
13587{
13588 Lisp_Object current_dir;
13589
b7826503 13590 CHECK_STRING (document);
55dcfc15
AI
13591
13592 /* Encode filename and current directory. */
13593 current_dir = ENCODE_FILE (current_buffer->directory);
13594 document = ENCODE_FILE (document);
13595 if ((int) ShellExecute (NULL,
6fc2811b 13596 (STRINGP (operation) ?
d5db4077
KR
13597 SDATA (operation) : NULL),
13598 SDATA (document),
55dcfc15 13599 (STRINGP (parameters) ?
d5db4077
KR
13600 SDATA (parameters) : NULL),
13601 SDATA (current_dir),
55dcfc15
AI
13602 (INTEGERP (show_flag) ?
13603 XINT (show_flag) : SW_SHOWDEFAULT))
13604 > 32)
13605 return Qt;
90d97e64 13606 error ("ShellExecute failed: %s", w32_strerror (0));
55dcfc15
AI
13607}
13608
ccc2d29c
GV
13609/* Lookup virtual keycode from string representing the name of a
13610 non-ascii keystroke into the corresponding virtual key, using
13611 lispy_function_keys. */
13612static int
13613lookup_vk_code (char *key)
13614{
13615 int i;
13616
13617 for (i = 0; i < 256; i++)
13618 if (lispy_function_keys[i] != 0
13619 && strcmp (lispy_function_keys[i], key) == 0)
13620 return i;
13621
13622 return -1;
13623}
13624
13625/* Convert a one-element vector style key sequence to a hot key
13626 definition. */
13627static int
13628w32_parse_hot_key (key)
13629 Lisp_Object key;
13630{
13631 /* Copied from Fdefine_key and store_in_keymap. */
13632 register Lisp_Object c;
13633 int vk_code;
13634 int lisp_modifiers;
13635 int w32_modifiers;
13636 struct gcpro gcpro1;
13637
b7826503 13638 CHECK_VECTOR (key);
ccc2d29c
GV
13639
13640 if (XFASTINT (Flength (key)) != 1)
13641 return Qnil;
13642
13643 GCPRO1 (key);
13644
13645 c = Faref (key, make_number (0));
13646
13647 if (CONSP (c) && lucid_event_type_list_p (c))
13648 c = Fevent_convert_list (c);
13649
13650 UNGCPRO;
13651
13652 if (! INTEGERP (c) && ! SYMBOLP (c))
13653 error ("Key definition is invalid");
13654
13655 /* Work out the base key and the modifiers. */
13656 if (SYMBOLP (c))
13657 {
13658 c = parse_modifiers (c);
13659 lisp_modifiers = Fcar (Fcdr (c));
13660 c = Fcar (c);
13661 if (!SYMBOLP (c))
13662 abort ();
d5db4077 13663 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
ccc2d29c
GV
13664 }
13665 else if (INTEGERP (c))
13666 {
13667 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
13668 /* Many ascii characters are their own virtual key code. */
13669 vk_code = XINT (c) & CHARACTERBITS;
13670 }
13671
13672 if (vk_code < 0 || vk_code > 255)
13673 return Qnil;
13674
13675 if ((lisp_modifiers & meta_modifier) != 0
13676 && !NILP (Vw32_alt_is_meta))
13677 lisp_modifiers |= alt_modifier;
13678
71eab8d1
AI
13679 /* Supply defs missing from mingw32. */
13680#ifndef MOD_ALT
13681#define MOD_ALT 0x0001
13682#define MOD_CONTROL 0x0002
13683#define MOD_SHIFT 0x0004
13684#define MOD_WIN 0x0008
13685#endif
13686
ccc2d29c
GV
13687 /* Convert lisp modifiers to Windows hot-key form. */
13688 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
13689 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
13690 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
13691 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
13692
13693 return HOTKEY (vk_code, w32_modifiers);
13694}
13695
74e1aeec
JR
13696DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
13697 Sw32_register_hot_key, 1, 1, 0,
13698 doc: /* Register KEY as a hot-key combination.
13699Certain key combinations like Alt-Tab are reserved for system use on
13700Windows, and therefore are normally intercepted by the system. However,
13701most of these key combinations can be received by registering them as
13702hot-keys, overriding their special meaning.
13703
13704KEY must be a one element key definition in vector form that would be
13705acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
13706modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
13707is always interpreted as the Windows modifier keys.
13708
13709The return value is the hotkey-id if registered, otherwise nil. */)
ccc2d29c
GV
13710 (key)
13711 Lisp_Object key;
13712{
13713 key = w32_parse_hot_key (key);
13714
13715 if (NILP (Fmemq (key, w32_grabbed_keys)))
13716 {
13717 /* Reuse an empty slot if possible. */
13718 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
13719
13720 /* Safe to add new key to list, even if we have focus. */
13721 if (NILP (item))
13722 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
13723 else
f3fbd155 13724 XSETCAR (item, key);
ccc2d29c
GV
13725
13726 /* Notify input thread about new hot-key definition, so that it
13727 takes effect without needing to switch focus. */
13728 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
13729 (WPARAM) key, 0);
13730 }
13731
13732 return key;
13733}
13734
74e1aeec
JR
13735DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
13736 Sw32_unregister_hot_key, 1, 1, 0,
13737 doc: /* Unregister HOTKEY as a hot-key combination. */)
ccc2d29c
GV
13738 (key)
13739 Lisp_Object key;
13740{
13741 Lisp_Object item;
13742
13743 if (!INTEGERP (key))
13744 key = w32_parse_hot_key (key);
13745
13746 item = Fmemq (key, w32_grabbed_keys);
13747
13748 if (!NILP (item))
13749 {
13750 /* Notify input thread about hot-key definition being removed, so
13751 that it takes effect without needing focus switch. */
13752 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
13753 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
13754 {
13755 MSG msg;
13756 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13757 }
13758 return Qt;
13759 }
13760 return Qnil;
13761}
13762
74e1aeec
JR
13763DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
13764 Sw32_registered_hot_keys, 0, 0, 0,
13765 doc: /* Return list of registered hot-key IDs. */)
ccc2d29c
GV
13766 ()
13767{
13768 return Fcopy_sequence (w32_grabbed_keys);
13769}
13770
74e1aeec
JR
13771DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
13772 Sw32_reconstruct_hot_key, 1, 1, 0,
13773 doc: /* Convert hot-key ID to a lisp key combination. */)
ccc2d29c
GV
13774 (hotkeyid)
13775 Lisp_Object hotkeyid;
13776{
13777 int vk_code, w32_modifiers;
13778 Lisp_Object key;
13779
b7826503 13780 CHECK_NUMBER (hotkeyid);
ccc2d29c
GV
13781
13782 vk_code = HOTKEY_VK_CODE (hotkeyid);
13783 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
13784
13785 if (lispy_function_keys[vk_code])
13786 key = intern (lispy_function_keys[vk_code]);
13787 else
13788 key = make_number (vk_code);
13789
13790 key = Fcons (key, Qnil);
13791 if (w32_modifiers & MOD_SHIFT)
3ef68e6b 13792 key = Fcons (Qshift, key);
ccc2d29c 13793 if (w32_modifiers & MOD_CONTROL)
3ef68e6b 13794 key = Fcons (Qctrl, key);
ccc2d29c 13795 if (w32_modifiers & MOD_ALT)
3ef68e6b 13796 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
ccc2d29c 13797 if (w32_modifiers & MOD_WIN)
3ef68e6b 13798 key = Fcons (Qhyper, key);
ccc2d29c
GV
13799
13800 return key;
13801}
adcc3809 13802
74e1aeec
JR
13803DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
13804 Sw32_toggle_lock_key, 1, 2, 0,
13805 doc: /* Toggle the state of the lock key KEY.
13806KEY can be `capslock', `kp-numlock', or `scroll'.
13807If the optional parameter NEW-STATE is a number, then the state of KEY
13808is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
adcc3809
GV
13809 (key, new_state)
13810 Lisp_Object key, new_state;
13811{
13812 int vk_code;
adcc3809
GV
13813
13814 if (EQ (key, intern ("capslock")))
13815 vk_code = VK_CAPITAL;
13816 else if (EQ (key, intern ("kp-numlock")))
13817 vk_code = VK_NUMLOCK;
13818 else if (EQ (key, intern ("scroll")))
13819 vk_code = VK_SCROLL;
13820 else
13821 return Qnil;
13822
13823 if (!dwWindowsThreadId)
13824 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
13825
13826 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
13827 (WPARAM) vk_code, (LPARAM) new_state))
13828 {
13829 MSG msg;
13830 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13831 return make_number (msg.wParam);
13832 }
13833 return Qnil;
13834}
ee78dc32 13835\f
2254bcde 13836DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
74e1aeec
JR
13837 doc: /* Return storage information about the file system FILENAME is on.
13838Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
13839storage of the file system, FREE is the free storage, and AVAIL is the
13840storage available to a non-superuser. All 3 numbers are in bytes.
13841If the underlying system call fails, value is nil. */)
2254bcde
AI
13842 (filename)
13843 Lisp_Object filename;
13844{
13845 Lisp_Object encoded, value;
13846
b7826503 13847 CHECK_STRING (filename);
2254bcde
AI
13848 filename = Fexpand_file_name (filename, Qnil);
13849 encoded = ENCODE_FILE (filename);
13850
13851 value = Qnil;
13852
13853 /* Determining the required information on Windows turns out, sadly,
13854 to be more involved than one would hope. The original Win32 api
13855 call for this will return bogus information on some systems, but we
13856 must dynamically probe for the replacement api, since that was
13857 added rather late on. */
13858 {
13859 HMODULE hKernel = GetModuleHandle ("kernel32");
13860 BOOL (*pfn_GetDiskFreeSpaceEx)
13861 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
13862 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
13863
13864 /* On Windows, we may need to specify the root directory of the
13865 volume holding FILENAME. */
13866 char rootname[MAX_PATH];
d5db4077 13867 char *name = SDATA (encoded);
2254bcde
AI
13868
13869 /* find the root name of the volume if given */
13870 if (isalpha (name[0]) && name[1] == ':')
13871 {
13872 rootname[0] = name[0];
13873 rootname[1] = name[1];
13874 rootname[2] = '\\';
13875 rootname[3] = 0;
13876 }
13877 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
13878 {
13879 char *str = rootname;
13880 int slashes = 4;
13881 do
13882 {
13883 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
13884 break;
13885 *str++ = *name++;
13886 }
13887 while ( *name );
13888
13889 *str++ = '\\';
13890 *str = 0;
13891 }
13892
13893 if (pfn_GetDiskFreeSpaceEx)
13894 {
ac849ba4
JR
13895 /* Unsigned large integers cannot be cast to double, so
13896 use signed ones instead. */
2254bcde
AI
13897 LARGE_INTEGER availbytes;
13898 LARGE_INTEGER freebytes;
13899 LARGE_INTEGER totalbytes;
13900
13901 if (pfn_GetDiskFreeSpaceEx(rootname,
ac849ba4
JR
13902 (ULARGE_INTEGER *)&availbytes,
13903 (ULARGE_INTEGER *)&totalbytes,
13904 (ULARGE_INTEGER *)&freebytes))
2254bcde
AI
13905 value = list3 (make_float ((double) totalbytes.QuadPart),
13906 make_float ((double) freebytes.QuadPart),
13907 make_float ((double) availbytes.QuadPart));
13908 }
13909 else
13910 {
13911 DWORD sectors_per_cluster;
13912 DWORD bytes_per_sector;
13913 DWORD free_clusters;
13914 DWORD total_clusters;
13915
13916 if (GetDiskFreeSpace(rootname,
13917 &sectors_per_cluster,
13918 &bytes_per_sector,
13919 &free_clusters,
13920 &total_clusters))
13921 value = list3 (make_float ((double) total_clusters
13922 * sectors_per_cluster * bytes_per_sector),
13923 make_float ((double) free_clusters
13924 * sectors_per_cluster * bytes_per_sector),
13925 make_float ((double) free_clusters
13926 * sectors_per_cluster * bytes_per_sector));
13927 }
13928 }
13929
13930 return value;
13931}
13932\f
0e3fcdef
JR
13933/***********************************************************************
13934 Initialization
13935 ***********************************************************************/
13936
6d906347
KS
13937/* Keep this list in the same order as frame_parms in frame.c.
13938 Use 0 for unsupported frame parameters. */
13939
13940frame_parm_handler w32_frame_parm_handlers[] =
13941{
13942 x_set_autoraise,
13943 x_set_autolower,
13944 x_set_background_color,
13945 x_set_border_color,
13946 x_set_border_width,
13947 x_set_cursor_color,
13948 x_set_cursor_type,
13949 x_set_font,
13950 x_set_foreground_color,
13951 x_set_icon_name,
13952 x_set_icon_type,
13953 x_set_internal_border_width,
13954 x_set_menu_bar_lines,
13955 x_set_mouse_color,
13956 x_explicitly_set_name,
13957 x_set_scroll_bar_width,
13958 x_set_title,
13959 x_set_unsplittable,
13960 x_set_vertical_scroll_bars,
13961 x_set_visibility,
13962 x_set_tool_bar_lines,
13963 0, /* x_set_scroll_bar_foreground, */
13964 0, /* x_set_scroll_bar_background, */
13965 x_set_screen_gamma,
13966 x_set_line_spacing,
13967 x_set_fringe_width,
13968 x_set_fringe_width,
13969 0, /* x_set_wait_for_wm, */
13970 x_set_fullscreen,
13971};
13972
0e3fcdef 13973void
fbd6baed 13974syms_of_w32fns ()
ee78dc32 13975{
afc390dc
JR
13976 globals_of_w32fns ();
13977 /* This is zero if not using MS-Windows. */
1edf84e7 13978 w32_in_use = 0;
9eb16b62
JR
13979 track_mouse_window = NULL;
13980
d285988b
JR
13981 w32_visible_system_caret_hwnd = NULL;
13982
ee78dc32
GV
13983 Qnone = intern ("none");
13984 staticpro (&Qnone);
ee78dc32
GV
13985 Qsuppress_icon = intern ("suppress-icon");
13986 staticpro (&Qsuppress_icon);
ee78dc32
GV
13987 Qundefined_color = intern ("undefined-color");
13988 staticpro (&Qundefined_color);
dfff8a69
JR
13989 Qcenter = intern ("center");
13990 staticpro (&Qcenter);
dc220243
JR
13991 Qcancel_timer = intern ("cancel-timer");
13992 staticpro (&Qcancel_timer);
ee78dc32 13993
adcc3809
GV
13994 Qhyper = intern ("hyper");
13995 staticpro (&Qhyper);
13996 Qsuper = intern ("super");
13997 staticpro (&Qsuper);
13998 Qmeta = intern ("meta");
13999 staticpro (&Qmeta);
14000 Qalt = intern ("alt");
14001 staticpro (&Qalt);
14002 Qctrl = intern ("ctrl");
14003 staticpro (&Qctrl);
14004 Qcontrol = intern ("control");
14005 staticpro (&Qcontrol);
14006 Qshift = intern ("shift");
14007 staticpro (&Qshift);
f7b9d4d1 14008 /* This is the end of symbol initialization. */
adcc3809 14009
6fc2811b
JR
14010 /* Text property `display' should be nonsticky by default. */
14011 Vtext_property_default_nonsticky
14012 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
14013
14014
14015 Qlaplace = intern ("laplace");
14016 staticpro (&Qlaplace);
3cf3436e
JR
14017 Qemboss = intern ("emboss");
14018 staticpro (&Qemboss);
14019 Qedge_detection = intern ("edge-detection");
14020 staticpro (&Qedge_detection);
14021 Qheuristic = intern ("heuristic");
14022 staticpro (&Qheuristic);
14023 QCmatrix = intern (":matrix");
14024 staticpro (&QCmatrix);
14025 QCcolor_adjustment = intern (":color-adjustment");
14026 staticpro (&QCcolor_adjustment);
14027 QCmask = intern (":mask");
14028 staticpro (&QCmask);
6fc2811b 14029
ee78dc32
GV
14030 Fput (Qundefined_color, Qerror_conditions,
14031 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
14032 Fput (Qundefined_color, Qerror_message,
14033 build_string ("Undefined color"));
14034
ccc2d29c
GV
14035 staticpro (&w32_grabbed_keys);
14036 w32_grabbed_keys = Qnil;
14037
fbd6baed 14038 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
74e1aeec 14039 doc: /* An array of color name mappings for windows. */);
fbd6baed 14040 Vw32_color_map = Qnil;
ee78dc32 14041
fbd6baed 14042 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
74e1aeec
JR
14043 doc: /* Non-nil if alt key presses are passed on to Windows.
14044When non-nil, for example, alt pressed and released and then space will
14045open the System menu. When nil, Emacs silently swallows alt key events. */);
fbd6baed 14046 Vw32_pass_alt_to_system = Qnil;
da36a4d6 14047
fbd6baed 14048 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
74e1aeec
JR
14049 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
14050When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
fbd6baed 14051 Vw32_alt_is_meta = Qt;
8c205c63 14052
7d081355 14053 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
74e1aeec 14054 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
7d081355
AI
14055 XSETINT (Vw32_quit_key, 0);
14056
7d0393cf 14057 DEFVAR_LISP ("w32-pass-lwindow-to-system",
ccc2d29c 14058 &Vw32_pass_lwindow_to_system,
74e1aeec
JR
14059 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
14060When non-nil, the Start menu is opened by tapping the key. */);
ccc2d29c
GV
14061 Vw32_pass_lwindow_to_system = Qt;
14062
7d0393cf 14063 DEFVAR_LISP ("w32-pass-rwindow-to-system",
ccc2d29c 14064 &Vw32_pass_rwindow_to_system,
74e1aeec
JR
14065 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
14066When non-nil, the Start menu is opened by tapping the key. */);
ccc2d29c
GV
14067 Vw32_pass_rwindow_to_system = Qt;
14068
adcc3809
GV
14069 DEFVAR_INT ("w32-phantom-key-code",
14070 &Vw32_phantom_key_code,
74e1aeec
JR
14071 doc: /* Virtual key code used to generate \"phantom\" key presses.
14072Value is a number between 0 and 255.
14073
14074Phantom key presses are generated in order to stop the system from
14075acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
14076`w32-pass-rwindow-to-system' is nil. */);
ce6059da
AI
14077 /* Although 255 is technically not a valid key code, it works and
14078 means that this hack won't interfere with any real key code. */
14079 Vw32_phantom_key_code = 255;
adcc3809 14080
7d0393cf 14081 DEFVAR_LISP ("w32-enable-num-lock",
ccc2d29c 14082 &Vw32_enable_num_lock,
74e1aeec
JR
14083 doc: /* Non-nil if Num Lock should act normally.
14084Set to nil to see Num Lock as the key `kp-numlock'. */);
ccc2d29c
GV
14085 Vw32_enable_num_lock = Qt;
14086
7d0393cf 14087 DEFVAR_LISP ("w32-enable-caps-lock",
ccc2d29c 14088 &Vw32_enable_caps_lock,
74e1aeec
JR
14089 doc: /* Non-nil if Caps Lock should act normally.
14090Set to nil to see Caps Lock as the key `capslock'. */);
ccc2d29c
GV
14091 Vw32_enable_caps_lock = Qt;
14092
14093 DEFVAR_LISP ("w32-scroll-lock-modifier",
14094 &Vw32_scroll_lock_modifier,
74e1aeec
JR
14095 doc: /* Modifier to use for the Scroll Lock on state.
14096The value can be hyper, super, meta, alt, control or shift for the
14097respective modifier, or nil to see Scroll Lock as the key `scroll'.
14098Any other value will cause the key to be ignored. */);
ccc2d29c
GV
14099 Vw32_scroll_lock_modifier = Qt;
14100
14101 DEFVAR_LISP ("w32-lwindow-modifier",
14102 &Vw32_lwindow_modifier,
74e1aeec
JR
14103 doc: /* Modifier to use for the left \"Windows\" key.
14104The value can be hyper, super, meta, alt, control or shift for the
14105respective modifier, or nil to appear as the key `lwindow'.
14106Any other value will cause the key to be ignored. */);
ccc2d29c
GV
14107 Vw32_lwindow_modifier = Qnil;
14108
14109 DEFVAR_LISP ("w32-rwindow-modifier",
14110 &Vw32_rwindow_modifier,
74e1aeec
JR
14111 doc: /* Modifier to use for the right \"Windows\" key.
14112The value can be hyper, super, meta, alt, control or shift for the
14113respective modifier, or nil to appear as the key `rwindow'.
14114Any other value will cause the key to be ignored. */);
ccc2d29c
GV
14115 Vw32_rwindow_modifier = Qnil;
14116
14117 DEFVAR_LISP ("w32-apps-modifier",
14118 &Vw32_apps_modifier,
74e1aeec
JR
14119 doc: /* Modifier to use for the \"Apps\" key.
14120The value can be hyper, super, meta, alt, control or shift for the
14121respective modifier, or nil to appear as the key `apps'.
14122Any other value will cause the key to be ignored. */);
ccc2d29c 14123 Vw32_apps_modifier = Qnil;
da36a4d6 14124
d84b082d 14125 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
74e1aeec 14126 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
d84b082d 14127 w32_enable_synthesized_fonts = 0;
5ac45f98 14128
fbd6baed 14129 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
74e1aeec 14130 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
fbd6baed 14131 Vw32_enable_palette = Qt;
5ac45f98 14132
fbd6baed
GV
14133 DEFVAR_INT ("w32-mouse-button-tolerance",
14134 &Vw32_mouse_button_tolerance,
74e1aeec
JR
14135 doc: /* Analogue of double click interval for faking middle mouse events.
14136The value is the minimum time in milliseconds that must elapse between
14137left/right button down events before they are considered distinct events.
14138If both mouse buttons are depressed within this interval, a middle mouse
14139button down event is generated instead. */);
fbd6baed 14140 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
5ac45f98 14141
fbd6baed
GV
14142 DEFVAR_INT ("w32-mouse-move-interval",
14143 &Vw32_mouse_move_interval,
74e1aeec
JR
14144 doc: /* Minimum interval between mouse move events.
14145The value is the minimum time in milliseconds that must elapse between
14146successive mouse move (or scroll bar drag) events before they are
14147reported as lisp events. */);
247be837 14148 XSETINT (Vw32_mouse_move_interval, 0);
84fb1139 14149
74214547
JR
14150 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
14151 &w32_pass_extra_mouse_buttons_to_system,
14152 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
14153Recent versions of Windows support mice with up to five buttons.
14154Since most applications don't support these extra buttons, most mouse
14155drivers will allow you to map them to functions at the system level.
14156If this variable is non-nil, Emacs will pass them on, allowing the
14157system to handle them. */);
14158 w32_pass_extra_mouse_buttons_to_system = 0;
14159
ee78dc32 14160 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
6e2d67d8 14161 doc: /* List of directories to search for window system bitmap files. */);
ee78dc32
GV
14162 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
14163
14164 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
74e1aeec
JR
14165 doc: /* The shape of the pointer when over text.
14166Changing the value does not affect existing frames
14167unless you set the mouse color. */);
ee78dc32
GV
14168 Vx_pointer_shape = Qnil;
14169
ee78dc32
GV
14170 Vx_nontext_pointer_shape = Qnil;
14171
14172 Vx_mode_pointer_shape = Qnil;
14173
0af913d7 14174 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
74e1aeec
JR
14175 doc: /* The shape of the pointer when Emacs is busy.
14176This variable takes effect when you create a new frame
14177or when you set the mouse color. */);
0af913d7 14178 Vx_hourglass_pointer_shape = Qnil;
6fc2811b 14179
0af913d7 14180 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
74e1aeec 14181 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
0af913d7 14182 display_hourglass_p = 1;
7d0393cf 14183
0af913d7 14184 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
74e1aeec
JR
14185 doc: /* *Seconds to wait before displaying an hourglass pointer.
14186Value must be an integer or float. */);
0af913d7 14187 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
f79e6790 14188
6fc2811b 14189 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
ee78dc32 14190 &Vx_sensitive_text_pointer_shape,
74e1aeec
JR
14191 doc: /* The shape of the pointer when over mouse-sensitive text.
14192This variable takes effect when you create a new frame
14193or when you set the mouse color. */);
ee78dc32
GV
14194 Vx_sensitive_text_pointer_shape = Qnil;
14195
4694d762
JR
14196 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
14197 &Vx_window_horizontal_drag_shape,
74e1aeec
JR
14198 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
14199This variable takes effect when you create a new frame
14200or when you set the mouse color. */);
4694d762
JR
14201 Vx_window_horizontal_drag_shape = Qnil;
14202
ee78dc32 14203 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
74e1aeec 14204 doc: /* A string indicating the foreground color of the cursor box. */);
ee78dc32
GV
14205 Vx_cursor_fore_pixel = Qnil;
14206
3cf3436e 14207 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
b3700ae7
JR
14208 doc: /* Maximum size for tooltips.
14209Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
3cf3436e 14210 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
7d0393cf 14211
ee78dc32 14212 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
74e1aeec
JR
14213 doc: /* Non-nil if no window manager is in use.
14214Emacs doesn't try to figure this out; this is always nil
14215unless you set it to something else. */);
ee78dc32
GV
14216 /* We don't have any way to find this out, so set it to nil
14217 and maybe the user would like to set it to t. */
14218 Vx_no_window_manager = Qnil;
14219
4587b026
GV
14220 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
14221 &Vx_pixel_size_width_font_regexp,
74e1aeec
JR
14222 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
14223
14224Since Emacs gets width of a font matching with this regexp from
14225PIXEL_SIZE field of the name, font finding mechanism gets faster for
14226such a font. This is especially effective for such large fonts as
14227Chinese, Japanese, and Korean. */);
4587b026
GV
14228 Vx_pixel_size_width_font_regexp = Qnil;
14229
6fc2811b 14230 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
74e1aeec
JR
14231 doc: /* Time after which cached images are removed from the cache.
14232When an image has not been displayed this many seconds, remove it
14233from the image cache. Value must be an integer or nil with nil
14234meaning don't clear the cache. */);
6fc2811b
JR
14235 Vimage_cache_eviction_delay = make_number (30 * 60);
14236
33d52f9c
GV
14237 DEFVAR_LISP ("w32-bdf-filename-alist",
14238 &Vw32_bdf_filename_alist,
74e1aeec 14239 doc: /* List of bdf fonts and their corresponding filenames. */);
33d52f9c
GV
14240 Vw32_bdf_filename_alist = Qnil;
14241
1075afa9
GV
14242 DEFVAR_BOOL ("w32-strict-fontnames",
14243 &w32_strict_fontnames,
74e1aeec
JR
14244 doc: /* Non-nil means only use fonts that are exact matches for those requested.
14245Default is nil, which allows old fontnames that are not XLFD compliant,
14246and allows third-party CJK display to work by specifying false charset
14247fields to trick Emacs into translating to Big5, SJIS etc.
14248Setting this to t will prevent wrong fonts being selected when
14249fontsets are automatically created. */);
1075afa9
GV
14250 w32_strict_fontnames = 0;
14251
c0611964
AI
14252 DEFVAR_BOOL ("w32-strict-painting",
14253 &w32_strict_painting,
74e1aeec
JR
14254 doc: /* Non-nil means use strict rules for repainting frames.
14255Set this to nil to get the old behaviour for repainting; this should
14256only be necessary if the default setting causes problems. */);
c0611964
AI
14257 w32_strict_painting = 1;
14258
dfff8a69
JR
14259 DEFVAR_LISP ("w32-charset-info-alist",
14260 &Vw32_charset_info_alist,
b3700ae7
JR
14261 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
14262Each entry should be of the form:
74e1aeec
JR
14263
14264 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
14265
14266where CHARSET_NAME is a string used in font names to identify the charset,
14267WINDOWS_CHARSET is a symbol that can be one of:
14268w32-charset-ansi, w32-charset-default, w32-charset-symbol,
14269w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
14270w32-charset-chinesebig5,
74e1aeec
JR
14271w32-charset-johab, w32-charset-hebrew,
14272w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
14273w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
14274w32-charset-russian, w32-charset-mac, w32-charset-baltic,
74e1aeec 14275w32-charset-unicode,
74e1aeec
JR
14276or w32-charset-oem.
14277CODEPAGE should be an integer specifying the codepage that should be used
14278to display the character set, t to do no translation and output as Unicode,
14279or nil to do no translation and output as 8 bit (or multibyte on far-east
14280versions of Windows) characters. */);
dfff8a69
JR
14281 Vw32_charset_info_alist = Qnil;
14282
14283 staticpro (&Qw32_charset_ansi);
14284 Qw32_charset_ansi = intern ("w32-charset-ansi");
14285 staticpro (&Qw32_charset_symbol);
14286 Qw32_charset_symbol = intern ("w32-charset-symbol");
14287 staticpro (&Qw32_charset_shiftjis);
14288 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
767b1ff0
JR
14289 staticpro (&Qw32_charset_hangeul);
14290 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
dfff8a69
JR
14291 staticpro (&Qw32_charset_chinesebig5);
14292 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
14293 staticpro (&Qw32_charset_gb2312);
14294 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
14295 staticpro (&Qw32_charset_oem);
14296 Qw32_charset_oem = intern ("w32-charset-oem");
14297
14298#ifdef JOHAB_CHARSET
14299 {
14300 static int w32_extra_charsets_defined = 1;
74e1aeec
JR
14301 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
14302 doc: /* Internal variable. */);
dfff8a69
JR
14303
14304 staticpro (&Qw32_charset_johab);
14305 Qw32_charset_johab = intern ("w32-charset-johab");
14306 staticpro (&Qw32_charset_easteurope);
14307 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
14308 staticpro (&Qw32_charset_turkish);
14309 Qw32_charset_turkish = intern ("w32-charset-turkish");
14310 staticpro (&Qw32_charset_baltic);
14311 Qw32_charset_baltic = intern ("w32-charset-baltic");
14312 staticpro (&Qw32_charset_russian);
14313 Qw32_charset_russian = intern ("w32-charset-russian");
14314 staticpro (&Qw32_charset_arabic);
14315 Qw32_charset_arabic = intern ("w32-charset-arabic");
14316 staticpro (&Qw32_charset_greek);
14317 Qw32_charset_greek = intern ("w32-charset-greek");
14318 staticpro (&Qw32_charset_hebrew);
14319 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
767b1ff0
JR
14320 staticpro (&Qw32_charset_vietnamese);
14321 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
dfff8a69
JR
14322 staticpro (&Qw32_charset_thai);
14323 Qw32_charset_thai = intern ("w32-charset-thai");
14324 staticpro (&Qw32_charset_mac);
14325 Qw32_charset_mac = intern ("w32-charset-mac");
14326 }
14327#endif
14328
14329#ifdef UNICODE_CHARSET
14330 {
14331 static int w32_unicode_charset_defined = 1;
14332 DEFVAR_BOOL ("w32-unicode-charset-defined",
74e1aeec
JR
14333 &w32_unicode_charset_defined,
14334 doc: /* Internal variable. */);
dfff8a69
JR
14335
14336 staticpro (&Qw32_charset_unicode);
14337 Qw32_charset_unicode = intern ("w32-charset-unicode");
14338#endif
14339
767b1ff0 14340#if 0 /* TODO: Port to W32 */
6fc2811b
JR
14341 defsubr (&Sx_change_window_property);
14342 defsubr (&Sx_delete_window_property);
14343 defsubr (&Sx_window_property);
14344#endif
2d764c78 14345 defsubr (&Sxw_display_color_p);
ee78dc32 14346 defsubr (&Sx_display_grayscale_p);
2d764c78
EZ
14347 defsubr (&Sxw_color_defined_p);
14348 defsubr (&Sxw_color_values);
ee78dc32
GV
14349 defsubr (&Sx_server_max_request_size);
14350 defsubr (&Sx_server_vendor);
14351 defsubr (&Sx_server_version);
14352 defsubr (&Sx_display_pixel_width);
14353 defsubr (&Sx_display_pixel_height);
14354 defsubr (&Sx_display_mm_width);
14355 defsubr (&Sx_display_mm_height);
14356 defsubr (&Sx_display_screens);
14357 defsubr (&Sx_display_planes);
14358 defsubr (&Sx_display_color_cells);
14359 defsubr (&Sx_display_visual_class);
14360 defsubr (&Sx_display_backing_store);
14361 defsubr (&Sx_display_save_under);
ee78dc32 14362 defsubr (&Sx_create_frame);
ee78dc32
GV
14363 defsubr (&Sx_open_connection);
14364 defsubr (&Sx_close_connection);
14365 defsubr (&Sx_display_list);
14366 defsubr (&Sx_synchronize);
14367
fbd6baed 14368 /* W32 specific functions */
ee78dc32 14369
1edf84e7 14370 defsubr (&Sw32_focus_frame);
fbd6baed
GV
14371 defsubr (&Sw32_select_font);
14372 defsubr (&Sw32_define_rgb_color);
14373 defsubr (&Sw32_default_color_map);
14374 defsubr (&Sw32_load_color_file);
1edf84e7 14375 defsubr (&Sw32_send_sys_command);
55dcfc15 14376 defsubr (&Sw32_shell_execute);
ccc2d29c
GV
14377 defsubr (&Sw32_register_hot_key);
14378 defsubr (&Sw32_unregister_hot_key);
14379 defsubr (&Sw32_registered_hot_keys);
14380 defsubr (&Sw32_reconstruct_hot_key);
adcc3809 14381 defsubr (&Sw32_toggle_lock_key);
33d52f9c 14382 defsubr (&Sw32_find_bdf_fonts);
4587b026 14383
2254bcde
AI
14384 defsubr (&Sfile_system_info);
14385
4587b026
GV
14386 /* Setting callback functions for fontset handler. */
14387 get_font_info_func = w32_get_font_info;
6fc2811b
JR
14388
14389#if 0 /* This function pointer doesn't seem to be used anywhere.
14390 And the pointer assigned has the wrong type, anyway. */
4587b026 14391 list_fonts_func = w32_list_fonts;
6fc2811b
JR
14392#endif
14393
4587b026
GV
14394 load_font_func = w32_load_font;
14395 find_ccl_program_func = w32_find_ccl_program;
14396 query_font_func = w32_query_font;
14397 set_frame_fontset_func = x_set_font;
10b4bc33 14398 get_font_repertory_func = x_get_font_repertory;
4587b026 14399 check_window_system_func = check_w32;
6fc2811b 14400
6fc2811b
JR
14401 /* Images. */
14402 Qxbm = intern ("xbm");
14403 staticpro (&Qxbm);
a93f4566
GM
14404 QCconversion = intern (":conversion");
14405 staticpro (&QCconversion);
6fc2811b
JR
14406 QCheuristic_mask = intern (":heuristic-mask");
14407 staticpro (&QCheuristic_mask);
14408 QCcolor_symbols = intern (":color-symbols");
14409 staticpro (&QCcolor_symbols);
6fc2811b
JR
14410 QCascent = intern (":ascent");
14411 staticpro (&QCascent);
14412 QCmargin = intern (":margin");
14413 staticpro (&QCmargin);
14414 QCrelief = intern (":relief");
14415 staticpro (&QCrelief);
14416 Qpostscript = intern ("postscript");
14417 staticpro (&Qpostscript);
14418 QCloader = intern (":loader");
14419 staticpro (&QCloader);
14420 QCbounding_box = intern (":bounding-box");
14421 staticpro (&QCbounding_box);
14422 QCpt_width = intern (":pt-width");
14423 staticpro (&QCpt_width);
14424 QCpt_height = intern (":pt-height");
14425 staticpro (&QCpt_height);
14426 QCindex = intern (":index");
14427 staticpro (&QCindex);
14428 Qpbm = intern ("pbm");
14429 staticpro (&Qpbm);
14430
14431#if HAVE_XPM
14432 Qxpm = intern ("xpm");
14433 staticpro (&Qxpm);
14434#endif
7d0393cf 14435
6fc2811b
JR
14436#if HAVE_JPEG
14437 Qjpeg = intern ("jpeg");
14438 staticpro (&Qjpeg);
7d0393cf 14439#endif
6fc2811b
JR
14440
14441#if HAVE_TIFF
14442 Qtiff = intern ("tiff");
14443 staticpro (&Qtiff);
7d0393cf 14444#endif
6fc2811b
JR
14445
14446#if HAVE_GIF
14447 Qgif = intern ("gif");
14448 staticpro (&Qgif);
14449#endif
14450
14451#if HAVE_PNG
14452 Qpng = intern ("png");
14453 staticpro (&Qpng);
14454#endif
14455
14456 defsubr (&Sclear_image_cache);
ac849ba4
JR
14457 defsubr (&Simage_size);
14458 defsubr (&Simage_mask_p);
6fc2811b 14459
463f5630
KH
14460#if GLYPH_DEBUG
14461 defsubr (&Simagep);
14462 defsubr (&Slookup_image);
14463#endif
14464
0af913d7
GM
14465 hourglass_atimer = NULL;
14466 hourglass_shown_p = 0;
6fc2811b
JR
14467 defsubr (&Sx_show_tip);
14468 defsubr (&Sx_hide_tip);
6fc2811b 14469 tip_timer = Qnil;
57fa2774
JR
14470 staticpro (&tip_timer);
14471 tip_frame = Qnil;
14472 staticpro (&tip_frame);
6fc2811b 14473
ca56d953
JR
14474 last_show_tip_args = Qnil;
14475 staticpro (&last_show_tip_args);
14476
6fc2811b
JR
14477 defsubr (&Sx_file_dialog);
14478}
14479
c922a224 14480
9785d95b
BK
14481/*
14482 globals_of_w32fns is used to initialize those global variables that
14483 must always be initialized on startup even when the global variable
14484 initialized is non zero (see the function main in emacs.c).
14485 globals_of_w32fns is called from syms_of_w32fns when the global
14486 variable initialized is 0 and directly from main when initialized
14487 is non zero.
14488 */
14489void globals_of_w32fns ()
14490{
14491 HMODULE user32_lib = GetModuleHandle ("user32.dll");
ccc0fdaa
JR
14492 /*
14493 TrackMouseEvent not available in all versions of Windows, so must load
14494 it dynamically. Do it once, here, instead of every time it is used.
9785d95b 14495 */
ccc0fdaa
JR
14496 track_mouse_event_fn = (TrackMouseEvent_Proc)
14497 GetProcAddress (user32_lib, "TrackMouseEvent");
14498 /* ditto for GetClipboardSequenceNumber. */
14499 clipboard_sequence_fn = (ClipboardSequence_Proc)
14500 GetProcAddress (user32_lib, "GetClipboardSequenceNumber");
9785d95b 14501}
6fc2811b 14502
839b1909
JR
14503/* Initialize image types. Based on which libraries are available. */
14504static void
14505init_external_image_libraries ()
6fc2811b 14506{
afc390dc 14507 HINSTANCE library;
7d0393cf 14508
6fc2811b 14509#if HAVE_XPM
c736ffda
JR
14510 if ((library = LoadLibrary ("libXpm.dll")))
14511 {
14512 if (init_xpm_functions (library))
14513 define_image_type (&xpm_type);
14514 }
14515
6fc2811b 14516#endif
7d0393cf 14517
6fc2811b 14518#if HAVE_JPEG
afc390dc 14519 /* Try loading jpeg library under probable names. */
c922a224 14520 if ((library = LoadLibrary ("libjpeg.dll"))
100dcd40 14521 || (library = LoadLibrary ("jpeg-62.dll"))
c922a224 14522 || (library = LoadLibrary ("jpeg.dll")))
afc390dc
JR
14523 {
14524 if (init_jpeg_functions (library))
14525 define_image_type (&jpeg_type);
14526 }
6fc2811b 14527#endif
7d0393cf 14528
6fc2811b 14529#if HAVE_TIFF
12b918b2
JB
14530 if (library = LoadLibrary ("libtiff.dll"))
14531 {
14532 if (init_tiff_functions (library))
14533 define_image_type (&tiff_type);
14534 }
6fc2811b 14535#endif
919f1e88 14536
6fc2811b 14537#if HAVE_GIF
1ffb278b
JB
14538 if (library = LoadLibrary ("libungif.dll"))
14539 {
14540 if (init_gif_functions (library))
14541 define_image_type (&gif_type);
14542 }
6fc2811b 14543#endif
7d0393cf 14544
6fc2811b 14545#if HAVE_PNG
839b1909
JR
14546 /* Ensure zlib is loaded. Try debug version first. */
14547 if (!LoadLibrary ("zlibd.dll"))
14548 LoadLibrary ("zlib.dll");
14549
14550 /* Try loading libpng under probable names. */
afc390dc
JR
14551 if ((library = LoadLibrary ("libpng13d.dll"))
14552 || (library = LoadLibrary ("libpng13.dll"))
14553 || (library = LoadLibrary ("libpng12d.dll"))
14554 || (library = LoadLibrary ("libpng12.dll"))
14555 || (library = LoadLibrary ("libpng.dll")))
839b1909 14556 {
afc390dc 14557 if (init_png_functions (library))
839b1909
JR
14558 define_image_type (&png_type);
14559 }
6fc2811b 14560#endif
ee78dc32
GV
14561}
14562
839b1909
JR
14563void
14564init_xfns ()
14565{
14566 image_types = NULL;
14567 Vimage_types = Qnil;
14568
14569 define_image_type (&pbm_type);
14570 define_image_type (&xbm_type);
14571
14572#if 0 /* TODO : Ghostscript support for W32 */
14573 define_image_type (&gs_type);
14574#endif
14575
14576 /* Image types that rely on external libraries are loaded dynamically
14577 if the library is available. */
14578 init_external_image_libraries ();
14579}
14580
ee78dc32
GV
14581#undef abort
14582
7d0393cf 14583void
fbd6baed 14584w32_abort()
ee78dc32 14585{
5ac45f98
GV
14586 int button;
14587 button = MessageBox (NULL,
14588 "A fatal error has occurred!\n\n"
14589 "Select Abort to exit, Retry to debug, Ignore to continue",
14590 "Emacs Abort Dialog",
14591 MB_ICONEXCLAMATION | MB_TASKMODAL
14592 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
14593 switch (button)
14594 {
14595 case IDRETRY:
14596 DebugBreak ();
14597 break;
14598 case IDIGNORE:
14599 break;
14600 case IDABORT:
14601 default:
14602 abort ();
14603 break;
14604 }
ee78dc32 14605}
d573caac 14606
83c75055
GV
14607/* For convenience when debugging. */
14608int
14609w32_last_error()
14610{
14611 return GetLastError ();
14612}