(x_wm_set_icon_position): Define return value as void.
[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"
4587b026 32#include "charset.h"
71eab8d1 33#include "dispextern.h"
ee78dc32 34#include "w32term.h"
c7501041 35#include "keyboard.h"
ee78dc32
GV
36#include "frame.h"
37#include "window.h"
38#include "buffer.h"
126f2e35 39#include "fontset.h"
6fc2811b 40#include "intervals.h"
ee78dc32 41#include "blockinput.h"
57bda87a 42#include "epaths.h"
489f9371 43#include "w32heap.h"
ee78dc32 44#include "termhooks.h"
4587b026 45#include "coding.h"
3545439c 46#include "ccl.h"
6fc2811b
JR
47#include "systime.h"
48
49#include "bitmaps/gray.xbm"
ee78dc32
GV
50
51#include <commdlg.h>
cb9e33d4 52#include <shellapi.h>
6fc2811b 53#include <ctype.h>
ee78dc32 54
1030b26b
JR
55#include <dlgs.h>
56#define FILE_NAME_TEXT_FIELD edt1
57
9785d95b
BK
58void syms_of_w32fns ();
59void globals_of_w32fns ();
839b1909 60static void init_external_image_libraries ();
9785d95b 61
ee78dc32 62extern void free_frame_menubar ();
6fc2811b 63extern double atof ();
9eb16b62
JR
64extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
65extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
66extern void w32_free_menu_strings P_ ((HWND));
67
5ac45f98 68extern int quit_char;
ee78dc32 69
ccc2d29c
GV
70extern char *lispy_function_keys[];
71
6fc2811b
JR
72/* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
73 it, and including `bitmaps/gray' more than once is a problem when
74 config.h defines `static' as an empty replacement string. */
75
76int gray_bitmap_width = gray_width;
77int gray_bitmap_height = gray_height;
78unsigned char *gray_bitmap_bits = gray_bits;
79
ee78dc32 80/* The colormap for converting color names to RGB values */
fbd6baed 81Lisp_Object Vw32_color_map;
ee78dc32 82
da36a4d6 83/* Non nil if alt key presses are passed on to Windows. */
fbd6baed 84Lisp_Object Vw32_pass_alt_to_system;
da36a4d6 85
8c205c63
RS
86/* Non nil if alt key is translated to meta_modifier, nil if it is translated
87 to alt_modifier. */
fbd6baed 88Lisp_Object Vw32_alt_is_meta;
8c205c63 89
7d081355
AI
90/* If non-zero, the windows virtual key code for an alternative quit key. */
91Lisp_Object Vw32_quit_key;
92
ccc2d29c
GV
93/* Non nil if left window key events are passed on to Windows (this only
94 affects whether "tapping" the key opens the Start menu). */
95Lisp_Object Vw32_pass_lwindow_to_system;
96
97/* Non nil if right window key events are passed on to Windows (this
98 only affects whether "tapping" the key opens the Start menu). */
99Lisp_Object Vw32_pass_rwindow_to_system;
100
adcc3809
GV
101/* Virtual key code used to generate "phantom" key presses in order
102 to stop system from acting on Windows key events. */
103Lisp_Object Vw32_phantom_key_code;
104
ccc2d29c
GV
105/* Modifier associated with the left "Windows" key, or nil to act as a
106 normal key. */
107Lisp_Object Vw32_lwindow_modifier;
108
109/* Modifier associated with the right "Windows" key, or nil to act as a
110 normal key. */
111Lisp_Object Vw32_rwindow_modifier;
112
113/* Modifier associated with the "Apps" key, or nil to act as a normal
114 key. */
115Lisp_Object Vw32_apps_modifier;
116
117/* Value is nil if Num Lock acts as a function key. */
118Lisp_Object Vw32_enable_num_lock;
119
120/* Value is nil if Caps Lock acts as a function key. */
121Lisp_Object Vw32_enable_caps_lock;
122
123/* Modifier associated with Scroll Lock, or nil to act as a normal key. */
124Lisp_Object Vw32_scroll_lock_modifier;
da36a4d6 125
7ce9aaca 126/* Switch to control whether we inhibit requests for synthesized bold
6fc2811b 127 and italic versions of fonts. */
d84b082d 128int w32_enable_synthesized_fonts;
5ac45f98
GV
129
130/* Enable palette management. */
fbd6baed 131Lisp_Object Vw32_enable_palette;
5ac45f98
GV
132
133/* Control how close left/right button down events must be to
134 be converted to a middle button down event. */
fbd6baed 135Lisp_Object Vw32_mouse_button_tolerance;
5ac45f98 136
84fb1139
KH
137/* Minimum interval between mouse movement (and scroll bar drag)
138 events that are passed on to the event loop. */
fbd6baed 139Lisp_Object Vw32_mouse_move_interval;
84fb1139 140
74214547
JR
141/* Flag to indicate if XBUTTON events should be passed on to Windows. */
142int w32_pass_extra_mouse_buttons_to_system;
143
ee78dc32
GV
144/* Non nil if no window manager is in use. */
145Lisp_Object Vx_no_window_manager;
146
0af913d7 147/* Non-zero means we're allowed to display a hourglass pointer. */
dfff8a69 148
0af913d7 149int display_hourglass_p;
6fc2811b 150
ee78dc32
GV
151/* The background and shape of the mouse pointer, and shape when not
152 over text or in the modeline. */
dfff8a69 153
ee78dc32 154Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
c9b2104d 155Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape, Vx_hand_shape;
6fc2811b 156
ee78dc32 157/* The shape when over mouse-sensitive text. */
dfff8a69 158
ee78dc32
GV
159Lisp_Object Vx_sensitive_text_pointer_shape;
160
c9b2104d
JR
161#ifndef IDC_HAND
162#define IDC_HAND MAKEINTRESOURCE(32649)
163#endif
164
ee78dc32 165/* Color of chars displayed in cursor box. */
dfff8a69 166
ee78dc32
GV
167Lisp_Object Vx_cursor_fore_pixel;
168
1edf84e7 169/* Nonzero if using Windows. */
dfff8a69 170
1edf84e7
GV
171static int w32_in_use;
172
ee78dc32 173/* Search path for bitmap files. */
dfff8a69 174
ee78dc32
GV
175Lisp_Object Vx_bitmap_file_path;
176
4587b026 177/* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
dfff8a69 178
4587b026
GV
179Lisp_Object Vx_pixel_size_width_font_regexp;
180
33d52f9c
GV
181/* Alist of bdf fonts and the files that define them. */
182Lisp_Object Vw32_bdf_filename_alist;
183
f46e6225 184/* A flag to control whether fonts are matched strictly or not. */
1075afa9
GV
185int w32_strict_fontnames;
186
c0611964
AI
187/* A flag to control whether we should only repaint if GetUpdateRect
188 indicates there is an update region. */
189int w32_strict_painting;
190
dfff8a69
JR
191/* Associative list linking character set strings to Windows codepages. */
192Lisp_Object Vw32_charset_info_alist;
193
194/* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
195#ifndef VIETNAMESE_CHARSET
196#define VIETNAMESE_CHARSET 163
197#endif
198
ee78dc32 199Lisp_Object Qnone;
ee78dc32 200Lisp_Object Qsuppress_icon;
ee78dc32 201Lisp_Object Qundefined_color;
dfff8a69 202Lisp_Object Qcenter;
dc220243 203Lisp_Object Qcancel_timer;
adcc3809
GV
204Lisp_Object Qhyper;
205Lisp_Object Qsuper;
206Lisp_Object Qmeta;
207Lisp_Object Qalt;
208Lisp_Object Qctrl;
209Lisp_Object Qcontrol;
210Lisp_Object Qshift;
211
dfff8a69
JR
212Lisp_Object Qw32_charset_ansi;
213Lisp_Object Qw32_charset_default;
214Lisp_Object Qw32_charset_symbol;
215Lisp_Object Qw32_charset_shiftjis;
767b1ff0 216Lisp_Object Qw32_charset_hangeul;
dfff8a69
JR
217Lisp_Object Qw32_charset_gb2312;
218Lisp_Object Qw32_charset_chinesebig5;
219Lisp_Object Qw32_charset_oem;
220
71eab8d1
AI
221#ifndef JOHAB_CHARSET
222#define JOHAB_CHARSET 130
223#endif
dfff8a69
JR
224#ifdef JOHAB_CHARSET
225Lisp_Object Qw32_charset_easteurope;
226Lisp_Object Qw32_charset_turkish;
227Lisp_Object Qw32_charset_baltic;
228Lisp_Object Qw32_charset_russian;
229Lisp_Object Qw32_charset_arabic;
230Lisp_Object Qw32_charset_greek;
231Lisp_Object Qw32_charset_hebrew;
767b1ff0 232Lisp_Object Qw32_charset_vietnamese;
dfff8a69
JR
233Lisp_Object Qw32_charset_thai;
234Lisp_Object Qw32_charset_johab;
235Lisp_Object Qw32_charset_mac;
236#endif
237
238#ifdef UNICODE_CHARSET
239Lisp_Object Qw32_charset_unicode;
240#endif
241
5ac45f98
GV
242/* State variables for emulating a three button mouse. */
243#define LMOUSE 1
244#define MMOUSE 2
245#define RMOUSE 4
246
247static int button_state = 0;
fbd6baed 248static W32Msg saved_mouse_button_msg;
48094ace 249static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
fbd6baed 250static W32Msg saved_mouse_move_msg;
48094ace 251static unsigned mouse_move_timer = 0;
84fb1139 252
9eb16b62
JR
253/* Window that is tracking the mouse. */
254static HWND track_mouse_window;
f60ae425
BK
255
256typedef BOOL (WINAPI * TrackMouseEvent_Proc) (
257 IN OUT LPTRACKMOUSEEVENT lpEventTrack
258 );
259
260TrackMouseEvent_Proc track_mouse_event_fn=NULL;
9eb16b62 261
93fbe8b7 262/* W95 mousewheel handler */
7d0393cf 263unsigned int msh_mousewheel = 0;
93fbe8b7 264
48094ace 265/* Timers */
84fb1139
KH
266#define MOUSE_BUTTON_ID 1
267#define MOUSE_MOVE_ID 2
48094ace
JR
268#define MENU_FREE_ID 3
269/* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
270 is received. */
271#define MENU_FREE_DELAY 1000
272static unsigned menu_free_timer = 0;
5ac45f98 273
ee78dc32 274/* The below are defined in frame.c. */
dfff8a69 275
ee78dc32
GV
276extern Lisp_Object Vwindow_system_version;
277
937e601e
AI
278#ifdef GLYPH_DEBUG
279int image_cache_refcount, dpyinfo_refcount;
280#endif
281
282
fbd6baed
GV
283/* From w32term.c. */
284extern Lisp_Object Vw32_num_mouse_buttons;
ccc2d29c 285extern Lisp_Object Vw32_recognize_altgr;
5ac45f98 286
65906840 287extern HWND w32_system_caret_hwnd;
93f2ca61 288
65906840
JR
289extern int w32_system_caret_height;
290extern int w32_system_caret_x;
291extern int w32_system_caret_y;
93f2ca61
JR
292extern int w32_use_visible_system_caret;
293
d285988b 294static HWND w32_visible_system_caret_hwnd;
65906840 295
ee78dc32 296\f
1edf84e7
GV
297/* Error if we are not connected to MS-Windows. */
298void
299check_w32 ()
300{
301 if (! w32_in_use)
302 error ("MS-Windows not in use or not initialized");
303}
304
305/* Nonzero if we can use mouse menus.
306 You should not call this unless HAVE_MENUS is defined. */
7d0393cf 307
1edf84e7
GV
308int
309have_menus_p ()
310{
311 return w32_in_use;
312}
313
ee78dc32 314/* Extract a frame as a FRAME_PTR, defaulting to the selected frame
fbd6baed 315 and checking validity for W32. */
ee78dc32
GV
316
317FRAME_PTR
318check_x_frame (frame)
319 Lisp_Object frame;
320{
321 FRAME_PTR f;
322
323 if (NILP (frame))
6fc2811b 324 frame = selected_frame;
b7826503 325 CHECK_LIVE_FRAME (frame);
6fc2811b 326 f = XFRAME (frame);
fbd6baed
GV
327 if (! FRAME_W32_P (f))
328 error ("non-w32 frame used");
ee78dc32
GV
329 return f;
330}
331
7d0393cf 332/* Let the user specify a display with a frame.
fbd6baed 333 nil stands for the selected frame--or, if that is not a w32 frame,
ee78dc32
GV
334 the first display on the list. */
335
6d906347 336struct w32_display_info *
ee78dc32
GV
337check_x_display_info (frame)
338 Lisp_Object frame;
339{
340 if (NILP (frame))
341 {
6fc2811b 342 struct frame *sf = XFRAME (selected_frame);
7d0393cf 343
6fc2811b
JR
344 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
345 return FRAME_W32_DISPLAY_INFO (sf);
ee78dc32 346 else
fbd6baed 347 return &one_w32_display_info;
ee78dc32
GV
348 }
349 else if (STRINGP (frame))
350 return x_display_info_for_name (frame);
351 else
352 {
353 FRAME_PTR f;
354
b7826503 355 CHECK_LIVE_FRAME (frame);
ee78dc32 356 f = XFRAME (frame);
fbd6baed
GV
357 if (! FRAME_W32_P (f))
358 error ("non-w32 frame used");
359 return FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
360 }
361}
362\f
fbd6baed 363/* Return the Emacs frame-object corresponding to an w32 window.
ee78dc32
GV
364 It could be the frame's main window or an icon window. */
365
366/* This function can be called during GC, so use GC_xxx type test macros. */
367
368struct frame *
369x_window_to_frame (dpyinfo, wdesc)
fbd6baed 370 struct w32_display_info *dpyinfo;
ee78dc32
GV
371 HWND wdesc;
372{
373 Lisp_Object tail, frame;
374 struct frame *f;
375
8e713be6 376 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
ee78dc32 377 {
8e713be6 378 frame = XCAR (tail);
ee78dc32
GV
379 if (!GC_FRAMEP (frame))
380 continue;
381 f = XFRAME (frame);
2d764c78 382 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
ee78dc32 383 continue;
0af913d7 384 if (f->output_data.w32->hourglass_window == wdesc)
f79e6790
JR
385 return f;
386
fbd6baed 387 if (FRAME_W32_WINDOW (f) == wdesc)
ee78dc32
GV
388 return f;
389 }
390 return 0;
391}
392
393\f
394
395/* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
396 id, which is just an int that this section returns. Bitmaps are
397 reference counted so they can be shared among frames.
398
399 Bitmap indices are guaranteed to be > 0, so a negative number can
400 be used to indicate no bitmap.
401
402 If you use x_create_bitmap_from_data, then you must keep track of
403 the bitmaps yourself. That is, creating a bitmap from the same
404 data more than once will not be caught. */
405
406
407/* Functions to access the contents of a bitmap, given an id. */
408
409int
410x_bitmap_height (f, id)
411 FRAME_PTR f;
412 int id;
413{
fbd6baed 414 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
ee78dc32
GV
415}
416
417int
418x_bitmap_width (f, id)
419 FRAME_PTR f;
420 int id;
421{
fbd6baed 422 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
ee78dc32
GV
423}
424
425int
426x_bitmap_pixmap (f, id)
427 FRAME_PTR f;
428 int id;
429{
fbd6baed 430 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
ee78dc32
GV
431}
432
433
434/* Allocate a new bitmap record. Returns index of new record. */
435
436static int
437x_allocate_bitmap_record (f)
438 FRAME_PTR f;
439{
fbd6baed 440 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
441 int i;
442
443 if (dpyinfo->bitmaps == NULL)
444 {
445 dpyinfo->bitmaps_size = 10;
446 dpyinfo->bitmaps
fbd6baed 447 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
ee78dc32
GV
448 dpyinfo->bitmaps_last = 1;
449 return 1;
450 }
451
452 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
453 return ++dpyinfo->bitmaps_last;
454
455 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
456 if (dpyinfo->bitmaps[i].refcount == 0)
457 return i + 1;
458
459 dpyinfo->bitmaps_size *= 2;
460 dpyinfo->bitmaps
fbd6baed
GV
461 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
462 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
ee78dc32
GV
463 return ++dpyinfo->bitmaps_last;
464}
465
466/* Add one reference to the reference count of the bitmap with id ID. */
467
468void
469x_reference_bitmap (f, id)
470 FRAME_PTR f;
471 int id;
472{
fbd6baed 473 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
ee78dc32
GV
474}
475
476/* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
477
478int
479x_create_bitmap_from_data (f, bits, width, height)
480 struct frame *f;
481 char *bits;
482 unsigned int width, height;
483{
fbd6baed 484 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
485 Pixmap bitmap;
486 int id;
487
488 bitmap = CreateBitmap (width, height,
fbd6baed
GV
489 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
490 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
ee78dc32
GV
491 bits);
492
493 if (! bitmap)
494 return -1;
495
496 id = x_allocate_bitmap_record (f);
497 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
498 dpyinfo->bitmaps[id - 1].file = NULL;
499 dpyinfo->bitmaps[id - 1].hinst = NULL;
500 dpyinfo->bitmaps[id - 1].refcount = 1;
501 dpyinfo->bitmaps[id - 1].depth = 1;
502 dpyinfo->bitmaps[id - 1].height = height;
503 dpyinfo->bitmaps[id - 1].width = width;
504
505 return id;
506}
507
508/* Create bitmap from file FILE for frame F. */
509
510int
511x_create_bitmap_from_file (f, file)
512 struct frame *f;
513 Lisp_Object file;
514{
515 return -1;
767b1ff0 516#if 0 /* TODO : bitmap support */
fbd6baed 517 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32 518 unsigned int width, height;
6fc2811b 519 HBITMAP bitmap;
ee78dc32
GV
520 int xhot, yhot, result, id;
521 Lisp_Object found;
522 int fd;
523 char *filename;
524 HINSTANCE hinst;
525
526 /* Look for an existing bitmap with the same name. */
527 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
528 {
529 if (dpyinfo->bitmaps[id].refcount
530 && dpyinfo->bitmaps[id].file
d5db4077 531 && !strcmp (dpyinfo->bitmaps[id].file, (char *) SDATA (file)))
ee78dc32
GV
532 {
533 ++dpyinfo->bitmaps[id].refcount;
534 return id + 1;
535 }
536 }
537
538 /* Search bitmap-file-path for the file, if appropriate. */
de2413e9 539 fd = openp (Vx_bitmap_file_path, file, Qnil, &found, Qnil);
ee78dc32
GV
540 if (fd < 0)
541 return -1;
6fc2811b 542 emacs_close (fd);
ee78dc32 543
d5db4077 544 filename = (char *) SDATA (found);
ee78dc32
GV
545
546 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
547
548 if (hinst == NULL)
549 return -1;
550
7d0393cf 551
fbd6baed 552 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
ee78dc32
GV
553 filename, &width, &height, &bitmap, &xhot, &yhot);
554 if (result != BitmapSuccess)
555 return -1;
556
557 id = x_allocate_bitmap_record (f);
558 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
559 dpyinfo->bitmaps[id - 1].refcount = 1;
d5db4077 560 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (SCHARS (file) + 1);
ee78dc32
GV
561 dpyinfo->bitmaps[id - 1].depth = 1;
562 dpyinfo->bitmaps[id - 1].height = height;
563 dpyinfo->bitmaps[id - 1].width = width;
d5db4077 564 strcpy (dpyinfo->bitmaps[id - 1].file, SDATA (file));
ee78dc32
GV
565
566 return id;
767b1ff0 567#endif /* TODO */
ee78dc32
GV
568}
569
570/* Remove reference to bitmap with id number ID. */
571
33d52f9c 572void
ee78dc32
GV
573x_destroy_bitmap (f, id)
574 FRAME_PTR f;
575 int id;
576{
fbd6baed 577 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
ee78dc32
GV
578
579 if (id > 0)
580 {
581 --dpyinfo->bitmaps[id - 1].refcount;
582 if (dpyinfo->bitmaps[id - 1].refcount == 0)
583 {
584 BLOCK_INPUT;
585 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
586 if (dpyinfo->bitmaps[id - 1].file)
587 {
6fc2811b 588 xfree (dpyinfo->bitmaps[id - 1].file);
ee78dc32
GV
589 dpyinfo->bitmaps[id - 1].file = NULL;
590 }
591 UNBLOCK_INPUT;
592 }
593 }
594}
595
596/* Free all the bitmaps for the display specified by DPYINFO. */
597
598static void
599x_destroy_all_bitmaps (dpyinfo)
fbd6baed 600 struct w32_display_info *dpyinfo;
ee78dc32
GV
601{
602 int i;
603 for (i = 0; i < dpyinfo->bitmaps_last; i++)
604 if (dpyinfo->bitmaps[i].refcount > 0)
605 {
606 DeleteObject (dpyinfo->bitmaps[i].pixmap);
607 if (dpyinfo->bitmaps[i].file)
6fc2811b 608 xfree (dpyinfo->bitmaps[i].file);
ee78dc32
GV
609 }
610 dpyinfo->bitmaps_last = 0;
611}
612\f
ca56d953
JR
613BOOL my_show_window P_ ((struct frame *, HWND, int));
614void my_set_window_pos P_ ((HWND, HWND, int, int, int, int, UINT));
937e601e
AI
615static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
616static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
6d906347 617
767b1ff0 618/* TODO: Native Input Method support; see x_create_im. */
6fc2811b
JR
619void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
620void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
621void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
622void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
623void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
624void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
625void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
626void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 627void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 628void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 629void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
6fc2811b 630void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
3cf3436e
JR
631static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
632 Lisp_Object));
ee78dc32 633
ee78dc32 634
ee78dc32 635\f
ee78dc32
GV
636
637/* Store the screen positions of frame F into XPTR and YPTR.
638 These are the positions of the containing window manager window,
639 not Emacs's own window. */
640
641void
642x_real_positions (f, xptr, yptr)
643 FRAME_PTR f;
644 int *xptr, *yptr;
645{
646 POINT pt;
f7b9d4d1 647 RECT rect;
3c190163 648
f7b9d4d1
JR
649 GetClientRect(FRAME_W32_WINDOW(f), &rect);
650 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
651
652 pt.x = rect.left;
653 pt.y = rect.top;
ee78dc32 654
fbd6baed 655 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
ee78dc32 656
f7b9d4d1
JR
657 /* Remember x_pixels_diff and y_pixels_diff. */
658 f->output_data.w32->x_pixels_diff = pt.x - rect.left;
659 f->output_data.w32->y_pixels_diff = pt.y - rect.top;
660
ee78dc32
GV
661 *xptr = pt.x;
662 *yptr = pt.y;
663}
664
ee78dc32
GV
665\f
666
74e1aeec
JR
667DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
668 Sw32_define_rgb_color, 4, 4, 0,
669 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
670This adds or updates a named color to w32-color-map, making it
671available for use. The original entry's RGB ref is returned, or nil
672if the entry is new. */)
5ac45f98
GV
673 (red, green, blue, name)
674 Lisp_Object red, green, blue, name;
ee78dc32 675{
5ac45f98
GV
676 Lisp_Object rgb;
677 Lisp_Object oldrgb = Qnil;
678 Lisp_Object entry;
679
b7826503
PJ
680 CHECK_NUMBER (red);
681 CHECK_NUMBER (green);
682 CHECK_NUMBER (blue);
683 CHECK_STRING (name);
ee78dc32 684
5ac45f98 685 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
ee78dc32 686
5ac45f98 687 BLOCK_INPUT;
ee78dc32 688
fbd6baed
GV
689 /* replace existing entry in w32-color-map or add new entry. */
690 entry = Fassoc (name, Vw32_color_map);
5ac45f98
GV
691 if (NILP (entry))
692 {
693 entry = Fcons (name, rgb);
fbd6baed 694 Vw32_color_map = Fcons (entry, Vw32_color_map);
5ac45f98
GV
695 }
696 else
697 {
698 oldrgb = Fcdr (entry);
699 Fsetcdr (entry, rgb);
700 }
701
702 UNBLOCK_INPUT;
703
704 return (oldrgb);
ee78dc32
GV
705}
706
74e1aeec
JR
707DEFUN ("w32-load-color-file", Fw32_load_color_file,
708 Sw32_load_color_file, 1, 1, 0,
709 doc: /* Create an alist of color entries from an external file.
710Assign this value to w32-color-map to replace the existing color map.
711
712The file should define one named RGB color per line like so:
713 R G B name
714where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
5ac45f98
GV
715 (filename)
716 Lisp_Object filename;
717{
718 FILE *fp;
719 Lisp_Object cmap = Qnil;
720 Lisp_Object abspath;
721
b7826503 722 CHECK_STRING (filename);
5ac45f98
GV
723 abspath = Fexpand_file_name (filename, Qnil);
724
d5db4077 725 fp = fopen (SDATA (filename), "rt");
5ac45f98
GV
726 if (fp)
727 {
728 char buf[512];
729 int red, green, blue;
730 int num;
731
732 BLOCK_INPUT;
733
734 while (fgets (buf, sizeof (buf), fp) != NULL) {
735 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
736 {
737 char *name = buf + num;
738 num = strlen (name) - 1;
739 if (name[num] == '\n')
740 name[num] = 0;
741 cmap = Fcons (Fcons (build_string (name),
742 make_number (RGB (red, green, blue))),
743 cmap);
744 }
745 }
746 fclose (fp);
747
748 UNBLOCK_INPUT;
749 }
750
751 return cmap;
752}
ee78dc32 753
fbd6baed 754/* The default colors for the w32 color map */
7d0393cf 755typedef struct colormap_t
ee78dc32
GV
756{
757 char *name;
758 COLORREF colorref;
759} colormap_t;
760
7d0393cf 761colormap_t w32_color_map[] =
ee78dc32 762{
1da8a614
GV
763 {"snow" , PALETTERGB (255,250,250)},
764 {"ghost white" , PALETTERGB (248,248,255)},
765 {"GhostWhite" , PALETTERGB (248,248,255)},
766 {"white smoke" , PALETTERGB (245,245,245)},
767 {"WhiteSmoke" , PALETTERGB (245,245,245)},
768 {"gainsboro" , PALETTERGB (220,220,220)},
769 {"floral white" , PALETTERGB (255,250,240)},
770 {"FloralWhite" , PALETTERGB (255,250,240)},
771 {"old lace" , PALETTERGB (253,245,230)},
772 {"OldLace" , PALETTERGB (253,245,230)},
773 {"linen" , PALETTERGB (250,240,230)},
774 {"antique white" , PALETTERGB (250,235,215)},
775 {"AntiqueWhite" , PALETTERGB (250,235,215)},
776 {"papaya whip" , PALETTERGB (255,239,213)},
777 {"PapayaWhip" , PALETTERGB (255,239,213)},
778 {"blanched almond" , PALETTERGB (255,235,205)},
779 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
780 {"bisque" , PALETTERGB (255,228,196)},
781 {"peach puff" , PALETTERGB (255,218,185)},
782 {"PeachPuff" , PALETTERGB (255,218,185)},
783 {"navajo white" , PALETTERGB (255,222,173)},
784 {"NavajoWhite" , PALETTERGB (255,222,173)},
785 {"moccasin" , PALETTERGB (255,228,181)},
786 {"cornsilk" , PALETTERGB (255,248,220)},
787 {"ivory" , PALETTERGB (255,255,240)},
788 {"lemon chiffon" , PALETTERGB (255,250,205)},
789 {"LemonChiffon" , PALETTERGB (255,250,205)},
790 {"seashell" , PALETTERGB (255,245,238)},
791 {"honeydew" , PALETTERGB (240,255,240)},
792 {"mint cream" , PALETTERGB (245,255,250)},
793 {"MintCream" , PALETTERGB (245,255,250)},
794 {"azure" , PALETTERGB (240,255,255)},
795 {"alice blue" , PALETTERGB (240,248,255)},
796 {"AliceBlue" , PALETTERGB (240,248,255)},
797 {"lavender" , PALETTERGB (230,230,250)},
798 {"lavender blush" , PALETTERGB (255,240,245)},
799 {"LavenderBlush" , PALETTERGB (255,240,245)},
800 {"misty rose" , PALETTERGB (255,228,225)},
801 {"MistyRose" , PALETTERGB (255,228,225)},
802 {"white" , PALETTERGB (255,255,255)},
803 {"black" , PALETTERGB ( 0, 0, 0)},
804 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
805 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
806 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
807 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
808 {"dim gray" , PALETTERGB (105,105,105)},
809 {"DimGray" , PALETTERGB (105,105,105)},
810 {"dim grey" , PALETTERGB (105,105,105)},
811 {"DimGrey" , PALETTERGB (105,105,105)},
812 {"slate gray" , PALETTERGB (112,128,144)},
813 {"SlateGray" , PALETTERGB (112,128,144)},
814 {"slate grey" , PALETTERGB (112,128,144)},
815 {"SlateGrey" , PALETTERGB (112,128,144)},
816 {"light slate gray" , PALETTERGB (119,136,153)},
817 {"LightSlateGray" , PALETTERGB (119,136,153)},
818 {"light slate grey" , PALETTERGB (119,136,153)},
819 {"LightSlateGrey" , PALETTERGB (119,136,153)},
820 {"gray" , PALETTERGB (190,190,190)},
821 {"grey" , PALETTERGB (190,190,190)},
822 {"light grey" , PALETTERGB (211,211,211)},
823 {"LightGrey" , PALETTERGB (211,211,211)},
824 {"light gray" , PALETTERGB (211,211,211)},
825 {"LightGray" , PALETTERGB (211,211,211)},
826 {"midnight blue" , PALETTERGB ( 25, 25,112)},
827 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
828 {"navy" , PALETTERGB ( 0, 0,128)},
829 {"navy blue" , PALETTERGB ( 0, 0,128)},
830 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
831 {"cornflower blue" , PALETTERGB (100,149,237)},
832 {"CornflowerBlue" , PALETTERGB (100,149,237)},
833 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
834 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
835 {"slate blue" , PALETTERGB (106, 90,205)},
836 {"SlateBlue" , PALETTERGB (106, 90,205)},
837 {"medium slate blue" , PALETTERGB (123,104,238)},
838 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
839 {"light slate blue" , PALETTERGB (132,112,255)},
840 {"LightSlateBlue" , PALETTERGB (132,112,255)},
841 {"medium blue" , PALETTERGB ( 0, 0,205)},
842 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
843 {"royal blue" , PALETTERGB ( 65,105,225)},
844 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
845 {"blue" , PALETTERGB ( 0, 0,255)},
846 {"dodger blue" , PALETTERGB ( 30,144,255)},
847 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
848 {"deep sky blue" , PALETTERGB ( 0,191,255)},
849 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
850 {"sky blue" , PALETTERGB (135,206,235)},
851 {"SkyBlue" , PALETTERGB (135,206,235)},
852 {"light sky blue" , PALETTERGB (135,206,250)},
853 {"LightSkyBlue" , PALETTERGB (135,206,250)},
854 {"steel blue" , PALETTERGB ( 70,130,180)},
855 {"SteelBlue" , PALETTERGB ( 70,130,180)},
856 {"light steel blue" , PALETTERGB (176,196,222)},
857 {"LightSteelBlue" , PALETTERGB (176,196,222)},
858 {"light blue" , PALETTERGB (173,216,230)},
859 {"LightBlue" , PALETTERGB (173,216,230)},
860 {"powder blue" , PALETTERGB (176,224,230)},
861 {"PowderBlue" , PALETTERGB (176,224,230)},
862 {"pale turquoise" , PALETTERGB (175,238,238)},
863 {"PaleTurquoise" , PALETTERGB (175,238,238)},
864 {"dark turquoise" , PALETTERGB ( 0,206,209)},
865 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
866 {"medium turquoise" , PALETTERGB ( 72,209,204)},
867 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
868 {"turquoise" , PALETTERGB ( 64,224,208)},
869 {"cyan" , PALETTERGB ( 0,255,255)},
870 {"light cyan" , PALETTERGB (224,255,255)},
871 {"LightCyan" , PALETTERGB (224,255,255)},
872 {"cadet blue" , PALETTERGB ( 95,158,160)},
873 {"CadetBlue" , PALETTERGB ( 95,158,160)},
874 {"medium aquamarine" , PALETTERGB (102,205,170)},
875 {"MediumAquamarine" , PALETTERGB (102,205,170)},
876 {"aquamarine" , PALETTERGB (127,255,212)},
877 {"dark green" , PALETTERGB ( 0,100, 0)},
878 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
879 {"dark olive green" , PALETTERGB ( 85,107, 47)},
880 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
881 {"dark sea green" , PALETTERGB (143,188,143)},
882 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
883 {"sea green" , PALETTERGB ( 46,139, 87)},
884 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
885 {"medium sea green" , PALETTERGB ( 60,179,113)},
886 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
887 {"light sea green" , PALETTERGB ( 32,178,170)},
888 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
889 {"pale green" , PALETTERGB (152,251,152)},
890 {"PaleGreen" , PALETTERGB (152,251,152)},
891 {"spring green" , PALETTERGB ( 0,255,127)},
892 {"SpringGreen" , PALETTERGB ( 0,255,127)},
893 {"lawn green" , PALETTERGB (124,252, 0)},
894 {"LawnGreen" , PALETTERGB (124,252, 0)},
895 {"green" , PALETTERGB ( 0,255, 0)},
896 {"chartreuse" , PALETTERGB (127,255, 0)},
897 {"medium spring green" , PALETTERGB ( 0,250,154)},
898 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
899 {"green yellow" , PALETTERGB (173,255, 47)},
900 {"GreenYellow" , PALETTERGB (173,255, 47)},
901 {"lime green" , PALETTERGB ( 50,205, 50)},
902 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
903 {"yellow green" , PALETTERGB (154,205, 50)},
904 {"YellowGreen" , PALETTERGB (154,205, 50)},
905 {"forest green" , PALETTERGB ( 34,139, 34)},
906 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
907 {"olive drab" , PALETTERGB (107,142, 35)},
908 {"OliveDrab" , PALETTERGB (107,142, 35)},
909 {"dark khaki" , PALETTERGB (189,183,107)},
910 {"DarkKhaki" , PALETTERGB (189,183,107)},
911 {"khaki" , PALETTERGB (240,230,140)},
912 {"pale goldenrod" , PALETTERGB (238,232,170)},
913 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
914 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
915 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
916 {"light yellow" , PALETTERGB (255,255,224)},
917 {"LightYellow" , PALETTERGB (255,255,224)},
918 {"yellow" , PALETTERGB (255,255, 0)},
919 {"gold" , PALETTERGB (255,215, 0)},
920 {"light goldenrod" , PALETTERGB (238,221,130)},
921 {"LightGoldenrod" , PALETTERGB (238,221,130)},
922 {"goldenrod" , PALETTERGB (218,165, 32)},
923 {"dark goldenrod" , PALETTERGB (184,134, 11)},
924 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
925 {"rosy brown" , PALETTERGB (188,143,143)},
926 {"RosyBrown" , PALETTERGB (188,143,143)},
927 {"indian red" , PALETTERGB (205, 92, 92)},
928 {"IndianRed" , PALETTERGB (205, 92, 92)},
929 {"saddle brown" , PALETTERGB (139, 69, 19)},
930 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
931 {"sienna" , PALETTERGB (160, 82, 45)},
932 {"peru" , PALETTERGB (205,133, 63)},
933 {"burlywood" , PALETTERGB (222,184,135)},
934 {"beige" , PALETTERGB (245,245,220)},
935 {"wheat" , PALETTERGB (245,222,179)},
936 {"sandy brown" , PALETTERGB (244,164, 96)},
937 {"SandyBrown" , PALETTERGB (244,164, 96)},
938 {"tan" , PALETTERGB (210,180,140)},
939 {"chocolate" , PALETTERGB (210,105, 30)},
940 {"firebrick" , PALETTERGB (178,34, 34)},
941 {"brown" , PALETTERGB (165,42, 42)},
942 {"dark salmon" , PALETTERGB (233,150,122)},
943 {"DarkSalmon" , PALETTERGB (233,150,122)},
944 {"salmon" , PALETTERGB (250,128,114)},
945 {"light salmon" , PALETTERGB (255,160,122)},
946 {"LightSalmon" , PALETTERGB (255,160,122)},
947 {"orange" , PALETTERGB (255,165, 0)},
948 {"dark orange" , PALETTERGB (255,140, 0)},
949 {"DarkOrange" , PALETTERGB (255,140, 0)},
950 {"coral" , PALETTERGB (255,127, 80)},
951 {"light coral" , PALETTERGB (240,128,128)},
952 {"LightCoral" , PALETTERGB (240,128,128)},
953 {"tomato" , PALETTERGB (255, 99, 71)},
954 {"orange red" , PALETTERGB (255, 69, 0)},
955 {"OrangeRed" , PALETTERGB (255, 69, 0)},
956 {"red" , PALETTERGB (255, 0, 0)},
957 {"hot pink" , PALETTERGB (255,105,180)},
958 {"HotPink" , PALETTERGB (255,105,180)},
959 {"deep pink" , PALETTERGB (255, 20,147)},
960 {"DeepPink" , PALETTERGB (255, 20,147)},
961 {"pink" , PALETTERGB (255,192,203)},
962 {"light pink" , PALETTERGB (255,182,193)},
963 {"LightPink" , PALETTERGB (255,182,193)},
964 {"pale violet red" , PALETTERGB (219,112,147)},
965 {"PaleVioletRed" , PALETTERGB (219,112,147)},
966 {"maroon" , PALETTERGB (176, 48, 96)},
967 {"medium violet red" , PALETTERGB (199, 21,133)},
968 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
969 {"violet red" , PALETTERGB (208, 32,144)},
970 {"VioletRed" , PALETTERGB (208, 32,144)},
971 {"magenta" , PALETTERGB (255, 0,255)},
972 {"violet" , PALETTERGB (238,130,238)},
973 {"plum" , PALETTERGB (221,160,221)},
974 {"orchid" , PALETTERGB (218,112,214)},
975 {"medium orchid" , PALETTERGB (186, 85,211)},
976 {"MediumOrchid" , PALETTERGB (186, 85,211)},
977 {"dark orchid" , PALETTERGB (153, 50,204)},
978 {"DarkOrchid" , PALETTERGB (153, 50,204)},
979 {"dark violet" , PALETTERGB (148, 0,211)},
980 {"DarkViolet" , PALETTERGB (148, 0,211)},
981 {"blue violet" , PALETTERGB (138, 43,226)},
982 {"BlueViolet" , PALETTERGB (138, 43,226)},
983 {"purple" , PALETTERGB (160, 32,240)},
984 {"medium purple" , PALETTERGB (147,112,219)},
985 {"MediumPurple" , PALETTERGB (147,112,219)},
986 {"thistle" , PALETTERGB (216,191,216)},
987 {"gray0" , PALETTERGB ( 0, 0, 0)},
988 {"grey0" , PALETTERGB ( 0, 0, 0)},
989 {"dark grey" , PALETTERGB (169,169,169)},
990 {"DarkGrey" , PALETTERGB (169,169,169)},
991 {"dark gray" , PALETTERGB (169,169,169)},
992 {"DarkGray" , PALETTERGB (169,169,169)},
993 {"dark blue" , PALETTERGB ( 0, 0,139)},
994 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
995 {"dark cyan" , PALETTERGB ( 0,139,139)},
996 {"DarkCyan" , PALETTERGB ( 0,139,139)},
997 {"dark magenta" , PALETTERGB (139, 0,139)},
998 {"DarkMagenta" , PALETTERGB (139, 0,139)},
999 {"dark red" , PALETTERGB (139, 0, 0)},
1000 {"DarkRed" , PALETTERGB (139, 0, 0)},
1001 {"light green" , PALETTERGB (144,238,144)},
1002 {"LightGreen" , PALETTERGB (144,238,144)},
ee78dc32
GV
1003};
1004
fbd6baed 1005DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
74e1aeec 1006 0, 0, 0, doc: /* Return the default color map. */)
ee78dc32
GV
1007 ()
1008{
1009 int i;
fbd6baed 1010 colormap_t *pc = w32_color_map;
ee78dc32 1011 Lisp_Object cmap;
7d0393cf 1012
ee78dc32 1013 BLOCK_INPUT;
7d0393cf 1014
ee78dc32 1015 cmap = Qnil;
7d0393cf
JB
1016
1017 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
ee78dc32
GV
1018 pc++, i++)
1019 cmap = Fcons (Fcons (build_string (pc->name),
1020 make_number (pc->colorref)),
1021 cmap);
7d0393cf 1022
ee78dc32 1023 UNBLOCK_INPUT;
7d0393cf 1024
ee78dc32
GV
1025 return (cmap);
1026}
ee78dc32 1027
7d0393cf 1028Lisp_Object
fbd6baed 1029w32_to_x_color (rgb)
ee78dc32
GV
1030 Lisp_Object rgb;
1031{
1032 Lisp_Object color;
7d0393cf 1033
b7826503 1034 CHECK_NUMBER (rgb);
7d0393cf 1035
ee78dc32 1036 BLOCK_INPUT;
7d0393cf 1037
fbd6baed 1038 color = Frassq (rgb, Vw32_color_map);
7d0393cf 1039
ee78dc32 1040 UNBLOCK_INPUT;
7d0393cf 1041
ee78dc32
GV
1042 if (!NILP (color))
1043 return (Fcar (color));
1044 else
1045 return Qnil;
1046}
1047
5d7fed93
GV
1048COLORREF
1049w32_color_map_lookup (colorname)
1050 char *colorname;
1051{
1052 Lisp_Object tail, ret = Qnil;
1053
1054 BLOCK_INPUT;
1055
1056 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1057 {
1058 register Lisp_Object elt, tem;
1059
1060 elt = Fcar (tail);
1061 if (!CONSP (elt)) continue;
1062
1063 tem = Fcar (elt);
1064
d5db4077 1065 if (lstrcmpi (SDATA (tem), colorname) == 0)
5d7fed93
GV
1066 {
1067 ret = XUINT (Fcdr (elt));
1068 break;
1069 }
1070
1071 QUIT;
1072 }
1073
1074
1075 UNBLOCK_INPUT;
1076
1077 return ret;
1078}
1079
7d0393cf 1080COLORREF
fbd6baed 1081x_to_w32_color (colorname)
ee78dc32
GV
1082 char * colorname;
1083{
8edb0a6f
JR
1084 register Lisp_Object ret = Qnil;
1085
ee78dc32 1086 BLOCK_INPUT;
1edf84e7
GV
1087
1088 if (colorname[0] == '#')
1089 {
1090 /* Could be an old-style RGB Device specification. */
1091 char *color;
1092 int size;
1093 color = colorname + 1;
7d0393cf 1094
1edf84e7
GV
1095 size = strlen(color);
1096 if (size == 3 || size == 6 || size == 9 || size == 12)
1097 {
1098 UINT colorval;
1099 int i, pos;
1100 pos = 0;
1101 size /= 3;
1102 colorval = 0;
7d0393cf 1103
1edf84e7
GV
1104 for (i = 0; i < 3; i++)
1105 {
1106 char *end;
1107 char t;
1108 unsigned long value;
1109
1110 /* The check for 'x' in the following conditional takes into
1111 account the fact that strtol allows a "0x" in front of
1112 our numbers, and we don't. */
1113 if (!isxdigit(color[0]) || color[1] == 'x')
1114 break;
1115 t = color[size];
1116 color[size] = '\0';
1117 value = strtoul(color, &end, 16);
1118 color[size] = t;
1119 if (errno == ERANGE || end - color != size)
1120 break;
1121 switch (size)
1122 {
1123 case 1:
1124 value = value * 0x10;
1125 break;
1126 case 2:
1127 break;
1128 case 3:
1129 value /= 0x10;
1130 break;
1131 case 4:
1132 value /= 0x100;
1133 break;
1134 }
1135 colorval |= (value << pos);
1136 pos += 0x8;
1137 if (i == 2)
1138 {
1139 UNBLOCK_INPUT;
1140 return (colorval);
1141 }
1142 color = end;
1143 }
1144 }
1145 }
1146 else if (strnicmp(colorname, "rgb:", 4) == 0)
1147 {
1148 char *color;
1149 UINT colorval;
1150 int i, pos;
1151 pos = 0;
1152
1153 colorval = 0;
1154 color = colorname + 4;
1155 for (i = 0; i < 3; i++)
1156 {
1157 char *end;
1158 unsigned long value;
7d0393cf 1159
1edf84e7
GV
1160 /* The check for 'x' in the following conditional takes into
1161 account the fact that strtol allows a "0x" in front of
1162 our numbers, and we don't. */
1163 if (!isxdigit(color[0]) || color[1] == 'x')
1164 break;
1165 value = strtoul(color, &end, 16);
1166 if (errno == ERANGE)
1167 break;
1168 switch (end - color)
1169 {
1170 case 1:
1171 value = value * 0x10 + value;
1172 break;
1173 case 2:
1174 break;
1175 case 3:
1176 value /= 0x10;
1177 break;
1178 case 4:
1179 value /= 0x100;
1180 break;
1181 default:
1182 value = ULONG_MAX;
1183 }
1184 if (value == ULONG_MAX)
1185 break;
1186 colorval |= (value << pos);
1187 pos += 0x8;
1188 if (i == 2)
1189 {
1190 if (*end != '\0')
1191 break;
1192 UNBLOCK_INPUT;
1193 return (colorval);
1194 }
1195 if (*end != '/')
1196 break;
1197 color = end + 1;
1198 }
1199 }
1200 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1201 {
1202 /* This is an RGB Intensity specification. */
1203 char *color;
1204 UINT colorval;
1205 int i, pos;
1206 pos = 0;
1207
1208 colorval = 0;
1209 color = colorname + 5;
1210 for (i = 0; i < 3; i++)
1211 {
1212 char *end;
1213 double value;
1214 UINT val;
1215
1216 value = strtod(color, &end);
1217 if (errno == ERANGE)
1218 break;
1219 if (value < 0.0 || value > 1.0)
1220 break;
1221 val = (UINT)(0x100 * value);
7d0393cf 1222 /* We used 0x100 instead of 0xFF to give a continuous
1edf84e7
GV
1223 range between 0.0 and 1.0 inclusive. The next statement
1224 fixes the 1.0 case. */
1225 if (val == 0x100)
1226 val = 0xFF;
1227 colorval |= (val << pos);
1228 pos += 0x8;
1229 if (i == 2)
1230 {
1231 if (*end != '\0')
1232 break;
1233 UNBLOCK_INPUT;
1234 return (colorval);
1235 }
1236 if (*end != '/')
1237 break;
1238 color = end + 1;
1239 }
1240 }
1241 /* I am not going to attempt to handle any of the CIE color schemes
1242 or TekHVC, since I don't know the algorithms for conversion to
1243 RGB. */
f695b4b1
GV
1244
1245 /* If we fail to lookup the color name in w32_color_map, then check the
7d0393cf 1246 colorname to see if it can be crudely approximated: If the X color
f695b4b1
GV
1247 ends in a number (e.g., "darkseagreen2"), strip the number and
1248 return the result of looking up the base color name. */
1249 ret = w32_color_map_lookup (colorname);
7d0393cf 1250 if (NILP (ret))
ee78dc32 1251 {
f695b4b1 1252 int len = strlen (colorname);
ee78dc32 1253
7d0393cf 1254 if (isdigit (colorname[len - 1]))
f695b4b1 1255 {
8b77111c 1256 char *ptr, *approx = alloca (len + 1);
ee78dc32 1257
f695b4b1
GV
1258 strcpy (approx, colorname);
1259 ptr = &approx[len - 1];
7d0393cf 1260 while (ptr > approx && isdigit (*ptr))
f695b4b1 1261 *ptr-- = '\0';
ee78dc32 1262
f695b4b1 1263 ret = w32_color_map_lookup (approx);
ee78dc32 1264 }
ee78dc32 1265 }
7d0393cf 1266
ee78dc32 1267 UNBLOCK_INPUT;
ee78dc32
GV
1268 return ret;
1269}
1270
5ac45f98
GV
1271
1272void
fbd6baed 1273w32_regenerate_palette (FRAME_PTR f)
5ac45f98 1274{
fbd6baed 1275 struct w32_palette_entry * list;
5ac45f98
GV
1276 LOGPALETTE * log_palette;
1277 HPALETTE new_palette;
1278 int i;
1279
1280 /* don't bother trying to create palette if not supported */
fbd6baed 1281 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
5ac45f98
GV
1282 return;
1283
1284 log_palette = (LOGPALETTE *)
1285 alloca (sizeof (LOGPALETTE) +
fbd6baed 1286 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
5ac45f98 1287 log_palette->palVersion = 0x300;
fbd6baed 1288 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
5ac45f98 1289
fbd6baed 1290 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
5ac45f98 1291 for (i = 0;
fbd6baed 1292 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
5ac45f98
GV
1293 i++, list = list->next)
1294 log_palette->palPalEntry[i] = list->entry;
1295
1296 new_palette = CreatePalette (log_palette);
1297
1298 enter_crit ();
1299
fbd6baed
GV
1300 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1301 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1302 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
5ac45f98
GV
1303
1304 /* Realize display palette and garbage all frames. */
1305 release_frame_dc (f, get_frame_dc (f));
1306
1307 leave_crit ();
1308}
1309
fbd6baed
GV
1310#define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1311#define SET_W32_COLOR(pe, color) \
5ac45f98
GV
1312 do \
1313 { \
1314 pe.peRed = GetRValue (color); \
1315 pe.peGreen = GetGValue (color); \
1316 pe.peBlue = GetBValue (color); \
1317 pe.peFlags = 0; \
1318 } while (0)
1319
1320#if 0
1321/* Keep these around in case we ever want to track color usage. */
1322void
fbd6baed 1323w32_map_color (FRAME_PTR f, COLORREF color)
5ac45f98 1324{
fbd6baed 1325 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
5ac45f98 1326
fbd6baed 1327 if (NILP (Vw32_enable_palette))
5ac45f98
GV
1328 return;
1329
1330 /* check if color is already mapped */
1331 while (list)
1332 {
fbd6baed 1333 if (W32_COLOR (list->entry) == color)
5ac45f98
GV
1334 {
1335 ++list->refcount;
1336 return;
1337 }
1338 list = list->next;
1339 }
1340
1341 /* not already mapped, so add to list and recreate Windows palette */
fbd6baed
GV
1342 list = (struct w32_palette_entry *)
1343 xmalloc (sizeof (struct w32_palette_entry));
1344 SET_W32_COLOR (list->entry, color);
5ac45f98 1345 list->refcount = 1;
fbd6baed
GV
1346 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1347 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1348 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
5ac45f98
GV
1349
1350 /* set flag that palette must be regenerated */
fbd6baed 1351 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
5ac45f98
GV
1352}
1353
1354void
fbd6baed 1355w32_unmap_color (FRAME_PTR f, COLORREF color)
5ac45f98 1356{
fbd6baed
GV
1357 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1358 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
5ac45f98 1359
fbd6baed 1360 if (NILP (Vw32_enable_palette))
5ac45f98
GV
1361 return;
1362
1363 /* check if color is already mapped */
1364 while (list)
1365 {
fbd6baed 1366 if (W32_COLOR (list->entry) == color)
5ac45f98
GV
1367 {
1368 if (--list->refcount == 0)
1369 {
1370 *prev = list->next;
1371 xfree (list);
fbd6baed 1372 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
5ac45f98
GV
1373 break;
1374 }
1375 else
1376 return;
1377 }
1378 prev = &list->next;
1379 list = list->next;
1380 }
1381
1382 /* set flag that palette must be regenerated */
fbd6baed 1383 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
5ac45f98
GV
1384}
1385#endif
1386
6fc2811b
JR
1387
1388/* Gamma-correct COLOR on frame F. */
1389
1390void
1391gamma_correct (f, color)
1392 struct frame *f;
1393 COLORREF *color;
1394{
1395 if (f->gamma)
1396 {
1397 *color = PALETTERGB (
1398 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1399 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1400 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1401 }
1402}
1403
1404
ee78dc32
GV
1405/* Decide if color named COLOR is valid for the display associated with
1406 the selected frame; if so, return the rgb values in COLOR_DEF.
1407 If ALLOC is nonzero, allocate a new colormap cell. */
1408
1409int
6fc2811b 1410w32_defined_color (f, color, color_def, alloc)
ee78dc32
GV
1411 FRAME_PTR f;
1412 char *color;
6fc2811b 1413 XColor *color_def;
ee78dc32
GV
1414 int alloc;
1415{
1416 register Lisp_Object tem;
6fc2811b 1417 COLORREF w32_color_ref;
3c190163 1418
fbd6baed 1419 tem = x_to_w32_color (color);
3c190163 1420
7d0393cf 1421 if (!NILP (tem))
ee78dc32 1422 {
d88c567c
JR
1423 if (f)
1424 {
1425 /* Apply gamma correction. */
1426 w32_color_ref = XUINT (tem);
1427 gamma_correct (f, &w32_color_ref);
1428 XSETINT (tem, w32_color_ref);
1429 }
9badad41
JR
1430
1431 /* Map this color to the palette if it is enabled. */
fbd6baed 1432 if (!NILP (Vw32_enable_palette))
5ac45f98 1433 {
fbd6baed 1434 struct w32_palette_entry * entry =
d88c567c 1435 one_w32_display_info.color_list;
fbd6baed 1436 struct w32_palette_entry ** prev =
d88c567c 1437 &one_w32_display_info.color_list;
7d0393cf 1438
5ac45f98
GV
1439 /* check if color is already mapped */
1440 while (entry)
1441 {
fbd6baed 1442 if (W32_COLOR (entry->entry) == XUINT (tem))
5ac45f98
GV
1443 break;
1444 prev = &entry->next;
1445 entry = entry->next;
1446 }
1447
1448 if (entry == NULL && alloc)
1449 {
1450 /* not already mapped, so add to list */
fbd6baed
GV
1451 entry = (struct w32_palette_entry *)
1452 xmalloc (sizeof (struct w32_palette_entry));
1453 SET_W32_COLOR (entry->entry, XUINT (tem));
5ac45f98
GV
1454 entry->next = NULL;
1455 *prev = entry;
d88c567c 1456 one_w32_display_info.num_colors++;
5ac45f98
GV
1457
1458 /* set flag that palette must be regenerated */
d88c567c 1459 one_w32_display_info.regen_palette = TRUE;
5ac45f98
GV
1460 }
1461 }
1462 /* Ensure COLORREF value is snapped to nearest color in (default)
1463 palette by simulating the PALETTERGB macro. This works whether
1464 or not the display device has a palette. */
6fc2811b
JR
1465 w32_color_ref = XUINT (tem) | 0x2000000;
1466
6fc2811b 1467 color_def->pixel = w32_color_ref;
197edd35
JR
1468 color_def->red = GetRValue (w32_color_ref) * 256;
1469 color_def->green = GetGValue (w32_color_ref) * 256;
1470 color_def->blue = GetBValue (w32_color_ref) * 256;
6fc2811b 1471
ee78dc32 1472 return 1;
5ac45f98 1473 }
7d0393cf 1474 else
3c190163
GV
1475 {
1476 return 0;
1477 }
ee78dc32
GV
1478}
1479
1480/* Given a string ARG naming a color, compute a pixel value from it
1481 suitable for screen F.
1482 If F is not a color screen, return DEF (default) regardless of what
1483 ARG says. */
1484
1485int
1486x_decode_color (f, arg, def)
1487 FRAME_PTR f;
1488 Lisp_Object arg;
1489 int def;
1490{
6fc2811b 1491 XColor cdef;
ee78dc32 1492
b7826503 1493 CHECK_STRING (arg);
ee78dc32 1494
d5db4077 1495 if (strcmp (SDATA (arg), "black") == 0)
ee78dc32 1496 return BLACK_PIX_DEFAULT (f);
d5db4077 1497 else if (strcmp (SDATA (arg), "white") == 0)
ee78dc32
GV
1498 return WHITE_PIX_DEFAULT (f);
1499
fbd6baed 1500 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
ee78dc32
GV
1501 return def;
1502
6fc2811b 1503 /* w32_defined_color is responsible for coping with failures
ee78dc32 1504 by looking for a near-miss. */
d5db4077 1505 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
6fc2811b 1506 return cdef.pixel;
ee78dc32
GV
1507
1508 /* defined_color failed; return an ultimate default. */
1509 return def;
1510}
1511\f
6fc2811b
JR
1512
1513
ee78dc32
GV
1514/* Functions called only from `x_set_frame_param'
1515 to set individual parameters.
1516
fbd6baed 1517 If FRAME_W32_WINDOW (f) is 0,
ee78dc32
GV
1518 the frame is being created and its window does not exist yet.
1519 In that case, just record the parameter's new value
1520 in the standard place; do not attempt to change the window. */
1521
1522void
1523x_set_foreground_color (f, arg, oldval)
1524 struct frame *f;
1525 Lisp_Object arg, oldval;
1526{
3cf3436e
JR
1527 struct w32_output *x = f->output_data.w32;
1528 PIX_TYPE fg, old_fg;
1529
1530 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1531 old_fg = FRAME_FOREGROUND_PIXEL (f);
1532 FRAME_FOREGROUND_PIXEL (f) = fg;
5ac45f98 1533
fbd6baed 1534 if (FRAME_W32_WINDOW (f) != 0)
ee78dc32 1535 {
3cf3436e
JR
1536 if (x->cursor_pixel == old_fg)
1537 x->cursor_pixel = fg;
1538
6fc2811b 1539 update_face_from_frame_parameter (f, Qforeground_color, arg);
ee78dc32
GV
1540 if (FRAME_VISIBLE_P (f))
1541 redraw_frame (f);
1542 }
1543}
1544
1545void
1546x_set_background_color (f, arg, oldval)
1547 struct frame *f;
1548 Lisp_Object arg, oldval;
1549{
6fc2811b 1550 FRAME_BACKGROUND_PIXEL (f)
ee78dc32
GV
1551 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1552
fbd6baed 1553 if (FRAME_W32_WINDOW (f) != 0)
ee78dc32 1554 {
6fc2811b
JR
1555 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1556 FRAME_BACKGROUND_PIXEL (f));
ee78dc32 1557
6fc2811b 1558 update_face_from_frame_parameter (f, Qbackground_color, arg);
ee78dc32
GV
1559
1560 if (FRAME_VISIBLE_P (f))
1561 redraw_frame (f);
1562 }
1563}
1564
1565void
1566x_set_mouse_color (f, arg, oldval)
1567 struct frame *f;
1568 Lisp_Object arg, oldval;
1569{
7d63e5e3 1570 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
dfc465d3 1571 int count;
ee78dc32
GV
1572 int mask_color;
1573
1574 if (!EQ (Qnil, arg))
fbd6baed 1575 f->output_data.w32->mouse_pixel
ee78dc32 1576 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
6fc2811b
JR
1577 mask_color = FRAME_BACKGROUND_PIXEL (f);
1578
1579 /* Don't let pointers be invisible. */
fbd6baed 1580 if (mask_color == f->output_data.w32->mouse_pixel
6fc2811b
JR
1581 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1582 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
ee78dc32 1583
767b1ff0 1584#if 0 /* TODO : cursor changes */
ee78dc32
GV
1585 BLOCK_INPUT;
1586
1587 /* It's not okay to crash if the user selects a screwy cursor. */
fadca6c6 1588 count = x_catch_errors (FRAME_W32_DISPLAY (f));
ee78dc32
GV
1589
1590 if (!EQ (Qnil, Vx_pointer_shape))
1591 {
b7826503 1592 CHECK_NUMBER (Vx_pointer_shape);
fbd6baed 1593 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
ee78dc32
GV
1594 }
1595 else
fbd6baed
GV
1596 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1597 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
ee78dc32
GV
1598
1599 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1600 {
b7826503 1601 CHECK_NUMBER (Vx_nontext_pointer_shape);
fbd6baed 1602 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
ee78dc32
GV
1603 XINT (Vx_nontext_pointer_shape));
1604 }
1605 else
fbd6baed
GV
1606 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1607 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
ee78dc32 1608
0af913d7 1609 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
6fc2811b 1610 {
b7826503 1611 CHECK_NUMBER (Vx_hourglass_pointer_shape);
0af913d7
GM
1612 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1613 XINT (Vx_hourglass_pointer_shape));
6fc2811b
JR
1614 }
1615 else
0af913d7 1616 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
6fc2811b 1617 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
7d0393cf 1618
6fc2811b 1619 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
ee78dc32
GV
1620 if (!EQ (Qnil, Vx_mode_pointer_shape))
1621 {
b7826503 1622 CHECK_NUMBER (Vx_mode_pointer_shape);
fbd6baed 1623 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
ee78dc32
GV
1624 XINT (Vx_mode_pointer_shape));
1625 }
1626 else
fbd6baed
GV
1627 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1628 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
ee78dc32
GV
1629
1630 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1631 {
b7826503 1632 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
7d63e5e3 1633 hand_cursor
fbd6baed 1634 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
ee78dc32
GV
1635 XINT (Vx_sensitive_text_pointer_shape));
1636 }
1637 else
7d63e5e3 1638 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
ee78dc32 1639
4694d762
JR
1640 if (!NILP (Vx_window_horizontal_drag_shape))
1641 {
b7826503 1642 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
4694d762
JR
1643 horizontal_drag_cursor
1644 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1645 XINT (Vx_window_horizontal_drag_shape));
1646 }
1647 else
1648 horizontal_drag_cursor
1649 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1650
ee78dc32 1651 /* Check and report errors with the above calls. */
fbd6baed 1652 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
fadca6c6 1653 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
ee78dc32
GV
1654
1655 {
1656 XColor fore_color, back_color;
1657
fbd6baed 1658 fore_color.pixel = f->output_data.w32->mouse_pixel;
ee78dc32 1659 back_color.pixel = mask_color;
fbd6baed
GV
1660 XQueryColor (FRAME_W32_DISPLAY (f),
1661 DefaultColormap (FRAME_W32_DISPLAY (f),
1662 DefaultScreen (FRAME_W32_DISPLAY (f))),
ee78dc32 1663 &fore_color);
fbd6baed
GV
1664 XQueryColor (FRAME_W32_DISPLAY (f),
1665 DefaultColormap (FRAME_W32_DISPLAY (f),
1666 DefaultScreen (FRAME_W32_DISPLAY (f))),
ee78dc32 1667 &back_color);
fbd6baed 1668 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
ee78dc32 1669 &fore_color, &back_color);
fbd6baed 1670 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
ee78dc32 1671 &fore_color, &back_color);
fbd6baed 1672 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
ee78dc32 1673 &fore_color, &back_color);
7d63e5e3 1674 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
ee78dc32 1675 &fore_color, &back_color);
0af913d7 1676 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
6fc2811b 1677 &fore_color, &back_color);
ee78dc32
GV
1678 }
1679
fbd6baed 1680 if (FRAME_W32_WINDOW (f) != 0)
6fc2811b 1681 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
ee78dc32 1682
fbd6baed
GV
1683 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1684 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1685 f->output_data.w32->text_cursor = cursor;
1686
1687 if (nontext_cursor != f->output_data.w32->nontext_cursor
1688 && f->output_data.w32->nontext_cursor != 0)
1689 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1690 f->output_data.w32->nontext_cursor = nontext_cursor;
1691
0af913d7
GM
1692 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1693 && f->output_data.w32->hourglass_cursor != 0)
1694 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1695 f->output_data.w32->hourglass_cursor = hourglass_cursor;
6fc2811b 1696
fbd6baed
GV
1697 if (mode_cursor != f->output_data.w32->modeline_cursor
1698 && f->output_data.w32->modeline_cursor != 0)
1699 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1700 f->output_data.w32->modeline_cursor = mode_cursor;
7d0393cf 1701
7d63e5e3
KS
1702 if (hand_cursor != f->output_data.w32->hand_cursor
1703 && f->output_data.w32->hand_cursor != 0)
1704 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1705 f->output_data.w32->hand_cursor = hand_cursor;
fbd6baed
GV
1706
1707 XFlush (FRAME_W32_DISPLAY (f));
ee78dc32 1708 UNBLOCK_INPUT;
6fc2811b
JR
1709
1710 update_face_from_frame_parameter (f, Qmouse_color, arg);
767b1ff0 1711#endif /* TODO */
ee78dc32
GV
1712}
1713
70a0239a 1714/* Defined in w32term.c. */
ee78dc32
GV
1715void
1716x_set_cursor_color (f, arg, oldval)
1717 struct frame *f;
1718 Lisp_Object arg, oldval;
1719{
70a0239a 1720 unsigned long fore_pixel, pixel;
ee78dc32 1721
dfff8a69 1722 if (!NILP (Vx_cursor_fore_pixel))
ee78dc32 1723 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
70a0239a 1724 WHITE_PIX_DEFAULT (f));
ee78dc32 1725 else
6fc2811b 1726 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
70a0239a 1727
6759f872 1728 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
7d0393cf 1729
ee78dc32 1730 /* Make sure that the cursor color differs from the background color. */
70a0239a 1731 if (pixel == FRAME_BACKGROUND_PIXEL (f))
ee78dc32 1732 {
70a0239a
JR
1733 pixel = f->output_data.w32->mouse_pixel;
1734 if (pixel == fore_pixel)
6fc2811b 1735 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
ee78dc32 1736 }
70a0239a 1737
ac849ba4 1738 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
70a0239a 1739 f->output_data.w32->cursor_pixel = pixel;
ee78dc32 1740
fbd6baed 1741 if (FRAME_W32_WINDOW (f) != 0)
ee78dc32 1742 {
0327b4cc
JR
1743 BLOCK_INPUT;
1744 /* Update frame's cursor_gc. */
1745 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1746 f->output_data.w32->cursor_gc->background = pixel;
1747
1748 UNBLOCK_INPUT;
1749
ee78dc32
GV
1750 if (FRAME_VISIBLE_P (f))
1751 {
70a0239a
JR
1752 x_update_cursor (f, 0);
1753 x_update_cursor (f, 1);
ee78dc32
GV
1754 }
1755 }
6fc2811b
JR
1756
1757 update_face_from_frame_parameter (f, Qcursor_color, arg);
ee78dc32
GV
1758}
1759
33d52f9c
GV
1760/* Set the border-color of frame F to pixel value PIX.
1761 Note that this does not fully take effect if done before
7d0393cf 1762 F has a window. */
6d906347 1763
33d52f9c
GV
1764void
1765x_set_border_pixel (f, pix)
1766 struct frame *f;
1767 int pix;
1768{
6d906347 1769
33d52f9c
GV
1770 f->output_data.w32->border_pixel = pix;
1771
1772 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
1773 {
1774 if (FRAME_VISIBLE_P (f))
1775 redraw_frame (f);
1776 }
1777}
1778
ee78dc32
GV
1779/* Set the border-color of frame F to value described by ARG.
1780 ARG can be a string naming a color.
1781 The border-color is used for the border that is drawn by the server.
1782 Note that this does not fully take effect if done before
1783 F has a window; it must be redone when the window is created. */
1784
1785void
1786x_set_border_color (f, arg, oldval)
1787 struct frame *f;
1788 Lisp_Object arg, oldval;
1789{
ee78dc32
GV
1790 int pix;
1791
b7826503 1792 CHECK_STRING (arg);
ee78dc32 1793 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
ee78dc32 1794 x_set_border_pixel (f, pix);
6fc2811b 1795 update_face_from_frame_parameter (f, Qborder_color, arg);
ee78dc32
GV
1796}
1797
dfff8a69
JR
1798
1799void
1800x_set_cursor_type (f, arg, oldval)
1801 FRAME_PTR f;
1802 Lisp_Object arg, oldval;
1803{
50e363e6 1804 set_frame_cursor_types (f, arg);
ee78dc32 1805
623cdbf2 1806 /* Make sure the cursor gets redrawn. */
c922a224 1807 cursor_type_changed = 1;
ee78dc32 1808}
dfff8a69 1809\f
ee78dc32
GV
1810void
1811x_set_icon_type (f, arg, oldval)
1812 struct frame *f;
1813 Lisp_Object arg, oldval;
1814{
ee78dc32
GV
1815 int result;
1816
eb7576ce
GV
1817 if (NILP (arg) && NILP (oldval))
1818 return;
1819
7d0393cf 1820 if (STRINGP (arg) && STRINGP (oldval)
eb7576ce
GV
1821 && EQ (Fstring_equal (oldval, arg), Qt))
1822 return;
1823
1824 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
ee78dc32
GV
1825 return;
1826
1827 BLOCK_INPUT;
ee78dc32 1828
eb7576ce 1829 result = x_bitmap_icon (f, arg);
ee78dc32
GV
1830 if (result)
1831 {
1832 UNBLOCK_INPUT;
1833 error ("No icon window available");
1834 }
1835
ee78dc32 1836 UNBLOCK_INPUT;
ee78dc32
GV
1837}
1838
ee78dc32
GV
1839void
1840x_set_icon_name (f, arg, oldval)
1841 struct frame *f;
1842 Lisp_Object arg, oldval;
1843{
ee78dc32
GV
1844 if (STRINGP (arg))
1845 {
1846 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1847 return;
1848 }
1849 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
1850 return;
1851
1852 f->icon_name = arg;
1853
1854#if 0
fbd6baed 1855 if (f->output_data.w32->icon_bitmap != 0)
ee78dc32
GV
1856 return;
1857
1858 BLOCK_INPUT;
1859
1860 result = x_text_icon (f,
d5db4077
KR
1861 (char *) SDATA ((!NILP (f->icon_name)
1862 ? f->icon_name
1863 : !NILP (f->title)
1864 ? f->title
1865 : f->name)));
ee78dc32
GV
1866
1867 if (result)
1868 {
1869 UNBLOCK_INPUT;
1870 error ("No icon window available");
1871 }
1872
1873 /* If the window was unmapped (and its icon was mapped),
1874 the new icon is not mapped, so map the window in its stead. */
1875 if (FRAME_VISIBLE_P (f))
1876 {
1877#ifdef USE_X_TOOLKIT
fbd6baed 1878 XtPopup (f->output_data.w32->widget, XtGrabNone);
ee78dc32 1879#endif
fbd6baed 1880 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
ee78dc32
GV
1881 }
1882
fbd6baed 1883 XFlush (FRAME_W32_DISPLAY (f));
ee78dc32
GV
1884 UNBLOCK_INPUT;
1885#endif
1886}
1887
a1258667 1888\f
ee78dc32
GV
1889void
1890x_set_menu_bar_lines (f, value, oldval)
1891 struct frame *f;
1892 Lisp_Object value, oldval;
1893{
1894 int nlines;
1895 int olines = FRAME_MENU_BAR_LINES (f);
1896
1897 /* Right now, menu bars don't work properly in minibuf-only frames;
1898 most of the commands try to apply themselves to the minibuffer
6fc2811b 1899 frame itself, and get an error because you can't switch buffers
ee78dc32
GV
1900 in or split the minibuffer window. */
1901 if (FRAME_MINIBUF_ONLY_P (f))
1902 return;
1903
1904 if (INTEGERP (value))
1905 nlines = XINT (value);
1906 else
1907 nlines = 0;
1908
1909 FRAME_MENU_BAR_LINES (f) = 0;
1910 if (nlines)
1911 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1912 else
1913 {
1914 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1915 free_frame_menubar (f);
1916 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1edf84e7
GV
1917
1918 /* Adjust the frame size so that the client (text) dimensions
1919 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1920 set correctly. */
1921 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
6fc2811b 1922 do_pending_window_change (0);
ee78dc32 1923 }
6fc2811b
JR
1924 adjust_glyphs (f);
1925}
1926
1927
1928/* Set the number of lines used for the tool bar of frame F to VALUE.
1929 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
1930 is the old number of tool bar lines. This function changes the
1931 height of all windows on frame F to match the new tool bar height.
1932 The frame's height doesn't change. */
1933
1934void
1935x_set_tool_bar_lines (f, value, oldval)
1936 struct frame *f;
1937 Lisp_Object value, oldval;
1938{
36f8209a
JR
1939 int delta, nlines, root_height;
1940 Lisp_Object root_window;
6fc2811b 1941
dc220243
JR
1942 /* Treat tool bars like menu bars. */
1943 if (FRAME_MINIBUF_ONLY_P (f))
1944 return;
1945
6fc2811b
JR
1946 /* Use VALUE only if an integer >= 0. */
1947 if (INTEGERP (value) && XINT (value) >= 0)
1948 nlines = XFASTINT (value);
1949 else
1950 nlines = 0;
1951
1952 /* Make sure we redisplay all windows in this frame. */
1953 ++windows_or_buffers_changed;
1954
1955 delta = nlines - FRAME_TOOL_BAR_LINES (f);
36f8209a
JR
1956
1957 /* Don't resize the tool-bar to more than we have room for. */
1958 root_window = FRAME_ROOT_WINDOW (f);
1959 root_height = XINT (XWINDOW (root_window)->height);
1960 if (root_height - delta < 1)
1961 {
1962 delta = root_height - 1;
1963 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
1964 }
1965
6fc2811b 1966 FRAME_TOOL_BAR_LINES (f) = nlines;
6d906347 1967 change_window_heights (root_window, delta);
6fc2811b 1968 adjust_glyphs (f);
36f8209a
JR
1969
1970 /* We also have to make sure that the internal border at the top of
1971 the frame, below the menu bar or tool bar, is redrawn when the
1972 tool bar disappears. This is so because the internal border is
1973 below the tool bar if one is displayed, but is below the menu bar
1974 if there isn't a tool bar. The tool bar draws into the area
1975 below the menu bar. */
1976 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
1977 {
1978 updating_frame = f;
1979 clear_frame ();
1980 clear_current_matrices (f);
1981 updating_frame = NULL;
1982 }
1983
1984 /* If the tool bar gets smaller, the internal border below it
1985 has to be cleared. It was formerly part of the display
1986 of the larger tool bar, and updating windows won't clear it. */
1987 if (delta < 0)
1988 {
1989 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1990 int width = PIXEL_WIDTH (f);
1991 int y = nlines * CANON_Y_UNIT (f);
1992
1993 BLOCK_INPUT;
1994 {
1995 HDC hdc = get_frame_dc (f);
1996 w32_clear_area (f, hdc, 0, y, width, height);
1997 release_frame_dc (f, hdc);
1998 }
1999 UNBLOCK_INPUT;
3cf3436e
JR
2000
2001 if (WINDOWP (f->tool_bar_window))
2002 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
36f8209a 2003 }
ee78dc32
GV
2004}
2005
6fc2811b 2006
ee78dc32 2007/* Change the name of frame F to NAME. If NAME is nil, set F's name to
fbd6baed 2008 w32_id_name.
ee78dc32
GV
2009
2010 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2011 name; if NAME is a string, set F's name to NAME and set
2012 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2013
2014 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2015 suggesting a new name, which lisp code should override; if
2016 F->explicit_name is set, ignore the new name; otherwise, set it. */
2017
2018void
2019x_set_name (f, name, explicit)
2020 struct frame *f;
2021 Lisp_Object name;
2022 int explicit;
2023{
7d0393cf 2024 /* Make sure that requests from lisp code override requests from
ee78dc32
GV
2025 Emacs redisplay code. */
2026 if (explicit)
2027 {
2028 /* If we're switching from explicit to implicit, we had better
2029 update the mode lines and thereby update the title. */
2030 if (f->explicit_name && NILP (name))
2031 update_mode_lines = 1;
2032
2033 f->explicit_name = ! NILP (name);
2034 }
2035 else if (f->explicit_name)
2036 return;
2037
fbd6baed 2038 /* If NAME is nil, set the name to the w32_id_name. */
ee78dc32
GV
2039 if (NILP (name))
2040 {
2041 /* Check for no change needed in this very common case
2042 before we do any consing. */
fbd6baed 2043 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
d5db4077 2044 SDATA (f->name)))
ee78dc32 2045 return;
fbd6baed 2046 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
ee78dc32
GV
2047 }
2048 else
b7826503 2049 CHECK_STRING (name);
ee78dc32
GV
2050
2051 /* Don't change the name if it's already NAME. */
2052 if (! NILP (Fstring_equal (name, f->name)))
2053 return;
2054
1edf84e7
GV
2055 f->name = name;
2056
2057 /* For setting the frame title, the title parameter should override
2058 the name parameter. */
2059 if (! NILP (f->title))
2060 name = f->title;
2061
fbd6baed 2062 if (FRAME_W32_WINDOW (f))
ee78dc32 2063 {
6fc2811b 2064 if (STRING_MULTIBYTE (name))
dfff8a69 2065 name = ENCODE_SYSTEM (name);
6fc2811b 2066
ee78dc32 2067 BLOCK_INPUT;
d5db4077 2068 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
ee78dc32
GV
2069 UNBLOCK_INPUT;
2070 }
ee78dc32
GV
2071}
2072
2073/* This function should be called when the user's lisp code has
2074 specified a name for the frame; the name will override any set by the
2075 redisplay code. */
2076void
2077x_explicitly_set_name (f, arg, oldval)
2078 FRAME_PTR f;
2079 Lisp_Object arg, oldval;
2080{
2081 x_set_name (f, arg, 1);
2082}
2083
2084/* This function should be called by Emacs redisplay code to set the
2085 name; names set this way will never override names set by the user's
2086 lisp code. */
2087void
2088x_implicitly_set_name (f, arg, oldval)
2089 FRAME_PTR f;
2090 Lisp_Object arg, oldval;
2091{
2092 x_set_name (f, arg, 0);
2093}
1edf84e7
GV
2094\f
2095/* Change the title of frame F to NAME.
2096 If NAME is nil, use the frame name as the title.
2097
2098 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2099 name; if NAME is a string, set F's name to NAME and set
2100 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2101
2102 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2103 suggesting a new name, which lisp code should override; if
2104 F->explicit_name is set, ignore the new name; otherwise, set it. */
ee78dc32 2105
1edf84e7 2106void
6fc2811b 2107x_set_title (f, name, old_name)
1edf84e7 2108 struct frame *f;
6fc2811b 2109 Lisp_Object name, old_name;
1edf84e7
GV
2110{
2111 /* Don't change the title if it's already NAME. */
2112 if (EQ (name, f->title))
2113 return;
2114
2115 update_mode_lines = 1;
2116
2117 f->title = name;
2118
2119 if (NILP (name))
2120 name = f->name;
2121
2122 if (FRAME_W32_WINDOW (f))
2123 {
6fc2811b 2124 if (STRING_MULTIBYTE (name))
dfff8a69 2125 name = ENCODE_SYSTEM (name);
6fc2811b 2126
1edf84e7 2127 BLOCK_INPUT;
d5db4077 2128 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
1edf84e7
GV
2129 UNBLOCK_INPUT;
2130 }
2131}
ee78dc32 2132
ee78dc32 2133
6d906347 2134x_set_scroll_bar_default_width (f)
ee78dc32 2135 struct frame *f;
ee78dc32 2136{
6fc2811b
JR
2137 int wid = FONT_WIDTH (f->output_data.w32->font);
2138
6d906347
KS
2139 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2140 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2141 wid - 1) / wid;
ee78dc32 2142}
6d906347 2143
ee78dc32 2144\f
7d0393cf 2145/* Subroutines of creating a frame. */
ee78dc32 2146
ee78dc32
GV
2147
2148/* Return the value of parameter PARAM.
2149
2150 First search ALIST, then Vdefault_frame_alist, then the X defaults
2151 database, using ATTRIBUTE as the attribute name and CLASS as its class.
2152
2153 Convert the resource to the type specified by desired_type.
2154
2155 If no default is specified, return Qunbound. If you call
6fc2811b 2156 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
ee78dc32
GV
2157 and don't let it get stored in any Lisp-visible variables! */
2158
2159static Lisp_Object
6fc2811b 2160w32_get_arg (alist, param, attribute, class, type)
ee78dc32
GV
2161 Lisp_Object alist, param;
2162 char *attribute;
2163 char *class;
2164 enum resource_types type;
2165{
6d906347
KS
2166 return x_get_arg (check_x_display_info (Qnil),
2167 alist, param, attribute, class, type);
ee78dc32
GV
2168}
2169
2170\f
c9b2104d
JR
2171Cursor
2172w32_load_cursor (LPCTSTR name)
2173{
2174 /* Try first to load cursor from application resource. */
2175 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle(NULL),
2176 name, IMAGE_CURSOR, 0, 0,
2177 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2178 if (!cursor)
2179 {
2180 /* Then try to load a shared predefined cursor. */
2181 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
2182 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2183 }
2184 return cursor;
2185}
ee78dc32 2186
fbd6baed 2187extern LRESULT CALLBACK w32_wnd_proc ();
ee78dc32 2188
7d0393cf 2189BOOL
fbd6baed 2190w32_init_class (hinst)
ee78dc32
GV
2191 HINSTANCE hinst;
2192{
2193 WNDCLASS wc;
2194
5ac45f98 2195 wc.style = CS_HREDRAW | CS_VREDRAW;
fbd6baed 2196 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
ee78dc32
GV
2197 wc.cbClsExtra = 0;
2198 wc.cbWndExtra = WND_EXTRA_BYTES;
2199 wc.hInstance = hinst;
2200 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
c9b2104d 2201 wc.hCursor = w32_load_cursor (IDC_ARROW);
4587b026 2202 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
ee78dc32
GV
2203 wc.lpszMenuName = NULL;
2204 wc.lpszClassName = EMACS_CLASS;
2205
2206 return (RegisterClass (&wc));
2207}
2208
7d0393cf 2209HWND
fbd6baed 2210w32_createscrollbar (f, bar)
ee78dc32
GV
2211 struct frame *f;
2212 struct scroll_bar * bar;
2213{
2214 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2215 /* Position and size of scroll bar. */
6fc2811b 2216 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
7d0393cf 2217 XINT(bar->top),
6fc2811b
JR
2218 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
2219 XINT(bar->height),
fbd6baed 2220 FRAME_W32_WINDOW (f),
ee78dc32
GV
2221 NULL,
2222 hinst,
2223 NULL));
2224}
2225
7d0393cf 2226void
fbd6baed 2227w32_createwindow (f)
ee78dc32
GV
2228 struct frame *f;
2229{
2230 HWND hwnd;
1edf84e7
GV
2231 RECT rect;
2232
2233 rect.left = rect.top = 0;
2234 rect.right = PIXEL_WIDTH (f);
2235 rect.bottom = PIXEL_HEIGHT (f);
7d0393cf 2236
1edf84e7
GV
2237 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2238 FRAME_EXTERNAL_MENU_BAR (f));
7d0393cf 2239
ee78dc32 2240 /* Do first time app init */
7d0393cf 2241
ee78dc32
GV
2242 if (!hprevinst)
2243 {
fbd6baed 2244 w32_init_class (hinst);
ee78dc32 2245 }
7d0393cf 2246
1edf84e7
GV
2247 FRAME_W32_WINDOW (f) = hwnd
2248 = CreateWindow (EMACS_CLASS,
2249 f->namebuf,
9ead1b60 2250 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
1edf84e7
GV
2251 f->output_data.w32->left_pos,
2252 f->output_data.w32->top_pos,
2253 rect.right - rect.left,
2254 rect.bottom - rect.top,
2255 NULL,
2256 NULL,
2257 hinst,
2258 NULL);
2259
ee78dc32
GV
2260 if (hwnd)
2261 {
1edf84e7
GV
2262 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
2263 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
2264 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
2265 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
6fc2811b 2266 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
ee78dc32 2267
cb9e33d4
RS
2268 /* Enable drag-n-drop. */
2269 DragAcceptFiles (hwnd, TRUE);
7d0393cf 2270
5ac45f98
GV
2271 /* Do this to discard the default setting specified by our parent. */
2272 ShowWindow (hwnd, SW_HIDE);
3c190163 2273 }
3c190163
GV
2274}
2275
7d0393cf 2276void
ee78dc32 2277my_post_msg (wmsg, hwnd, msg, wParam, lParam)
fbd6baed 2278 W32Msg * wmsg;
ee78dc32
GV
2279 HWND hwnd;
2280 UINT msg;
2281 WPARAM wParam;
2282 LPARAM lParam;
2283{
2284 wmsg->msg.hwnd = hwnd;
2285 wmsg->msg.message = msg;
2286 wmsg->msg.wParam = wParam;
2287 wmsg->msg.lParam = lParam;
2288 wmsg->msg.time = GetMessageTime ();
2289
2290 post_msg (wmsg);
2291}
2292
e9e23e23 2293/* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
a1a80b40
GV
2294 between left and right keys as advertised. We test for this
2295 support dynamically, and set a flag when the support is absent. If
2296 absent, we keep track of the left and right control and alt keys
2297 ourselves. This is particularly necessary on keyboards that rely
2298 upon the AltGr key, which is represented as having the left control
2299 and right alt keys pressed. For these keyboards, we need to know
2300 when the left alt key has been pressed in addition to the AltGr key
2301 so that we can properly support M-AltGr-key sequences (such as M-@
2302 on Swedish keyboards). */
2303
2304#define EMACS_LCONTROL 0
2305#define EMACS_RCONTROL 1
2306#define EMACS_LMENU 2
2307#define EMACS_RMENU 3
2308
2309static int modifiers[4];
2310static int modifiers_recorded;
2311static int modifier_key_support_tested;
2312
2313static void
2314test_modifier_support (unsigned int wparam)
2315{
2316 unsigned int l, r;
2317
2318 if (wparam != VK_CONTROL && wparam != VK_MENU)
2319 return;
2320 if (wparam == VK_CONTROL)
2321 {
2322 l = VK_LCONTROL;
2323 r = VK_RCONTROL;
2324 }
2325 else
2326 {
2327 l = VK_LMENU;
2328 r = VK_RMENU;
2329 }
2330 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2331 modifiers_recorded = 1;
2332 else
2333 modifiers_recorded = 0;
2334 modifier_key_support_tested = 1;
2335}
2336
2337static void
2338record_keydown (unsigned int wparam, unsigned int lparam)
2339{
2340 int i;
2341
2342 if (!modifier_key_support_tested)
2343 test_modifier_support (wparam);
2344
2345 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2346 return;
2347
2348 if (wparam == VK_CONTROL)
2349 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2350 else
2351 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2352
2353 modifiers[i] = 1;
2354}
2355
2356static void
2357record_keyup (unsigned int wparam, unsigned int lparam)
2358{
2359 int i;
2360
2361 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2362 return;
2363
2364 if (wparam == VK_CONTROL)
2365 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2366 else
2367 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2368
2369 modifiers[i] = 0;
2370}
2371
da36a4d6 2372/* Emacs can lose focus while a modifier key has been pressed. When
7d0393cf 2373 it regains focus, be conservative and clear all modifiers since
da36a4d6
GV
2374 we cannot reconstruct the left and right modifier state. */
2375static void
2376reset_modifiers ()
2377{
8681157a
RS
2378 SHORT ctrl, alt;
2379
adcc3809
GV
2380 if (GetFocus () == NULL)
2381 /* Emacs doesn't have keyboard focus. Do nothing. */
da36a4d6 2382 return;
8681157a
RS
2383
2384 ctrl = GetAsyncKeyState (VK_CONTROL);
2385 alt = GetAsyncKeyState (VK_MENU);
2386
8681157a
RS
2387 if (!(ctrl & 0x08000))
2388 /* Clear any recorded control modifier state. */
2389 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2390
2391 if (!(alt & 0x08000))
2392 /* Clear any recorded alt modifier state. */
2393 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2394
adcc3809
GV
2395 /* Update the state of all modifier keys, because modifiers used in
2396 hot-key combinations can get stuck on if Emacs loses focus as a
2397 result of a hot-key being pressed. */
2398 {
2399 BYTE keystate[256];
2400
2401#define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2402
2403 GetKeyboardState (keystate);
2404 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2405 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2406 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2407 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2408 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2409 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2410 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2411 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2412 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2413 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2414 SetKeyboardState (keystate);
2415 }
da36a4d6
GV
2416}
2417
7830e24b
RS
2418/* Synchronize modifier state with what is reported with the current
2419 keystroke. Even if we cannot distinguish between left and right
2420 modifier keys, we know that, if no modifiers are set, then neither
2421 the left or right modifier should be set. */
2422static void
2423sync_modifiers ()
2424{
2425 if (!modifiers_recorded)
2426 return;
2427
7d0393cf 2428 if (!(GetKeyState (VK_CONTROL) & 0x8000))
7830e24b
RS
2429 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2430
7d0393cf 2431 if (!(GetKeyState (VK_MENU) & 0x8000))
7830e24b
RS
2432 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2433}
2434
a1a80b40
GV
2435static int
2436modifier_set (int vkey)
2437{
ccc2d29c 2438 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
891560d6 2439 return (GetKeyState (vkey) & 0x1);
a1a80b40
GV
2440 if (!modifiers_recorded)
2441 return (GetKeyState (vkey) & 0x8000);
2442
2443 switch (vkey)
2444 {
2445 case VK_LCONTROL:
2446 return modifiers[EMACS_LCONTROL];
2447 case VK_RCONTROL:
2448 return modifiers[EMACS_RCONTROL];
2449 case VK_LMENU:
2450 return modifiers[EMACS_LMENU];
2451 case VK_RMENU:
2452 return modifiers[EMACS_RMENU];
a1a80b40
GV
2453 }
2454 return (GetKeyState (vkey) & 0x8000);
2455}
2456
ccc2d29c
GV
2457/* Convert between the modifier bits W32 uses and the modifier bits
2458 Emacs uses. */
2459
2460unsigned int
2461w32_key_to_modifier (int key)
2462{
2463 Lisp_Object key_mapping;
2464
2465 switch (key)
2466 {
2467 case VK_LWIN:
2468 key_mapping = Vw32_lwindow_modifier;
2469 break;
2470 case VK_RWIN:
2471 key_mapping = Vw32_rwindow_modifier;
2472 break;
2473 case VK_APPS:
2474 key_mapping = Vw32_apps_modifier;
2475 break;
2476 case VK_SCROLL:
2477 key_mapping = Vw32_scroll_lock_modifier;
2478 break;
2479 default:
2480 key_mapping = Qnil;
2481 }
2482
adcc3809
GV
2483 /* NB. This code runs in the input thread, asychronously to the lisp
2484 thread, so we must be careful to ensure access to lisp data is
2485 thread-safe. The following code is safe because the modifier
2486 variable values are updated atomically from lisp and symbols are
2487 not relocated by GC. Also, we don't have to worry about seeing GC
2488 markbits here. */
2489 if (EQ (key_mapping, Qhyper))
ccc2d29c 2490 return hyper_modifier;
adcc3809 2491 if (EQ (key_mapping, Qsuper))
ccc2d29c 2492 return super_modifier;
adcc3809 2493 if (EQ (key_mapping, Qmeta))
ccc2d29c 2494 return meta_modifier;
adcc3809 2495 if (EQ (key_mapping, Qalt))
ccc2d29c 2496 return alt_modifier;
adcc3809 2497 if (EQ (key_mapping, Qctrl))
ccc2d29c 2498 return ctrl_modifier;
adcc3809 2499 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
ccc2d29c 2500 return ctrl_modifier;
adcc3809 2501 if (EQ (key_mapping, Qshift))
ccc2d29c
GV
2502 return shift_modifier;
2503
2504 /* Don't generate any modifier if not explicitly requested. */
2505 return 0;
2506}
2507
2508unsigned int
2509w32_get_modifiers ()
2510{
2511 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2512 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2513 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2514 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2515 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2516 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2517 (modifier_set (VK_MENU) ?
2518 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2519}
2520
a1a80b40
GV
2521/* We map the VK_* modifiers into console modifier constants
2522 so that we can use the same routines to handle both console
2523 and window input. */
2524
2525static int
ccc2d29c 2526construct_console_modifiers ()
a1a80b40
GV
2527{
2528 int mods;
2529
a1a80b40
GV
2530 mods = 0;
2531 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2532 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
ccc2d29c
GV
2533 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2534 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
a1a80b40
GV
2535 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2536 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2537 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2538 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
ccc2d29c
GV
2539 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2540 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2541 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
a1a80b40
GV
2542
2543 return mods;
2544}
2545
ccc2d29c
GV
2546static int
2547w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
da36a4d6 2548{
ccc2d29c
GV
2549 int mods;
2550
2551 /* Convert to emacs modifiers. */
2552 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2553
2554 return mods;
2555}
da36a4d6 2556
ccc2d29c
GV
2557unsigned int
2558map_keypad_keys (unsigned int virt_key, unsigned int extended)
2559{
2560 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2561 return virt_key;
da36a4d6 2562
ccc2d29c 2563 if (virt_key == VK_RETURN)
da36a4d6
GV
2564 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2565
ccc2d29c
GV
2566 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2567 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2568
2569 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2570 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2571
2572 if (virt_key == VK_CLEAR)
2573 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2574
2575 return virt_key;
2576}
2577
2578/* List of special key combinations which w32 would normally capture,
2579 but emacs should grab instead. Not directly visible to lisp, to
2580 simplify synchronization. Each item is an integer encoding a virtual
2581 key code and modifier combination to capture. */
2582Lisp_Object w32_grabbed_keys;
2583
2584#define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
2585#define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2586#define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2587#define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2588
2589/* Register hot-keys for reserved key combinations when Emacs has
2590 keyboard focus, since this is the only way Emacs can receive key
2591 combinations like Alt-Tab which are used by the system. */
2592
2593static void
2594register_hot_keys (hwnd)
2595 HWND hwnd;
2596{
2597 Lisp_Object keylist;
2598
2599 /* Use GC_CONSP, since we are called asynchronously. */
2600 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2601 {
2602 Lisp_Object key = XCAR (keylist);
2603
2604 /* Deleted entries get set to nil. */
2605 if (!INTEGERP (key))
2606 continue;
2607
2608 RegisterHotKey (hwnd, HOTKEY_ID (key),
2609 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2610 }
2611}
2612
2613static void
2614unregister_hot_keys (hwnd)
2615 HWND hwnd;
2616{
2617 Lisp_Object keylist;
2618
2619 /* Use GC_CONSP, since we are called asynchronously. */
2620 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2621 {
2622 Lisp_Object key = XCAR (keylist);
2623
2624 if (!INTEGERP (key))
2625 continue;
2626
2627 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2628 }
2629}
2630
5ac45f98
GV
2631/* Main message dispatch loop. */
2632
1edf84e7
GV
2633static void
2634w32_msg_pump (deferred_msg * msg_buf)
5ac45f98
GV
2635{
2636 MSG msg;
ccc2d29c
GV
2637 int result;
2638 HWND focus_window;
93fbe8b7
GV
2639
2640 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
7d0393cf 2641
5ac45f98
GV
2642 while (GetMessage (&msg, NULL, 0, 0))
2643 {
2644 if (msg.hwnd == NULL)
2645 {
2646 switch (msg.message)
2647 {
3ef68e6b
AI
2648 case WM_NULL:
2649 /* Produced by complete_deferred_msg; just ignore. */
2650 break;
5ac45f98 2651 case WM_EMACS_CREATEWINDOW:
fbd6baed 2652 w32_createwindow ((struct frame *) msg.wParam);
1edf84e7
GV
2653 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2654 abort ();
5ac45f98 2655 break;
dfdb4047
GV
2656 case WM_EMACS_SETLOCALE:
2657 SetThreadLocale (msg.wParam);
2658 /* Reply is not expected. */
2659 break;
ccc2d29c
GV
2660 case WM_EMACS_SETKEYBOARDLAYOUT:
2661 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2662 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2663 result, 0))
2664 abort ();
2665 break;
2666 case WM_EMACS_REGISTER_HOT_KEY:
2667 focus_window = GetFocus ();
2668 if (focus_window != NULL)
2669 RegisterHotKey (focus_window,
2670 HOTKEY_ID (msg.wParam),
2671 HOTKEY_MODIFIERS (msg.wParam),
2672 HOTKEY_VK_CODE (msg.wParam));
2673 /* Reply is not expected. */
2674 break;
2675 case WM_EMACS_UNREGISTER_HOT_KEY:
2676 focus_window = GetFocus ();
2677 if (focus_window != NULL)
2678 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
adcc3809
GV
2679 /* Mark item as erased. NB: this code must be
2680 thread-safe. The next line is okay because the cons
2681 cell is never made into garbage and is not relocated by
2682 GC. */
f3fbd155 2683 XSETCAR ((Lisp_Object) msg.lParam, Qnil);
ccc2d29c
GV
2684 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2685 abort ();
2686 break;
adcc3809
GV
2687 case WM_EMACS_TOGGLE_LOCK_KEY:
2688 {
2689 int vk_code = (int) msg.wParam;
2690 int cur_state = (GetKeyState (vk_code) & 1);
2691 Lisp_Object new_state = (Lisp_Object) msg.lParam;
2692
2693 /* NB: This code must be thread-safe. It is safe to
2694 call NILP because symbols are not relocated by GC,
2695 and pointer here is not touched by GC (so the markbit
2696 can't be set). Numbers are safe because they are
2697 immediate values. */
2698 if (NILP (new_state)
2699 || (NUMBERP (new_state)
8edb0a6f 2700 && ((XUINT (new_state)) & 1) != cur_state))
adcc3809
GV
2701 {
2702 one_w32_display_info.faked_key = vk_code;
2703
2704 keybd_event ((BYTE) vk_code,
2705 (BYTE) MapVirtualKey (vk_code, 0),
2706 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2707 keybd_event ((BYTE) vk_code,
2708 (BYTE) MapVirtualKey (vk_code, 0),
2709 KEYEVENTF_EXTENDEDKEY | 0, 0);
2710 keybd_event ((BYTE) vk_code,
2711 (BYTE) MapVirtualKey (vk_code, 0),
2712 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2713 cur_state = !cur_state;
2714 }
2715 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2716 cur_state, 0))
2717 abort ();
2718 }
2719 break;
1edf84e7 2720 default:
1edf84e7 2721 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
5ac45f98
GV
2722 }
2723 }
2724 else
2725 {
2726 DispatchMessage (&msg);
2727 }
1edf84e7
GV
2728
2729 /* Exit nested loop when our deferred message has completed. */
2730 if (msg_buf->completed)
2731 break;
5ac45f98 2732 }
1edf84e7
GV
2733}
2734
2735deferred_msg * deferred_msg_head;
2736
2737static deferred_msg *
2738find_deferred_msg (HWND hwnd, UINT msg)
2739{
2740 deferred_msg * item;
2741
2742 /* Don't actually need synchronization for read access, since
2743 modification of single pointer is always atomic. */
2744 /* enter_crit (); */
2745
2746 for (item = deferred_msg_head; item != NULL; item = item->next)
2747 if (item->w32msg.msg.hwnd == hwnd
2748 && item->w32msg.msg.message == msg)
2749 break;
2750
2751 /* leave_crit (); */
2752
2753 return item;
2754}
2755
2756static LRESULT
2757send_deferred_msg (deferred_msg * msg_buf,
2758 HWND hwnd,
2759 UINT msg,
2760 WPARAM wParam,
2761 LPARAM lParam)
2762{
2763 /* Only input thread can send deferred messages. */
2764 if (GetCurrentThreadId () != dwWindowsThreadId)
2765 abort ();
2766
2767 /* It is an error to send a message that is already deferred. */
2768 if (find_deferred_msg (hwnd, msg) != NULL)
2769 abort ();
2770
2771 /* Enforced synchronization is not needed because this is the only
2772 function that alters deferred_msg_head, and the following critical
2773 section is guaranteed to only be serially reentered (since only the
2774 input thread can call us). */
2775
2776 /* enter_crit (); */
2777
2778 msg_buf->completed = 0;
2779 msg_buf->next = deferred_msg_head;
2780 deferred_msg_head = msg_buf;
2781 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2782
2783 /* leave_crit (); */
2784
2785 /* Start a new nested message loop to process other messages until
2786 this one is completed. */
2787 w32_msg_pump (msg_buf);
2788
2789 deferred_msg_head = msg_buf->next;
2790
2791 return msg_buf->result;
2792}
2793
2794void
2795complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2796{
2797 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2798
2799 if (msg_buf == NULL)
3ef68e6b
AI
2800 /* Message may have been cancelled, so don't abort(). */
2801 return;
1edf84e7
GV
2802
2803 msg_buf->result = result;
2804 msg_buf->completed = 1;
2805
2806 /* Ensure input thread is woken so it notices the completion. */
2807 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2808}
2809
3ef68e6b
AI
2810void
2811cancel_all_deferred_msgs ()
2812{
2813 deferred_msg * item;
2814
2815 /* Don't actually need synchronization for read access, since
2816 modification of single pointer is always atomic. */
2817 /* enter_crit (); */
2818
2819 for (item = deferred_msg_head; item != NULL; item = item->next)
2820 {
2821 item->result = 0;
2822 item->completed = 1;
2823 }
2824
2825 /* leave_crit (); */
2826
2827 /* Ensure input thread is woken so it notices the completion. */
2828 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2829}
1edf84e7 2830
7d0393cf 2831DWORD
1edf84e7
GV
2832w32_msg_worker (dw)
2833 DWORD dw;
2834{
2835 MSG msg;
2836 deferred_msg dummy_buf;
2837
2838 /* Ensure our message queue is created */
7d0393cf 2839
1edf84e7 2840 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
7d0393cf 2841
1edf84e7
GV
2842 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2843 abort ();
2844
2845 memset (&dummy_buf, 0, sizeof (dummy_buf));
2846 dummy_buf.w32msg.msg.hwnd = NULL;
2847 dummy_buf.w32msg.msg.message = WM_NULL;
2848
2849 /* This is the inital message loop which should only exit when the
2850 application quits. */
2851 w32_msg_pump (&dummy_buf);
2852
2853 return 0;
5ac45f98
GV
2854}
2855
3ef68e6b
AI
2856static void
2857post_character_message (hwnd, msg, wParam, lParam, modifiers)
2858 HWND hwnd;
2859 UINT msg;
2860 WPARAM wParam;
2861 LPARAM lParam;
2862 DWORD modifiers;
2863
2864{
2865 W32Msg wmsg;
2866
2867 wmsg.dwModifiers = modifiers;
2868
2869 /* Detect quit_char and set quit-flag directly. Note that we
2870 still need to post a message to ensure the main thread will be
2871 woken up if blocked in sys_select(), but we do NOT want to post
2872 the quit_char message itself (because it will usually be as if
2873 the user had typed quit_char twice). Instead, we post a dummy
2874 message that has no particular effect. */
2875 {
2876 int c = wParam;
2877 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2878 c = make_ctrl_char (c) & 0377;
7d081355
AI
2879 if (c == quit_char
2880 || (wmsg.dwModifiers == 0 &&
2881 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
3ef68e6b
AI
2882 {
2883 Vquit_flag = Qt;
2884
2885 /* The choice of message is somewhat arbitrary, as long as
2886 the main thread handler just ignores it. */
2887 msg = WM_NULL;
2888
2889 /* Interrupt any blocking system calls. */
2890 signal_quit ();
2891
2892 /* As a safety precaution, forcibly complete any deferred
2893 messages. This is a kludge, but I don't see any particularly
2894 clean way to handle the situation where a deferred message is
2895 "dropped" in the lisp thread, and will thus never be
2896 completed, eg. by the user trying to activate the menubar
2897 when the lisp thread is busy, and then typing C-g when the
2898 menubar doesn't open promptly (with the result that the
2899 menubar never responds at all because the deferred
2900 WM_INITMENU message is never completed). Another problem
2901 situation is when the lisp thread calls SendMessage (to send
2902 a window manager command) when a message has been deferred;
2903 the lisp thread gets blocked indefinitely waiting for the
2904 deferred message to be completed, which itself is waiting for
2905 the lisp thread to respond.
2906
2907 Note that we don't want to block the input thread waiting for
2908 a reponse from the lisp thread (although that would at least
2909 solve the deadlock problem above), because we want to be able
2910 to receive C-g to interrupt the lisp thread. */
2911 cancel_all_deferred_msgs ();
2912 }
2913 }
2914
2915 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2916}
2917
ee78dc32
GV
2918/* Main window procedure */
2919
7d0393cf 2920LRESULT CALLBACK
fbd6baed 2921w32_wnd_proc (hwnd, msg, wParam, lParam)
ee78dc32
GV
2922 HWND hwnd;
2923 UINT msg;
2924 WPARAM wParam;
2925 LPARAM lParam;
2926{
2927 struct frame *f;
fbd6baed
GV
2928 struct w32_display_info *dpyinfo = &one_w32_display_info;
2929 W32Msg wmsg;
84fb1139 2930 int windows_translate;
576ba81c 2931 int key;
84fb1139 2932
a6085637
KH
2933 /* Note that it is okay to call x_window_to_frame, even though we are
2934 not running in the main lisp thread, because frame deletion
2935 requires the lisp thread to synchronize with this thread. Thus, if
2936 a frame struct is returned, it can be used without concern that the
2937 lisp thread might make it disappear while we are using it.
2938
2939 NB. Walking the frame list in this thread is safe (as long as
2940 writes of Lisp_Object slots are atomic, which they are on Windows).
2941 Although delete-frame can destructively modify the frame list while
2942 we are walking it, a garbage collection cannot occur until after
2943 delete-frame has synchronized with this thread.
2944
2945 It is also safe to use functions that make GDI calls, such as
fbd6baed 2946 w32_clear_rect, because these functions must obtain a DC handle
a6085637
KH
2947 from the frame struct using get_frame_dc which is thread-aware. */
2948
7d0393cf 2949 switch (msg)
ee78dc32
GV
2950 {
2951 case WM_ERASEBKGND:
a6085637
KH
2952 f = x_window_to_frame (dpyinfo, hwnd);
2953 if (f)
2954 {
9badad41 2955 HDC hdc = get_frame_dc (f);
a6085637 2956 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
9badad41
JR
2957 w32_clear_rect (f, hdc, &wmsg.rect);
2958 release_frame_dc (f, hdc);
ce6059da
AI
2959
2960#if defined (W32_DEBUG_DISPLAY)
18f0b342
AI
2961 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2962 f,
2963 wmsg.rect.left, wmsg.rect.top,
2964 wmsg.rect.right, wmsg.rect.bottom));
ce6059da 2965#endif /* W32_DEBUG_DISPLAY */
a6085637 2966 }
5ac45f98
GV
2967 return 1;
2968 case WM_PALETTECHANGED:
2969 /* ignore our own changes */
2970 if ((HWND)wParam != hwnd)
2971 {
a6085637
KH
2972 f = x_window_to_frame (dpyinfo, hwnd);
2973 if (f)
2974 /* get_frame_dc will realize our palette and force all
2975 frames to be redrawn if needed. */
2976 release_frame_dc (f, get_frame_dc (f));
5ac45f98
GV
2977 }
2978 return 0;
ee78dc32 2979 case WM_PAINT:
ce6059da 2980 {
55dcfc15
AI
2981 PAINTSTRUCT paintStruct;
2982 RECT update_rect;
aa35b6ad 2983 bzero (&update_rect, sizeof (update_rect));
55dcfc15 2984
18f0b342
AI
2985 f = x_window_to_frame (dpyinfo, hwnd);
2986 if (f == 0)
2987 {
2988 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2989 return 0;
2990 }
2991
55dcfc15
AI
2992 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2993 fails. Apparently this can happen under some
2994 circumstances. */
aa35b6ad 2995 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
55dcfc15
AI
2996 {
2997 enter_crit ();
2998 BeginPaint (hwnd, &paintStruct);
2999
aa35b6ad
JR
3000 /* The rectangles returned by GetUpdateRect and BeginPaint
3001 do not always match. Play it safe by assuming both areas
3002 are invalid. */
3003 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
55dcfc15
AI
3004
3005#if defined (W32_DEBUG_DISPLAY)
18f0b342
AI
3006 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
3007 f,
3008 wmsg.rect.left, wmsg.rect.top,
3009 wmsg.rect.right, wmsg.rect.bottom));
3010 DebPrint ((" [update region is %d,%d-%d,%d]\n",
55dcfc15
AI
3011 update_rect.left, update_rect.top,
3012 update_rect.right, update_rect.bottom));
3013#endif
3014 EndPaint (hwnd, &paintStruct);
3015 leave_crit ();
3016
3017 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
7d0393cf 3018
55dcfc15
AI
3019 return 0;
3020 }
c0611964
AI
3021
3022 /* If GetUpdateRect returns 0 (meaning there is no update
3023 region), assume the whole window needs to be repainted. */
3024 GetClientRect(hwnd, &wmsg.rect);
3025 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3026 return 0;
ee78dc32 3027 }
a1a80b40 3028
ccc2d29c
GV
3029 case WM_INPUTLANGCHANGE:
3030 /* Inform lisp thread of keyboard layout changes. */
3031 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3032
3033 /* Clear dead keys in the keyboard state; for simplicity only
3034 preserve modifier key states. */
3035 {
3036 int i;
3037 BYTE keystate[256];
3038
3039 GetKeyboardState (keystate);
3040 for (i = 0; i < 256; i++)
3041 if (1
3042 && i != VK_SHIFT
3043 && i != VK_LSHIFT
3044 && i != VK_RSHIFT
3045 && i != VK_CAPITAL
3046 && i != VK_NUMLOCK
3047 && i != VK_SCROLL
3048 && i != VK_CONTROL
3049 && i != VK_LCONTROL
3050 && i != VK_RCONTROL
3051 && i != VK_MENU
3052 && i != VK_LMENU
3053 && i != VK_RMENU
3054 && i != VK_LWIN
3055 && i != VK_RWIN)
3056 keystate[i] = 0;
3057 SetKeyboardState (keystate);
3058 }
3059 goto dflt;
3060
3061 case WM_HOTKEY:
3062 /* Synchronize hot keys with normal input. */
3063 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3064 return (0);
3065
a1a80b40
GV
3066 case WM_KEYUP:
3067 case WM_SYSKEYUP:
3068 record_keyup (wParam, lParam);
3069 goto dflt;
3070
ee78dc32
GV
3071 case WM_KEYDOWN:
3072 case WM_SYSKEYDOWN:
ccc2d29c
GV
3073 /* Ignore keystrokes we fake ourself; see below. */
3074 if (dpyinfo->faked_key == wParam)
3075 {
3076 dpyinfo->faked_key = 0;
576ba81c
AI
3077 /* Make sure TranslateMessage sees them though (as long as
3078 they don't produce WM_CHAR messages). This ensures that
3079 indicator lights are toggled promptly on Windows 9x, for
3080 example. */
3081 if (lispy_function_keys[wParam] != 0)
3082 {
3083 windows_translate = 1;
3084 goto translate;
3085 }
3086 return 0;
ccc2d29c
GV
3087 }
3088
7830e24b
RS
3089 /* Synchronize modifiers with current keystroke. */
3090 sync_modifiers ();
a1a80b40 3091 record_keydown (wParam, lParam);
ccc2d29c 3092 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
84fb1139
KH
3093
3094 windows_translate = 0;
ccc2d29c
GV
3095
3096 switch (wParam)
3097 {
3098 case VK_LWIN:
3099 if (NILP (Vw32_pass_lwindow_to_system))
3100 {
3101 /* Prevent system from acting on keyup (which opens the
3102 Start menu if no other key was pressed) by simulating a
3103 press of Space which we will ignore. */
3104 if (GetAsyncKeyState (wParam) & 1)
3105 {
adcc3809 3106 if (NUMBERP (Vw32_phantom_key_code))
576ba81c 3107 key = XUINT (Vw32_phantom_key_code) & 255;
adcc3809 3108 else
576ba81c
AI
3109 key = VK_SPACE;
3110 dpyinfo->faked_key = key;
3111 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
ccc2d29c
GV
3112 }
3113 }
3114 if (!NILP (Vw32_lwindow_modifier))
3115 return 0;
3116 break;
3117 case VK_RWIN:
3118 if (NILP (Vw32_pass_rwindow_to_system))
3119 {
3120 if (GetAsyncKeyState (wParam) & 1)
3121 {
adcc3809 3122 if (NUMBERP (Vw32_phantom_key_code))
576ba81c 3123 key = XUINT (Vw32_phantom_key_code) & 255;
adcc3809 3124 else
576ba81c
AI
3125 key = VK_SPACE;
3126 dpyinfo->faked_key = key;
3127 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
ccc2d29c
GV
3128 }
3129 }
3130 if (!NILP (Vw32_rwindow_modifier))
3131 return 0;
3132 break;
576ba81c 3133 case VK_APPS:
ccc2d29c
GV
3134 if (!NILP (Vw32_apps_modifier))
3135 return 0;
3136 break;
3137 case VK_MENU:
7d0393cf 3138 if (NILP (Vw32_pass_alt_to_system))
adcc3809
GV
3139 /* Prevent DefWindowProc from activating the menu bar if an
3140 Alt key is pressed and released by itself. */
ccc2d29c 3141 return 0;
84fb1139 3142 windows_translate = 1;
ccc2d29c 3143 break;
7d0393cf 3144 case VK_CAPITAL:
ccc2d29c
GV
3145 /* Decide whether to treat as modifier or function key. */
3146 if (NILP (Vw32_enable_caps_lock))
3147 goto disable_lock_key;
adcc3809
GV
3148 windows_translate = 1;
3149 break;
ccc2d29c
GV
3150 case VK_NUMLOCK:
3151 /* Decide whether to treat as modifier or function key. */
3152 if (NILP (Vw32_enable_num_lock))
3153 goto disable_lock_key;
adcc3809
GV
3154 windows_translate = 1;
3155 break;
ccc2d29c
GV
3156 case VK_SCROLL:
3157 /* Decide whether to treat as modifier or function key. */
3158 if (NILP (Vw32_scroll_lock_modifier))
3159 goto disable_lock_key;
adcc3809
GV
3160 windows_translate = 1;
3161 break;
ccc2d29c 3162 disable_lock_key:
adcc3809
GV
3163 /* Ensure the appropriate lock key state (and indicator light)
3164 remains in the same state. We do this by faking another
3165 press of the relevant key. Apparently, this really is the
3166 only way to toggle the state of the indicator lights. */
3167 dpyinfo->faked_key = wParam;
3168 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3169 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3170 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3171 KEYEVENTF_EXTENDEDKEY | 0, 0);
3172 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3173 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3174 /* Ensure indicator lights are updated promptly on Windows 9x
3175 (TranslateMessage apparently does this), after forwarding
3176 input event. */
3177 post_character_message (hwnd, msg, wParam, lParam,
3178 w32_get_key_modifiers (wParam, lParam));
3179 windows_translate = 1;
ccc2d29c 3180 break;
7d0393cf 3181 case VK_CONTROL:
ccc2d29c
GV
3182 case VK_SHIFT:
3183 case VK_PROCESSKEY: /* Generated by IME. */
3184 windows_translate = 1;
3185 break;
adcc3809
GV
3186 case VK_CANCEL:
3187 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3188 which is confusing for purposes of key binding; convert
3189 VK_CANCEL events into VK_PAUSE events. */
3190 wParam = VK_PAUSE;
3191 break;
3192 case VK_PAUSE:
3193 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3194 for purposes of key binding; convert these back into
3195 VK_NUMLOCK events, at least when we want to see NumLock key
3196 presses. (Note that there is never any possibility that
3197 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3198 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3199 wParam = VK_NUMLOCK;
3200 break;
ccc2d29c
GV
3201 default:
3202 /* If not defined as a function key, change it to a WM_CHAR message. */
3203 if (lispy_function_keys[wParam] == 0)
3204 {
adcc3809
GV
3205 DWORD modifiers = construct_console_modifiers ();
3206
ccc2d29c
GV
3207 if (!NILP (Vw32_recognize_altgr)
3208 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3209 {
3210 /* Always let TranslateMessage handle AltGr key chords;
3211 for some reason, ToAscii doesn't always process AltGr
3212 chords correctly. */
3213 windows_translate = 1;
3214 }
adcc3809 3215 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
ccc2d29c 3216 {
adcc3809
GV
3217 /* Handle key chords including any modifiers other
3218 than shift directly, in order to preserve as much
3219 modifier information as possible. */
ccc2d29c
GV
3220 if ('A' <= wParam && wParam <= 'Z')
3221 {
3222 /* Don't translate modified alphabetic keystrokes,
3223 so the user doesn't need to constantly switch
3224 layout to type control or meta keystrokes when
3225 the normal layout translates alphabetic
3226 characters to non-ascii characters. */
3227 if (!modifier_set (VK_SHIFT))
3228 wParam += ('a' - 'A');
3229 msg = WM_CHAR;
3230 }
3231 else
3232 {
3233 /* Try to handle other keystrokes by determining the
3234 base character (ie. translating the base key plus
3235 shift modifier). */
3236 int add;
3237 int isdead = 0;
3238 KEY_EVENT_RECORD key;
7d0393cf 3239
ccc2d29c
GV
3240 key.bKeyDown = TRUE;
3241 key.wRepeatCount = 1;
3242 key.wVirtualKeyCode = wParam;
3243 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3244 key.uChar.AsciiChar = 0;
adcc3809 3245 key.dwControlKeyState = modifiers;
ccc2d29c
GV
3246
3247 add = w32_kbd_patch_key (&key);
3248 /* 0 means an unrecognised keycode, negative means
3249 dead key. Ignore both. */
3250 while (--add >= 0)
3251 {
3252 /* Forward asciified character sequence. */
3253 post_character_message
3254 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
3255 w32_get_key_modifiers (wParam, lParam));
3256 w32_kbd_patch_key (&key);
3257 }
3258 return 0;
3259 }
3260 }
3261 else
3262 {
3263 /* Let TranslateMessage handle everything else. */
3264 windows_translate = 1;
3265 }
3266 }
3267 }
a1a80b40 3268
adcc3809 3269 translate:
84fb1139
KH
3270 if (windows_translate)
3271 {
e9e23e23 3272 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
84fb1139 3273
e9e23e23
GV
3274 windows_msg.time = GetMessageTime ();
3275 TranslateMessage (&windows_msg);
84fb1139
KH
3276 goto dflt;
3277 }
3278
ee78dc32 3279 /* Fall through */
7d0393cf 3280
ee78dc32
GV
3281 case WM_SYSCHAR:
3282 case WM_CHAR:
ccc2d29c
GV
3283 post_character_message (hwnd, msg, wParam, lParam,
3284 w32_get_key_modifiers (wParam, lParam));
ee78dc32 3285 break;
da36a4d6 3286
5ac45f98
GV
3287 /* Simulate middle mouse button events when left and right buttons
3288 are used together, but only if user has two button mouse. */
ee78dc32 3289 case WM_LBUTTONDOWN:
5ac45f98 3290 case WM_RBUTTONDOWN:
7ce9aaca 3291 if (XINT (Vw32_num_mouse_buttons) > 2)
5ac45f98
GV
3292 goto handle_plain_button;
3293
3294 {
3295 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3296 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3297
3cb20f4a
RS
3298 if (button_state & this)
3299 return 0;
5ac45f98
GV
3300
3301 if (button_state == 0)
3302 SetCapture (hwnd);
3303
3304 button_state |= this;
3305
3306 if (button_state & other)
3307 {
84fb1139 3308 if (mouse_button_timer)
5ac45f98 3309 {
84fb1139
KH
3310 KillTimer (hwnd, mouse_button_timer);
3311 mouse_button_timer = 0;
5ac45f98
GV
3312
3313 /* Generate middle mouse event instead. */
3314 msg = WM_MBUTTONDOWN;
3315 button_state |= MMOUSE;
3316 }
3317 else if (button_state & MMOUSE)
3318 {
3319 /* Ignore button event if we've already generated a
3320 middle mouse down event. This happens if the
3321 user releases and press one of the two buttons
3322 after we've faked a middle mouse event. */
3323 return 0;
3324 }
3325 else
3326 {
3327 /* Flush out saved message. */
84fb1139 3328 post_msg (&saved_mouse_button_msg);
5ac45f98 3329 }
fbd6baed 3330 wmsg.dwModifiers = w32_get_modifiers ();
5ac45f98
GV
3331 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3332
3333 /* Clear message buffer. */
84fb1139 3334 saved_mouse_button_msg.msg.hwnd = 0;
5ac45f98
GV
3335 }
3336 else
3337 {
3338 /* Hold onto message for now. */
84fb1139 3339 mouse_button_timer =
adcc3809
GV
3340 SetTimer (hwnd, MOUSE_BUTTON_ID,
3341 XINT (Vw32_mouse_button_tolerance), NULL);
84fb1139
KH
3342 saved_mouse_button_msg.msg.hwnd = hwnd;
3343 saved_mouse_button_msg.msg.message = msg;
3344 saved_mouse_button_msg.msg.wParam = wParam;
3345 saved_mouse_button_msg.msg.lParam = lParam;
3346 saved_mouse_button_msg.msg.time = GetMessageTime ();
fbd6baed 3347 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
5ac45f98
GV
3348 }
3349 }
3350 return 0;
3351
ee78dc32 3352 case WM_LBUTTONUP:
5ac45f98 3353 case WM_RBUTTONUP:
7ce9aaca 3354 if (XINT (Vw32_num_mouse_buttons) > 2)
5ac45f98
GV
3355 goto handle_plain_button;
3356
3357 {
3358 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3359 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3360
3cb20f4a
RS
3361 if ((button_state & this) == 0)
3362 return 0;
5ac45f98
GV
3363
3364 button_state &= ~this;
3365
3366 if (button_state & MMOUSE)
3367 {
3368 /* Only generate event when second button is released. */
3369 if ((button_state & other) == 0)
3370 {
3371 msg = WM_MBUTTONUP;
3372 button_state &= ~MMOUSE;
3373
3374 if (button_state) abort ();
3375 }
3376 else
3377 return 0;
3378 }
3379 else
3380 {
3381 /* Flush out saved message if necessary. */
84fb1139 3382 if (saved_mouse_button_msg.msg.hwnd)
5ac45f98 3383 {
84fb1139 3384 post_msg (&saved_mouse_button_msg);
5ac45f98
GV
3385 }
3386 }
fbd6baed 3387 wmsg.dwModifiers = w32_get_modifiers ();
5ac45f98
GV
3388 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3389
3390 /* Always clear message buffer and cancel timer. */
84fb1139
KH
3391 saved_mouse_button_msg.msg.hwnd = 0;
3392 KillTimer (hwnd, mouse_button_timer);
3393 mouse_button_timer = 0;
5ac45f98
GV
3394
3395 if (button_state == 0)
3396 ReleaseCapture ();
3397 }
3398 return 0;
3399
74214547
JR
3400 case WM_XBUTTONDOWN:
3401 case WM_XBUTTONUP:
3402 if (w32_pass_extra_mouse_buttons_to_system)
3403 goto dflt;
3404 /* else fall through and process them. */
ee78dc32
GV
3405 case WM_MBUTTONDOWN:
3406 case WM_MBUTTONUP:
5ac45f98 3407 handle_plain_button:
ee78dc32
GV
3408 {
3409 BOOL up;
1edf84e7 3410 int button;
ee78dc32 3411
74214547 3412 if (parse_button (msg, HIWORD (wParam), &button, &up))
ee78dc32
GV
3413 {
3414 if (up) ReleaseCapture ();
3415 else SetCapture (hwnd);
7d0393cf 3416 button = (button == 0) ? LMOUSE :
1edf84e7
GV
3417 ((button == 1) ? MMOUSE : RMOUSE);
3418 if (up)
3419 button_state &= ~button;
3420 else
3421 button_state |= button;
ee78dc32
GV
3422 }
3423 }
7d0393cf 3424
fbd6baed 3425 wmsg.dwModifiers = w32_get_modifiers ();
ee78dc32 3426 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
74214547
JR
3427
3428 /* Need to return true for XBUTTON messages, false for others,
3429 to indicate that we processed the message. */
3430 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
5ac45f98 3431
5ac45f98 3432 case WM_MOUSEMOVE:
9eb16b62
JR
3433 /* If the mouse has just moved into the frame, start tracking
3434 it, so we will be notified when it leaves the frame. Mouse
3435 tracking only works under W98 and NT4 and later. On earlier
3436 versions, there is no way of telling when the mouse leaves the
3437 frame, so we just have to put up with help-echo and mouse
3438 highlighting remaining while the frame is not active. */
3439 if (track_mouse_event_fn && !track_mouse_window)
3440 {
3441 TRACKMOUSEEVENT tme;
3442 tme.cbSize = sizeof (tme);
3443 tme.dwFlags = TME_LEAVE;
3444 tme.hwndTrack = hwnd;
3445
3446 track_mouse_event_fn (&tme);
3447 track_mouse_window = hwnd;
3448 }
3449 case WM_VSCROLL:
fbd6baed 3450 if (XINT (Vw32_mouse_move_interval) <= 0
84fb1139
KH
3451 || (msg == WM_MOUSEMOVE && button_state == 0))
3452 {
fbd6baed 3453 wmsg.dwModifiers = w32_get_modifiers ();
84fb1139
KH
3454 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3455 return 0;
3456 }
7d0393cf 3457
84fb1139
KH
3458 /* Hang onto mouse move and scroll messages for a bit, to avoid
3459 sending such events to Emacs faster than it can process them.
3460 If we get more events before the timer from the first message
3461 expires, we just replace the first message. */
3462
3463 if (saved_mouse_move_msg.msg.hwnd == 0)
3464 mouse_move_timer =
adcc3809
GV
3465 SetTimer (hwnd, MOUSE_MOVE_ID,
3466 XINT (Vw32_mouse_move_interval), NULL);
84fb1139
KH
3467
3468 /* Hold onto message for now. */
3469 saved_mouse_move_msg.msg.hwnd = hwnd;
3470 saved_mouse_move_msg.msg.message = msg;
3471 saved_mouse_move_msg.msg.wParam = wParam;
3472 saved_mouse_move_msg.msg.lParam = lParam;
3473 saved_mouse_move_msg.msg.time = GetMessageTime ();
fbd6baed 3474 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
7d0393cf 3475
84fb1139
KH
3476 return 0;
3477
1edf84e7
GV
3478 case WM_MOUSEWHEEL:
3479 wmsg.dwModifiers = w32_get_modifiers ();
3480 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3481 return 0;
3482
cb9e33d4
RS
3483 case WM_DROPFILES:
3484 wmsg.dwModifiers = w32_get_modifiers ();
3485 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3486 return 0;
3487
84fb1139
KH
3488 case WM_TIMER:
3489 /* Flush out saved messages if necessary. */
3490 if (wParam == mouse_button_timer)
5ac45f98 3491 {
84fb1139
KH
3492 if (saved_mouse_button_msg.msg.hwnd)
3493 {
3494 post_msg (&saved_mouse_button_msg);
3495 saved_mouse_button_msg.msg.hwnd = 0;
3496 }
3497 KillTimer (hwnd, mouse_button_timer);
3498 mouse_button_timer = 0;
3499 }
3500 else if (wParam == mouse_move_timer)
3501 {
3502 if (saved_mouse_move_msg.msg.hwnd)
3503 {
3504 post_msg (&saved_mouse_move_msg);
3505 saved_mouse_move_msg.msg.hwnd = 0;
3506 }
3507 KillTimer (hwnd, mouse_move_timer);
3508 mouse_move_timer = 0;
5ac45f98 3509 }
48094ace
JR
3510 else if (wParam == menu_free_timer)
3511 {
3512 KillTimer (hwnd, menu_free_timer);
3513 menu_free_timer = 0;
27605fa7 3514 f = x_window_to_frame (dpyinfo, hwnd);
48094ace
JR
3515 if (!f->output_data.w32->menu_command_in_progress)
3516 {
3517 /* Free memory used by owner-drawn and help-echo strings. */
3518 w32_free_menu_strings (hwnd);
3519 f->output_data.w32->menubar_active = 0;
3520 }
3521 }
5ac45f98 3522 return 0;
7d0393cf 3523
84fb1139
KH
3524 case WM_NCACTIVATE:
3525 /* Windows doesn't send us focus messages when putting up and
e9e23e23 3526 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
84fb1139
KH
3527 The only indication we get that something happened is receiving
3528 this message afterwards. So this is a good time to reset our
3529 keyboard modifiers' state. */
3530 reset_modifiers ();
3531 goto dflt;
da36a4d6 3532
1edf84e7 3533 case WM_INITMENU:
487163ac
AI
3534 button_state = 0;
3535 ReleaseCapture ();
1edf84e7
GV
3536 /* We must ensure menu bar is fully constructed and up to date
3537 before allowing user interaction with it. To achieve this
3538 we send this message to the lisp thread and wait for a
3539 reply (whose value is not actually needed) to indicate that
3540 the menu bar is now ready for use, so we can now return.
3541
3542 To remain responsive in the meantime, we enter a nested message
3543 loop that can process all other messages.
3544
3545 However, we skip all this if the message results from calling
3546 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3547 thread a message because it is blocked on us at this point. We
3548 set menubar_active before calling TrackPopupMenu to indicate
3549 this (there is no possibility of confusion with real menubar
3550 being active). */
3551
3552 f = x_window_to_frame (dpyinfo, hwnd);
3553 if (f
3554 && (f->output_data.w32->menubar_active
3555 /* We can receive this message even in the absence of a
3556 menubar (ie. when the system menu is activated) - in this
3557 case we do NOT want to forward the message, otherwise it
3558 will cause the menubar to suddenly appear when the user
3559 had requested it to be turned off! */
3560 || f->output_data.w32->menubar_widget == NULL))
3561 return 0;
3562
3563 {
3564 deferred_msg msg_buf;
3565
3566 /* Detect if message has already been deferred; in this case
3567 we cannot return any sensible value to ignore this. */
3568 if (find_deferred_msg (hwnd, msg) != NULL)
3569 abort ();
3570
3571 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3572 }
3573
3574 case WM_EXITMENULOOP:
3575 f = x_window_to_frame (dpyinfo, hwnd);
3576
48094ace
JR
3577 /* If a menu command is not already in progress, check again
3578 after a short delay, since Windows often (always?) sends the
3579 WM_EXITMENULOOP before the corresponding WM_COMMAND message. */
3580 if (f && !f->output_data.w32->menu_command_in_progress)
3581 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
1edf84e7
GV
3582 goto dflt;
3583
126f2e35 3584 case WM_MENUSELECT:
4e3a1c61
JR
3585 /* Direct handling of help_echo in menus. Should be safe now
3586 that we generate the help_echo by placing a help event in the
3587 keyboard buffer. */
ca56d953 3588 {
ca56d953
JR
3589 HMENU menu = (HMENU) lParam;
3590 UINT menu_item = (UINT) LOWORD (wParam);
3591 UINT flags = (UINT) HIWORD (wParam);
3592
4e3a1c61 3593 w32_menu_display_help (hwnd, menu, menu_item, flags);
ca56d953 3594 }
126f2e35
JR
3595 return 0;
3596
87996783
GV
3597 case WM_MEASUREITEM:
3598 f = x_window_to_frame (dpyinfo, hwnd);
3599 if (f)
3600 {
3601 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3602
3603 if (pMis->CtlType == ODT_MENU)
3604 {
3605 /* Work out dimensions for popup menu titles. */
3606 char * title = (char *) pMis->itemData;
3607 HDC hdc = GetDC (hwnd);
3608 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3609 LOGFONT menu_logfont;
3610 HFONT old_font;
3611 SIZE size;
3612
3613 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3614 menu_logfont.lfWeight = FW_BOLD;
3615 menu_font = CreateFontIndirect (&menu_logfont);
3616 old_font = SelectObject (hdc, menu_font);
3617
dfff8a69
JR
3618 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3619 if (title)
3620 {
3621 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3622 pMis->itemWidth = size.cx;
3623 if (pMis->itemHeight < size.cy)
3624 pMis->itemHeight = size.cy;
3625 }
3626 else
3627 pMis->itemWidth = 0;
87996783
GV
3628
3629 SelectObject (hdc, old_font);
3630 DeleteObject (menu_font);
3631 ReleaseDC (hwnd, hdc);
3632 return TRUE;
3633 }
3634 }
3635 return 0;
3636
3637 case WM_DRAWITEM:
3638 f = x_window_to_frame (dpyinfo, hwnd);
3639 if (f)
3640 {
3641 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3642
3643 if (pDis->CtlType == ODT_MENU)
3644 {
3645 /* Draw popup menu title. */
3646 char * title = (char *) pDis->itemData;
212da13b
JR
3647 if (title)
3648 {
3649 HDC hdc = pDis->hDC;
3650 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3651 LOGFONT menu_logfont;
3652 HFONT old_font;
3653
3654 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3655 menu_logfont.lfWeight = FW_BOLD;
3656 menu_font = CreateFontIndirect (&menu_logfont);
3657 old_font = SelectObject (hdc, menu_font);
3658
3659 /* Always draw title as if not selected. */
3660 ExtTextOut (hdc,
3661 pDis->rcItem.left
3662 + GetSystemMetrics (SM_CXMENUCHECK),
3663 pDis->rcItem.top,
3664 ETO_OPAQUE, &pDis->rcItem,
3665 title, strlen (title), NULL);
3666
3667 SelectObject (hdc, old_font);
3668 DeleteObject (menu_font);
3669 }
87996783
GV
3670 return TRUE;
3671 }
3672 }
3673 return 0;
3674
1edf84e7
GV
3675#if 0
3676 /* Still not right - can't distinguish between clicks in the
3677 client area of the frame from clicks forwarded from the scroll
3678 bars - may have to hook WM_NCHITTEST to remember the mouse
3679 position and then check if it is in the client area ourselves. */
3680 case WM_MOUSEACTIVATE:
3681 /* Discard the mouse click that activates a frame, allowing the
3682 user to click anywhere without changing point (or worse!).
3683 Don't eat mouse clicks on scrollbars though!! */
3684 if (LOWORD (lParam) == HTCLIENT )
3685 return MA_ACTIVATEANDEAT;
3686 goto dflt;
3687#endif
3688
9eb16b62
JR
3689 case WM_MOUSELEAVE:
3690 /* No longer tracking mouse. */
3691 track_mouse_window = NULL;
3692
1edf84e7 3693 case WM_ACTIVATEAPP:
ccc2d29c 3694 case WM_ACTIVATE:
1edf84e7
GV
3695 case WM_WINDOWPOSCHANGED:
3696 case WM_SHOWWINDOW:
3697 /* Inform lisp thread that a frame might have just been obscured
3698 or exposed, so should recheck visibility of all frames. */
3699 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3700 goto dflt;
3701
da36a4d6 3702 case WM_SETFOCUS:
adcc3809
GV
3703 dpyinfo->faked_key = 0;
3704 reset_modifiers ();
ccc2d29c
GV
3705 register_hot_keys (hwnd);
3706 goto command;
8681157a 3707 case WM_KILLFOCUS:
ccc2d29c 3708 unregister_hot_keys (hwnd);
487163ac
AI
3709 button_state = 0;
3710 ReleaseCapture ();
65906840
JR
3711 /* Relinquish the system caret. */
3712 if (w32_system_caret_hwnd)
3713 {
93f2ca61 3714 w32_visible_system_caret_hwnd = NULL;
d285988b
JR
3715 w32_system_caret_hwnd = NULL;
3716 DestroyCaret ();
65906840 3717 }
48094ace
JR
3718 goto command;
3719 case WM_COMMAND:
3720 f = x_window_to_frame (dpyinfo, hwnd);
3721 if (f && HIWORD (wParam) == 0)
3722 {
3723 f->output_data.w32->menu_command_in_progress = 1;
3724 if (menu_free_timer)
3725 {
3726 KillTimer (hwnd, menu_free_timer);
7d0393cf 3727 menu_free_timer = 0;
48094ace
JR
3728 }
3729 }
ee78dc32
GV
3730 case WM_MOVE:
3731 case WM_SIZE:
ccc2d29c 3732 command:
fbd6baed 3733 wmsg.dwModifiers = w32_get_modifiers ();
ee78dc32
GV
3734 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3735 goto dflt;
8847d890
RS
3736
3737 case WM_CLOSE:
fbd6baed 3738 wmsg.dwModifiers = w32_get_modifiers ();
8847d890
RS
3739 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3740 return 0;
3741
ee78dc32 3742 case WM_WINDOWPOSCHANGING:
bfd6edcc
JR
3743 /* Don't restrict the sizing of tip frames. */
3744 if (hwnd == tip_window)
3745 return 0;
ee78dc32
GV
3746 {
3747 WINDOWPLACEMENT wp;
3748 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
1edf84e7
GV
3749
3750 wp.length = sizeof (WINDOWPLACEMENT);
ee78dc32 3751 GetWindowPlacement (hwnd, &wp);
7d0393cf 3752
1edf84e7 3753 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
ee78dc32
GV
3754 {
3755 RECT rect;
3756 int wdiff;
3757 int hdiff;
1edf84e7
GV
3758 DWORD font_width;
3759 DWORD line_height;
3760 DWORD internal_border;
3761 DWORD scrollbar_extra;
ee78dc32 3762 RECT wr;
7d0393cf 3763
5ac45f98 3764 wp.length = sizeof(wp);
ee78dc32 3765 GetWindowRect (hwnd, &wr);
7d0393cf 3766
3c190163 3767 enter_crit ();
7d0393cf 3768
1edf84e7
GV
3769 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3770 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3771 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3772 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
7d0393cf 3773
3c190163 3774 leave_crit ();
7d0393cf 3775
ee78dc32 3776 memset (&rect, 0, sizeof (rect));
7d0393cf 3777 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
ee78dc32
GV
3778 GetMenu (hwnd) != NULL);
3779
1edf84e7
GV
3780 /* Force width and height of client area to be exact
3781 multiples of the character cell dimensions. */
3782 wdiff = (lppos->cx - (rect.right - rect.left)
3783 - 2 * internal_border - scrollbar_extra)
3784 % font_width;
3785 hdiff = (lppos->cy - (rect.bottom - rect.top)
3786 - 2 * internal_border)
3787 % line_height;
7d0393cf 3788
ee78dc32
GV
3789 if (wdiff || hdiff)
3790 {
7d0393cf
JB
3791 /* For right/bottom sizing we can just fix the sizes.
3792 However for top/left sizing we will need to fix the X
ee78dc32 3793 and Y positions as well. */
7d0393cf 3794
ee78dc32
GV
3795 lppos->cx -= wdiff;
3796 lppos->cy -= hdiff;
7d0393cf
JB
3797
3798 if (wp.showCmd != SW_SHOWMAXIMIZED
1edf84e7 3799 && (lppos->flags & SWP_NOMOVE) == 0)
ee78dc32
GV
3800 {
3801 if (lppos->x != wr.left || lppos->y != wr.top)
3802 {
3803 lppos->x += wdiff;
3804 lppos->y += hdiff;
3805 }
3806 else
3807 {
3808 lppos->flags |= SWP_NOMOVE;
3809 }
3810 }
7d0393cf 3811
1edf84e7 3812 return 0;
ee78dc32
GV
3813 }
3814 }
3815 }
7d0393cf 3816
ee78dc32 3817 goto dflt;
1edf84e7 3818
b1f918f8
GV
3819 case WM_GETMINMAXINFO:
3820 /* Hack to correct bug that allows Emacs frames to be resized
3821 below the Minimum Tracking Size. */
3822 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
bf853fee
AI
3823 /* Hack to allow resizing the Emacs frame above the screen size.
3824 Note that Windows 9x limits coordinates to 16-bits. */
3825 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3826 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
b1f918f8
GV
3827 return 0;
3828
c9b2104d
JR
3829 case WM_SETCURSOR:
3830 if (LOWORD (lParam) == HTCLIENT)
3831 return 0;
3832
3833 goto dflt;
c922a224 3834
c9b2104d
JR
3835 case WM_EMACS_SETCURSOR:
3836 {
3837 Cursor cursor = (Cursor) wParam;
3838 if (cursor)
3839 SetCursor (cursor);
3840 return 0;
3841 }
c922a224 3842
1edf84e7
GV
3843 case WM_EMACS_CREATESCROLLBAR:
3844 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3845 (struct scroll_bar *) lParam);
3846
5ac45f98 3847 case WM_EMACS_SHOWWINDOW:
1edf84e7
GV
3848 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3849
dfdb4047 3850 case WM_EMACS_SETFOREGROUND:
ce6059da
AI
3851 {
3852 HWND foreground_window;
3853 DWORD foreground_thread, retval;
3854
3855 /* On NT 5.0, and apparently Windows 98, it is necessary to
3856 attach to the thread that currently has focus in order to
3857 pull the focus away from it. */
3858 foreground_window = GetForegroundWindow ();
3859 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3860 if (!foreground_window
3861 || foreground_thread == GetCurrentThreadId ()
3862 || !AttachThreadInput (GetCurrentThreadId (),
3863 foreground_thread, TRUE))
3864 foreground_thread = 0;
3865
3866 retval = SetForegroundWindow ((HWND) wParam);
3867
3868 /* Detach from the previous foreground thread. */
3869 if (foreground_thread)
3870 AttachThreadInput (GetCurrentThreadId (),
3871 foreground_thread, FALSE);
3872
3873 return retval;
3874 }
dfdb4047 3875
5ac45f98
GV
3876 case WM_EMACS_SETWINDOWPOS:
3877 {
1edf84e7
GV
3878 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3879 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5ac45f98
GV
3880 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3881 }
1edf84e7 3882
ee78dc32 3883 case WM_EMACS_DESTROYWINDOW:
cb9e33d4 3884 DragAcceptFiles ((HWND) wParam, FALSE);
1edf84e7
GV
3885 return DestroyWindow ((HWND) wParam);
3886
93f2ca61
JR
3887 case WM_EMACS_HIDE_CARET:
3888 return HideCaret (hwnd);
3889
3890 case WM_EMACS_SHOW_CARET:
3891 return ShowCaret (hwnd);
3892
65906840
JR
3893 case WM_EMACS_DESTROY_CARET:
3894 w32_system_caret_hwnd = NULL;
93f2ca61 3895 w32_visible_system_caret_hwnd = NULL;
65906840
JR
3896 return DestroyCaret ();
3897
3898 case WM_EMACS_TRACK_CARET:
3899 /* If there is currently no system caret, create one. */
3900 if (w32_system_caret_hwnd == NULL)
3901 {
93f2ca61
JR
3902 /* Use the default caret width, and avoid changing it
3903 unneccesarily, as it confuses screen reader software. */
65906840 3904 w32_system_caret_hwnd = hwnd;
93f2ca61 3905 CreateCaret (hwnd, NULL, 0,
65906840
JR
3906 w32_system_caret_height);
3907 }
7d0393cf 3908
93f2ca61
JR
3909 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3910 return 0;
3911 /* Ensure visible caret gets turned on when requested. */
3912 else if (w32_use_visible_system_caret
3913 && w32_visible_system_caret_hwnd != hwnd)
3914 {
3915 w32_visible_system_caret_hwnd = hwnd;
3916 return ShowCaret (hwnd);
3917 }
3918 /* Ensure visible caret gets turned off when requested. */
3919 else if (!w32_use_visible_system_caret
3920 && w32_visible_system_caret_hwnd)
3921 {
3922 w32_visible_system_caret_hwnd = NULL;
3923 return HideCaret (hwnd);
3924 }
3925 else
3926 return 1;
65906840 3927
1edf84e7
GV
3928 case WM_EMACS_TRACKPOPUPMENU:
3929 {
3930 UINT flags;
3931 POINT *pos;
3932 int retval;
3933 pos = (POINT *)lParam;
3934 flags = TPM_CENTERALIGN;
3935 if (button_state & LMOUSE)
3936 flags |= TPM_LEFTBUTTON;
3937 else if (button_state & RMOUSE)
3938 flags |= TPM_RIGHTBUTTON;
7d0393cf 3939
87996783
GV
3940 /* Remember we did a SetCapture on the initial mouse down event,
3941 so for safety, we make sure the capture is cancelled now. */
3942 ReleaseCapture ();
490822ff 3943 button_state = 0;
87996783 3944
1edf84e7
GV
3945 /* Use menubar_active to indicate that WM_INITMENU is from
3946 TrackPopupMenu below, and should be ignored. */
3947 f = x_window_to_frame (dpyinfo, hwnd);
3948 if (f)
3949 f->output_data.w32->menubar_active = 1;
7d0393cf
JB
3950
3951 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
1edf84e7
GV
3952 0, hwnd, NULL))
3953 {
3954 MSG amsg;
3955 /* Eat any mouse messages during popupmenu */
3956 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
3957 PM_REMOVE));
3958 /* Get the menu selection, if any */
3959 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
3960 {
3961 retval = LOWORD (amsg.wParam);
3962 }
3963 else
3964 {
3965 retval = 0;
3966 }
1edf84e7
GV
3967 }
3968 else
3969 {
3970 retval = -1;
3971 }
3972
3973 return retval;
3974 }
3975
ee78dc32 3976 default:
93fbe8b7
GV
3977 /* Check for messages registered at runtime. */
3978 if (msg == msh_mousewheel)
3979 {
3980 wmsg.dwModifiers = w32_get_modifiers ();
3981 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3982 return 0;
3983 }
7d0393cf 3984
ee78dc32
GV
3985 dflt:
3986 return DefWindowProc (hwnd, msg, wParam, lParam);
3987 }
7d0393cf 3988
1edf84e7
GV
3989
3990 /* The most common default return code for handled messages is 0. */
3991 return 0;
ee78dc32
GV
3992}
3993
7d0393cf 3994void
ee78dc32
GV
3995my_create_window (f)
3996 struct frame * f;
3997{
3998 MSG msg;
3999
1edf84e7
GV
4000 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4001 abort ();
ee78dc32
GV
4002 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4003}
4004
ca56d953
JR
4005
4006/* Create a tooltip window. Unlike my_create_window, we do not do this
4007 indirectly via the Window thread, as we do not need to process Window
4008 messages for the tooltip. Creating tooltips indirectly also creates
4009 deadlocks when tooltips are created for menu items. */
7d0393cf 4010void
ca56d953
JR
4011my_create_tip_window (f)
4012 struct frame *f;
4013{
bfd6edcc 4014 RECT rect;
ca56d953 4015
bfd6edcc
JR
4016 rect.left = rect.top = 0;
4017 rect.right = PIXEL_WIDTH (f);
4018 rect.bottom = PIXEL_HEIGHT (f);
4019
4020 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4021 FRAME_EXTERNAL_MENU_BAR (f));
4022
4023 tip_window = FRAME_W32_WINDOW (f)
ca56d953
JR
4024 = CreateWindow (EMACS_CLASS,
4025 f->namebuf,
4026 f->output_data.w32->dwStyle,
4027 f->output_data.w32->left_pos,
4028 f->output_data.w32->top_pos,
bfd6edcc
JR
4029 rect.right - rect.left,
4030 rect.bottom - rect.top,
ca56d953
JR
4031 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4032 NULL,
4033 hinst,
4034 NULL);
4035
bfd6edcc 4036 if (tip_window)
ca56d953 4037 {
bfd6edcc
JR
4038 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
4039 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
4040 SetWindowLong (tip_window, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
4041 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4042
4043 /* Tip frames have no scrollbars. */
4044 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
ca56d953
JR
4045
4046 /* Do this to discard the default setting specified by our parent. */
bfd6edcc 4047 ShowWindow (tip_window, SW_HIDE);
ca56d953
JR
4048 }
4049}
4050
4051
fbd6baed 4052/* Create and set up the w32 window for frame F. */
ee78dc32
GV
4053
4054static void
fbd6baed 4055w32_window (f, window_prompting, minibuffer_only)
ee78dc32
GV
4056 struct frame *f;
4057 long window_prompting;
4058 int minibuffer_only;
4059{
4060 BLOCK_INPUT;
4061
4062 /* Use the resource name as the top-level window name
4063 for looking up resources. Make a non-Lisp copy
4064 for the window manager, so GC relocation won't bother it.
4065
4066 Elsewhere we specify the window name for the window manager. */
7d0393cf 4067
ee78dc32 4068 {
d5db4077 4069 char *str = (char *) SDATA (Vx_resource_name);
ee78dc32
GV
4070 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4071 strcpy (f->namebuf, str);
4072 }
4073
4074 my_create_window (f);
4075
4076 validate_x_resource_name ();
4077
4078 /* x_set_name normally ignores requests to set the name if the
4079 requested name is the same as the current name. This is the one
4080 place where that assumption isn't correct; f->name is set, but
4081 the server hasn't been told. */
4082 {
4083 Lisp_Object name;
4084 int explicit = f->explicit_name;
4085
4086 f->explicit_name = 0;
4087 name = f->name;
4088 f->name = Qnil;
4089 x_set_name (f, name, explicit);
4090 }
4091
4092 UNBLOCK_INPUT;
4093
4094 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4095 initialize_frame_menubar (f);
4096
fbd6baed 4097 if (FRAME_W32_WINDOW (f) == 0)
ee78dc32
GV
4098 error ("Unable to create window");
4099}
4100
4101/* Handle the icon stuff for this window. Perhaps later we might
4102 want an x_set_icon_position which can be called interactively as
4103 well. */
4104
4105static void
4106x_icon (f, parms)
4107 struct frame *f;
4108 Lisp_Object parms;
4109{
4110 Lisp_Object icon_x, icon_y;
4111
e9e23e23 4112 /* Set the position of the icon. Note that Windows 95 groups all
ee78dc32 4113 icons in the tray. */
6fc2811b
JR
4114 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4115 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
ee78dc32
GV
4116 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4117 {
b7826503
PJ
4118 CHECK_NUMBER (icon_x);
4119 CHECK_NUMBER (icon_y);
ee78dc32
GV
4120 }
4121 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4122 error ("Both left and top icon corners of icon must be specified");
4123
4124 BLOCK_INPUT;
4125
4126 if (! EQ (icon_x, Qunbound))
4127 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4128
1edf84e7
GV
4129#if 0 /* TODO */
4130 /* Start up iconic or window? */
4131 x_wm_set_window_state
6fc2811b 4132 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
1edf84e7
GV
4133 ? IconicState
4134 : NormalState));
4135
d5db4077 4136 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
1edf84e7 4137 ? f->icon_name
d5db4077 4138 : f->name)));
1edf84e7
GV
4139#endif
4140
ee78dc32
GV
4141 UNBLOCK_INPUT;
4142}
4143
6fc2811b
JR
4144
4145static void
4146x_make_gc (f)
4147 struct frame *f;
4148{
4149 XGCValues gc_values;
4150
4151 BLOCK_INPUT;
4152
4153 /* Create the GC's of this frame.
4154 Note that many default values are used. */
4155
4156 /* Normal video */
4157 gc_values.font = f->output_data.w32->font;
4158
4159 /* Cursor has cursor-color background, background-color foreground. */
4160 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4161 gc_values.background = f->output_data.w32->cursor_pixel;
4162 f->output_data.w32->cursor_gc
4163 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4164 (GCFont | GCForeground | GCBackground),
4165 &gc_values);
4166
4167 /* Reliefs. */
4168 f->output_data.w32->white_relief.gc = 0;
4169 f->output_data.w32->black_relief.gc = 0;
4170
4171 UNBLOCK_INPUT;
4172}
4173
4174
937e601e
AI
4175/* Handler for signals raised during x_create_frame and
4176 x_create_top_frame. FRAME is the frame which is partially
4177 constructed. */
4178
4179static Lisp_Object
4180unwind_create_frame (frame)
4181 Lisp_Object frame;
4182{
4183 struct frame *f = XFRAME (frame);
4184
4185 /* If frame is ``official'', nothing to do. */
4186 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
4187 {
4188#ifdef GLYPH_DEBUG
4189 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4190#endif
7d0393cf 4191
937e601e
AI
4192 x_free_frame_resources (f);
4193
4194 /* Check that reference counts are indeed correct. */
4195 xassert (dpyinfo->reference_count == dpyinfo_refcount);
4196 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
c844a81a
GM
4197
4198 return Qt;
937e601e 4199 }
7d0393cf 4200
937e601e
AI
4201 return Qnil;
4202}
4203
4204
ee78dc32
GV
4205DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4206 1, 1, 0,
74e1aeec
JR
4207 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4208Returns an Emacs frame object.
4209ALIST is an alist of frame parameters.
4210If the parameters specify that the frame should not have a minibuffer,
4211and do not specify a specific minibuffer window to use,
4212then `default-minibuffer-frame' must be a frame whose minibuffer can
4213be shared by the new frame.
4214
4215This function is an internal primitive--use `make-frame' instead. */)
ee78dc32
GV
4216 (parms)
4217 Lisp_Object parms;
4218{
4219 struct frame *f;
4220 Lisp_Object frame, tem;
4221 Lisp_Object name;
4222 int minibuffer_only = 0;
4223 long window_prompting = 0;
4224 int width, height;
331379bf 4225 int count = SPECPDL_INDEX ();
1edf84e7 4226 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
ee78dc32 4227 Lisp_Object display;
6fc2811b 4228 struct w32_display_info *dpyinfo = NULL;
ee78dc32
GV
4229 Lisp_Object parent;
4230 struct kboard *kb;
4231
4587b026
GV
4232 check_w32 ();
4233
ee78dc32
GV
4234 /* Use this general default value to start with
4235 until we know if this frame has a specified name. */
4236 Vx_resource_name = Vinvocation_name;
4237
6fc2811b 4238 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
ee78dc32
GV
4239 if (EQ (display, Qunbound))
4240 display = Qnil;
4241 dpyinfo = check_x_display_info (display);
4242#ifdef MULTI_KBOARD
4243 kb = dpyinfo->kboard;
4244#else
4245 kb = &the_only_kboard;
4246#endif
4247
6fc2811b 4248 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
ee78dc32
GV
4249 if (!STRINGP (name)
4250 && ! EQ (name, Qunbound)
4251 && ! NILP (name))
4252 error ("Invalid frame name--not a string or nil");
4253
4254 if (STRINGP (name))
4255 Vx_resource_name = name;
4256
4257 /* See if parent window is specified. */
6fc2811b 4258 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
ee78dc32
GV
4259 if (EQ (parent, Qunbound))
4260 parent = Qnil;
4261 if (! NILP (parent))
b7826503 4262 CHECK_NUMBER (parent);
ee78dc32 4263
1edf84e7
GV
4264 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4265 /* No need to protect DISPLAY because that's not used after passing
4266 it to make_frame_without_minibuffer. */
4267 frame = Qnil;
4268 GCPRO4 (parms, parent, name, frame);
1660f34a
JR
4269 tem = w32_get_arg (parms, Qminibuffer, "minibuffer", "Minibuffer",
4270 RES_TYPE_SYMBOL);
ee78dc32
GV
4271 if (EQ (tem, Qnone) || NILP (tem))
4272 f = make_frame_without_minibuffer (Qnil, kb, display);
4273 else if (EQ (tem, Qonly))
4274 {
4275 f = make_minibuffer_frame ();
4276 minibuffer_only = 1;
4277 }
4278 else if (WINDOWP (tem))
4279 f = make_frame_without_minibuffer (tem, kb, display);
4280 else
4281 f = make_frame (1);
4282
1edf84e7
GV
4283 XSETFRAME (frame, f);
4284
ee78dc32
GV
4285 /* Note that Windows does support scroll bars. */
4286 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
6d906347 4287
5ac45f98
GV
4288 /* By default, make scrollbars the system standard width. */
4289 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
ee78dc32 4290
fbd6baed 4291 f->output_method = output_w32;
6fc2811b
JR
4292 f->output_data.w32 =
4293 (struct w32_output *) xmalloc (sizeof (struct w32_output));
fbd6baed 4294 bzero (f->output_data.w32, sizeof (struct w32_output));
4587b026 4295 FRAME_FONTSET (f) = -1;
937e601e 4296 record_unwind_protect (unwind_create_frame, frame);
4587b026 4297
1edf84e7 4298 f->icon_name
6fc2811b 4299 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
1edf84e7
GV
4300 if (! STRINGP (f->icon_name))
4301 f->icon_name = Qnil;
4302
fbd6baed 4303/* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
ee78dc32
GV
4304#ifdef MULTI_KBOARD
4305 FRAME_KBOARD (f) = kb;
4306#endif
4307
4308 /* Specify the parent under which to make this window. */
4309
4310 if (!NILP (parent))
4311 {
1660f34a 4312 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
fbd6baed 4313 f->output_data.w32->explicit_parent = 1;
ee78dc32
GV
4314 }
4315 else
4316 {
fbd6baed
GV
4317 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4318 f->output_data.w32->explicit_parent = 0;
ee78dc32
GV
4319 }
4320
ee78dc32
GV
4321 /* Set the name; the functions to which we pass f expect the name to
4322 be set. */
4323 if (EQ (name, Qunbound) || NILP (name))
4324 {
fbd6baed 4325 f->name = build_string (dpyinfo->w32_id_name);
ee78dc32
GV
4326 f->explicit_name = 0;
4327 }
4328 else
4329 {
4330 f->name = name;
4331 f->explicit_name = 1;
4332 /* use the frame's title when getting resources for this frame. */
4333 specbind (Qx_resource_name, name);
4334 }
4335
4336 /* Extract the window parameters from the supplied values
4337 that are needed to determine window geometry. */
4338 {
4339 Lisp_Object font;
4340
6fc2811b
JR
4341 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
4342
ee78dc32
GV
4343 BLOCK_INPUT;
4344 /* First, try whatever font the caller has specified. */
4345 if (STRINGP (font))
4587b026
GV
4346 {
4347 tem = Fquery_fontset (font, Qnil);
4348 if (STRINGP (tem))
d5db4077 4349 font = x_new_fontset (f, SDATA (tem));
4587b026 4350 else
d5db4077 4351 font = x_new_font (f, SDATA (font));
4587b026 4352 }
ee78dc32
GV
4353 /* Try out a font which we hope has bold and italic variations. */
4354 if (!STRINGP (font))
e39649be 4355 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
ee78dc32 4356 if (! STRINGP (font))
6fc2811b 4357 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
ee78dc32
GV
4358 /* If those didn't work, look for something which will at least work. */
4359 if (! STRINGP (font))
6fc2811b 4360 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
ee78dc32
GV
4361 UNBLOCK_INPUT;
4362 if (! STRINGP (font))
1edf84e7 4363 font = build_string ("Fixedsys");
ee78dc32 4364
7d0393cf 4365 x_default_parameter (f, parms, Qfont, font,
6fc2811b 4366 "font", "Font", RES_TYPE_STRING);
ee78dc32
GV
4367 }
4368
4369 x_default_parameter (f, parms, Qborder_width, make_number (2),
1660f34a 4370 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
ee78dc32
GV
4371 /* This defaults to 2 in order to match xterm. We recognize either
4372 internalBorderWidth or internalBorder (which is what xterm calls
4373 it). */
4374 if (NILP (Fassq (Qinternal_border_width, parms)))
4375 {
4376 Lisp_Object value;
4377
6fc2811b 4378 value = w32_get_arg (parms, Qinternal_border_width,
1660f34a 4379 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
ee78dc32
GV
4380 if (! EQ (value, Qunbound))
4381 parms = Fcons (Fcons (Qinternal_border_width, value),
4382 parms);
4383 }
1edf84e7 4384 /* Default internalBorderWidth to 0 on Windows to match other programs. */
ee78dc32 4385 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
1660f34a
JR
4386 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4387 x_default_parameter (f, parms, Qvertical_scroll_bars, Qright,
4388 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
ee78dc32
GV
4389
4390 /* Also do the stuff which must be set before the window exists. */
4391 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6fc2811b 4392 "foreground", "Foreground", RES_TYPE_STRING);
ee78dc32 4393 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6fc2811b 4394 "background", "Background", RES_TYPE_STRING);
ee78dc32 4395 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6fc2811b 4396 "pointerColor", "Foreground", RES_TYPE_STRING);
ee78dc32 4397 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6fc2811b 4398 "cursorColor", "Foreground", RES_TYPE_STRING);
ee78dc32 4399 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6fc2811b
JR
4400 "borderColor", "BorderColor", RES_TYPE_STRING);
4401 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
4402 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
dfff8a69
JR
4403 x_default_parameter (f, parms, Qline_spacing, Qnil,
4404 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
41c1bdd9
KS
4405 x_default_parameter (f, parms, Qleft_fringe, Qnil,
4406 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4407 x_default_parameter (f, parms, Qright_fringe, Qnil,
4408 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
6fc2811b 4409
ee78dc32 4410
6fc2811b
JR
4411 /* Init faces before x_default_parameter is called for scroll-bar
4412 parameters because that function calls x_set_scroll_bar_width,
4413 which calls change_frame_size, which calls Fset_window_buffer,
4414 which runs hooks, which call Fvertical_motion. At the end, we
4415 end up in init_iterator with a null face cache, which should not
4416 happen. */
4417 init_frame_faces (f);
7d0393cf 4418
ee78dc32 4419 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
6fc2811b 4420 "menuBar", "MenuBar", RES_TYPE_NUMBER);
d3109773 4421 x_default_parameter (f, parms, Qtool_bar_lines, make_number (1),
6fc2811b 4422 "toolBar", "ToolBar", RES_TYPE_NUMBER);
919f1e88 4423
1edf84e7 4424 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
6fc2811b 4425 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
1edf84e7 4426 x_default_parameter (f, parms, Qtitle, Qnil,
6fc2811b 4427 "title", "Title", RES_TYPE_STRING);
f7b9d4d1
JR
4428 x_default_parameter (f, parms, Qfullscreen, Qnil,
4429 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
ee78dc32 4430
fbd6baed
GV
4431 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4432 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
3cf3436e 4433
c9b2104d
JR
4434 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4435 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4436 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
7d63e5e3 4437 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
c9b2104d
JR
4438 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4439 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
c9b2104d 4440
6d906347 4441 window_prompting = x_figure_window_size (f, parms, 1);
ee78dc32 4442
6fc2811b
JR
4443 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4444 f->no_split = minibuffer_only || EQ (tem, Qt);
4445
fbd6baed 4446 w32_window (f, window_prompting, minibuffer_only);
ee78dc32 4447 x_icon (f, parms);
6fc2811b
JR
4448
4449 x_make_gc (f);
4450
4451 /* Now consider the frame official. */
4452 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
4453 Vframe_list = Fcons (frame, Vframe_list);
ee78dc32
GV
4454
4455 /* We need to do this after creating the window, so that the
4456 icon-creation functions can say whose icon they're describing. */
4457 x_default_parameter (f, parms, Qicon_type, Qnil,
6fc2811b 4458 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
ee78dc32
GV
4459
4460 x_default_parameter (f, parms, Qauto_raise, Qnil,
6fc2811b 4461 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
ee78dc32 4462 x_default_parameter (f, parms, Qauto_lower, Qnil,
6fc2811b 4463 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
ee78dc32 4464 x_default_parameter (f, parms, Qcursor_type, Qbox,
6fc2811b
JR
4465 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4466 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
4467 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
ee78dc32
GV
4468
4469 /* Dimensions, especially f->height, must be done via change_frame_size.
4470 Change will not be effected unless different from the current
4471 f->height. */
4472 width = f->width;
4473 height = f->height;
dc220243 4474
1026b400
RS
4475 f->height = 0;
4476 SET_FRAME_WIDTH (f, 0);
6fc2811b
JR
4477 change_frame_size (f, height, width, 1, 0, 0);
4478
6fc2811b
JR
4479 /* Tell the server what size and position, etc, we want, and how
4480 badly we want them. This should be done after we have the menu
4481 bar so that its size can be taken into account. */
ee78dc32
GV
4482 BLOCK_INPUT;
4483 x_wm_set_size_hint (f, window_prompting, 0);
4484 UNBLOCK_INPUT;
4485
815d969e
JR
4486 /* Avoid a bug that causes the new frame to never become visible if
4487 an echo area message is displayed during the following call1. */
4488 specbind(Qredisplay_dont_pause, Qt);
4489
4694d762
JR
4490 /* Set up faces after all frame parameters are known. This call
4491 also merges in face attributes specified for new frames. If we
4492 don't do this, the `menu' face for instance won't have the right
4493 colors, and the menu bar won't appear in the specified colors for
4494 new frames. */
4495 call1 (Qface_set_after_frame_default, frame);
4496
6fc2811b
JR
4497 /* Make the window appear on the frame and enable display, unless
4498 the caller says not to. However, with explicit parent, Emacs
4499 cannot control visibility, so don't try. */
fbd6baed 4500 if (! f->output_data.w32->explicit_parent)
ee78dc32
GV
4501 {
4502 Lisp_Object visibility;
4503
6fc2811b 4504 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
ee78dc32
GV
4505 if (EQ (visibility, Qunbound))
4506 visibility = Qt;
4507
4508 if (EQ (visibility, Qicon))
4509 x_iconify_frame (f);
4510 else if (! NILP (visibility))
4511 x_make_frame_visible (f);
4512 else
4513 /* Must have been Qnil. */
4514 ;
4515 }
6fc2811b 4516 UNGCPRO;
7d0393cf 4517
9e57df62
GM
4518 /* Make sure windows on this frame appear in calls to next-window
4519 and similar functions. */
4520 Vwindow_list = Qnil;
7d0393cf 4521
ee78dc32
GV
4522 return unbind_to (count, frame);
4523}
4524
4525/* FRAME is used only to get a handle on the X display. We don't pass the
4526 display info directly because we're called from frame.c, which doesn't
4527 know about that structure. */
4528Lisp_Object
4529x_get_focus_frame (frame)
4530 struct frame *frame;
4531{
fbd6baed 4532 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
ee78dc32 4533 Lisp_Object xfocus;
fbd6baed 4534 if (! dpyinfo->w32_focus_frame)
ee78dc32
GV
4535 return Qnil;
4536
fbd6baed 4537 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
ee78dc32
GV
4538 return xfocus;
4539}
1edf84e7
GV
4540
4541DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
74e1aeec 4542 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
1edf84e7
GV
4543 (frame)
4544 Lisp_Object frame;
4545{
4546 x_focus_on_frame (check_x_frame (frame));
4547 return Qnil;
4548}
4549
ee78dc32 4550\f
767b1ff0
JR
4551/* Return the charset portion of a font name. */
4552char * xlfd_charset_of_font (char * fontname)
4553{
4554 char *charset, *encoding;
4555
4556 encoding = strrchr(fontname, '-');
ceb12877 4557 if (!encoding || encoding == fontname)
767b1ff0
JR
4558 return NULL;
4559
478ea067
AI
4560 for (charset = encoding - 1; charset >= fontname; charset--)
4561 if (*charset == '-')
4562 break;
767b1ff0 4563
478ea067 4564 if (charset == fontname || strcmp(charset, "-*-*") == 0)
767b1ff0
JR
4565 return NULL;
4566
4567 return charset + 1;
4568}
4569
33d52f9c
GV
4570struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
4571 int size, char* filename);
8edb0a6f 4572static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
c7501041
EZ
4573static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
4574 char * charset);
4575static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
33d52f9c 4576
8edb0a6f 4577static struct font_info *
33d52f9c 4578w32_load_system_font (f,fontname,size)
55dcfc15
AI
4579 struct frame *f;
4580 char * fontname;
4581 int size;
ee78dc32 4582{
4587b026
GV
4583 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4584 Lisp_Object font_names;
4585
4587b026
GV
4586 /* Get a list of all the fonts that match this name. Once we
4587 have a list of matching fonts, we compare them against the fonts
4588 we already have loaded by comparing names. */
4589 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
4590
4591 if (!NILP (font_names))
3c190163 4592 {
4587b026
GV
4593 Lisp_Object tail;
4594 int i;
4587b026
GV
4595
4596 /* First check if any are already loaded, as that is cheaper
4597 than loading another one. */
4598 for (i = 0; i < dpyinfo->n_fonts; i++)
8e713be6 4599 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
6fc2811b
JR
4600 if (dpyinfo->font_table[i].name
4601 && (!strcmp (dpyinfo->font_table[i].name,
d5db4077 4602 SDATA (XCAR (tail)))
6fc2811b 4603 || !strcmp (dpyinfo->font_table[i].full_name,
d5db4077 4604 SDATA (XCAR (tail)))))
4587b026 4605 return (dpyinfo->font_table + i);
6fc2811b 4606
d5db4077 4607 fontname = (char *) SDATA (XCAR (font_names));
4587b026 4608 }
1075afa9 4609 else if (w32_strict_fontnames)
5ca0cd71
GV
4610 {
4611 /* If EnumFontFamiliesEx was available, we got a full list of
4612 fonts back so stop now to avoid the possibility of loading a
4613 random font. If we had to fall back to EnumFontFamilies, the
4614 list is incomplete, so continue whether the font we want was
4615 listed or not. */
4616 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
4617 FARPROC enum_font_families_ex
1075afa9 4618 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5ca0cd71
GV
4619 if (enum_font_families_ex)
4620 return NULL;
4621 }
4587b026
GV
4622
4623 /* Load the font and add it to the table. */
4624 {
767b1ff0 4625 char *full_name, *encoding, *charset;
4587b026
GV
4626 XFontStruct *font;
4627 struct font_info *fontp;
3c190163 4628 LOGFONT lf;
4587b026 4629 BOOL ok;
19c291d3 4630 int codepage;
6fc2811b 4631 int i;
5ac45f98 4632
4587b026 4633 if (!fontname || !x_to_w32_font (fontname, &lf))
3c190163 4634 return (NULL);
5ac45f98 4635
4587b026
GV
4636 if (!*lf.lfFaceName)
4637 /* If no name was specified for the font, we get a random font
4638 from CreateFontIndirect - this is not particularly
4639 desirable, especially since CreateFontIndirect does not
4640 fill out the missing name in lf, so we never know what we
4641 ended up with. */
4642 return NULL;
4643
c8d88d08 4644 lf.lfQuality = DEFAULT_QUALITY;
d65a9cdc 4645
3c190163 4646 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
c6be3860 4647 bzero (font, sizeof (*font));
5ac45f98 4648
33d52f9c
GV
4649 /* Set bdf to NULL to indicate that this is a Windows font. */
4650 font->bdf = NULL;
5ac45f98 4651
3c190163 4652 BLOCK_INPUT;
5ac45f98
GV
4653
4654 font->hfont = CreateFontIndirect (&lf);
ee78dc32 4655
7d0393cf 4656 if (font->hfont == NULL)
1a292d24
AI
4657 {
4658 ok = FALSE;
7d0393cf
JB
4659 }
4660 else
1a292d24
AI
4661 {
4662 HDC hdc;
4663 HANDLE oldobj;
19c291d3
AI
4664
4665 codepage = w32_codepage_for_font (fontname);
1a292d24
AI
4666
4667 hdc = GetDC (dpyinfo->root_window);
4668 oldobj = SelectObject (hdc, font->hfont);
5c6682be 4669
1a292d24 4670 ok = GetTextMetrics (hdc, &font->tm);
5c6682be
JR
4671 if (codepage == CP_UNICODE)
4672 font->double_byte_p = 1;
4673 else
8b77111c
AI
4674 {
4675 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
4676 don't report themselves as double byte fonts, when
4677 patently they are. So instead of trusting
4678 GetFontLanguageInfo, we check the properties of the
4679 codepage directly, since that is ultimately what we are
4680 working from anyway. */
4681 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
4682 CPINFO cpi = {0};
4683 GetCPInfo (codepage, &cpi);
4684 font->double_byte_p = cpi.MaxCharSize > 1;
4685 }
5c6682be 4686
1a292d24
AI
4687 SelectObject (hdc, oldobj);
4688 ReleaseDC (dpyinfo->root_window, hdc);
6fc2811b
JR
4689 /* Fill out details in lf according to the font that was
4690 actually loaded. */
4691 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
4692 lf.lfWidth = font->tm.tmAveCharWidth;
4693 lf.lfWeight = font->tm.tmWeight;
4694 lf.lfItalic = font->tm.tmItalic;
4695 lf.lfCharSet = font->tm.tmCharSet;
4696 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
d88c567c 4697 ? VARIABLE_PITCH : FIXED_PITCH);
6fc2811b
JR
4698 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
4699 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
c6be3860
AI
4700
4701 w32_cache_char_metrics (font);
1a292d24 4702 }
5ac45f98 4703
1a292d24 4704 UNBLOCK_INPUT;
5ac45f98 4705
4587b026
GV
4706 if (!ok)
4707 {
1a292d24
AI
4708 w32_unload_font (dpyinfo, font);
4709 return (NULL);
4710 }
ee78dc32 4711
6fc2811b
JR
4712 /* Find a free slot in the font table. */
4713 for (i = 0; i < dpyinfo->n_fonts; ++i)
4714 if (dpyinfo->font_table[i].name == NULL)
4715 break;
4716
4717 /* If no free slot found, maybe enlarge the font table. */
4718 if (i == dpyinfo->n_fonts
4719 && dpyinfo->n_fonts == dpyinfo->font_table_size)
4587b026 4720 {
6fc2811b
JR
4721 int sz;
4722 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
4723 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
4587b026 4724 dpyinfo->font_table
6fc2811b 4725 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
4587b026
GV
4726 }
4727
6fc2811b
JR
4728 fontp = dpyinfo->font_table + i;
4729 if (i == dpyinfo->n_fonts)
4730 ++dpyinfo->n_fonts;
4587b026
GV
4731
4732 /* Now fill in the slots of *FONTP. */
4733 BLOCK_INPUT;
4734 fontp->font = font;
6fc2811b 4735 fontp->font_idx = i;
4587b026
GV
4736 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
4737 bcopy (fontname, fontp->name, strlen (fontname) + 1);
4738
767b1ff0
JR
4739 charset = xlfd_charset_of_font (fontname);
4740
19c291d3
AI
4741 /* Cache the W32 codepage for a font. This makes w32_encode_char
4742 (called for every glyph during redisplay) much faster. */
4743 fontp->codepage = codepage;
4744
4587b026
GV
4745 /* Work out the font's full name. */
4746 full_name = (char *)xmalloc (100);
767b1ff0 4747 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
4587b026
GV
4748 fontp->full_name = full_name;
4749 else
4750 {
4751 /* If all else fails - just use the name we used to load it. */
4752 xfree (full_name);
4753 fontp->full_name = fontp->name;
4754 }
4755
4756 fontp->size = FONT_WIDTH (font);
4757 fontp->height = FONT_HEIGHT (font);
4758
4759 /* The slot `encoding' specifies how to map a character
4760 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
126f2e35
JR
4761 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
4762 (0:0x20..0x7F, 1:0xA0..0xFF,
4763 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
4587b026 4764 2:0xA020..0xFF7F). For the moment, we don't know which charset
6fc2811b 4765 uses this font. So, we set information in fontp->encoding[1]
4587b026
GV
4766 which is never used by any charset. If mapping can't be
4767 decided, set FONT_ENCODING_NOT_DECIDED. */
33d52f9c
GV
4768
4769 /* SJIS fonts need to be set to type 4, all others seem to work as
4770 type FONT_ENCODING_NOT_DECIDED. */
4771 encoding = strrchr (fontp->name, '-');
d84b082d 4772 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
1c885fe1 4773 fontp->encoding[1] = 4;
33d52f9c 4774 else
1c885fe1 4775 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
4587b026
GV
4776
4777 /* The following three values are set to 0 under W32, which is
4778 what they get set to if XGetFontProperty fails under X. */
4779 fontp->baseline_offset = 0;
4780 fontp->relative_compose = 0;
33d52f9c 4781 fontp->default_ascent = 0;
4587b026 4782
6fc2811b
JR
4783 /* Set global flag fonts_changed_p to non-zero if the font loaded
4784 has a character with a smaller width than any other character
f7b9d4d1 4785 before, or if the font loaded has a smaller height than any
6fc2811b
JR
4786 other font loaded before. If this happens, it will make a
4787 glyph matrix reallocation necessary. */
f7b9d4d1 4788 fonts_changed_p |= x_compute_min_glyph_bounds (f);
4587b026 4789 UNBLOCK_INPUT;
4587b026
GV
4790 return fontp;
4791 }
4792}
4793
33d52f9c
GV
4794/* Load font named FONTNAME of size SIZE for frame F, and return a
4795 pointer to the structure font_info while allocating it dynamically.
4796 If loading fails, return NULL. */
4797struct font_info *
4798w32_load_font (f,fontname,size)
4799struct frame *f;
4800char * fontname;
4801int size;
4802{
4803 Lisp_Object bdf_fonts;
4804 struct font_info *retval = NULL;
4805
8edb0a6f 4806 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
33d52f9c
GV
4807
4808 while (!retval && CONSP (bdf_fonts))
4809 {
4810 char *bdf_name, *bdf_file;
4811 Lisp_Object bdf_pair;
4812
d5db4077 4813 bdf_name = SDATA (XCAR (bdf_fonts));
8e713be6 4814 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
d5db4077 4815 bdf_file = SDATA (XCDR (bdf_pair));
33d52f9c
GV
4816
4817 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
4818
8e713be6 4819 bdf_fonts = XCDR (bdf_fonts);
33d52f9c
GV
4820 }
4821
4822 if (retval)
4823 return retval;
4824
4825 return w32_load_system_font(f, fontname, size);
4826}
4827
4828
7d0393cf 4829void
fbd6baed
GV
4830w32_unload_font (dpyinfo, font)
4831 struct w32_display_info *dpyinfo;
ee78dc32
GV
4832 XFontStruct * font;
4833{
7d0393cf 4834 if (font)
ee78dc32 4835 {
c6be3860 4836 if (font->per_char) xfree (font->per_char);
33d52f9c
GV
4837 if (font->bdf) w32_free_bdf_font (font->bdf);
4838
3c190163 4839 if (font->hfont) DeleteObject(font->hfont);
ee78dc32
GV
4840 xfree (font);
4841 }
4842}
4843
fbd6baed 4844/* The font conversion stuff between x and w32 */
ee78dc32
GV
4845
4846/* X font string is as follows (from faces.el)
4847 * (let ((- "[-?]")
4848 * (foundry "[^-]+")
4849 * (family "[^-]+")
4850 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
4851 * (weight\? "\\([^-]*\\)") ; 1
4852 * (slant "\\([ior]\\)") ; 2
4853 * (slant\? "\\([^-]?\\)") ; 2
4854 * (swidth "\\([^-]*\\)") ; 3
4855 * (adstyle "[^-]*") ; 4
4856 * (pixelsize "[0-9]+")
4857 * (pointsize "[0-9][0-9]+")
4858 * (resx "[0-9][0-9]+")
4859 * (resy "[0-9][0-9]+")
4860 * (spacing "[cmp?*]")
4861 * (avgwidth "[0-9]+")
4862 * (registry "[^-]+")
4863 * (encoding "[^-]+")
4864 * )
ee78dc32 4865 */
ee78dc32 4866
7d0393cf 4867static LONG
fbd6baed 4868x_to_w32_weight (lpw)
ee78dc32
GV
4869 char * lpw;
4870{
4871 if (!lpw) return (FW_DONTCARE);
5ac45f98
GV
4872
4873 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
4874 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
4875 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
4876 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
1edf84e7 4877 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5ac45f98
GV
4878 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
4879 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
4880 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
4881 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
4882 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
ee78dc32 4883 else
5ac45f98 4884 return FW_DONTCARE;
ee78dc32
GV
4885}
4886
5ac45f98 4887
7d0393cf 4888static char *
fbd6baed 4889w32_to_x_weight (fnweight)
ee78dc32
GV
4890 int fnweight;
4891{
5ac45f98
GV
4892 if (fnweight >= FW_HEAVY) return "heavy";
4893 if (fnweight >= FW_EXTRABOLD) return "extrabold";
4894 if (fnweight >= FW_BOLD) return "bold";
03f8fb34 4895 if (fnweight >= FW_SEMIBOLD) return "demibold";
5ac45f98
GV
4896 if (fnweight >= FW_MEDIUM) return "medium";
4897 if (fnweight >= FW_NORMAL) return "normal";
4898 if (fnweight >= FW_LIGHT) return "light";
4899 if (fnweight >= FW_EXTRALIGHT) return "extralight";
4900 if (fnweight >= FW_THIN) return "thin";
4901 else
4902 return "*";
4903}
4904
8edb0a6f 4905static LONG
fbd6baed 4906x_to_w32_charset (lpcs)
5ac45f98
GV
4907 char * lpcs;
4908{
767b1ff0 4909 Lisp_Object this_entry, w32_charset;
8b77111c
AI
4910 char *charset;
4911 int len = strlen (lpcs);
4912
4913 /* Support "*-#nnn" format for unknown charsets. */
4914 if (strncmp (lpcs, "*-#", 3) == 0)
4915 return atoi (lpcs + 3);
4916
4917 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
4918 charset = alloca (len + 1);
4919 strcpy (charset, lpcs);
4920 lpcs = strchr (charset, '*');
4921 if (lpcs)
4922 *lpcs = 0;
4587b026 4923
dfff8a69
JR
4924 /* Look through w32-charset-info-alist for the character set.
4925 Format of each entry is
4926 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
4927 */
8b77111c 4928 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
4587b026 4929
767b1ff0
JR
4930 if (NILP(this_entry))
4931 {
4932 /* At startup, we want iso8859-1 fonts to come up properly. */
8b77111c 4933 if (stricmp(charset, "iso8859-1") == 0)
767b1ff0
JR
4934 return ANSI_CHARSET;
4935 else
4936 return DEFAULT_CHARSET;
4937 }
4938
4939 w32_charset = Fcar (Fcdr (this_entry));
4940
d84b082d 4941 /* Translate Lisp symbol to number. */
767b1ff0
JR
4942 if (w32_charset == Qw32_charset_ansi)
4943 return ANSI_CHARSET;
4944 if (w32_charset == Qw32_charset_symbol)
4945 return SYMBOL_CHARSET;
4946 if (w32_charset == Qw32_charset_shiftjis)
4947 return SHIFTJIS_CHARSET;
4948 if (w32_charset == Qw32_charset_hangeul)
4949 return HANGEUL_CHARSET;
4950 if (w32_charset == Qw32_charset_chinesebig5)
4951 return CHINESEBIG5_CHARSET;
4952 if (w32_charset == Qw32_charset_gb2312)
4953 return GB2312_CHARSET;
4954 if (w32_charset == Qw32_charset_oem)
4955 return OEM_CHARSET;
dfff8a69 4956#ifdef JOHAB_CHARSET
767b1ff0
JR
4957 if (w32_charset == Qw32_charset_johab)
4958 return JOHAB_CHARSET;
4959 if (w32_charset == Qw32_charset_easteurope)
4960 return EASTEUROPE_CHARSET;
4961 if (w32_charset == Qw32_charset_turkish)
4962 return TURKISH_CHARSET;
4963 if (w32_charset == Qw32_charset_baltic)
4964 return BALTIC_CHARSET;
4965 if (w32_charset == Qw32_charset_russian)
4966 return RUSSIAN_CHARSET;
4967 if (w32_charset == Qw32_charset_arabic)
4968 return ARABIC_CHARSET;
4969 if (w32_charset == Qw32_charset_greek)
4970 return GREEK_CHARSET;
4971 if (w32_charset == Qw32_charset_hebrew)
4972 return HEBREW_CHARSET;
4973 if (w32_charset == Qw32_charset_vietnamese)
4974 return VIETNAMESE_CHARSET;
4975 if (w32_charset == Qw32_charset_thai)
4976 return THAI_CHARSET;
4977 if (w32_charset == Qw32_charset_mac)
4978 return MAC_CHARSET;
dfff8a69 4979#endif /* JOHAB_CHARSET */
5ac45f98 4980#ifdef UNICODE_CHARSET
767b1ff0
JR
4981 if (w32_charset == Qw32_charset_unicode)
4982 return UNICODE_CHARSET;
5ac45f98 4983#endif
dfff8a69
JR
4984
4985 return DEFAULT_CHARSET;
5ac45f98
GV
4986}
4987
dfff8a69 4988
8edb0a6f 4989static char *
fbd6baed 4990w32_to_x_charset (fncharset)
5ac45f98
GV
4991 int fncharset;
4992{
5e905a57 4993 static char buf[32];
767b1ff0 4994 Lisp_Object charset_type;
1edf84e7 4995
5ac45f98
GV
4996 switch (fncharset)
4997 {
767b1ff0
JR
4998 case ANSI_CHARSET:
4999 /* Handle startup case of w32-charset-info-alist not
5000 being set up yet. */
5001 if (NILP(Vw32_charset_info_alist))
5002 return "iso8859-1";
5003 charset_type = Qw32_charset_ansi;
5004 break;
5005 case DEFAULT_CHARSET:
5006 charset_type = Qw32_charset_default;
5007 break;
5008 case SYMBOL_CHARSET:
5009 charset_type = Qw32_charset_symbol;
5010 break;
5011 case SHIFTJIS_CHARSET:
5012 charset_type = Qw32_charset_shiftjis;
5013 break;
5014 case HANGEUL_CHARSET:
5015 charset_type = Qw32_charset_hangeul;
5016 break;
5017 case GB2312_CHARSET:
5018 charset_type = Qw32_charset_gb2312;
5019 break;
5020 case CHINESEBIG5_CHARSET:
5021 charset_type = Qw32_charset_chinesebig5;
5022 break;
5023 case OEM_CHARSET:
5024 charset_type = Qw32_charset_oem;
5025 break;
4587b026
GV
5026
5027 /* More recent versions of Windows (95 and NT4.0) define more
5028 character sets. */
5029#ifdef EASTEUROPE_CHARSET
767b1ff0
JR
5030 case EASTEUROPE_CHARSET:
5031 charset_type = Qw32_charset_easteurope;
5032 break;
5033 case TURKISH_CHARSET:
5034 charset_type = Qw32_charset_turkish;
5035 break;
5036 case BALTIC_CHARSET:
5037 charset_type = Qw32_charset_baltic;
5038 break;
33d52f9c 5039 case RUSSIAN_CHARSET:
767b1ff0
JR
5040 charset_type = Qw32_charset_russian;
5041 break;
5042 case ARABIC_CHARSET:
5043 charset_type = Qw32_charset_arabic;
5044 break;
5045 case GREEK_CHARSET:
5046 charset_type = Qw32_charset_greek;
5047 break;
5048 case HEBREW_CHARSET:
5049 charset_type = Qw32_charset_hebrew;
5050 break;
5051 case VIETNAMESE_CHARSET:
5052 charset_type = Qw32_charset_vietnamese;
5053 break;
5054 case THAI_CHARSET:
5055 charset_type = Qw32_charset_thai;
5056 break;
5057 case MAC_CHARSET:
5058 charset_type = Qw32_charset_mac;
5059 break;
5060 case JOHAB_CHARSET:
5061 charset_type = Qw32_charset_johab;
5062 break;
4587b026
GV
5063#endif
5064
5ac45f98 5065#ifdef UNICODE_CHARSET
767b1ff0
JR
5066 case UNICODE_CHARSET:
5067 charset_type = Qw32_charset_unicode;
5068 break;
5ac45f98 5069#endif
767b1ff0
JR
5070 default:
5071 /* Encode numerical value of unknown charset. */
5072 sprintf (buf, "*-#%u", fncharset);
5073 return buf;
5ac45f98 5074 }
7d0393cf 5075
767b1ff0
JR
5076 {
5077 Lisp_Object rest;
5078 char * best_match = NULL;
5079
5080 /* Look through w32-charset-info-alist for the character set.
5081 Prefer ISO codepages, and prefer lower numbers in the ISO
5082 range. Only return charsets for codepages which are installed.
5083
5084 Format of each entry is
5085 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5086 */
5087 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5088 {
5089 char * x_charset;
5090 Lisp_Object w32_charset;
5091 Lisp_Object codepage;
5092
5093 Lisp_Object this_entry = XCAR (rest);
5094
5095 /* Skip invalid entries in alist. */
5096 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5097 || !CONSP (XCDR (this_entry))
5098 || !SYMBOLP (XCAR (XCDR (this_entry))))
5099 continue;
5100
d5db4077 5101 x_charset = SDATA (XCAR (this_entry));
767b1ff0
JR
5102 w32_charset = XCAR (XCDR (this_entry));
5103 codepage = XCDR (XCDR (this_entry));
5104
5105 /* Look for Same charset and a valid codepage (or non-int
5106 which means ignore). */
5107 if (w32_charset == charset_type
5108 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5109 || IsValidCodePage (XINT (codepage))))
5110 {
5111 /* If we don't have a match already, then this is the
5112 best. */
5113 if (!best_match)
5114 best_match = x_charset;
5115 /* If this is an ISO codepage, and the best so far isn't,
5116 then this is better. */
d84b082d
JR
5117 else if (strnicmp (best_match, "iso", 3) != 0
5118 && strnicmp (x_charset, "iso", 3) == 0)
767b1ff0
JR
5119 best_match = x_charset;
5120 /* If both are ISO8859 codepages, choose the one with the
5121 lowest number in the encoding field. */
d84b082d
JR
5122 else if (strnicmp (best_match, "iso8859-", 8) == 0
5123 && strnicmp (x_charset, "iso8859-", 8) == 0)
767b1ff0
JR
5124 {
5125 int best_enc = atoi (best_match + 8);
5126 int this_enc = atoi (x_charset + 8);
5127 if (this_enc > 0 && this_enc < best_enc)
5128 best_match = x_charset;
7d0393cf 5129 }
767b1ff0
JR
5130 }
5131 }
5132
5133 /* If no match, encode the numeric value. */
5134 if (!best_match)
5135 {
5136 sprintf (buf, "*-#%u", fncharset);
5137 return buf;
5138 }
5139
5e905a57
JR
5140 strncpy(buf, best_match, 31);
5141 buf[31] = '\0';
767b1ff0
JR
5142 return buf;
5143 }
ee78dc32
GV
5144}
5145
dfff8a69 5146
d84b082d
JR
5147/* Return all the X charsets that map to a font. */
5148static Lisp_Object
5149w32_to_all_x_charsets (fncharset)
5150 int fncharset;
5151{
5152 static char buf[32];
5153 Lisp_Object charset_type;
5154 Lisp_Object retval = Qnil;
5155
5156 switch (fncharset)
5157 {
5158 case ANSI_CHARSET:
5159 /* Handle startup case of w32-charset-info-alist not
5160 being set up yet. */
5161 if (NILP(Vw32_charset_info_alist))
d86c35ee
JR
5162 return Fcons (build_string ("iso8859-1"), Qnil);
5163
d84b082d
JR
5164 charset_type = Qw32_charset_ansi;
5165 break;
5166 case DEFAULT_CHARSET:
5167 charset_type = Qw32_charset_default;
5168 break;
5169 case SYMBOL_CHARSET:
5170 charset_type = Qw32_charset_symbol;
5171 break;
5172 case SHIFTJIS_CHARSET:
5173 charset_type = Qw32_charset_shiftjis;
5174 break;
5175 case HANGEUL_CHARSET:
5176 charset_type = Qw32_charset_hangeul;
5177 break;
5178 case GB2312_CHARSET:
5179 charset_type = Qw32_charset_gb2312;
5180 break;
5181 case CHINESEBIG5_CHARSET:
5182 charset_type = Qw32_charset_chinesebig5;
5183 break;
5184 case OEM_CHARSET:
5185 charset_type = Qw32_charset_oem;
5186 break;
5187
5188 /* More recent versions of Windows (95 and NT4.0) define more
5189 character sets. */
5190#ifdef EASTEUROPE_CHARSET
5191 case EASTEUROPE_CHARSET:
5192 charset_type = Qw32_charset_easteurope;
5193 break;
5194 case TURKISH_CHARSET:
5195 charset_type = Qw32_charset_turkish;
5196 break;
5197 case BALTIC_CHARSET:
5198 charset_type = Qw32_charset_baltic;
5199 break;
5200 case RUSSIAN_CHARSET:
5201 charset_type = Qw32_charset_russian;
5202 break;
5203 case ARABIC_CHARSET:
5204 charset_type = Qw32_charset_arabic;
5205 break;
5206 case GREEK_CHARSET:
5207 charset_type = Qw32_charset_greek;
5208 break;
5209 case HEBREW_CHARSET:
5210 charset_type = Qw32_charset_hebrew;
5211 break;
5212 case VIETNAMESE_CHARSET:
5213 charset_type = Qw32_charset_vietnamese;
5214 break;
5215 case THAI_CHARSET:
5216 charset_type = Qw32_charset_thai;
5217 break;
5218 case MAC_CHARSET:
5219 charset_type = Qw32_charset_mac;
5220 break;
5221 case JOHAB_CHARSET:
5222 charset_type = Qw32_charset_johab;
5223 break;
5224#endif
5225
5226#ifdef UNICODE_CHARSET
5227 case UNICODE_CHARSET:
5228 charset_type = Qw32_charset_unicode;
5229 break;
5230#endif
5231 default:
5232 /* Encode numerical value of unknown charset. */
5233 sprintf (buf, "*-#%u", fncharset);
5234 return Fcons (build_string (buf), Qnil);
5235 }
7d0393cf 5236
d84b082d
JR
5237 {
5238 Lisp_Object rest;
5239 /* Look through w32-charset-info-alist for the character set.
5240 Only return charsets for codepages which are installed.
5241
5242 Format of each entry in Vw32_charset_info_alist is
5243 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5244 */
5245 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5246 {
5247 Lisp_Object x_charset;
5248 Lisp_Object w32_charset;
5249 Lisp_Object codepage;
5250
5251 Lisp_Object this_entry = XCAR (rest);
5252
5253 /* Skip invalid entries in alist. */
5254 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5255 || !CONSP (XCDR (this_entry))
5256 || !SYMBOLP (XCAR (XCDR (this_entry))))
5257 continue;
5258
5259 x_charset = XCAR (this_entry);
5260 w32_charset = XCAR (XCDR (this_entry));
5261 codepage = XCDR (XCDR (this_entry));
5262
5263 /* Look for Same charset and a valid codepage (or non-int
5264 which means ignore). */
5265 if (w32_charset == charset_type
5266 && (!INTEGERP (codepage) || codepage == CP_DEFAULT
5267 || IsValidCodePage (XINT (codepage))))
5268 {
5269 retval = Fcons (x_charset, retval);
5270 }
5271 }
5272
5273 /* If no match, encode the numeric value. */
5274 if (NILP (retval))
5275 {
5276 sprintf (buf, "*-#%u", fncharset);
5277 return Fcons (build_string (buf), Qnil);
5278 }
5279
5280 return retval;
5281 }
5282}
5283
dfff8a69
JR
5284/* Get the Windows codepage corresponding to the specified font. The
5285 charset info in the font name is used to look up
5286 w32-charset-to-codepage-alist. */
7d0393cf 5287int
dfff8a69
JR
5288w32_codepage_for_font (char *fontname)
5289{
767b1ff0
JR
5290 Lisp_Object codepage, entry;
5291 char *charset_str, *charset, *end;
dfff8a69 5292
767b1ff0 5293 if (NILP (Vw32_charset_info_alist))
dfff8a69
JR
5294 return CP_DEFAULT;
5295
767b1ff0
JR
5296 /* Extract charset part of font string. */
5297 charset = xlfd_charset_of_font (fontname);
5298
5299 if (!charset)
ceb12877 5300 return CP_UNKNOWN;
767b1ff0 5301
8b77111c 5302 charset_str = (char *) alloca (strlen (charset) + 1);
767b1ff0
JR
5303 strcpy (charset_str, charset);
5304
8b77111c 5305#if 0
dfff8a69
JR
5306 /* Remove leading "*-". */
5307 if (strncmp ("*-", charset_str, 2) == 0)
5308 charset = charset_str + 2;
5309 else
8b77111c 5310#endif
dfff8a69
JR
5311 charset = charset_str;
5312
5313 /* Stop match at wildcard (including preceding '-'). */
5314 if (end = strchr (charset, '*'))
5315 {
5316 if (end > charset && *(end-1) == '-')
5317 end--;
5318 *end = '\0';
5319 }
5320
767b1ff0
JR
5321 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
5322 if (NILP (entry))
ceb12877 5323 return CP_UNKNOWN;
767b1ff0
JR
5324
5325 codepage = Fcdr (Fcdr (entry));
5326
5327 if (NILP (codepage))
5328 return CP_8BIT;
5329 else if (XFASTINT (codepage) == XFASTINT (Qt))
5330 return CP_UNICODE;
5331 else if (INTEGERP (codepage))
dfff8a69
JR
5332 return XINT (codepage);
5333 else
ceb12877 5334 return CP_UNKNOWN;
dfff8a69
JR
5335}
5336
5337
7d0393cf 5338static BOOL
767b1ff0 5339w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
ee78dc32
GV
5340 LOGFONT * lplogfont;
5341 char * lpxstr;
5342 int len;
767b1ff0 5343 char * specific_charset;
ee78dc32 5344{
6fc2811b 5345 char* fonttype;
f46e6225 5346 char *fontname;
3cb20f4a
RS
5347 char height_pixels[8];
5348 char height_dpi[8];
5349 char width_pixels[8];
4587b026 5350 char *fontname_dash;
ac849ba4
JR
5351 int display_resy = (int) one_w32_display_info.resy;
5352 int display_resx = (int) one_w32_display_info.resx;
f46e6225
GV
5353 int bufsz;
5354 struct coding_system coding;
3cb20f4a
RS
5355
5356 if (!lpxstr) abort ();
ee78dc32 5357
3cb20f4a
RS
5358 if (!lplogfont)
5359 return FALSE;
5360
6fc2811b
JR
5361 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5362 fonttype = "raster";
5363 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5364 fonttype = "outline";
5365 else
5366 fonttype = "unknown";
5367
1fa3a200 5368 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
f46e6225 5369 &coding);
aab5ac44
KH
5370 coding.src_multibyte = 0;
5371 coding.dst_multibyte = 1;
f46e6225 5372 coding.mode |= CODING_MODE_LAST_BLOCK;
65413122
KH
5373 /* We explicitely disable composition handling because selection
5374 data should not contain any composition sequence. */
5375 coding.composing = COMPOSITION_DISABLED;
f46e6225
GV
5376 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
5377
5378 fontname = alloca(sizeof(*fontname) * bufsz);
5379 decode_coding (&coding, lplogfont->lfFaceName, fontname,
5380 strlen(lplogfont->lfFaceName), bufsz - 1);
5381 *(fontname + coding.produced) = '\0';
4587b026
GV
5382
5383 /* Replace dashes with underscores so the dashes are not
f46e6225 5384 misinterpreted. */
4587b026
GV
5385 fontname_dash = fontname;
5386 while (fontname_dash = strchr (fontname_dash, '-'))
5387 *fontname_dash = '_';
5388
3cb20f4a 5389 if (lplogfont->lfHeight)
ee78dc32 5390 {
3cb20f4a
RS
5391 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
5392 sprintf (height_dpi, "%u",
33d52f9c 5393 abs (lplogfont->lfHeight) * 720 / display_resy);
5ac45f98
GV
5394 }
5395 else
ee78dc32 5396 {
3cb20f4a
RS
5397 strcpy (height_pixels, "*");
5398 strcpy (height_dpi, "*");
ee78dc32 5399 }
3cb20f4a
RS
5400 if (lplogfont->lfWidth)
5401 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5402 else
5403 strcpy (width_pixels, "*");
5404
5405 _snprintf (lpxstr, len - 1,
6fc2811b
JR
5406 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5407 fonttype, /* foundry */
4587b026
GV
5408 fontname, /* family */
5409 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5410 lplogfont->lfItalic?'i':'r', /* slant */
5411 /* setwidth name */
5412 /* add style name */
5413 height_pixels, /* pixel size */
5414 height_dpi, /* point size */
33d52f9c
GV
5415 display_resx, /* resx */
5416 display_resy, /* resy */
4587b026
GV
5417 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5418 ? 'p' : 'c', /* spacing */
5419 width_pixels, /* avg width */
767b1ff0 5420 specific_charset ? specific_charset
7d0393cf 5421 : w32_to_x_charset (lplogfont->lfCharSet)
767b1ff0 5422 /* charset registry and encoding */
3cb20f4a
RS
5423 );
5424
ee78dc32
GV
5425 lpxstr[len - 1] = 0; /* just to be sure */
5426 return (TRUE);
5427}
5428
7d0393cf 5429static BOOL
fbd6baed 5430x_to_w32_font (lpxstr, lplogfont)
ee78dc32
GV
5431 char * lpxstr;
5432 LOGFONT * lplogfont;
5433{
f46e6225
GV
5434 struct coding_system coding;
5435
ee78dc32 5436 if (!lplogfont) return (FALSE);
f46e6225 5437
ee78dc32 5438 memset (lplogfont, 0, sizeof (*lplogfont));
5ac45f98 5439
1a292d24 5440 /* Set default value for each field. */
771c47d5 5441#if 1
ee78dc32
GV
5442 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5443 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5444 lplogfont->lfQuality = DEFAULT_QUALITY;
5ac45f98
GV
5445#else
5446 /* go for maximum quality */
5447 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5448 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5449 lplogfont->lfQuality = PROOF_QUALITY;
5450#endif
5451
1a292d24
AI
5452 lplogfont->lfCharSet = DEFAULT_CHARSET;
5453 lplogfont->lfWeight = FW_DONTCARE;
5454 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5455
5ac45f98
GV
5456 if (!lpxstr)
5457 return FALSE;
5458
5459 /* Provide a simple escape mechanism for specifying Windows font names
5460 * directly -- if font spec does not beginning with '-', assume this
5461 * format:
5462 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5463 */
7d0393cf 5464
5ac45f98
GV
5465 if (*lpxstr == '-')
5466 {
33d52f9c
GV
5467 int fields, tem;
5468 char name[50], weight[20], slant, pitch, pixels[10], height[10],
8b77111c 5469 width[10], resy[10], remainder[50];
5ac45f98 5470 char * encoding;
ac849ba4 5471 int dpi = (int) one_w32_display_info.resy;
5ac45f98
GV
5472
5473 fields = sscanf (lpxstr,
8b77111c 5474 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
33d52f9c 5475 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
8b77111c
AI
5476 if (fields == EOF)
5477 return (FALSE);
5478
5479 /* In the general case when wildcards cover more than one field,
5480 we don't know which field is which, so don't fill any in.
5481 However, we need to cope with this particular form, which is
5482 generated by font_list_1 (invoked by try_font_list):
5483 "-raster-6x10-*-gb2312*-*"
5484 and make sure to correctly parse the charset field. */
5485 if (fields == 3)
5486 {
5487 fields = sscanf (lpxstr,
5488 "-%*[^-]-%49[^-]-*-%49s",
5489 name, remainder);
5490 }
5491 else if (fields < 9)
5492 {
5493 fields = 0;
5494 remainder[0] = 0;
5495 }
6fc2811b 5496
5ac45f98
GV
5497 if (fields > 0 && name[0] != '*')
5498 {
8ea3e054
RS
5499 int bufsize;
5500 unsigned char *buf;
5501
f46e6225 5502 setup_coding_system
1fa3a200 5503 (Fcheck_coding_system (Vlocale_coding_system), &coding);
aab5ac44
KH
5504 coding.src_multibyte = 1;
5505 coding.dst_multibyte = 1;
8ea3e054
RS
5506 bufsize = encoding_buffer_size (&coding, strlen (name));
5507 buf = (unsigned char *) alloca (bufsize);
f46e6225 5508 coding.mode |= CODING_MODE_LAST_BLOCK;
8ea3e054
RS
5509 encode_coding (&coding, name, buf, strlen (name), bufsize);
5510 if (coding.produced >= LF_FACESIZE)
5511 coding.produced = LF_FACESIZE - 1;
5512 buf[coding.produced] = 0;
5513 strcpy (lplogfont->lfFaceName, buf);
5ac45f98
GV
5514 }
5515 else
5516 {
6fc2811b 5517 lplogfont->lfFaceName[0] = '\0';
5ac45f98
GV
5518 }
5519
5520 fields--;
5521
fbd6baed 5522 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5ac45f98
GV
5523
5524 fields--;
5525
c8874f14 5526 lplogfont->lfItalic = (fields > 0 && slant == 'i');
5ac45f98
GV
5527
5528 fields--;
5529
5530 if (fields > 0 && pixels[0] != '*')
5531 lplogfont->lfHeight = atoi (pixels);
5532
5533 fields--;
5ac45f98 5534 fields--;
33d52f9c
GV
5535 if (fields > 0 && resy[0] != '*')
5536 {
6fc2811b 5537 tem = atoi (resy);
33d52f9c
GV
5538 if (tem > 0) dpi = tem;
5539 }
5ac45f98 5540
33d52f9c
GV
5541 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
5542 lplogfont->lfHeight = atoi (height) * dpi / 720;
5543
5544 if (fields > 0)
5ac45f98
GV
5545 lplogfont->lfPitchAndFamily =
5546 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
5547
5548 fields--;
5549
5550 if (fields > 0 && width[0] != '*')
5551 lplogfont->lfWidth = atoi (width) / 10;
5552
5553 fields--;
5554
4587b026 5555 /* Strip the trailing '-' if present. (it shouldn't be, as it
d88c567c 5556 fails the test against xlfd-tight-regexp in fontset.el). */
3c190163 5557 {
5ac45f98
GV
5558 int len = strlen (remainder);
5559 if (len > 0 && remainder[len-1] == '-')
5560 remainder[len-1] = 0;
ee78dc32 5561 }
5ac45f98 5562 encoding = remainder;
8b77111c 5563#if 0
5ac45f98
GV
5564 if (strncmp (encoding, "*-", 2) == 0)
5565 encoding += 2;
8b77111c
AI
5566#endif
5567 lplogfont->lfCharSet = x_to_w32_charset (encoding);
5ac45f98
GV
5568 }
5569 else
5570 {
5571 int fields;
5572 char name[100], height[10], width[10], weight[20];
a1a80b40 5573
5ac45f98
GV
5574 fields = sscanf (lpxstr,
5575 "%99[^:]:%9[^:]:%9[^:]:%19s",
5576 name, height, width, weight);
5577
5578 if (fields == EOF) return (FALSE);
5579
5580 if (fields > 0)
5581 {
5582 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
5583 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
5584 }
5585 else
5586 {
5587 lplogfont->lfFaceName[0] = 0;
5588 }
5589
5590 fields--;
5591
5592 if (fields > 0)
5593 lplogfont->lfHeight = atoi (height);
5594
5595 fields--;
5596
5597 if (fields > 0)
5598 lplogfont->lfWidth = atoi (width);
5599
5600 fields--;
5601
fbd6baed 5602 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5ac45f98
GV
5603 }
5604
5605 /* This makes TrueType fonts work better. */
5606 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
6fc2811b 5607
ee78dc32
GV
5608 return (TRUE);
5609}
5610
d88c567c
JR
5611/* Strip the pixel height and point height from the given xlfd, and
5612 return the pixel height. If no pixel height is specified, calculate
5613 one from the point height, or if that isn't defined either, return
5614 0 (which usually signifies a scalable font).
5615*/
8edb0a6f
JR
5616static int
5617xlfd_strip_height (char *fontname)
d88c567c 5618{
8edb0a6f 5619 int pixel_height, field_number;
d88c567c
JR
5620 char *read_from, *write_to;
5621
5622 xassert (fontname);
5623
5624 pixel_height = field_number = 0;
5625 write_to = NULL;
5626
5627 /* Look for height fields. */
5628 for (read_from = fontname; *read_from; read_from++)
5629 {
5630 if (*read_from == '-')
5631 {
5632 field_number++;
5633 if (field_number == 7) /* Pixel height. */
5634 {
5635 read_from++;
5636 write_to = read_from;
5637
5638 /* Find end of field. */
5639 for (;*read_from && *read_from != '-'; read_from++)
5640 ;
5641
5642 /* Split the fontname at end of field. */
5643 if (*read_from)
5644 {
5645 *read_from = '\0';
5646 read_from++;
5647 }
5648 pixel_height = atoi (write_to);
5649 /* Blank out field. */
5650 if (read_from > write_to)
5651 {
5652 *write_to = '-';
5653 write_to++;
5654 }
767b1ff0 5655 /* If the pixel height field is at the end (partial xlfd),
d88c567c
JR
5656 return now. */
5657 else
5658 return pixel_height;
5659
5660 /* If we got a pixel height, the point height can be
5661 ignored. Just blank it out and break now. */
5662 if (pixel_height)
5663 {
5664 /* Find end of point size field. */
5665 for (; *read_from && *read_from != '-'; read_from++)
5666 ;
5667
5668 if (*read_from)
5669 read_from++;
5670
5671 /* Blank out the point size field. */
5672 if (read_from > write_to)
5673 {
5674 *write_to = '-';
5675 write_to++;
5676 }
5677 else
5678 return pixel_height;
5679
5680 break;
5681 }
5682 /* If the point height is already blank, break now. */
5683 if (*read_from == '-')
5684 {
5685 read_from++;
5686 break;
5687 }
5688 }
5689 else if (field_number == 8)
5690 {
5691 /* If we didn't get a pixel height, try to get the point
5692 height and convert that. */
5693 int point_size;
5694 char *point_size_start = read_from++;
5695
5696 /* Find end of field. */
5697 for (; *read_from && *read_from != '-'; read_from++)
5698 ;
5699
5700 if (*read_from)
5701 {
5702 *read_from = '\0';
5703 read_from++;
5704 }
5705
5706 point_size = atoi (point_size_start);
5707
5708 /* Convert to pixel height. */
5709 pixel_height = point_size
5710 * one_w32_display_info.height_in / 720;
5711
5712 /* Blank out this field and break. */
5713 *write_to = '-';
5714 write_to++;
5715 break;
5716 }
5717 }
5718 }
5719
5720 /* Shift the rest of the font spec into place. */
5721 if (write_to && read_from > write_to)
5722 {
5723 for (; *read_from; read_from++, write_to++)
5724 *write_to = *read_from;
5725 *write_to = '\0';
5726 }
5727
5728 return pixel_height;
5729}
5730
6fc2811b 5731/* Assume parameter 1 is fully qualified, no wildcards. */
7d0393cf 5732static BOOL
6fc2811b
JR
5733w32_font_match (fontname, pattern)
5734 char * fontname;
5735 char * pattern;
ee78dc32 5736{
e7c72122 5737 char *regex = alloca (strlen (pattern) * 2 + 3);
d88c567c 5738 char *font_name_copy = alloca (strlen (fontname) + 1);
6fc2811b 5739 char *ptr;
ee78dc32 5740
d88c567c
JR
5741 /* Copy fontname so we can modify it during comparison. */
5742 strcpy (font_name_copy, fontname);
5743
6fc2811b
JR
5744 ptr = regex;
5745 *ptr++ = '^';
ee78dc32 5746
6fc2811b
JR
5747 /* Turn pattern into a regexp and do a regexp match. */
5748 for (; *pattern; pattern++)
5749 {
5750 if (*pattern == '?')
5751 *ptr++ = '.';
5752 else if (*pattern == '*')
5753 {
5754 *ptr++ = '.';
5755 *ptr++ = '*';
5756 }
33d52f9c 5757 else
6fc2811b 5758 *ptr++ = *pattern;
ee78dc32 5759 }
6fc2811b
JR
5760 *ptr = '$';
5761 *(ptr + 1) = '\0';
5762
d88c567c
JR
5763 /* Strip out font heights and compare them seperately, since
5764 rounding error can cause mismatches. This also allows a
5765 comparison between a font that declares only a pixel height and a
5766 pattern that declares the point height.
5767 */
5768 {
5769 int font_height, pattern_height;
5770
5771 font_height = xlfd_strip_height (font_name_copy);
5772 pattern_height = xlfd_strip_height (regex);
5773
5774 /* Compare now, and don't bother doing expensive regexp matching
5775 if the heights differ. */
5776 if (font_height && pattern_height && (font_height != pattern_height))
5777 return FALSE;
5778 }
5779
6fc2811b 5780 return (fast_c_string_match_ignore_case (build_string (regex),
d88c567c 5781 font_name_copy) >= 0);
ee78dc32
GV
5782}
5783
5ca0cd71
GV
5784/* Callback functions, and a structure holding info they need, for
5785 listing system fonts on W32. We need one set of functions to do the
5786 job properly, but these don't work on NT 3.51 and earlier, so we
5787 have a second set which don't handle character sets properly to
5788 fall back on.
5789
5790 In both cases, there are two passes made. The first pass gets one
5791 font from each family, the second pass lists all the fonts from
5792 each family. */
5793
7d0393cf 5794typedef struct enumfont_t
ee78dc32
GV
5795{
5796 HDC hdc;
5797 int numFonts;
3cb20f4a 5798 LOGFONT logfont;
ee78dc32 5799 XFontStruct *size_ref;
23afac8f 5800 Lisp_Object pattern;
d84b082d 5801 Lisp_Object list;
ee78dc32
GV
5802} enumfont_t;
5803
d84b082d
JR
5804
5805static void
5806enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
5807
5808
7d0393cf 5809static int CALLBACK
ee78dc32
GV
5810enum_font_cb2 (lplf, lptm, FontType, lpef)
5811 ENUMLOGFONT * lplf;
5812 NEWTEXTMETRIC * lptm;
5813 int FontType;
5814 enumfont_t * lpef;
5815{
66895301
JR
5816 /* Ignore struck out and underlined versions of fonts. */
5817 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
5818 return 1;
5819
5820 /* Only return fonts with names starting with @ if they were
5821 explicitly specified, since Microsoft uses an initial @ to
5822 denote fonts for vertical writing, without providing a more
5823 convenient way of identifying them. */
5824 if (lplf->elfLogFont.lfFaceName[0] == '@'
5825 && lpef->logfont.lfFaceName[0] != '@')
5e905a57
JR
5826 return 1;
5827
4587b026
GV
5828 /* Check that the character set matches if it was specified */
5829 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
5830 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
5e905a57 5831 return 1;
4587b026 5832
6358474d
JR
5833 if (FontType == RASTER_FONTTYPE)
5834 {
5835 /* DBCS raster fonts have problems displaying, so skip them. */
5836 int charset = lplf->elfLogFont.lfCharSet;
5837 if (charset == SHIFTJIS_CHARSET
5838 || charset == HANGEUL_CHARSET
5839 || charset == CHINESEBIG5_CHARSET
5840 || charset == GB2312_CHARSET
5841#ifdef JOHAB_CHARSET
5842 || charset == JOHAB_CHARSET
5843#endif
5844 )
5845 return 1;
5846 }
5847
ee78dc32
GV
5848 {
5849 char buf[100];
4587b026 5850 Lisp_Object width = Qnil;
d84b082d 5851 Lisp_Object charset_list = Qnil;
767b1ff0 5852 char *charset = NULL;
ee78dc32 5853
6fc2811b
JR
5854 /* Truetype fonts do not report their true metrics until loaded */
5855 if (FontType != RASTER_FONTTYPE)
3cb20f4a 5856 {
23afac8f 5857 if (!NILP (lpef->pattern))
6fc2811b
JR
5858 {
5859 /* Scalable fonts are as big as you want them to be. */
5860 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
5861 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
5862 width = make_number (lpef->logfont.lfWidth);
5863 }
5864 else
5865 {
5866 lplf->elfLogFont.lfHeight = 0;
5867 lplf->elfLogFont.lfWidth = 0;
5868 }
3cb20f4a 5869 }
6fc2811b 5870
f46e6225
GV
5871 /* Make sure the height used here is the same as everywhere
5872 else (ie character height, not cell height). */
6fc2811b
JR
5873 if (lplf->elfLogFont.lfHeight > 0)
5874 {
5875 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
5876 if (FontType == RASTER_FONTTYPE)
5877 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
5878 else
5879 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
5880 }
4587b026 5881
23afac8f 5882 if (!NILP (lpef->pattern))
767b1ff0 5883 {
d5db4077 5884 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
767b1ff0 5885
644cefdf
JR
5886 /* We already checked charsets above, but DEFAULT_CHARSET
5887 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
5888 if (charset
5889 && strncmp (charset, "*-*", 3) != 0
5890 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
5891 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
5892 return 1;
767b1ff0
JR
5893 }
5894
d84b082d
JR
5895 if (charset)
5896 charset_list = Fcons (build_string (charset), Qnil);
5897 else
5898 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
ee78dc32 5899
d84b082d
JR
5900 /* Loop through the charsets. */
5901 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
ee78dc32 5902 {
d84b082d 5903 Lisp_Object this_charset = Fcar (charset_list);
d5db4077 5904 charset = SDATA (this_charset);
d84b082d
JR
5905
5906 /* List bold and italic variations if w32-enable-synthesized-fonts
5907 is non-nil and this is a plain font. */
5908 if (w32_enable_synthesized_fonts
5909 && lplf->elfLogFont.lfWeight == FW_NORMAL
5910 && lplf->elfLogFont.lfItalic == FALSE)
5911 {
5912 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5913 charset, width);
5914 /* bold. */
5915 lplf->elfLogFont.lfWeight = FW_BOLD;
5916 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5917 charset, width);
5918 /* bold italic. */
5919 lplf->elfLogFont.lfItalic = TRUE;
5920 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5921 charset, width);
5922 /* italic. */
5923 lplf->elfLogFont.lfWeight = FW_NORMAL;
5924 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5925 charset, width);
5926 }
5927 else
5928 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5929 charset, width);
ee78dc32
GV
5930 }
5931 }
6fc2811b 5932
5e905a57 5933 return 1;
ee78dc32
GV
5934}
5935
d84b082d
JR
5936static void
5937enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
5938 enumfont_t * lpef;
5939 LOGFONT * logfont;
5940 char * match_charset;
5941 Lisp_Object width;
5942{
5943 char buf[100];
5944
5945 if (!w32_to_x_font (logfont, buf, 100, match_charset))
5946 return;
5947
23afac8f 5948 if (NILP (lpef->pattern)
d5db4077 5949 || w32_font_match (buf, SDATA (lpef->pattern)))
d84b082d
JR
5950 {
5951 /* Check if we already listed this font. This may happen if
5952 w32_enable_synthesized_fonts is non-nil, and there are real
5953 bold and italic versions of the font. */
5954 Lisp_Object font_name = build_string (buf);
5955 if (NILP (Fmember (font_name, lpef->list)))
5956 {
23afac8f
JR
5957 Lisp_Object entry = Fcons (font_name, width);
5958 lpef->list = Fcons (entry, lpef->list);
d84b082d
JR
5959 lpef->numFonts++;
5960 }
5961 }
5962}
5963
5964
7d0393cf 5965static int CALLBACK
ee78dc32
GV
5966enum_font_cb1 (lplf, lptm, FontType, lpef)
5967 ENUMLOGFONT * lplf;
5968 NEWTEXTMETRIC * lptm;
5969 int FontType;
5970 enumfont_t * lpef;
5971{
5972 return EnumFontFamilies (lpef->hdc,
5973 lplf->elfLogFont.lfFaceName,
5974 (FONTENUMPROC) enum_font_cb2,
5975 (LPARAM) lpef);
5976}
5977
5978
8edb0a6f 5979static int CALLBACK
5ca0cd71
GV
5980enum_fontex_cb2 (lplf, lptm, font_type, lpef)
5981 ENUMLOGFONTEX * lplf;
5982 NEWTEXTMETRICEX * lptm;
5983 int font_type;
5984 enumfont_t * lpef;
5985{
5986 /* We are not interested in the extra info we get back from the 'Ex
5987 version - only the fact that we get character set variations
5988 enumerated seperately. */
5989 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
5990 font_type, lpef);
5991}
5992
8edb0a6f 5993static int CALLBACK
5ca0cd71
GV
5994enum_fontex_cb1 (lplf, lptm, font_type, lpef)
5995 ENUMLOGFONTEX * lplf;
5996 NEWTEXTMETRICEX * lptm;
5997 int font_type;
5998 enumfont_t * lpef;
5999{
6000 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6001 FARPROC enum_font_families_ex
6002 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6003 /* We don't really expect EnumFontFamiliesEx to disappear once we
6004 get here, so don't bother handling it gracefully. */
6005 if (enum_font_families_ex == NULL)
6006 error ("gdi32.dll has disappeared!");
6007 return enum_font_families_ex (lpef->hdc,
6008 &lplf->elfLogFont,
6009 (FONTENUMPROC) enum_fontex_cb2,
6010 (LPARAM) lpef, 0);
6011}
6012
4587b026
GV
6013/* Interface to fontset handler. (adapted from mw32font.c in Meadow
6014 and xterm.c in Emacs 20.3) */
6015
8edb0a6f 6016static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
33d52f9c
GV
6017{
6018 char *fontname, *ptnstr;
6019 Lisp_Object list, tem, newlist = Qnil;
55dcfc15 6020 int n_fonts = 0;
33d52f9c
GV
6021
6022 list = Vw32_bdf_filename_alist;
d5db4077 6023 ptnstr = SDATA (pattern);
33d52f9c 6024
8e713be6 6025 for ( ; CONSP (list); list = XCDR (list))
33d52f9c 6026 {
8e713be6 6027 tem = XCAR (list);
33d52f9c 6028 if (CONSP (tem))
d5db4077 6029 fontname = SDATA (XCAR (tem));
33d52f9c 6030 else if (STRINGP (tem))
d5db4077 6031 fontname = SDATA (tem);
33d52f9c
GV
6032 else
6033 continue;
6034
6035 if (w32_font_match (fontname, ptnstr))
5ca0cd71 6036 {
8e713be6 6037 newlist = Fcons (XCAR (tem), newlist);
5ca0cd71 6038 n_fonts++;
bd11cc09 6039 if (max_names >= 0 && n_fonts >= max_names)
5ca0cd71
GV
6040 break;
6041 }
33d52f9c
GV
6042 }
6043
6044 return newlist;
6045}
6046
5ca0cd71 6047
4587b026
GV
6048/* Return a list of names of available fonts matching PATTERN on frame
6049 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6050 to be listed. Frame F NULL means we have not yet created any
6051 frame, which means we can't get proper size info, as we don't have
6052 a device context to use for GetTextMetrics.
bd11cc09
JR
6053 MAXNAMES sets a limit on how many fonts to match. If MAXNAMES is
6054 negative, then all matching fonts are returned. */
4587b026
GV
6055
6056Lisp_Object
dc220243
JR
6057w32_list_fonts (f, pattern, size, maxnames)
6058 struct frame *f;
6059 Lisp_Object pattern;
6060 int size;
6061 int maxnames;
4587b026 6062{
6fc2811b 6063 Lisp_Object patterns, key = Qnil, tem, tpat;
4587b026 6064 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
33d52f9c 6065 struct w32_display_info *dpyinfo = &one_w32_display_info;
5ca0cd71 6066 int n_fonts = 0;
396594fe 6067
4587b026
GV
6068 patterns = Fassoc (pattern, Valternate_fontname_alist);
6069 if (NILP (patterns))
6070 patterns = Fcons (pattern, Qnil);
6071
8e713be6 6072 for (; CONSP (patterns); patterns = XCDR (patterns))
4587b026
GV
6073 {
6074 enumfont_t ef;
767b1ff0 6075 int codepage;
4587b026 6076
8e713be6 6077 tpat = XCAR (patterns);
4587b026 6078
767b1ff0
JR
6079 if (!STRINGP (tpat))
6080 continue;
6081
6082 /* Avoid expensive EnumFontFamilies functions if we are not
6083 going to be able to output one of these anyway. */
d5db4077 6084 codepage = w32_codepage_for_font (SDATA (tpat));
767b1ff0 6085 if (codepage != CP_8BIT && codepage != CP_UNICODE
ceb12877
AI
6086 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6087 && !IsValidCodePage(codepage))
767b1ff0
JR
6088 continue;
6089
4587b026
GV
6090 /* See if we cached the result for this particular query.
6091 The cache is an alist of the form:
6092 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6093 */
8e713be6 6094 if (tem = XCDR (dpyinfo->name_list_element),
33d52f9c 6095 !NILP (list = Fassoc (tpat, tem)))
4587b026
GV
6096 {
6097 list = Fcdr_safe (list);
6098 /* We have a cached list. Don't have to get the list again. */
6099 goto label_cached;
6100 }
6101
6102 BLOCK_INPUT;
6103 /* At first, put PATTERN in the cache. */
23afac8f
JR
6104 ef.pattern = tpat;
6105 ef.list = Qnil;
4587b026 6106 ef.numFonts = 0;
33d52f9c 6107
5ca0cd71
GV
6108 /* Use EnumFontFamiliesEx where it is available, as it knows
6109 about character sets. Fall back to EnumFontFamilies for
6110 older versions of NT that don't support the 'Ex function. */
d5db4077 6111 x_to_w32_font (SDATA (tpat), &ef.logfont);
4587b026 6112 {
5ca0cd71
GV
6113 LOGFONT font_match_pattern;
6114 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6115 FARPROC enum_font_families_ex
6116 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6117
6118 /* We do our own pattern matching so we can handle wildcards. */
6119 font_match_pattern.lfFaceName[0] = 0;
6120 font_match_pattern.lfPitchAndFamily = 0;
6121 /* We can use the charset, because if it is a wildcard it will
6122 be DEFAULT_CHARSET anyway. */
6123 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6124
33d52f9c 6125 ef.hdc = GetDC (dpyinfo->root_window);
4587b026 6126
5ca0cd71
GV
6127 if (enum_font_families_ex)
6128 enum_font_families_ex (ef.hdc,
6129 &font_match_pattern,
6130 (FONTENUMPROC) enum_fontex_cb1,
6131 (LPARAM) &ef, 0);
6132 else
6133 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6134 (LPARAM)&ef);
4587b026 6135
33d52f9c 6136 ReleaseDC (dpyinfo->root_window, ef.hdc);
4587b026
GV
6137 }
6138
6139 UNBLOCK_INPUT;
23afac8f 6140 list = ef.list;
4587b026
GV
6141
6142 /* Make a list of the fonts we got back.
6143 Store that in the font cache for the display. */
f3fbd155
KR
6144 XSETCDR (dpyinfo->name_list_element,
6145 Fcons (Fcons (tpat, list),
6146 XCDR (dpyinfo->name_list_element)));
4587b026
GV
6147
6148 label_cached:
6149 if (NILP (list)) continue; /* Try the remaining alternatives. */
6150
6151 newlist = second_best = Qnil;
6152
7d0393cf 6153 /* Make a list of the fonts that have the right width. */
8e713be6 6154 for (; CONSP (list); list = XCDR (list))
4587b026
GV
6155 {
6156 int found_size;
8e713be6 6157 tem = XCAR (list);
4587b026
GV
6158
6159 if (!CONSP (tem))
6160 continue;
8e713be6 6161 if (NILP (XCAR (tem)))
4587b026
GV
6162 continue;
6163 if (!size)
6164 {
8e713be6 6165 newlist = Fcons (XCAR (tem), newlist);
5ca0cd71 6166 n_fonts++;
bd11cc09 6167 if (maxnames >= 0 && n_fonts >= maxnames)
5ca0cd71
GV
6168 break;
6169 else
6170 continue;
4587b026 6171 }
8e713be6 6172 if (!INTEGERP (XCDR (tem)))
4587b026
GV
6173 {
6174 /* Since we don't yet know the size of the font, we must
6175 load it and try GetTextMetrics. */
4587b026
GV
6176 W32FontStruct thisinfo;
6177 LOGFONT lf;
6178 HDC hdc;
6179 HANDLE oldobj;
6180
d5db4077 6181 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
4587b026
GV
6182 continue;
6183
6184 BLOCK_INPUT;
33d52f9c 6185 thisinfo.bdf = NULL;
4587b026
GV
6186 thisinfo.hfont = CreateFontIndirect (&lf);
6187 if (thisinfo.hfont == NULL)
6188 continue;
6189
6190 hdc = GetDC (dpyinfo->root_window);
6191 oldobj = SelectObject (hdc, thisinfo.hfont);
6192 if (GetTextMetrics (hdc, &thisinfo.tm))
f3fbd155 6193 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
4587b026 6194 else
f3fbd155 6195 XSETCDR (tem, make_number (0));
4587b026
GV
6196 SelectObject (hdc, oldobj);
6197 ReleaseDC (dpyinfo->root_window, hdc);
6198 DeleteObject(thisinfo.hfont);
6199 UNBLOCK_INPUT;
6200 }
8e713be6 6201 found_size = XINT (XCDR (tem));
4587b026 6202 if (found_size == size)
5ca0cd71 6203 {
8e713be6 6204 newlist = Fcons (XCAR (tem), newlist);
5ca0cd71 6205 n_fonts++;
bd11cc09 6206 if (maxnames >= 0 && n_fonts >= maxnames)
5ca0cd71
GV
6207 break;
6208 }
4587b026
GV
6209 /* keep track of the closest matching size in case
6210 no exact match is found. */
6211 else if (found_size > 0)
6212 {
6213 if (NILP (second_best))
6214 second_best = tem;
7d0393cf 6215
4587b026
GV
6216 else if (found_size < size)
6217 {
8e713be6
KR
6218 if (XINT (XCDR (second_best)) > size
6219 || XINT (XCDR (second_best)) < found_size)
4587b026
GV
6220 second_best = tem;
6221 }
6222 else
6223 {
8e713be6
KR
6224 if (XINT (XCDR (second_best)) > size
6225 && XINT (XCDR (second_best)) >
4587b026
GV
6226 found_size)
6227 second_best = tem;
6228 }
6229 }
6230 }
6231
6232 if (!NILP (newlist))
6233 break;
6234 else if (!NILP (second_best))
6235 {
8e713be6 6236 newlist = Fcons (XCAR (second_best), Qnil);
4587b026
GV
6237 break;
6238 }
6239 }
6240
33d52f9c 6241 /* Include any bdf fonts. */
bd11cc09 6242 if (n_fonts < maxnames || maxnames < 0)
33d52f9c
GV
6243 {
6244 Lisp_Object combined[2];
5ca0cd71 6245 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
33d52f9c
GV
6246 combined[1] = newlist;
6247 newlist = Fnconc(2, combined);
6248 }
6249
4587b026
GV
6250 return newlist;
6251}
6252
5ca0cd71 6253
4587b026
GV
6254/* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6255struct font_info *
6256w32_get_font_info (f, font_idx)
6257 FRAME_PTR f;
6258 int font_idx;
6259{
6260 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6261}
6262
6263
6264struct font_info*
6265w32_query_font (struct frame *f, char *fontname)
6266{
6267 int i;
6268 struct font_info *pfi;
6269
6270 pfi = FRAME_W32_FONT_TABLE (f);
6271
6272 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6273 {
6274 if (strcmp(pfi->name, fontname) == 0) return pfi;
6275 }
6276
6277 return NULL;
6278}
6279
6280/* Find a CCL program for a font specified by FONTP, and set the member
6281 `encoder' of the structure. */
6282
6283void
6284w32_find_ccl_program (fontp)
6285 struct font_info *fontp;
6286{
3545439c 6287 Lisp_Object list, elt;
4587b026 6288
8e713be6 6289 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
4587b026 6290 {
8e713be6 6291 elt = XCAR (list);
4587b026 6292 if (CONSP (elt)
8e713be6
KR
6293 && STRINGP (XCAR (elt))
6294 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
4587b026 6295 >= 0))
3545439c
KH
6296 break;
6297 }
6298 if (! NILP (list))
6299 {
17eedd00
KH
6300 struct ccl_program *ccl
6301 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
3545439c 6302
8e713be6 6303 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
3545439c
KH
6304 xfree (ccl);
6305 else
6306 fontp->font_encoder = ccl;
4587b026
GV
6307 }
6308}
6309
6310\f
8edb0a6f
JR
6311/* Find BDF files in a specified directory. (use GCPRO when calling,
6312 as this calls lisp to get a directory listing). */
6313static Lisp_Object
6314w32_find_bdf_fonts_in_dir (Lisp_Object directory)
6315{
6316 Lisp_Object filelist, list = Qnil;
6317 char fontname[100];
6318
6319 if (!STRINGP(directory))
6320 return Qnil;
6321
6322 filelist = Fdirectory_files (directory, Qt,
6323 build_string (".*\\.[bB][dD][fF]"), Qt);
6324
6325 for ( ; CONSP(filelist); filelist = XCDR (filelist))
6326 {
6327 Lisp_Object filename = XCAR (filelist);
d5db4077 6328 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
8edb0a6f
JR
6329 store_in_alist (&list, build_string (fontname), filename);
6330 }
6331 return list;
6332}
6333
6fc2811b
JR
6334DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6335 1, 1, 0,
b3700ae7
JR
6336 doc: /* Return a list of BDF fonts in DIR.
6337The list is suitable for appending to w32-bdf-filename-alist. Fonts
6338which do not contain an xlfd description will not be included in the
6339list. DIR may be a list of directories. */)
6fc2811b
JR
6340 (directory)
6341 Lisp_Object directory;
6342{
6343 Lisp_Object list = Qnil;
6344 struct gcpro gcpro1, gcpro2;
ee78dc32 6345
6fc2811b
JR
6346 if (!CONSP (directory))
6347 return w32_find_bdf_fonts_in_dir (directory);
ee78dc32 6348
6fc2811b 6349 for ( ; CONSP (directory); directory = XCDR (directory))
ee78dc32 6350 {
6fc2811b
JR
6351 Lisp_Object pair[2];
6352 pair[0] = list;
6353 pair[1] = Qnil;
6354 GCPRO2 (directory, list);
6355 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
6356 list = Fnconc( 2, pair );
6357 UNGCPRO;
6358 }
6359 return list;
6360}
ee78dc32 6361
6fc2811b
JR
6362\f
6363DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
74e1aeec 6364 doc: /* Internal function called by `color-defined-p', which see. */)
6fc2811b
JR
6365 (color, frame)
6366 Lisp_Object color, frame;
6367{
6368 XColor foo;
6369 FRAME_PTR f = check_x_frame (frame);
ee78dc32 6370
b7826503 6371 CHECK_STRING (color);
ee78dc32 6372
d5db4077 6373 if (w32_defined_color (f, SDATA (color), &foo, 0))
6fc2811b
JR
6374 return Qt;
6375 else
6376 return Qnil;
6377}
ee78dc32 6378
2d764c78 6379DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
74e1aeec 6380 doc: /* Internal function called by `color-values', which see. */)
ee78dc32
GV
6381 (color, frame)
6382 Lisp_Object color, frame;
6383{
6fc2811b 6384 XColor foo;
ee78dc32
GV
6385 FRAME_PTR f = check_x_frame (frame);
6386
b7826503 6387 CHECK_STRING (color);
ee78dc32 6388
d5db4077 6389 if (w32_defined_color (f, SDATA (color), &foo, 0))
ee78dc32
GV
6390 {
6391 Lisp_Object rgb[3];
6392
6fc2811b
JR
6393 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
6394 | GetRValue (foo.pixel));
6395 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
6396 | GetGValue (foo.pixel));
6397 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
6398 | GetBValue (foo.pixel));
ee78dc32
GV
6399 return Flist (3, rgb);
6400 }
6401 else
6402 return Qnil;
6403}
6404
2d764c78 6405DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
74e1aeec 6406 doc: /* Internal function called by `display-color-p', which see. */)
ee78dc32
GV
6407 (display)
6408 Lisp_Object display;
6409{
fbd6baed 6410 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6411
6412 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6413 return Qnil;
6414
6415 return Qt;
6416}
6417
74e1aeec
JR
6418DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6419 Sx_display_grayscale_p, 0, 1, 0,
6420 doc: /* Return t if the X display supports shades of gray.
6421Note that color displays do support shades of gray.
6422The optional argument DISPLAY specifies which display to ask about.
6423DISPLAY should be either a frame or a display name (a string).
6424If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6425 (display)
6426 Lisp_Object display;
6427{
fbd6baed 6428 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6429
6430 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6431 return Qnil;
6432
6433 return Qt;
6434}
6435
74e1aeec
JR
6436DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6437 Sx_display_pixel_width, 0, 1, 0,
6438 doc: /* Returns the width in pixels of DISPLAY.
6439The optional argument DISPLAY specifies which display to ask about.
6440DISPLAY should be either a frame or a display name (a string).
6441If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6442 (display)
6443 Lisp_Object display;
6444{
fbd6baed 6445 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6446
6447 return make_number (dpyinfo->width);
6448}
6449
6450DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
74e1aeec
JR
6451 Sx_display_pixel_height, 0, 1, 0,
6452 doc: /* Returns the height in pixels of DISPLAY.
6453The optional argument DISPLAY specifies which display to ask about.
6454DISPLAY should be either a frame or a display name (a string).
6455If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6456 (display)
6457 Lisp_Object display;
6458{
fbd6baed 6459 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6460
6461 return make_number (dpyinfo->height);
6462}
6463
6464DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
74e1aeec
JR
6465 0, 1, 0,
6466 doc: /* Returns the number of bitplanes of DISPLAY.
6467The optional argument DISPLAY specifies which display to ask about.
6468DISPLAY should be either a frame or a display name (a string).
6469If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6470 (display)
6471 Lisp_Object display;
6472{
fbd6baed 6473 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6474
6475 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6476}
6477
6478DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
74e1aeec
JR
6479 0, 1, 0,
6480 doc: /* Returns the number of color cells of DISPLAY.
6481The optional argument DISPLAY specifies which display to ask about.
6482DISPLAY should be either a frame or a display name (a string).
6483If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6484 (display)
6485 Lisp_Object display;
6486{
fbd6baed 6487 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6488 HDC hdc;
6489 int cap;
6490
5ac45f98
GV
6491 hdc = GetDC (dpyinfo->root_window);
6492 if (dpyinfo->has_palette)
6493 cap = GetDeviceCaps (hdc,SIZEPALETTE);
6494 else
6495 cap = GetDeviceCaps (hdc,NUMCOLORS);
abf8c61b 6496
007776bc
JB
6497 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
6498 and because probably is more meaningful on Windows anyway */
abf8c61b 6499 if (cap < 0)
007776bc 6500 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
7d0393cf 6501
ee78dc32 6502 ReleaseDC (dpyinfo->root_window, hdc);
7d0393cf 6503
ee78dc32
GV
6504 return make_number (cap);
6505}
6506
6507DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6508 Sx_server_max_request_size,
74e1aeec
JR
6509 0, 1, 0,
6510 doc: /* Returns the maximum request size of the server 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 (1);
6520}
6521
6522DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
74e1aeec
JR
6523 doc: /* Returns the vendor ID string of the W32 system (Microsoft).
6524The optional argument DISPLAY specifies which display to ask about.
6525DISPLAY should be either a frame or a display name (a string).
6526If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6527 (display)
6528 Lisp_Object display;
6529{
dfff8a69 6530 return build_string ("Microsoft Corp.");
ee78dc32
GV
6531}
6532
6533DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
74e1aeec
JR
6534 doc: /* Returns the version numbers of the server of DISPLAY.
6535The value is a list of three integers: the major and minor
6536version numbers, and the vendor-specific release
6537number. See also the function `x-server-vendor'.
6538
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 return Fcons (make_number (w32_major_version),
58e0f0e4
AI
6546 Fcons (make_number (w32_minor_version),
6547 Fcons (make_number (w32_build_number), Qnil)));
ee78dc32
GV
6548}
6549
6550DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
74e1aeec
JR
6551 doc: /* Returns the number of screens on the server of DISPLAY.
6552The optional argument DISPLAY specifies which display to ask about.
6553DISPLAY should be either a frame or a display name (a string).
6554If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6555 (display)
6556 Lisp_Object display;
6557{
ee78dc32
GV
6558 return make_number (1);
6559}
6560
74e1aeec
JR
6561DEFUN ("x-display-mm-height", Fx_display_mm_height,
6562 Sx_display_mm_height, 0, 1, 0,
6563 doc: /* Returns the height in millimeters of DISPLAY.
6564The optional argument DISPLAY specifies which display to ask about.
6565DISPLAY should be either a frame or a display name (a string).
6566If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6567 (display)
6568 Lisp_Object display;
6569{
fbd6baed 6570 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6571 HDC hdc;
6572 int cap;
6573
5ac45f98 6574 hdc = GetDC (dpyinfo->root_window);
7d0393cf 6575
ee78dc32 6576 cap = GetDeviceCaps (hdc, VERTSIZE);
7d0393cf 6577
ee78dc32 6578 ReleaseDC (dpyinfo->root_window, hdc);
7d0393cf 6579
ee78dc32
GV
6580 return make_number (cap);
6581}
6582
6583DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
74e1aeec
JR
6584 doc: /* Returns the width in millimeters of DISPLAY.
6585The optional argument DISPLAY specifies which display to ask about.
6586DISPLAY should be either a frame or a display name (a string).
6587If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6588 (display)
6589 Lisp_Object display;
6590{
fbd6baed 6591 struct w32_display_info *dpyinfo = check_x_display_info (display);
ee78dc32
GV
6592
6593 HDC hdc;
6594 int cap;
6595
5ac45f98 6596 hdc = GetDC (dpyinfo->root_window);
7d0393cf 6597
ee78dc32 6598 cap = GetDeviceCaps (hdc, HORZSIZE);
7d0393cf 6599
ee78dc32 6600 ReleaseDC (dpyinfo->root_window, hdc);
7d0393cf 6601
ee78dc32
GV
6602 return make_number (cap);
6603}
6604
6605DEFUN ("x-display-backing-store", Fx_display_backing_store,
74e1aeec
JR
6606 Sx_display_backing_store, 0, 1, 0,
6607 doc: /* Returns an indication of whether DISPLAY does backing store.
6608The value may be `always', `when-mapped', or `not-useful'.
6609The optional argument DISPLAY specifies which display to ask about.
6610DISPLAY should be either a frame or a display name (a string).
6611If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6612 (display)
6613 Lisp_Object display;
6614{
6615 return intern ("not-useful");
6616}
6617
6618DEFUN ("x-display-visual-class", Fx_display_visual_class,
74e1aeec
JR
6619 Sx_display_visual_class, 0, 1, 0,
6620 doc: /* Returns the visual class of DISPLAY.
6621The value is one of the symbols `static-gray', `gray-scale',
6622`static-color', `pseudo-color', `true-color', or `direct-color'.
6623
6624The optional argument DISPLAY specifies which display to ask about.
6625DISPLAY should be either a frame or a display name (a string).
6626If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6627 (display)
6628 Lisp_Object display;
6629{
fbd6baed 6630 struct w32_display_info *dpyinfo = check_x_display_info (display);
abf8c61b 6631 Lisp_Object result = Qnil;
ee78dc32 6632
abf8c61b
AI
6633 if (dpyinfo->has_palette)
6634 result = intern ("pseudo-color");
6635 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6636 result = intern ("static-grey");
6637 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6638 result = intern ("static-color");
6639 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6640 result = intern ("true-color");
ee78dc32 6641
abf8c61b 6642 return result;
ee78dc32
GV
6643}
6644
6645DEFUN ("x-display-save-under", Fx_display_save_under,
74e1aeec
JR
6646 Sx_display_save_under, 0, 1, 0,
6647 doc: /* Returns t if DISPLAY supports the save-under feature.
6648The optional argument DISPLAY specifies which display to ask about.
6649DISPLAY should be either a frame or a display name (a string).
6650If omitted or nil, that stands for the selected frame's display. */)
ee78dc32
GV
6651 (display)
6652 Lisp_Object display;
6653{
6fc2811b
JR
6654 return Qnil;
6655}
6656\f
6657int
6658x_pixel_width (f)
6659 register struct frame *f;
6660{
6661 return PIXEL_WIDTH (f);
6662}
6663
6664int
6665x_pixel_height (f)
6666 register struct frame *f;
6667{
6668 return PIXEL_HEIGHT (f);
6669}
6670
6671int
6672x_char_width (f)
6673 register struct frame *f;
6674{
6675 return FONT_WIDTH (f->output_data.w32->font);
6676}
6677
6678int
6679x_char_height (f)
6680 register struct frame *f;
6681{
6682 return f->output_data.w32->line_height;
6683}
6684
6685int
6686x_screen_planes (f)
6687 register struct frame *f;
6688{
6689 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
6690}
6691\f
6692/* Return the display structure for the display named NAME.
6693 Open a new connection if necessary. */
6694
6695struct w32_display_info *
6696x_display_info_for_name (name)
6697 Lisp_Object name;
6698{
6699 Lisp_Object names;
6700 struct w32_display_info *dpyinfo;
6701
b7826503 6702 CHECK_STRING (name);
6fc2811b
JR
6703
6704 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
6705 dpyinfo;
6706 dpyinfo = dpyinfo->next, names = XCDR (names))
6707 {
6708 Lisp_Object tem;
6709 tem = Fstring_equal (XCAR (XCAR (names)), name);
6710 if (!NILP (tem))
6711 return dpyinfo;
6712 }
6713
6714 /* Use this general default value to start with. */
6715 Vx_resource_name = Vinvocation_name;
6716
6717 validate_x_resource_name ();
6718
6719 dpyinfo = w32_term_init (name, (unsigned char *)0,
d5db4077 6720 (char *) SDATA (Vx_resource_name));
6fc2811b
JR
6721
6722 if (dpyinfo == 0)
d5db4077 6723 error ("Cannot connect to server %s", SDATA (name));
6fc2811b
JR
6724
6725 w32_in_use = 1;
6726 XSETFASTINT (Vwindow_system_version, 3);
6727
6728 return dpyinfo;
6729}
6730
6731DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
74e1aeec
JR
6732 1, 3, 0, doc: /* Open a connection to a server.
6733DISPLAY is the name of the display to connect to.
6734Optional second arg XRM-STRING is a string of resources in xrdb format.
6735If the optional third arg MUST-SUCCEED is non-nil,
6736terminate Emacs if we can't open the connection. */)
6fc2811b
JR
6737 (display, xrm_string, must_succeed)
6738 Lisp_Object display, xrm_string, must_succeed;
6739{
6740 unsigned char *xrm_option;
6741 struct w32_display_info *dpyinfo;
6742
74e1aeec
JR
6743 /* If initialization has already been done, return now to avoid
6744 overwriting critical parts of one_w32_display_info. */
6745 if (w32_in_use)
6746 return Qnil;
6747
b7826503 6748 CHECK_STRING (display);
6fc2811b 6749 if (! NILP (xrm_string))
b7826503 6750 CHECK_STRING (xrm_string);
6fc2811b
JR
6751
6752 if (! EQ (Vwindow_system, intern ("w32")))
6753 error ("Not using Microsoft Windows");
6754
6755 /* Allow color mapping to be defined externally; first look in user's
6756 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6757 {
6758 Lisp_Object color_file;
6759 struct gcpro gcpro1;
6760
6761 color_file = build_string("~/rgb.txt");
6762
6763 GCPRO1 (color_file);
6764
6765 if (NILP (Ffile_readable_p (color_file)))
6766 color_file =
6767 Fexpand_file_name (build_string ("rgb.txt"),
6768 Fsymbol_value (intern ("data-directory")));
6769
6770 Vw32_color_map = Fw32_load_color_file (color_file);
6771
6772 UNGCPRO;
6773 }
6774 if (NILP (Vw32_color_map))
6775 Vw32_color_map = Fw32_default_color_map ();
6776
6777 if (! NILP (xrm_string))
d5db4077 6778 xrm_option = (unsigned char *) SDATA (xrm_string);
6fc2811b
JR
6779 else
6780 xrm_option = (unsigned char *) 0;
6781
6782 /* Use this general default value to start with. */
6783 /* First remove .exe suffix from invocation-name - it looks ugly. */
6784 {
6785 char basename[ MAX_PATH ], *str;
6786
d5db4077 6787 strcpy (basename, SDATA (Vinvocation_name));
6fc2811b
JR
6788 str = strrchr (basename, '.');
6789 if (str) *str = 0;
6790 Vinvocation_name = build_string (basename);
6791 }
6792 Vx_resource_name = Vinvocation_name;
6793
6794 validate_x_resource_name ();
6795
6796 /* This is what opens the connection and sets x_current_display.
6797 This also initializes many symbols, such as those used for input. */
6798 dpyinfo = w32_term_init (display, xrm_option,
d5db4077 6799 (char *) SDATA (Vx_resource_name));
6fc2811b
JR
6800
6801 if (dpyinfo == 0)
6802 {
6803 if (!NILP (must_succeed))
6804 fatal ("Cannot connect to server %s.\n",
d5db4077 6805 SDATA (display));
6fc2811b 6806 else
d5db4077 6807 error ("Cannot connect to server %s", SDATA (display));
6fc2811b
JR
6808 }
6809
6810 w32_in_use = 1;
6811
6812 XSETFASTINT (Vwindow_system_version, 3);
6813 return Qnil;
6814}
6815
6816DEFUN ("x-close-connection", Fx_close_connection,
6817 Sx_close_connection, 1, 1, 0,
74e1aeec
JR
6818 doc: /* Close the connection to DISPLAY's server.
6819For DISPLAY, specify either a frame or a display name (a string).
6820If DISPLAY is nil, that stands for the selected frame's display. */)
6fc2811b
JR
6821 (display)
6822 Lisp_Object display;
6823{
6824 struct w32_display_info *dpyinfo = check_x_display_info (display);
6825 int i;
6826
6827 if (dpyinfo->reference_count > 0)
6828 error ("Display still has frames on it");
6829
6830 BLOCK_INPUT;
6831 /* Free the fonts in the font table. */
6832 for (i = 0; i < dpyinfo->n_fonts; i++)
6833 if (dpyinfo->font_table[i].name)
6834 {
126f2e35
JR
6835 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
6836 xfree (dpyinfo->font_table[i].full_name);
6fc2811b 6837 xfree (dpyinfo->font_table[i].name);
6fc2811b
JR
6838 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
6839 }
6840 x_destroy_all_bitmaps (dpyinfo);
6841
6842 x_delete_display (dpyinfo);
6843 UNBLOCK_INPUT;
6844
6845 return Qnil;
6846}
6847
6848DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
74e1aeec 6849 doc: /* Return the list of display names that Emacs has connections to. */)
6fc2811b
JR
6850 ()
6851{
6852 Lisp_Object tail, result;
6853
6854 result = Qnil;
6855 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
6856 result = Fcons (XCAR (XCAR (tail)), result);
6857
6858 return result;
6859}
6860
6861DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
0a332240
PJ
6862 doc: /* This is a noop on W32 systems. */)
6863 (on, display)
6864 Lisp_Object display, on;
6fc2811b 6865{
6fc2811b
JR
6866 return Qnil;
6867}
6868
6869\f
6fc2811b
JR
6870/***********************************************************************
6871 Image types
6872 ***********************************************************************/
6873
6874/* Value is the number of elements of vector VECTOR. */
6875
6876#define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
6877
6878/* List of supported image types. Use define_image_type to add new
6879 types. Use lookup_image_type to find a type for a given symbol. */
6880
6881static struct image_type *image_types;
6882
6fc2811b
JR
6883/* The symbol `image' which is the car of the lists used to represent
6884 images in Lisp. */
6885
6886extern Lisp_Object Qimage;
6887
6888/* The symbol `xbm' which is used as the type symbol for XBM images. */
6889
6890Lisp_Object Qxbm;
6891
6892/* Keywords. */
6893
6fc2811b 6894extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
77814035
KS
6895extern Lisp_Object QCdata, QCtype;
6896Lisp_Object QCascent, QCmargin, QCrelief;
a93f4566 6897Lisp_Object QCconversion, QCcolor_symbols, QCheuristic_mask;
3cf3436e 6898Lisp_Object QCindex, QCmatrix, QCcolor_adjustment, QCmask;
6fc2811b
JR
6899
6900/* Other symbols. */
6901
3cf3436e 6902Lisp_Object Qlaplace, Qemboss, Qedge_detection, Qheuristic;
6fc2811b
JR
6903
6904/* Time in seconds after which images should be removed from the cache
6905 if not displayed. */
6906
6907Lisp_Object Vimage_cache_eviction_delay;
6908
6909/* Function prototypes. */
6910
6911static void define_image_type P_ ((struct image_type *type));
6912static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
6913static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
6914static void x_laplace P_ ((struct frame *, struct image *));
3cf3436e 6915static void x_emboss P_ ((struct frame *, struct image *));
6fc2811b
JR
6916static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
6917 Lisp_Object));
6918
dfff8a69 6919
6fc2811b
JR
6920/* Define a new image type from TYPE. This adds a copy of TYPE to
6921 image_types and adds the symbol *TYPE->type to Vimage_types. */
6922
6923static void
6924define_image_type (type)
6925 struct image_type *type;
6926{
6927 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
6928 The initialized data segment is read-only. */
6929 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
6930 bcopy (type, p, sizeof *p);
6931 p->next = image_types;
6932 image_types = p;
6933 Vimage_types = Fcons (*p->type, Vimage_types);
6934}
6935
6936
6937/* Look up image type SYMBOL, and return a pointer to its image_type
6938 structure. Value is null if SYMBOL is not a known image type. */
6939
6940static INLINE struct image_type *
6941lookup_image_type (symbol)
6942 Lisp_Object symbol;
6943{
6944 struct image_type *type;
6945
6946 for (type = image_types; type; type = type->next)
6947 if (EQ (symbol, *type->type))
6948 break;
6949
6950 return type;
6951}
6952
6953
6954/* Value is non-zero if OBJECT is a valid Lisp image specification. A
6955 valid image specification is a list whose car is the symbol
6956 `image', and whose rest is a property list. The property list must
6957 contain a value for key `:type'. That value must be the name of a
6958 supported image type. The rest of the property list depends on the
6959 image type. */
6960
6961int
6962valid_image_p (object)
6963 Lisp_Object object;
6964{
6965 int valid_p = 0;
7d0393cf 6966
6fc2811b
JR
6967 if (CONSP (object) && EQ (XCAR (object), Qimage))
6968 {
3cf3436e
JR
6969 Lisp_Object tem;
6970
6971 for (tem = XCDR (object); CONSP (tem); tem = XCDR (tem))
6972 if (EQ (XCAR (tem), QCtype))
6973 {
6974 tem = XCDR (tem);
6975 if (CONSP (tem) && SYMBOLP (XCAR (tem)))
6976 {
6977 struct image_type *type;
6978 type = lookup_image_type (XCAR (tem));
6979 if (type)
6980 valid_p = type->valid_p (object);
6981 }
6982
6983 break;
6984 }
6fc2811b
JR
6985 }
6986
6987 return valid_p;
6988}
6989
6990
6991/* Log error message with format string FORMAT and argument ARG.
6992 Signaling an error, e.g. when an image cannot be loaded, is not a
6993 good idea because this would interrupt redisplay, and the error
6994 message display would lead to another redisplay. This function
6995 therefore simply displays a message. */
6996
6997static void
6998image_error (format, arg1, arg2)
6999 char *format;
7000 Lisp_Object arg1, arg2;
7001{
7002 add_to_log (format, arg1, arg2);
7003}
7004
7005
7006\f
7007/***********************************************************************
7008 Image specifications
7009 ***********************************************************************/
7010
7011enum image_value_type
7012{
7013 IMAGE_DONT_CHECK_VALUE_TYPE,
7014 IMAGE_STRING_VALUE,
3cf3436e 7015 IMAGE_STRING_OR_NIL_VALUE,
6fc2811b
JR
7016 IMAGE_SYMBOL_VALUE,
7017 IMAGE_POSITIVE_INTEGER_VALUE,
8edb0a6f 7018 IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR,
6fc2811b 7019 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
dfff8a69 7020 IMAGE_ASCENT_VALUE,
6fc2811b
JR
7021 IMAGE_INTEGER_VALUE,
7022 IMAGE_FUNCTION_VALUE,
7023 IMAGE_NUMBER_VALUE,
7024 IMAGE_BOOL_VALUE
7025};
7026
7027/* Structure used when parsing image specifications. */
7028
7029struct image_keyword
7030{
7031 /* Name of keyword. */
7032 char *name;
7033
7034 /* The type of value allowed. */
7035 enum image_value_type type;
7036
7037 /* Non-zero means key must be present. */
7038 int mandatory_p;
7039
7040 /* Used to recognize duplicate keywords in a property list. */
7041 int count;
7042
7043 /* The value that was found. */
7044 Lisp_Object value;
7045};
7046
7047
7048static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7049 int, Lisp_Object));
7050static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7051
7052
7053/* Parse image spec SPEC according to KEYWORDS. A valid image spec
7054 has the format (image KEYWORD VALUE ...). One of the keyword/
7055 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7056 image_keywords structures of size NKEYWORDS describing other
7057 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7058
7059static int
7060parse_image_spec (spec, keywords, nkeywords, type)
7061 Lisp_Object spec;
7062 struct image_keyword *keywords;
7063 int nkeywords;
7064 Lisp_Object type;
7065{
7066 int i;
7067 Lisp_Object plist;
7068
7069 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7070 return 0;
7071
7072 plist = XCDR (spec);
7073 while (CONSP (plist))
7074 {
7075 Lisp_Object key, value;
7076
7077 /* First element of a pair must be a symbol. */
7078 key = XCAR (plist);
7079 plist = XCDR (plist);
7080 if (!SYMBOLP (key))
7081 return 0;
7082
7083 /* There must follow a value. */
7084 if (!CONSP (plist))
7085 return 0;
7086 value = XCAR (plist);
7087 plist = XCDR (plist);
7088
7089 /* Find key in KEYWORDS. Error if not found. */
7090 for (i = 0; i < nkeywords; ++i)
d5db4077 7091 if (strcmp (keywords[i].name, SDATA (SYMBOL_NAME (key))) == 0)
6fc2811b
JR
7092 break;
7093
7094 if (i == nkeywords)
7095 continue;
7096
7097 /* Record that we recognized the keyword. If a keywords
7098 was found more than once, it's an error. */
7099 keywords[i].value = value;
7100 ++keywords[i].count;
7d0393cf 7101
6fc2811b
JR
7102 if (keywords[i].count > 1)
7103 return 0;
7104
7105 /* Check type of value against allowed type. */
7106 switch (keywords[i].type)
7107 {
7108 case IMAGE_STRING_VALUE:
7109 if (!STRINGP (value))
7110 return 0;
7111 break;
7112
3cf3436e
JR
7113 case IMAGE_STRING_OR_NIL_VALUE:
7114 if (!STRINGP (value) && !NILP (value))
7115 return 0;
7116 break;
7117
6fc2811b
JR
7118 case IMAGE_SYMBOL_VALUE:
7119 if (!SYMBOLP (value))
7120 return 0;
7121 break;
7122
7123 case IMAGE_POSITIVE_INTEGER_VALUE:
7124 if (!INTEGERP (value) || XINT (value) <= 0)
7125 return 0;
7126 break;
7127
8edb0a6f
JR
7128 case IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR:
7129 if (INTEGERP (value) && XINT (value) >= 0)
7130 break;
7131 if (CONSP (value)
7132 && INTEGERP (XCAR (value)) && INTEGERP (XCDR (value))
7133 && XINT (XCAR (value)) >= 0 && XINT (XCDR (value)) >= 0)
7134 break;
7135 return 0;
7136
dfff8a69
JR
7137 case IMAGE_ASCENT_VALUE:
7138 if (SYMBOLP (value) && EQ (value, Qcenter))
7139 break;
7140 else if (INTEGERP (value)
7141 && XINT (value) >= 0
7142 && XINT (value) <= 100)
7143 break;
7144 return 0;
7145
6fc2811b
JR
7146 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7147 if (!INTEGERP (value) || XINT (value) < 0)
7148 return 0;
7149 break;
7150
7151 case IMAGE_DONT_CHECK_VALUE_TYPE:
7152 break;
7153
7154 case IMAGE_FUNCTION_VALUE:
7155 value = indirect_function (value);
7d0393cf 7156 if (SUBRP (value)
6fc2811b
JR
7157 || COMPILEDP (value)
7158 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7159 break;
7160 return 0;
7161
7162 case IMAGE_NUMBER_VALUE:
7163 if (!INTEGERP (value) && !FLOATP (value))
7164 return 0;
7165 break;
7166
7167 case IMAGE_INTEGER_VALUE:
7168 if (!INTEGERP (value))
7169 return 0;
7170 break;
7171
7172 case IMAGE_BOOL_VALUE:
7173 if (!NILP (value) && !EQ (value, Qt))
7174 return 0;
7175 break;
7176
7177 default:
7178 abort ();
7179 break;
7180 }
7181
7182 if (EQ (key, QCtype) && !EQ (type, value))
7183 return 0;
7184 }
7185
7186 /* Check that all mandatory fields are present. */
7187 for (i = 0; i < nkeywords; ++i)
7188 if (keywords[i].mandatory_p && keywords[i].count == 0)
7189 return 0;
7190
7191 return NILP (plist);
7192}
7193
7194
7195/* Return the value of KEY in image specification SPEC. Value is nil
7196 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7197 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7198
7199static Lisp_Object
7200image_spec_value (spec, key, found)
7201 Lisp_Object spec, key;
7202 int *found;
7203{
7204 Lisp_Object tail;
7d0393cf 7205
6fc2811b
JR
7206 xassert (valid_image_p (spec));
7207
7208 for (tail = XCDR (spec);
7209 CONSP (tail) && CONSP (XCDR (tail));
7210 tail = XCDR (XCDR (tail)))
7211 {
7212 if (EQ (XCAR (tail), key))
7213 {
7214 if (found)
7215 *found = 1;
7216 return XCAR (XCDR (tail));
7217 }
7218 }
7d0393cf 7219
6fc2811b
JR
7220 if (found)
7221 *found = 0;
7222 return Qnil;
7223}
7d0393cf 7224
6fc2811b 7225
ac849ba4
JR
7226DEFUN ("image-size", Fimage_size, Simage_size, 1, 3, 0,
7227 doc: /* Return the size of image SPEC as pair (WIDTH . HEIGHT).
7228PIXELS non-nil means return the size in pixels, otherwise return the
7229size in canonical character units.
7230FRAME is the frame on which the image will be displayed. FRAME nil
7231or omitted means use the selected frame. */)
7232 (spec, pixels, frame)
7233 Lisp_Object spec, pixels, frame;
7234{
7235 Lisp_Object size;
7236
7237 size = Qnil;
7238 if (valid_image_p (spec))
7239 {
7240 struct frame *f = check_x_frame (frame);
7241 int id = lookup_image (f, spec);
7242 struct image *img = IMAGE_FROM_ID (f, id);
7243 int width = img->width + 2 * img->hmargin;
7244 int height = img->height + 2 * img->vmargin;
7d0393cf 7245
ac849ba4
JR
7246 if (NILP (pixels))
7247 size = Fcons (make_float ((double) width / CANON_X_UNIT (f)),
7248 make_float ((double) height / CANON_Y_UNIT (f)));
7249 else
7250 size = Fcons (make_number (width), make_number (height));
7251 }
7252 else
7253 error ("Invalid image specification");
7254
7255 return size;
7256}
7257
7258
7259DEFUN ("image-mask-p", Fimage_mask_p, Simage_mask_p, 1, 2, 0,
7260 doc: /* Return t if image SPEC has a mask bitmap.
7261FRAME is the frame on which the image will be displayed. FRAME nil
7262or omitted means use the selected frame. */)
7263 (spec, frame)
7264 Lisp_Object spec, frame;
7265{
7266 Lisp_Object mask;
7267
7268 mask = Qnil;
7269 if (valid_image_p (spec))
7270 {
7271 struct frame *f = check_x_frame (frame);
7272 int id = lookup_image (f, spec);
7273 struct image *img = IMAGE_FROM_ID (f, id);
7274 if (img->mask)
7275 mask = Qt;
7276 }
7277 else
7278 error ("Invalid image specification");
7279
7280 return mask;
7281}
6fc2811b
JR
7282
7283\f
7284/***********************************************************************
7285 Image type independent image structures
7286 ***********************************************************************/
7287
7288static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7289static void free_image P_ ((struct frame *f, struct image *img));
197edd35 7290static void x_destroy_x_image P_ ((XImage *));
6fc2811b
JR
7291
7292
7293/* Allocate and return a new image structure for image specification
7294 SPEC. SPEC has a hash value of HASH. */
7295
7296static struct image *
7297make_image (spec, hash)
7298 Lisp_Object spec;
7299 unsigned hash;
7300{
7301 struct image *img = (struct image *) xmalloc (sizeof *img);
7d0393cf 7302
6fc2811b
JR
7303 xassert (valid_image_p (spec));
7304 bzero (img, sizeof *img);
7305 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7306 xassert (img->type != NULL);
7307 img->spec = spec;
7308 img->data.lisp_val = Qnil;
7309 img->ascent = DEFAULT_IMAGE_ASCENT;
7310 img->hash = hash;
7311 return img;
7312}
7313
7314
7315/* Free image IMG which was used on frame F, including its resources. */
7316
7317static void
7318free_image (f, img)
7319 struct frame *f;
7320 struct image *img;
7321{
7322 if (img)
7323 {
7324 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7325
7326 /* Remove IMG from the hash table of its cache. */
7327 if (img->prev)
7328 img->prev->next = img->next;
7329 else
7330 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7331
7332 if (img->next)
7333 img->next->prev = img->prev;
7334
7335 c->images[img->id] = NULL;
7336
7337 /* Free resources, then free IMG. */
7338 img->type->free (f, img);
7339 xfree (img);
7340 }
7341}
7342
7343
7344/* Prepare image IMG for display on frame F. Must be called before
7345 drawing an image. */
7346
7347void
7348prepare_image_for_display (f, img)
7349 struct frame *f;
7350 struct image *img;
7351{
7352 EMACS_TIME t;
7353
7354 /* We're about to display IMG, so set its timestamp to `now'. */
7355 EMACS_GET_TIME (t);
7356 img->timestamp = EMACS_SECS (t);
7357
7358 /* If IMG doesn't have a pixmap yet, load it now, using the image
7359 type dependent loader function. */
7360 if (img->pixmap == 0 && !img->load_failed_p)
7361 img->load_failed_p = img->type->load (f, img) == 0;
7362}
7d0393cf 7363
6fc2811b 7364
dfff8a69
JR
7365/* Value is the number of pixels for the ascent of image IMG when
7366 drawn in face FACE. */
7367
7368int
7369image_ascent (img, face)
7370 struct image *img;
7371 struct face *face;
7372{
8edb0a6f 7373 int height = img->height + img->vmargin;
dfff8a69
JR
7374 int ascent;
7375
7376 if (img->ascent == CENTERED_IMAGE_ASCENT)
7377 {
7378 if (face->font)
7379 ascent = height / 2 - (FONT_DESCENT(face->font)
7380 - FONT_BASE(face->font)) / 2;
7381 else
7382 ascent = height / 2;
7383 }
7384 else
ac849ba4 7385 ascent = (int) (height * img->ascent / 100.0);
dfff8a69
JR
7386
7387 return ascent;
7388}
7389
7390
6fc2811b 7391\f
a05e2bae
JR
7392/* Image background colors. */
7393
ac849ba4
JR
7394/* Find the "best" corner color of a bitmap. XIMG is assumed to a device
7395 context with the bitmap selected. */
7396static COLORREF
197edd35
JR
7397four_corners_best (img_dc, width, height)
7398 HDC img_dc;
a05e2bae
JR
7399 unsigned long width, height;
7400{
ac849ba4 7401 COLORREF corners[4], best;
a05e2bae
JR
7402 int i, best_count;
7403
197edd35
JR
7404 /* Get the colors at the corners of img_dc. */
7405 corners[0] = GetPixel (img_dc, 0, 0);
7406 corners[1] = GetPixel (img_dc, width - 1, 0);
7407 corners[2] = GetPixel (img_dc, width - 1, height - 1);
7408 corners[3] = GetPixel (img_dc, 0, height - 1);
a05e2bae
JR
7409
7410 /* Choose the most frequently found color as background. */
7411 for (i = best_count = 0; i < 4; ++i)
7412 {
7413 int j, n;
7d0393cf 7414
a05e2bae
JR
7415 for (j = n = 0; j < 4; ++j)
7416 if (corners[i] == corners[j])
7417 ++n;
7418
7419 if (n > best_count)
7420 best = corners[i], best_count = n;
7421 }
7422
7423 return best;
a05e2bae
JR
7424}
7425
7426/* Return the `background' field of IMG. If IMG doesn't have one yet,
197edd35
JR
7427 it is guessed heuristically. If non-zero, IMG_DC is an existing
7428 device context with the image selected to use for the heuristic. */
a05e2bae
JR
7429
7430unsigned long
197edd35 7431image_background (img, f, img_dc)
a05e2bae
JR
7432 struct image *img;
7433 struct frame *f;
197edd35 7434 HDC img_dc;
a05e2bae
JR
7435{
7436 if (! img->background_valid)
7437 /* IMG doesn't have a background yet, try to guess a reasonable value. */
7438 {
197edd35
JR
7439 int free_ximg = !img_dc;
7440 HGDIOBJ prev;
7441
7442 if (free_ximg)
7443 {
7444 HDC frame_dc = get_frame_dc (f);
7445 img_dc = CreateCompatibleDC (frame_dc);
7446 release_frame_dc (f, frame_dc);
a05e2bae 7447
197edd35
JR
7448 prev = SelectObject (img_dc, img->pixmap);
7449 }
a05e2bae 7450
197edd35 7451 img->background = four_corners_best (img_dc, img->width, img->height);
a05e2bae
JR
7452
7453 if (free_ximg)
197edd35
JR
7454 {
7455 SelectObject (img_dc, prev);
7456 DeleteDC (img_dc);
7457 }
a05e2bae
JR
7458
7459 img->background_valid = 1;
a05e2bae
JR
7460 }
7461
7462 return img->background;
7463}
7464
7465/* Return the `background_transparent' field of IMG. If IMG doesn't
7466 have one yet, it is guessed heuristically. If non-zero, MASK is an
7467 existing XImage object to use for the heuristic. */
7468
7469int
7470image_background_transparent (img, f, mask)
7471 struct image *img;
7472 struct frame *f;
197edd35 7473 HDC mask;
a05e2bae
JR
7474{
7475 if (! img->background_transparent_valid)
7476 /* IMG doesn't have a background yet, try to guess a reasonable value. */
7477 {
a05e2bae
JR
7478 if (img->mask)
7479 {
7480 int free_mask = !mask;
197edd35 7481 HGDIOBJ prev;
a05e2bae 7482
197edd35
JR
7483 if (free_mask)
7484 {
7485 HDC frame_dc = get_frame_dc (f);
7486 mask = CreateCompatibleDC (frame_dc);
7487 release_frame_dc (f, frame_dc);
7488
c922a224 7489 prev = SelectObject (mask, img->mask);
197edd35 7490 }
a05e2bae
JR
7491
7492 img->background_transparent
7493 = !four_corners_best (mask, img->width, img->height);
7494
7495 if (free_mask)
197edd35
JR
7496 {
7497 SelectObject (mask, prev);
7498 DeleteDC (mask);
7499 }
a05e2bae
JR
7500 }
7501 else
a05e2bae
JR
7502 img->background_transparent = 0;
7503
7504 img->background_transparent_valid = 1;
7505 }
7506
7507 return img->background_transparent;
7508}
7509
7510\f
6fc2811b
JR
7511/***********************************************************************
7512 Helper functions for X image types
7513 ***********************************************************************/
7514
a05e2bae
JR
7515static void x_clear_image_1 P_ ((struct frame *, struct image *, int,
7516 int, int));
6fc2811b
JR
7517static void x_clear_image P_ ((struct frame *f, struct image *img));
7518static unsigned long x_alloc_image_color P_ ((struct frame *f,
7519 struct image *img,
7520 Lisp_Object color_name,
7521 unsigned long dflt));
7522
a05e2bae
JR
7523
7524/* Clear X resources of image IMG on frame F. PIXMAP_P non-zero means
7525 free the pixmap if any. MASK_P non-zero means clear the mask
7526 pixmap if any. COLORS_P non-zero means free colors allocated for
7527 the image, if any. */
7528
7529static void
7530x_clear_image_1 (f, img, pixmap_p, mask_p, colors_p)
7531 struct frame *f;
7532 struct image *img;
7533 int pixmap_p, mask_p, colors_p;
7534{
a05e2bae
JR
7535 if (pixmap_p && img->pixmap)
7536 {
ac849ba4
JR
7537 DeleteObject (img->pixmap);
7538 img->pixmap = NULL;
a05e2bae
JR
7539 img->background_valid = 0;
7540 }
7541
7542 if (mask_p && img->mask)
7543 {
ac849ba4
JR
7544 DeleteObject (img->mask);
7545 img->mask = NULL;
a05e2bae
JR
7546 img->background_transparent_valid = 0;
7547 }
7d0393cf 7548
a05e2bae
JR
7549 if (colors_p && img->ncolors)
7550 {
bf76fe9c 7551#if 0 /* TODO: color table support. */
a05e2bae 7552 x_free_colors (f, img->colors, img->ncolors);
bf76fe9c 7553#endif
a05e2bae
JR
7554 xfree (img->colors);
7555 img->colors = NULL;
7556 img->ncolors = 0;
7557 }
a05e2bae
JR
7558}
7559
6fc2811b
JR
7560/* Free X resources of image IMG which is used on frame F. */
7561
7562static void
7563x_clear_image (f, img)
7564 struct frame *f;
7565 struct image *img;
7566{
6fc2811b
JR
7567 if (img->pixmap)
7568 {
7569 BLOCK_INPUT;
ac849ba4 7570 DeleteObject (img->pixmap);
6fc2811b
JR
7571 img->pixmap = 0;
7572 UNBLOCK_INPUT;
7573 }
7574
7575 if (img->ncolors)
7576 {
ac849ba4
JR
7577#if 0 /* TODO: color table support */
7578
6fc2811b 7579 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
7d0393cf 7580
6fc2811b
JR
7581 /* If display has an immutable color map, freeing colors is not
7582 necessary and some servers don't allow it. So don't do it. */
7583 if (class != StaticColor
7584 && class != StaticGray
7585 && class != TrueColor)
7586 {
7587 Colormap cmap;
7588 BLOCK_INPUT;
7589 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
7590 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
7591 img->ncolors, 0);
7592 UNBLOCK_INPUT;
7593 }
ac849ba4 7594#endif
7d0393cf 7595
6fc2811b
JR
7596 xfree (img->colors);
7597 img->colors = NULL;
7598 img->ncolors = 0;
7599 }
6fc2811b
JR
7600}
7601
7602
7603/* Allocate color COLOR_NAME for image IMG on frame F. If color
7604 cannot be allocated, use DFLT. Add a newly allocated color to
7605 IMG->colors, so that it can be freed again. Value is the pixel
7606 color. */
7607
7608static unsigned long
7609x_alloc_image_color (f, img, color_name, dflt)
7610 struct frame *f;
7611 struct image *img;
7612 Lisp_Object color_name;
7613 unsigned long dflt;
7614{
6fc2811b
JR
7615 XColor color;
7616 unsigned long result;
7617
7618 xassert (STRINGP (color_name));
7619
d5db4077 7620 if (w32_defined_color (f, SDATA (color_name), &color, 1))
6fc2811b
JR
7621 {
7622 /* This isn't called frequently so we get away with simply
7623 reallocating the color vector to the needed size, here. */
7624 ++img->ncolors;
7625 img->colors =
7626 (unsigned long *) xrealloc (img->colors,
7627 img->ncolors * sizeof *img->colors);
7628 img->colors[img->ncolors - 1] = color.pixel;
7629 result = color.pixel;
7630 }
7631 else
7632 result = dflt;
7633 return result;
6fc2811b
JR
7634}
7635
7636
7637\f
7638/***********************************************************************
7639 Image Cache
7640 ***********************************************************************/
7641
7642static void cache_image P_ ((struct frame *f, struct image *img));
3cf3436e 7643static void postprocess_image P_ ((struct frame *, struct image *));
197edd35 7644static void x_disable_image P_ ((struct frame *, struct image *));
6fc2811b
JR
7645
7646
7647/* Return a new, initialized image cache that is allocated from the
7648 heap. Call free_image_cache to free an image cache. */
7649
7650struct image_cache *
7651make_image_cache ()
7652{
7653 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
7654 int size;
7d0393cf 7655
6fc2811b
JR
7656 bzero (c, sizeof *c);
7657 c->size = 50;
7658 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
7659 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
7660 c->buckets = (struct image **) xmalloc (size);
7661 bzero (c->buckets, size);
7662 return c;
7663}
7664
7665
7666/* Free image cache of frame F. Be aware that X frames share images
7667 caches. */
7668
7669void
7670free_image_cache (f)
7671 struct frame *f;
7672{
7673 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7674 if (c)
7675 {
7676 int i;
7677
7678 /* Cache should not be referenced by any frame when freed. */
7679 xassert (c->refcount == 0);
7d0393cf 7680
6fc2811b
JR
7681 for (i = 0; i < c->used; ++i)
7682 free_image (f, c->images[i]);
7683 xfree (c->images);
7684 xfree (c);
7685 xfree (c->buckets);
7686 FRAME_X_IMAGE_CACHE (f) = NULL;
7687 }
7688}
7689
7690
7691/* Clear image cache of frame F. FORCE_P non-zero means free all
7692 images. FORCE_P zero means clear only images that haven't been
7693 displayed for some time. Should be called from time to time to
dfff8a69
JR
7694 reduce the number of loaded images. If image-eviction-seconds is
7695 non-nil, this frees images in the cache which weren't displayed for
6fc2811b
JR
7696 at least that many seconds. */
7697
7698void
7699clear_image_cache (f, force_p)
7700 struct frame *f;
7701 int force_p;
7702{
7703 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7704
7705 if (c && INTEGERP (Vimage_cache_eviction_delay))
7706 {
7707 EMACS_TIME t;
7708 unsigned long old;
0327b4cc 7709 int i, nfreed;
6fc2811b
JR
7710
7711 EMACS_GET_TIME (t);
7712 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
7d0393cf 7713
0327b4cc
JR
7714 /* Block input so that we won't be interrupted by a SIGIO
7715 while being in an inconsistent state. */
7716 BLOCK_INPUT;
7d0393cf 7717
0327b4cc 7718 for (i = nfreed = 0; i < c->used; ++i)
6fc2811b
JR
7719 {
7720 struct image *img = c->images[i];
7721 if (img != NULL
0327b4cc 7722 && (force_p || (img->timestamp < old)))
6fc2811b
JR
7723 {
7724 free_image (f, img);
0327b4cc 7725 ++nfreed;
6fc2811b
JR
7726 }
7727 }
7728
7729 /* We may be clearing the image cache because, for example,
7730 Emacs was iconified for a longer period of time. In that
7731 case, current matrices may still contain references to
7732 images freed above. So, clear these matrices. */
0327b4cc 7733 if (nfreed)
6fc2811b 7734 {
0327b4cc 7735 Lisp_Object tail, frame;
7d0393cf 7736
0327b4cc
JR
7737 FOR_EACH_FRAME (tail, frame)
7738 {
7739 struct frame *f = XFRAME (frame);
7740 if (FRAME_W32_P (f)
7741 && FRAME_X_IMAGE_CACHE (f) == c)
7742 clear_current_matrices (f);
7743 }
7744
6fc2811b
JR
7745 ++windows_or_buffers_changed;
7746 }
0327b4cc
JR
7747
7748 UNBLOCK_INPUT;
6fc2811b
JR
7749 }
7750}
7751
7752
7753DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
7754 0, 1, 0,
74e1aeec
JR
7755 doc: /* Clear the image cache of FRAME.
7756FRAME nil or omitted means use the selected frame.
7757FRAME t means clear the image caches of all frames. */)
6fc2811b
JR
7758 (frame)
7759 Lisp_Object frame;
7760{
7761 if (EQ (frame, Qt))
7762 {
7763 Lisp_Object tail;
7d0393cf 7764
6fc2811b
JR
7765 FOR_EACH_FRAME (tail, frame)
7766 if (FRAME_W32_P (XFRAME (frame)))
7767 clear_image_cache (XFRAME (frame), 1);
7768 }
7769 else
7770 clear_image_cache (check_x_frame (frame), 1);
7771
7772 return Qnil;
7773}
7774
7775
3cf3436e
JR
7776/* Compute masks and transform image IMG on frame F, as specified
7777 by the image's specification, */
7778
7779static void
7780postprocess_image (f, img)
7781 struct frame *f;
7782 struct image *img;
7783{
3cf3436e
JR
7784 /* Manipulation of the image's mask. */
7785 if (img->pixmap)
7786 {
7787 Lisp_Object conversion, spec;
7788 Lisp_Object mask;
7789
7790 spec = img->spec;
7d0393cf 7791
3cf3436e
JR
7792 /* `:heuristic-mask t'
7793 `:mask heuristic'
7794 means build a mask heuristically.
7795 `:heuristic-mask (R G B)'
7796 `:mask (heuristic (R G B))'
7797 means build a mask from color (R G B) in the
7798 image.
7799 `:mask nil'
7800 means remove a mask, if any. */
7d0393cf 7801
3cf3436e
JR
7802 mask = image_spec_value (spec, QCheuristic_mask, NULL);
7803 if (!NILP (mask))
7804 x_build_heuristic_mask (f, img, mask);
7805 else
7806 {
7807 int found_p;
7d0393cf 7808
3cf3436e 7809 mask = image_spec_value (spec, QCmask, &found_p);
7d0393cf 7810
3cf3436e
JR
7811 if (EQ (mask, Qheuristic))
7812 x_build_heuristic_mask (f, img, Qt);
7813 else if (CONSP (mask)
7814 && EQ (XCAR (mask), Qheuristic))
7815 {
7816 if (CONSP (XCDR (mask)))
7817 x_build_heuristic_mask (f, img, XCAR (XCDR (mask)));
7818 else
7819 x_build_heuristic_mask (f, img, XCDR (mask));
7820 }
7821 else if (NILP (mask) && found_p && img->mask)
7822 {
ac849ba4 7823 DeleteObject (img->mask);
3cf3436e
JR
7824 img->mask = NULL;
7825 }
7826 }
7d0393cf
JB
7827
7828
3cf3436e
JR
7829 /* Should we apply an image transformation algorithm? */
7830 conversion = image_spec_value (spec, QCconversion, NULL);
7831 if (EQ (conversion, Qdisabled))
7832 x_disable_image (f, img);
7833 else if (EQ (conversion, Qlaplace))
7834 x_laplace (f, img);
7835 else if (EQ (conversion, Qemboss))
7836 x_emboss (f, img);
7837 else if (CONSP (conversion)
7838 && EQ (XCAR (conversion), Qedge_detection))
7839 {
7840 Lisp_Object tem;
7841 tem = XCDR (conversion);
7842 if (CONSP (tem))
7843 x_edge_detection (f, img,
7844 Fplist_get (tem, QCmatrix),
7845 Fplist_get (tem, QCcolor_adjustment));
7846 }
7847 }
3cf3436e
JR
7848}
7849
7850
6fc2811b
JR
7851/* Return the id of image with Lisp specification SPEC on frame F.
7852 SPEC must be a valid Lisp image specification (see valid_image_p). */
7853
7854int
7855lookup_image (f, spec)
7856 struct frame *f;
7857 Lisp_Object spec;
7858{
7859 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7860 struct image *img;
7861 int i;
7862 unsigned hash;
7863 struct gcpro gcpro1;
7864 EMACS_TIME now;
7865
7866 /* F must be a window-system frame, and SPEC must be a valid image
7867 specification. */
7868 xassert (FRAME_WINDOW_P (f));
7869 xassert (valid_image_p (spec));
7d0393cf 7870
6fc2811b
JR
7871 GCPRO1 (spec);
7872
7873 /* Look up SPEC in the hash table of the image cache. */
7874 hash = sxhash (spec, 0);
7875 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
7876
7877 for (img = c->buckets[i]; img; img = img->next)
7878 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
7879 break;
7880
7881 /* If not found, create a new image and cache it. */
7882 if (img == NULL)
7883 {
3cf3436e
JR
7884 extern Lisp_Object Qpostscript;
7885
8edb0a6f 7886 BLOCK_INPUT;
6fc2811b
JR
7887 img = make_image (spec, hash);
7888 cache_image (f, img);
7889 img->load_failed_p = img->type->load (f, img) == 0;
6fc2811b
JR
7890
7891 /* If we can't load the image, and we don't have a width and
7892 height, use some arbitrary width and height so that we can
7893 draw a rectangle for it. */
7894 if (img->load_failed_p)
7895 {
7896 Lisp_Object value;
7897
7898 value = image_spec_value (spec, QCwidth, NULL);
7899 img->width = (INTEGERP (value)
7900 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
7901 value = image_spec_value (spec, QCheight, NULL);
7902 img->height = (INTEGERP (value)
7903 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
7904 }
7905 else
7906 {
7907 /* Handle image type independent image attributes
8f92c555 7908 `:ascent ASCENT', `:margin MARGIN', `:relief RELIEF',
a05e2bae
JR
7909 `:background COLOR'. */
7910 Lisp_Object ascent, margin, relief, bg;
6fc2811b
JR
7911
7912 ascent = image_spec_value (spec, QCascent, NULL);
7913 if (INTEGERP (ascent))
7914 img->ascent = XFASTINT (ascent);
dfff8a69
JR
7915 else if (EQ (ascent, Qcenter))
7916 img->ascent = CENTERED_IMAGE_ASCENT;
7917
6fc2811b
JR
7918 margin = image_spec_value (spec, QCmargin, NULL);
7919 if (INTEGERP (margin) && XINT (margin) >= 0)
8edb0a6f
JR
7920 img->vmargin = img->hmargin = XFASTINT (margin);
7921 else if (CONSP (margin) && INTEGERP (XCAR (margin))
7922 && INTEGERP (XCDR (margin)))
7923 {
7924 if (XINT (XCAR (margin)) > 0)
7925 img->hmargin = XFASTINT (XCAR (margin));
7926 if (XINT (XCDR (margin)) > 0)
7927 img->vmargin = XFASTINT (XCDR (margin));
7928 }
7d0393cf 7929
6fc2811b
JR
7930 relief = image_spec_value (spec, QCrelief, NULL);
7931 if (INTEGERP (relief))
7932 {
7933 img->relief = XINT (relief);
8edb0a6f
JR
7934 img->hmargin += abs (img->relief);
7935 img->vmargin += abs (img->relief);
6fc2811b
JR
7936 }
7937
a05e2bae
JR
7938 if (! img->background_valid)
7939 {
7940 bg = image_spec_value (img->spec, QCbackground, NULL);
7941 if (!NILP (bg))
7942 {
7943 img->background
7944 = x_alloc_image_color (f, img, bg,
7945 FRAME_BACKGROUND_PIXEL (f));
7946 img->background_valid = 1;
7947 }
7948 }
7949
3cf3436e
JR
7950 /* Do image transformations and compute masks, unless we
7951 don't have the image yet. */
7952 if (!EQ (*img->type->type, Qpostscript))
7953 postprocess_image (f, img);
6fc2811b 7954 }
3cf3436e 7955
8edb0a6f
JR
7956 UNBLOCK_INPUT;
7957 xassert (!interrupt_input_blocked);
6fc2811b
JR
7958 }
7959
7960 /* We're using IMG, so set its timestamp to `now'. */
7961 EMACS_GET_TIME (now);
7962 img->timestamp = EMACS_SECS (now);
7d0393cf 7963
6fc2811b 7964 UNGCPRO;
7d0393cf 7965
6fc2811b
JR
7966 /* Value is the image id. */
7967 return img->id;
7968}
7969
7970
7971/* Cache image IMG in the image cache of frame F. */
7972
7973static void
7974cache_image (f, img)
7975 struct frame *f;
7976 struct image *img;
7977{
7978 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7979 int i;
7980
7981 /* Find a free slot in c->images. */
7982 for (i = 0; i < c->used; ++i)
7983 if (c->images[i] == NULL)
7984 break;
7985
7986 /* If no free slot found, maybe enlarge c->images. */
7987 if (i == c->used && c->used == c->size)
7988 {
7989 c->size *= 2;
7990 c->images = (struct image **) xrealloc (c->images,
7991 c->size * sizeof *c->images);
7992 }
7993
7994 /* Add IMG to c->images, and assign IMG an id. */
7995 c->images[i] = img;
7996 img->id = i;
7997 if (i == c->used)
7998 ++c->used;
7999
8000 /* Add IMG to the cache's hash table. */
8001 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
8002 img->next = c->buckets[i];
8003 if (img->next)
8004 img->next->prev = img;
8005 img->prev = NULL;
8006 c->buckets[i] = img;
8007}
8008
8009
8010/* Call FN on every image in the image cache of frame F. Used to mark
8011 Lisp Objects in the image cache. */
8012
8013void
8014forall_images_in_image_cache (f, fn)
8015 struct frame *f;
8016 void (*fn) P_ ((struct image *img));
8017{
8018 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
8019 {
8020 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
8021 if (c)
8022 {
8023 int i;
8024 for (i = 0; i < c->used; ++i)
8025 if (c->images[i])
8026 fn (c->images[i]);
8027 }
8028 }
8029}
8030
8031
8032\f
8033/***********************************************************************
8034 W32 support code
8035 ***********************************************************************/
8036
839b1909
JR
8037/* Macro for defining functions that will be loaded from image DLLs. */
8038#define DEF_IMGLIB_FN(func) FARPROC fn_##func
c922a224 8039
839b1909
JR
8040/* Macro for loading those image functions from the library. */
8041#define LOAD_IMGLIB_FN(lib,func) { \
8042 fn_##func = (void *) GetProcAddress (lib, #func); \
8043 if (!fn_##func) return 0; \
c922a224 8044 }
839b1909 8045
6fc2811b
JR
8046static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
8047 XImage **, Pixmap *));
6fc2811b
JR
8048static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
8049
8050
8051/* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
8052 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
8053 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
ac849ba4
JR
8054 via xmalloc. DEPTH of zero signifies a 24 bit image, otherwise
8055 DEPTH should indicate the bit depth of the image. Print error
8056 messages via image_error if an error occurs. Value is non-zero if
8057 successful. */
6fc2811b
JR
8058
8059static int
8060x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
8061 struct frame *f;
8062 int width, height, depth;
8063 XImage **ximg;
8064 Pixmap *pixmap;
8065{
ac849ba4
JR
8066 BITMAPINFOHEADER *header;
8067 HDC hdc;
8068 int scanline_width_bits;
8069 int remainder;
8070 int palette_colors = 0;
6fc2811b 8071
ac849ba4
JR
8072 if (depth == 0)
8073 depth = 24;
6fc2811b 8074
ac849ba4
JR
8075 if (depth != 1 && depth != 4 && depth != 8
8076 && depth != 16 && depth != 24 && depth != 32)
8077 {
8078 image_error ("Invalid image bit depth specified", Qnil, Qnil);
8079 return 0;
8080 }
8081
8082 scanline_width_bits = width * depth;
8083 remainder = scanline_width_bits % 32;
8084
8085 if (remainder)
8086 scanline_width_bits += 32 - remainder;
8087
8088 /* Bitmaps with a depth less than 16 need a palette. */
8089 /* BITMAPINFO structure already contains the first RGBQUAD. */
8090 if (depth < 16)
8091 palette_colors = 1 << depth - 1;
8092
8093 *ximg = xmalloc (sizeof (XImage) + palette_colors * sizeof (RGBQUAD));
6fc2811b
JR
8094 if (*ximg == NULL)
8095 {
ac849ba4 8096 image_error ("Unable to allocate memory for XImage", Qnil, Qnil);
6fc2811b
JR
8097 return 0;
8098 }
8099
ac849ba4
JR
8100 header = &((*ximg)->info.bmiHeader);
8101 bzero (&((*ximg)->info), sizeof (BITMAPINFO));
8102 header->biSize = sizeof (*header);
8103 header->biWidth = width;
8104 header->biHeight = -height; /* negative indicates a top-down bitmap. */
8105 header->biPlanes = 1;
8106 header->biBitCount = depth;
8107 header->biCompression = BI_RGB;
8108 header->biClrUsed = palette_colors;
6fc2811b 8109
197edd35 8110 /* TODO: fill in palette. */
35624c03
JR
8111 if (depth == 1)
8112 {
8113 (*ximg)->info.bmiColors[0].rgbBlue = 0;
8114 (*ximg)->info.bmiColors[0].rgbGreen = 0;
8115 (*ximg)->info.bmiColors[0].rgbRed = 0;
8116 (*ximg)->info.bmiColors[0].rgbReserved = 0;
8117 (*ximg)->info.bmiColors[1].rgbBlue = 255;
8118 (*ximg)->info.bmiColors[1].rgbGreen = 255;
8119 (*ximg)->info.bmiColors[1].rgbRed = 255;
8120 (*ximg)->info.bmiColors[1].rgbReserved = 0;
8121 }
197edd35 8122
ac849ba4
JR
8123 hdc = get_frame_dc (f);
8124
8125 /* Create a DIBSection and raster array for the bitmap,
8126 and store its handle in *pixmap. */
197edd35
JR
8127 *pixmap = CreateDIBSection (hdc, &((*ximg)->info),
8128 (depth < 16) ? DIB_PAL_COLORS : DIB_RGB_COLORS,
ac849ba4
JR
8129 &((*ximg)->data), NULL, 0);
8130
8131 /* Realize display palette and garbage all frames. */
8132 release_frame_dc (f, hdc);
8133
8134 if (*pixmap == NULL)
6fc2811b 8135 {
ac849ba4
JR
8136 DWORD err = GetLastError();
8137 Lisp_Object errcode;
8138 /* All system errors are < 10000, so the following is safe. */
8139 XSETINT (errcode, (int) err);
8140 image_error ("Unable to create bitmap, error code %d", errcode, Qnil);
6fc2811b 8141 x_destroy_x_image (*ximg);
6fc2811b
JR
8142 return 0;
8143 }
ac849ba4 8144
6fc2811b
JR
8145 return 1;
8146}
8147
8148
8149/* Destroy XImage XIMG. Free XIMG->data. */
8150
8151static void
8152x_destroy_x_image (ximg)
8153 XImage *ximg;
8154{
8155 xassert (interrupt_input_blocked);
8156 if (ximg)
8157 {
ac849ba4 8158 /* Data will be freed by DestroyObject. */
6fc2811b 8159 ximg->data = NULL;
ac849ba4 8160 xfree (ximg);
6fc2811b
JR
8161 }
8162}
8163
8164
8165/* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8166 are width and height of both the image and pixmap. */
8167
8168static void
8169x_put_x_image (f, ximg, pixmap, width, height)
8170 struct frame *f;
8171 XImage *ximg;
8172 Pixmap pixmap;
c9b2104d 8173 int width, height;
6fc2811b 8174{
197edd35
JR
8175#if 0 /* I don't think this is necessary looking at where it is used. */
8176 HDC hdc = get_frame_dc (f);
8177 SetDIBits (hdc, pixmap, 0, height, ximg->data, &(ximg->info), DIB_RGB_COLORS);
8178 release_frame_dc (f, hdc);
6fc2811b 8179#endif
ac849ba4 8180}
6fc2811b
JR
8181
8182\f
8183/***********************************************************************
3cf3436e 8184 File Handling
6fc2811b
JR
8185 ***********************************************************************/
8186
8187static Lisp_Object x_find_image_file P_ ((Lisp_Object));
3cf3436e
JR
8188static char *slurp_file P_ ((char *, int *));
8189
6fc2811b
JR
8190
8191/* Find image file FILE. Look in data-directory, then
8192 x-bitmap-file-path. Value is the full name of the file found, or
8193 nil if not found. */
8194
8195static Lisp_Object
8196x_find_image_file (file)
8197 Lisp_Object file;
8198{
8199 Lisp_Object file_found, search_path;
8200 struct gcpro gcpro1, gcpro2;
8201 int fd;
8202
8203 file_found = Qnil;
8204 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8205 GCPRO2 (file_found, search_path);
8206
8207 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
de2413e9 8208 fd = openp (search_path, file, Qnil, &file_found, Qnil);
7d0393cf 8209
939d6465 8210 if (fd == -1)
6fc2811b
JR
8211 file_found = Qnil;
8212 else
8213 close (fd);
8214
8215 UNGCPRO;
8216 return file_found;
8217}
8218
8219
3cf3436e
JR
8220/* Read FILE into memory. Value is a pointer to a buffer allocated
8221 with xmalloc holding FILE's contents. Value is null if an error
8222 occurred. *SIZE is set to the size of the file. */
8223
8224static char *
8225slurp_file (file, size)
8226 char *file;
8227 int *size;
8228{
8229 FILE *fp = NULL;
8230 char *buf = NULL;
8231 struct stat st;
8232
8233 if (stat (file, &st) == 0
c45bb3b2 8234 && (fp = fopen (file, "rb")) != NULL
3cf3436e
JR
8235 && (buf = (char *) xmalloc (st.st_size),
8236 fread (buf, 1, st.st_size, fp) == st.st_size))
8237 {
8238 *size = st.st_size;
8239 fclose (fp);
8240 }
8241 else
8242 {
8243 if (fp)
8244 fclose (fp);
8245 if (buf)
8246 {
8247 xfree (buf);
8248 buf = NULL;
8249 }
8250 }
7d0393cf 8251
3cf3436e
JR
8252 return buf;
8253}
8254
8255
6fc2811b
JR
8256\f
8257/***********************************************************************
8258 XBM images
8259 ***********************************************************************/
8260
217e5be0 8261static int xbm_scan P_ ((char **, char *, char *, int *));
6fc2811b 8262static int xbm_load P_ ((struct frame *f, struct image *img));
217e5be0
JR
8263static int xbm_load_image P_ ((struct frame *f, struct image *img,
8264 char *, char *));
6fc2811b 8265static int xbm_image_p P_ ((Lisp_Object object));
217e5be0
JR
8266static int xbm_read_bitmap_data P_ ((char *, char *, int *, int *,
8267 unsigned char **));
8268static int xbm_file_p P_ ((Lisp_Object));
6fc2811b
JR
8269
8270
8271/* Indices of image specification fields in xbm_format, below. */
8272
8273enum xbm_keyword_index
8274{
8275 XBM_TYPE,
8276 XBM_FILE,
8277 XBM_WIDTH,
8278 XBM_HEIGHT,
8279 XBM_DATA,
8280 XBM_FOREGROUND,
8281 XBM_BACKGROUND,
8282 XBM_ASCENT,
8283 XBM_MARGIN,
8284 XBM_RELIEF,
8285 XBM_ALGORITHM,
8286 XBM_HEURISTIC_MASK,
a05e2bae 8287 XBM_MASK,
6fc2811b
JR
8288 XBM_LAST
8289};
8290
8291/* Vector of image_keyword structures describing the format
8292 of valid XBM image specifications. */
8293
8294static struct image_keyword xbm_format[XBM_LAST] =
8295{
8296 {":type", IMAGE_SYMBOL_VALUE, 1},
8297 {":file", IMAGE_STRING_VALUE, 0},
8298 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8299 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8300 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
217e5be0
JR
8301 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
8302 {":background", IMAGE_STRING_OR_NIL_VALUE, 0},
8303 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 8304 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 8305 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 8306 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
217e5be0
JR
8307 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8308 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
6fc2811b
JR
8309};
8310
8311/* Structure describing the image type XBM. */
8312
8313static struct image_type xbm_type =
8314{
8315 &Qxbm,
8316 xbm_image_p,
8317 xbm_load,
8318 x_clear_image,
8319 NULL
8320};
8321
8322/* Tokens returned from xbm_scan. */
8323
8324enum xbm_token
8325{
8326 XBM_TK_IDENT = 256,
8327 XBM_TK_NUMBER
8328};
8329
7d0393cf 8330
6fc2811b
JR
8331/* Return non-zero if OBJECT is a valid XBM-type image specification.
8332 A valid specification is a list starting with the symbol `image'
8333 The rest of the list is a property list which must contain an
8334 entry `:type xbm..
8335
8336 If the specification specifies a file to load, it must contain
8337 an entry `:file FILENAME' where FILENAME is a string.
8338
8339 If the specification is for a bitmap loaded from memory it must
8340 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8341 WIDTH and HEIGHT are integers > 0. DATA may be:
8342
8343 1. a string large enough to hold the bitmap data, i.e. it must
8344 have a size >= (WIDTH + 7) / 8 * HEIGHT
8345
8346 2. a bool-vector of size >= WIDTH * HEIGHT
8347
8348 3. a vector of strings or bool-vectors, one for each line of the
8349 bitmap.
8350
217e5be0
JR
8351 4. A string containing an in-memory XBM file. WIDTH and HEIGHT
8352 may not be specified in this case because they are defined in the
8353 XBM file.
8354
6fc2811b
JR
8355 Both the file and data forms may contain the additional entries
8356 `:background COLOR' and `:foreground COLOR'. If not present,
8357 foreground and background of the frame on which the image is
217e5be0 8358 displayed is used. */
6fc2811b
JR
8359
8360static int
8361xbm_image_p (object)
8362 Lisp_Object object;
8363{
8364 struct image_keyword kw[XBM_LAST];
7d0393cf 8365
6fc2811b
JR
8366 bcopy (xbm_format, kw, sizeof kw);
8367 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8368 return 0;
8369
8370 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8371
8372 if (kw[XBM_FILE].count)
8373 {
8374 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8375 return 0;
8376 }
217e5be0
JR
8377 else if (kw[XBM_DATA].count && xbm_file_p (kw[XBM_DATA].value))
8378 {
8379 /* In-memory XBM file. */
8380 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_FILE].count)
8381 return 0;
8382 }
6fc2811b
JR
8383 else
8384 {
8385 Lisp_Object data;
8386 int width, height;
8387
8388 /* Entries for `:width', `:height' and `:data' must be present. */
8389 if (!kw[XBM_WIDTH].count
8390 || !kw[XBM_HEIGHT].count
8391 || !kw[XBM_DATA].count)
8392 return 0;
8393
8394 data = kw[XBM_DATA].value;
8395 width = XFASTINT (kw[XBM_WIDTH].value);
8396 height = XFASTINT (kw[XBM_HEIGHT].value);
7d0393cf 8397
6fc2811b
JR
8398 /* Check type of data, and width and height against contents of
8399 data. */
8400 if (VECTORP (data))
8401 {
8402 int i;
7d0393cf 8403
6fc2811b
JR
8404 /* Number of elements of the vector must be >= height. */
8405 if (XVECTOR (data)->size < height)
8406 return 0;
8407
8408 /* Each string or bool-vector in data must be large enough
8409 for one line of the image. */
8410 for (i = 0; i < height; ++i)
8411 {
8412 Lisp_Object elt = XVECTOR (data)->contents[i];
8413
8414 if (STRINGP (elt))
8415 {
d5db4077 8416 if (SCHARS (elt)
6fc2811b
JR
8417 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8418 return 0;
8419 }
8420 else if (BOOL_VECTOR_P (elt))
8421 {
8422 if (XBOOL_VECTOR (elt)->size < width)
8423 return 0;
8424 }
8425 else
8426 return 0;
8427 }
8428 }
8429 else if (STRINGP (data))
8430 {
d5db4077 8431 if (SCHARS (data)
6fc2811b
JR
8432 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8433 return 0;
8434 }
8435 else if (BOOL_VECTOR_P (data))
8436 {
8437 if (XBOOL_VECTOR (data)->size < width * height)
8438 return 0;
8439 }
8440 else
8441 return 0;
8442 }
8443
6fc2811b
JR
8444 return 1;
8445}
8446
8447
8448/* Scan a bitmap file. FP is the stream to read from. Value is
8449 either an enumerator from enum xbm_token, or a character for a
8450 single-character token, or 0 at end of file. If scanning an
8451 identifier, store the lexeme of the identifier in SVAL. If
8452 scanning a number, store its value in *IVAL. */
8453
8454static int
3cf3436e
JR
8455xbm_scan (s, end, sval, ival)
8456 char **s, *end;
6fc2811b
JR
8457 char *sval;
8458 int *ival;
8459{
8460 int c;
3cf3436e
JR
8461
8462 loop:
8463
6fc2811b 8464 /* Skip white space. */
af3f7be7 8465 while (*s < end && (c = *(*s)++, isspace (c)))
6fc2811b
JR
8466 ;
8467
3cf3436e 8468 if (*s >= end)
6fc2811b
JR
8469 c = 0;
8470 else if (isdigit (c))
8471 {
8472 int value = 0, digit;
7d0393cf 8473
3cf3436e 8474 if (c == '0' && *s < end)
6fc2811b 8475 {
3cf3436e 8476 c = *(*s)++;
6fc2811b
JR
8477 if (c == 'x' || c == 'X')
8478 {
3cf3436e 8479 while (*s < end)
6fc2811b 8480 {
3cf3436e 8481 c = *(*s)++;
6fc2811b
JR
8482 if (isdigit (c))
8483 digit = c - '0';
8484 else if (c >= 'a' && c <= 'f')
8485 digit = c - 'a' + 10;
8486 else if (c >= 'A' && c <= 'F')
8487 digit = c - 'A' + 10;
8488 else
8489 break;
8490 value = 16 * value + digit;
8491 }
8492 }
8493 else if (isdigit (c))
8494 {
8495 value = c - '0';
3cf3436e
JR
8496 while (*s < end
8497 && (c = *(*s)++, isdigit (c)))
6fc2811b
JR
8498 value = 8 * value + c - '0';
8499 }
8500 }
8501 else
8502 {
8503 value = c - '0';
3cf3436e
JR
8504 while (*s < end
8505 && (c = *(*s)++, isdigit (c)))
6fc2811b
JR
8506 value = 10 * value + c - '0';
8507 }
8508
3cf3436e
JR
8509 if (*s < end)
8510 *s = *s - 1;
6fc2811b
JR
8511 *ival = value;
8512 c = XBM_TK_NUMBER;
8513 }
8514 else if (isalpha (c) || c == '_')
8515 {
8516 *sval++ = c;
3cf3436e
JR
8517 while (*s < end
8518 && (c = *(*s)++, (isalnum (c) || c == '_')))
6fc2811b
JR
8519 *sval++ = c;
8520 *sval = 0;
3cf3436e
JR
8521 if (*s < end)
8522 *s = *s - 1;
6fc2811b
JR
8523 c = XBM_TK_IDENT;
8524 }
3cf3436e
JR
8525 else if (c == '/' && **s == '*')
8526 {
8527 /* C-style comment. */
8528 ++*s;
8529 while (**s && (**s != '*' || *(*s + 1) != '/'))
8530 ++*s;
8531 if (**s)
8532 {
8533 *s += 2;
8534 goto loop;
8535 }
8536 }
6fc2811b
JR
8537
8538 return c;
8539}
8540
8541
217e5be0
JR
8542/* XBM bits seem to be backward within bytes compared with how
8543 Windows does things. */
8544static unsigned char reflect_byte (unsigned char orig)
8545{
8546 int i;
8547 unsigned char reflected = 0x00;
8548 for (i = 0; i < 8; i++)
8549 {
8550 if (orig & (0x01 << i))
8551 reflected |= 0x80 >> i;
8552 }
8553 return reflected;
8554}
8555
8556
af3f7be7
JR
8557/* Create a Windows bitmap from X bitmap data. */
8558static HBITMAP
8559w32_create_pixmap_from_bitmap_data (int width, int height, char *data)
8560{
8561 int i, j, w1, w2;
8562 char *bits, *p;
8563 HBITMAP bmp;
8564
8565 w1 = (width + 7) / 8; /* nb of 8bits elt in X bitmap */
8566 w2 = ((width + 15) / 16) * 2; /* nb of 16bits elt in W32 bitmap */
c736ffda 8567 bits = (char *) alloca (height * w2);
af3f7be7
JR
8568 bzero (bits, height * w2);
8569 for (i = 0; i < height; i++)
8570 {
8571 p = bits + i*w2;
8572 for (j = 0; j < w1; j++)
8573 *p++ = reflect_byte(*data++);
8574 }
8575 bmp = CreateBitmap (width, height, 1, 1, bits);
af3f7be7
JR
8576
8577 return bmp;
8578}
8579
8580
6fc2811b 8581/* Replacement for XReadBitmapFileData which isn't available under old
3cf3436e
JR
8582 X versions. CONTENTS is a pointer to a buffer to parse; END is the
8583 buffer's end. Set *WIDTH and *HEIGHT to the width and height of
8584 the image. Return in *DATA the bitmap data allocated with xmalloc.
8585 Value is non-zero if successful. DATA null means just test if
8586 CONTENTS looks like an in-memory XBM file. */
6fc2811b
JR
8587
8588static int
3cf3436e
JR
8589xbm_read_bitmap_data (contents, end, width, height, data)
8590 char *contents, *end;
6fc2811b
JR
8591 int *width, *height;
8592 unsigned char **data;
8593{
3cf3436e 8594 char *s = contents;
6fc2811b
JR
8595 char buffer[BUFSIZ];
8596 int padding_p = 0;
8597 int v10 = 0;
af3f7be7 8598 int bytes_per_line, i, nbytes;
6fc2811b
JR
8599 unsigned char *p;
8600 int value;
8601 int LA1;
8602
8603#define match() \
217e5be0 8604 LA1 = xbm_scan (&s, end, buffer, &value)
6fc2811b
JR
8605
8606#define expect(TOKEN) \
8607 if (LA1 != (TOKEN)) \
8608 goto failure; \
8609 else \
7d0393cf 8610 match ()
6fc2811b
JR
8611
8612#define expect_ident(IDENT) \
8613 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8614 match (); \
8615 else \
8616 goto failure
8617
6fc2811b 8618 *width = *height = -1;
3cf3436e
JR
8619 if (data)
8620 *data = NULL;
8621 LA1 = xbm_scan (&s, end, buffer, &value);
6fc2811b
JR
8622
8623 /* Parse defines for width, height and hot-spots. */
8624 while (LA1 == '#')
8625 {
8626 match ();
8627 expect_ident ("define");
8628 expect (XBM_TK_IDENT);
8629
8630 if (LA1 == XBM_TK_NUMBER);
8631 {
8632 char *p = strrchr (buffer, '_');
8633 p = p ? p + 1 : buffer;
8634 if (strcmp (p, "width") == 0)
8635 *width = value;
8636 else if (strcmp (p, "height") == 0)
8637 *height = value;
8638 }
8639 expect (XBM_TK_NUMBER);
8640 }
8641
8642 if (*width < 0 || *height < 0)
8643 goto failure;
3cf3436e
JR
8644 else if (data == NULL)
8645 goto success;
6fc2811b
JR
8646
8647 /* Parse bits. Must start with `static'. */
8648 expect_ident ("static");
8649 if (LA1 == XBM_TK_IDENT)
8650 {
8651 if (strcmp (buffer, "unsigned") == 0)
8652 {
7d0393cf 8653 match ();
6fc2811b
JR
8654 expect_ident ("char");
8655 }
8656 else if (strcmp (buffer, "short") == 0)
8657 {
8658 match ();
8659 v10 = 1;
af3f7be7
JR
8660 if (*width % 16 && *width % 16 < 9)
8661 padding_p = 1;
6fc2811b
JR
8662 }
8663 else if (strcmp (buffer, "char") == 0)
8664 match ();
8665 else
8666 goto failure;
8667 }
7d0393cf 8668 else
6fc2811b
JR
8669 goto failure;
8670
8671 expect (XBM_TK_IDENT);
8672 expect ('[');
8673 expect (']');
8674 expect ('=');
8675 expect ('{');
8676
af3f7be7
JR
8677 bytes_per_line = (*width + 7) / 8 + padding_p;
8678 nbytes = bytes_per_line * *height;
8679 p = *data = (char *) xmalloc (nbytes);
6fc2811b
JR
8680
8681 if (v10)
8682 {
6fc2811b
JR
8683 for (i = 0; i < nbytes; i += 2)
8684 {
8685 int val = value;
8686 expect (XBM_TK_NUMBER);
8687
35624c03 8688 *p++ = ~ val;
af3f7be7 8689 if (!padding_p || ((i + 2) % bytes_per_line))
35624c03 8690 *p++ = ~ (value >> 8);
7d0393cf 8691
6fc2811b
JR
8692 if (LA1 == ',' || LA1 == '}')
8693 match ();
8694 else
8695 goto failure;
8696 }
8697 }
8698 else
8699 {
8700 for (i = 0; i < nbytes; ++i)
8701 {
8702 int val = value;
8703 expect (XBM_TK_NUMBER);
7d0393cf 8704
35624c03 8705 *p++ = ~ val;
217e5be0 8706
6fc2811b
JR
8707 if (LA1 == ',' || LA1 == '}')
8708 match ();
8709 else
8710 goto failure;
8711 }
8712 }
8713
3cf3436e 8714 success:
6fc2811b
JR
8715 return 1;
8716
8717 failure:
3cf3436e
JR
8718
8719 if (data && *data)
6fc2811b
JR
8720 {
8721 xfree (*data);
8722 *data = NULL;
8723 }
8724 return 0;
8725
8726#undef match
8727#undef expect
8728#undef expect_ident
8729}
8730
516eea8e
JR
8731static void convert_mono_to_color_image (f, img, foreground, background)
8732 struct frame *f;
8733 struct image *img;
8734 COLORREF foreground, background;
8735{
8736 HDC hdc, old_img_dc, new_img_dc;
8737 HGDIOBJ old_prev, new_prev;
8738 HBITMAP new_pixmap;
8739
8740 hdc = get_frame_dc (f);
8741 old_img_dc = CreateCompatibleDC (hdc);
8742 new_img_dc = CreateCompatibleDC (hdc);
8743 new_pixmap = CreateCompatibleBitmap (hdc, img->width, img->height);
8744 release_frame_dc (f, hdc);
8745 old_prev = SelectObject (old_img_dc, img->pixmap);
8746 new_prev = SelectObject (new_img_dc, new_pixmap);
8747 SetTextColor (new_img_dc, foreground);
8748 SetBkColor (new_img_dc, background);
8749
8750 BitBlt (new_img_dc, 0, 0, img->width, img->height, old_img_dc,
8751 0, 0, SRCCOPY);
8752
8753 SelectObject (old_img_dc, old_prev);
c922a224 8754 SelectObject (new_img_dc, new_prev);
516eea8e
JR
8755 DeleteDC (old_img_dc);
8756 DeleteDC (new_img_dc);
8757 DeleteObject (img->pixmap);
8758 if (new_pixmap == 0)
8759 fprintf (stderr, "Failed to convert image to color.\n");
8760 else
8761 img->pixmap = new_pixmap;
8762}
6fc2811b 8763
3cf3436e
JR
8764/* Load XBM image IMG which will be displayed on frame F from buffer
8765 CONTENTS. END is the end of the buffer. Value is non-zero if
8766 successful. */
6fc2811b
JR
8767
8768static int
3cf3436e 8769xbm_load_image (f, img, contents, end)
6fc2811b
JR
8770 struct frame *f;
8771 struct image *img;
3cf3436e 8772 char *contents, *end;
6fc2811b
JR
8773{
8774 int rc;
8775 unsigned char *data;
8776 int success_p = 0;
7d0393cf 8777
3cf3436e 8778 rc = xbm_read_bitmap_data (contents, end, &img->width, &img->height, &data);
6fc2811b
JR
8779 if (rc)
8780 {
6fc2811b
JR
8781 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8782 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
516eea8e 8783 int non_default_colors = 0;
6fc2811b 8784 Lisp_Object value;
7d0393cf 8785
6fc2811b
JR
8786 xassert (img->width > 0 && img->height > 0);
8787
8788 /* Get foreground and background colors, maybe allocate colors. */
8789 value = image_spec_value (img->spec, QCforeground, NULL);
8790 if (!NILP (value))
516eea8e
JR
8791 {
8792 foreground = x_alloc_image_color (f, img, value, foreground);
8793 non_default_colors = 1;
8794 }
6fc2811b
JR
8795 value = image_spec_value (img->spec, QCbackground, NULL);
8796 if (!NILP (value))
a05e2bae
JR
8797 {
8798 background = x_alloc_image_color (f, img, value, background);
8799 img->background = background;
8800 img->background_valid = 1;
516eea8e 8801 non_default_colors = 1;
a05e2bae 8802 }
6fc2811b 8803 img->pixmap
af3f7be7 8804 = w32_create_pixmap_from_bitmap_data (img->width, img->height, data);
ac849ba4 8805
516eea8e
JR
8806 /* If colors were specified, transfer the bitmap to a color one. */
8807 if (non_default_colors)
8808 convert_mono_to_color_image (f, img, foreground, background);
8809
6fc2811b
JR
8810 xfree (data);
8811
8812 if (img->pixmap == 0)
8813 {
8814 x_clear_image (f, img);
3cf3436e 8815 image_error ("Unable to create X pixmap for `%s'", img->spec, Qnil);
6fc2811b
JR
8816 }
8817 else
8818 success_p = 1;
6fc2811b
JR
8819 }
8820 else
8821 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8822
6fc2811b
JR
8823 return success_p;
8824}
8825
8826
3cf3436e
JR
8827/* Value is non-zero if DATA looks like an in-memory XBM file. */
8828
8829static int
8830xbm_file_p (data)
8831 Lisp_Object data;
8832{
8833 int w, h;
8834 return (STRINGP (data)
d5db4077
KR
8835 && xbm_read_bitmap_data (SDATA (data),
8836 (SDATA (data)
8837 + SBYTES (data)),
3cf3436e
JR
8838 &w, &h, NULL));
8839}
8840
7d0393cf 8841
6fc2811b
JR
8842/* Fill image IMG which is used on frame F with pixmap data. Value is
8843 non-zero if successful. */
8844
8845static int
8846xbm_load (f, img)
8847 struct frame *f;
8848 struct image *img;
8849{
8850 int success_p = 0;
8851 Lisp_Object file_name;
8852
8853 xassert (xbm_image_p (img->spec));
8854
8855 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8856 file_name = image_spec_value (img->spec, QCfile, NULL);
8857 if (STRINGP (file_name))
3cf3436e
JR
8858 {
8859 Lisp_Object file;
8860 char *contents;
8861 int size;
8862 struct gcpro gcpro1;
8863
8864 file = x_find_image_file (file_name);
8865 GCPRO1 (file);
8866 if (!STRINGP (file))
8867 {
8868 image_error ("Cannot find image file `%s'", file_name, Qnil);
8869 UNGCPRO;
8870 return 0;
8871 }
8872
d5db4077 8873 contents = slurp_file (SDATA (file), &size);
3cf3436e
JR
8874 if (contents == NULL)
8875 {
8876 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8877 UNGCPRO;
8878 return 0;
8879 }
8880
8881 success_p = xbm_load_image (f, img, contents, contents + size);
8882 UNGCPRO;
8883 }
6fc2811b
JR
8884 else
8885 {
8886 struct image_keyword fmt[XBM_LAST];
8887 Lisp_Object data;
6fc2811b
JR
8888 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8889 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
516eea8e 8890 int non_default_colors = 0;
6fc2811b
JR
8891 char *bits;
8892 int parsed_p;
3cf3436e
JR
8893 int in_memory_file_p = 0;
8894
8895 /* See if data looks like an in-memory XBM file. */
8896 data = image_spec_value (img->spec, QCdata, NULL);
8897 in_memory_file_p = xbm_file_p (data);
6fc2811b 8898
217e5be0 8899 /* Parse the image specification. */
6fc2811b
JR
8900 bcopy (xbm_format, fmt, sizeof fmt);
8901 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
8902 xassert (parsed_p);
8903
8904 /* Get specified width, and height. */
3cf3436e
JR
8905 if (!in_memory_file_p)
8906 {
8907 img->width = XFASTINT (fmt[XBM_WIDTH].value);
8908 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
8909 xassert (img->width > 0 && img->height > 0);
8910 }
217e5be0 8911
6fc2811b 8912 /* Get foreground and background colors, maybe allocate colors. */
3cf3436e
JR
8913 if (fmt[XBM_FOREGROUND].count
8914 && STRINGP (fmt[XBM_FOREGROUND].value))
516eea8e
JR
8915 {
8916 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
8917 foreground);
8918 non_default_colors = 1;
8919 }
8920
3cf3436e
JR
8921 if (fmt[XBM_BACKGROUND].count
8922 && STRINGP (fmt[XBM_BACKGROUND].value))
516eea8e
JR
8923 {
8924 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
8925 background);
8926 non_default_colors = 1;
8927 }
6fc2811b 8928
3cf3436e 8929 if (in_memory_file_p)
d5db4077
KR
8930 success_p = xbm_load_image (f, img, SDATA (data),
8931 (SDATA (data)
8932 + SBYTES (data)));
3cf3436e 8933 else
6fc2811b 8934 {
3cf3436e
JR
8935 if (VECTORP (data))
8936 {
8937 int i;
8938 char *p;
8939 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
7d0393cf 8940
3cf3436e
JR
8941 p = bits = (char *) alloca (nbytes * img->height);
8942 for (i = 0; i < img->height; ++i, p += nbytes)
8943 {
8944 Lisp_Object line = XVECTOR (data)->contents[i];
8945 if (STRINGP (line))
d5db4077 8946 bcopy (SDATA (line), p, nbytes);
3cf3436e
JR
8947 else
8948 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
8949 }
8950 }
8951 else if (STRINGP (data))
d5db4077 8952 bits = SDATA (data);
3cf3436e
JR
8953 else
8954 bits = XBOOL_VECTOR (data)->data;
af3f7be7 8955
3cf3436e 8956 /* Create the pixmap. */
3cf3436e 8957 img->pixmap
af3f7be7
JR
8958 = w32_create_pixmap_from_bitmap_data (img->width, img->height,
8959 bits);
8960
516eea8e
JR
8961 /* If colors were specified, transfer the bitmap to a color one. */
8962 if (non_default_colors)
8963 convert_mono_to_color_image (f, img, foreground, background);
8964
3cf3436e
JR
8965 if (img->pixmap)
8966 success_p = 1;
8967 else
6fc2811b 8968 {
3cf3436e
JR
8969 image_error ("Unable to create pixmap for XBM image `%s'",
8970 img->spec, Qnil);
8971 x_clear_image (f, img);
6fc2811b
JR
8972 }
8973 }
6fc2811b
JR
8974 }
8975
8976 return success_p;
8977}
7d0393cf 8978
6fc2811b
JR
8979
8980\f
8981/***********************************************************************
8982 XPM images
8983 ***********************************************************************/
8984
7d0393cf 8985#if HAVE_XPM
6fc2811b
JR
8986
8987static int xpm_image_p P_ ((Lisp_Object object));
8988static int xpm_load P_ ((struct frame *f, struct image *img));
8989static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
8990
c736ffda
JR
8991/* Indicate to xpm.h that we don't have Xlib. */
8992#define FOR_MSW
8993/* simx.h in xpm defines XColor and XImage differently than Emacs. */
8994#define XColor xpm_XColor
8995#define XImage xpm_XImage
8996#define PIXEL_ALREADY_TYPEDEFED
6fc2811b 8997#include "X11/xpm.h"
c736ffda
JR
8998#undef FOR_MSW
8999#undef XColor
9000#undef XImage
9001#undef PIXEL_ALREADY_TYPEDEFED
6fc2811b
JR
9002
9003/* The symbol `xpm' identifying XPM-format images. */
9004
9005Lisp_Object Qxpm;
9006
9007/* Indices of image specification fields in xpm_format, below. */
9008
9009enum xpm_keyword_index
9010{
9011 XPM_TYPE,
9012 XPM_FILE,
9013 XPM_DATA,
9014 XPM_ASCENT,
9015 XPM_MARGIN,
9016 XPM_RELIEF,
9017 XPM_ALGORITHM,
9018 XPM_HEURISTIC_MASK,
a05e2bae 9019 XPM_MASK,
6fc2811b 9020 XPM_COLOR_SYMBOLS,
a05e2bae 9021 XPM_BACKGROUND,
6fc2811b
JR
9022 XPM_LAST
9023};
9024
9025/* Vector of image_keyword structures describing the format
9026 of valid XPM image specifications. */
9027
9028static struct image_keyword xpm_format[XPM_LAST] =
9029{
9030 {":type", IMAGE_SYMBOL_VALUE, 1},
9031 {":file", IMAGE_STRING_VALUE, 0},
9032 {":data", IMAGE_STRING_VALUE, 0},
8f92c555 9033 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 9034 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 9035 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 9036 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6fc2811b 9037 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
9038 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9039 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9040 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
9041};
9042
197edd35 9043/* Structure describing the image type XPM. */
6fc2811b
JR
9044
9045static struct image_type xpm_type =
9046{
9047 &Qxpm,
9048 xpm_image_p,
9049 xpm_load,
9050 x_clear_image,
9051 NULL
9052};
9053
9054
c736ffda
JR
9055/* XPM library details. */
9056
9057DEF_IMGLIB_FN (XpmFreeAttributes);
9058DEF_IMGLIB_FN (XpmCreateImageFromBuffer);
9059DEF_IMGLIB_FN (XpmReadFileToImage);
9060DEF_IMGLIB_FN (XImageFree);
9061
9062
9063static int
9064init_xpm_functions (library)
9065 HMODULE library;
9066{
9067 LOAD_IMGLIB_FN (library, XpmFreeAttributes);
9068 LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
9069 LOAD_IMGLIB_FN (library, XpmReadFileToImage);
9070 LOAD_IMGLIB_FN (library, XImageFree);
9071
9072 return 1;
9073}
9074
6fc2811b
JR
9075/* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
9076 for XPM images. Such a list must consist of conses whose car and
9077 cdr are strings. */
9078
9079static int
9080xpm_valid_color_symbols_p (color_symbols)
9081 Lisp_Object color_symbols;
9082{
9083 while (CONSP (color_symbols))
9084 {
9085 Lisp_Object sym = XCAR (color_symbols);
9086 if (!CONSP (sym)
9087 || !STRINGP (XCAR (sym))
9088 || !STRINGP (XCDR (sym)))
9089 break;
9090 color_symbols = XCDR (color_symbols);
9091 }
9092
9093 return NILP (color_symbols);
9094}
9095
9096
9097/* Value is non-zero if OBJECT is a valid XPM image specification. */
9098
9099static int
9100xpm_image_p (object)
9101 Lisp_Object object;
9102{
9103 struct image_keyword fmt[XPM_LAST];
9104 bcopy (xpm_format, fmt, sizeof fmt);
9105 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
9106 /* Either `:file' or `:data' must be present. */
9107 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
9108 /* Either no `:color-symbols' or it's a list of conses
9109 whose car and cdr are strings. */
9110 && (fmt[XPM_COLOR_SYMBOLS].count == 0
8f92c555 9111 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value)));
6fc2811b
JR
9112}
9113
9114
9115/* Load image IMG which will be displayed on frame F. Value is
9116 non-zero if successful. */
9117
9118static int
9119xpm_load (f, img)
9120 struct frame *f;
9121 struct image *img;
9122{
c736ffda
JR
9123 HDC hdc;
9124 int rc;
6fc2811b
JR
9125 XpmAttributes attrs;
9126 Lisp_Object specified_file, color_symbols;
c736ffda 9127 xpm_XImage * xpm_image, * xpm_mask;
6fc2811b
JR
9128
9129 /* Configure the XPM lib. Use the visual of frame F. Allocate
9130 close colors. Return colors allocated. */
9131 bzero (&attrs, sizeof attrs);
c736ffda
JR
9132 xpm_image = xpm_mask = NULL;
9133
9134#if 0
dfff8a69
JR
9135 attrs.visual = FRAME_X_VISUAL (f);
9136 attrs.colormap = FRAME_X_COLORMAP (f);
6fc2811b 9137 attrs.valuemask |= XpmVisual;
dfff8a69 9138 attrs.valuemask |= XpmColormap;
c736ffda 9139#endif
6fc2811b 9140 attrs.valuemask |= XpmReturnAllocPixels;
dfff8a69 9141#ifdef XpmAllocCloseColors
6fc2811b
JR
9142 attrs.alloc_close_colors = 1;
9143 attrs.valuemask |= XpmAllocCloseColors;
dfff8a69
JR
9144#else
9145 attrs.closeness = 600;
9146 attrs.valuemask |= XpmCloseness;
9147#endif
6fc2811b
JR
9148
9149 /* If image specification contains symbolic color definitions, add
9150 these to `attrs'. */
9151 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
9152 if (CONSP (color_symbols))
9153 {
9154 Lisp_Object tail;
9155 XpmColorSymbol *xpm_syms;
9156 int i, size;
7d0393cf 9157
6fc2811b
JR
9158 attrs.valuemask |= XpmColorSymbols;
9159
9160 /* Count number of symbols. */
9161 attrs.numsymbols = 0;
9162 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
9163 ++attrs.numsymbols;
9164
9165 /* Allocate an XpmColorSymbol array. */
9166 size = attrs.numsymbols * sizeof *xpm_syms;
9167 xpm_syms = (XpmColorSymbol *) alloca (size);
9168 bzero (xpm_syms, size);
9169 attrs.colorsymbols = xpm_syms;
9170
9171 /* Fill the color symbol array. */
9172 for (tail = color_symbols, i = 0;
9173 CONSP (tail);
9174 ++i, tail = XCDR (tail))
9175 {
9176 Lisp_Object name = XCAR (XCAR (tail));
9177 Lisp_Object color = XCDR (XCAR (tail));
d5db4077
KR
9178 xpm_syms[i].name = (char *) alloca (SCHARS (name) + 1);
9179 strcpy (xpm_syms[i].name, SDATA (name));
9180 xpm_syms[i].value = (char *) alloca (SCHARS (color) + 1);
9181 strcpy (xpm_syms[i].value, SDATA (color));
6fc2811b
JR
9182 }
9183 }
9184
9185 /* Create a pixmap for the image, either from a file, or from a
9186 string buffer containing data in the same format as an XPM file. */
c736ffda 9187
6fc2811b 9188 specified_file = image_spec_value (img->spec, QCfile, NULL);
177c0ea7 9189
c736ffda
JR
9190 {
9191 HDC frame_dc = get_frame_dc (f);
9192 hdc = CreateCompatibleDC (frame_dc);
9193 release_frame_dc (f, frame_dc);
9194 }
9195
6fc2811b
JR
9196 if (STRINGP (specified_file))
9197 {
9198 Lisp_Object file = x_find_image_file (specified_file);
9199 if (!STRINGP (file))
9200 {
9201 image_error ("Cannot find image file `%s'", specified_file, Qnil);
6fc2811b
JR
9202 return 0;
9203 }
7d0393cf 9204
c736ffda
JR
9205 /* XpmReadFileToPixmap is not available in the Windows port of
9206 libxpm. But XpmReadFileToImage almost does what we want. */
9207 rc = fn_XpmReadFileToImage (&hdc, SDATA (file),
9208 &xpm_image, &xpm_mask,
9209 &attrs);
6fc2811b
JR
9210 }
9211 else
9212 {
9213 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
c736ffda
JR
9214 /* XpmCreatePixmapFromBuffer is not available in the Windows port
9215 of libxpm. But XpmCreateImageFromBuffer almost does what we want. */
9216 rc = fn_XpmCreateImageFromBuffer (&hdc, SDATA (buffer),
9217 &xpm_image, &xpm_mask,
9218 &attrs);
6fc2811b 9219 }
6fc2811b
JR
9220
9221 if (rc == XpmSuccess)
9222 {
c736ffda
JR
9223 int i;
9224
9225 /* W32 XPM uses XImage to wrap what W32 Emacs calls a Pixmap,
9226 plus some duplicate attributes. */
9227 if (xpm_image && xpm_image->bitmap)
9228 {
9229 img->pixmap = xpm_image->bitmap;
9230 /* XImageFree in libXpm frees XImage struct without destroying
9231 the bitmap, which is what we want. */
9232 fn_XImageFree (xpm_image);
9233 }
9234 if (xpm_mask && xpm_mask->bitmap)
177c0ea7 9235 {
c736ffda
JR
9236 /* The mask appears to be inverted compared with what we expect.
9237 TODO: invert our expectations. See other places where we
9238 have to invert bits because our idea of masks is backwards. */
9239 HGDIOBJ old_obj;
9240 old_obj = SelectObject (hdc, xpm_mask->bitmap);
9241
9242 PatBlt (hdc, 0, 0, xpm_mask->width, xpm_mask->height, DSTINVERT);
9243 SelectObject (hdc, old_obj);
9244
9245 img->mask = xpm_mask->bitmap;
177c0ea7 9246 fn_XImageFree (xpm_mask);
c736ffda
JR
9247 DeleteDC (hdc);
9248 }
9249
9250 DeleteDC (hdc);
9251
6fc2811b
JR
9252 /* Remember allocated colors. */
9253 img->ncolors = attrs.nalloc_pixels;
9254 img->colors = (unsigned long *) xmalloc (img->ncolors
9255 * sizeof *img->colors);
9256 for (i = 0; i < attrs.nalloc_pixels; ++i)
9257 img->colors[i] = attrs.alloc_pixels[i];
9258
9259 img->width = attrs.width;
9260 img->height = attrs.height;
9261 xassert (img->width > 0 && img->height > 0);
9262
9263 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
c736ffda 9264 fn_XpmFreeAttributes (&attrs);
6fc2811b
JR
9265 }
9266 else
9267 {
c736ffda
JR
9268 DeleteDC (hdc);
9269
6fc2811b
JR
9270 switch (rc)
9271 {
9272 case XpmOpenFailed:
9273 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
9274 break;
7d0393cf 9275
6fc2811b
JR
9276 case XpmFileInvalid:
9277 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
9278 break;
7d0393cf 9279
6fc2811b
JR
9280 case XpmNoMemory:
9281 image_error ("Out of memory (%s)", img->spec, Qnil);
9282 break;
7d0393cf 9283
6fc2811b
JR
9284 case XpmColorFailed:
9285 image_error ("Color allocation error (%s)", img->spec, Qnil);
9286 break;
7d0393cf 9287
6fc2811b
JR
9288 default:
9289 image_error ("Unknown error (%s)", img->spec, Qnil);
9290 break;
9291 }
9292 }
9293
9294 return rc == XpmSuccess;
9295}
9296
9297#endif /* HAVE_XPM != 0 */
9298
9299\f
767b1ff0 9300#if 0 /* TODO : Color tables on W32. */
6fc2811b
JR
9301/***********************************************************************
9302 Color table
9303 ***********************************************************************/
9304
9305/* An entry in the color table mapping an RGB color to a pixel color. */
9306
9307struct ct_color
9308{
9309 int r, g, b;
9310 unsigned long pixel;
9311
9312 /* Next in color table collision list. */
9313 struct ct_color *next;
9314};
9315
9316/* The bucket vector size to use. Must be prime. */
9317
9318#define CT_SIZE 101
9319
9320/* Value is a hash of the RGB color given by R, G, and B. */
9321
9322#define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
9323
9324/* The color hash table. */
9325
9326struct ct_color **ct_table;
9327
9328/* Number of entries in the color table. */
9329
9330int ct_colors_allocated;
9331
9332/* Function prototypes. */
9333
9334static void init_color_table P_ ((void));
9335static void free_color_table P_ ((void));
9336static unsigned long *colors_in_color_table P_ ((int *n));
9337static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
9338static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
9339
9340
9341/* Initialize the color table. */
9342
9343static void
9344init_color_table ()
9345{
9346 int size = CT_SIZE * sizeof (*ct_table);
9347 ct_table = (struct ct_color **) xmalloc (size);
9348 bzero (ct_table, size);
9349 ct_colors_allocated = 0;
9350}
9351
9352
9353/* Free memory associated with the color table. */
9354
9355static void
9356free_color_table ()
9357{
9358 int i;
9359 struct ct_color *p, *next;
9360
9361 for (i = 0; i < CT_SIZE; ++i)
9362 for (p = ct_table[i]; p; p = next)
9363 {
9364 next = p->next;
9365 xfree (p);
9366 }
9367
9368 xfree (ct_table);
9369 ct_table = NULL;
9370}
9371
9372
9373/* Value is a pixel color for RGB color R, G, B on frame F. If an
9374 entry for that color already is in the color table, return the
9375 pixel color of that entry. Otherwise, allocate a new color for R,
9376 G, B, and make an entry in the color table. */
9377
9378static unsigned long
9379lookup_rgb_color (f, r, g, b)
9380 struct frame *f;
9381 int r, g, b;
9382{
9383 unsigned hash = CT_HASH_RGB (r, g, b);
9384 int i = hash % CT_SIZE;
9385 struct ct_color *p;
9386
9387 for (p = ct_table[i]; p; p = p->next)
9388 if (p->r == r && p->g == g && p->b == b)
9389 break;
9390
9391 if (p == NULL)
9392 {
9393 COLORREF color;
9394 Colormap cmap;
9395 int rc;
9396
9397 color = PALETTERGB (r, g, b);
9398
9399 ++ct_colors_allocated;
9400
9401 p = (struct ct_color *) xmalloc (sizeof *p);
9402 p->r = r;
9403 p->g = g;
9404 p->b = b;
9405 p->pixel = color;
9406 p->next = ct_table[i];
9407 ct_table[i] = p;
9408 }
9409
9410 return p->pixel;
9411}
9412
9413
9414/* Look up pixel color PIXEL which is used on frame F in the color
9415 table. If not already present, allocate it. Value is PIXEL. */
9416
9417static unsigned long
9418lookup_pixel_color (f, pixel)
9419 struct frame *f;
9420 unsigned long pixel;
9421{
9422 int i = pixel % CT_SIZE;
9423 struct ct_color *p;
9424
9425 for (p = ct_table[i]; p; p = p->next)
9426 if (p->pixel == pixel)
9427 break;
9428
9429 if (p == NULL)
9430 {
9431 XColor color;
9432 Colormap cmap;
9433 int rc;
9434
9435 BLOCK_INPUT;
7d0393cf 9436
6fc2811b
JR
9437 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9438 color.pixel = pixel;
9439 XQueryColor (NULL, cmap, &color);
9440 rc = x_alloc_nearest_color (f, cmap, &color);
9441 UNBLOCK_INPUT;
9442
9443 if (rc)
9444 {
9445 ++ct_colors_allocated;
7d0393cf 9446
6fc2811b
JR
9447 p = (struct ct_color *) xmalloc (sizeof *p);
9448 p->r = color.red;
9449 p->g = color.green;
9450 p->b = color.blue;
9451 p->pixel = pixel;
9452 p->next = ct_table[i];
9453 ct_table[i] = p;
9454 }
9455 else
9456 return FRAME_FOREGROUND_PIXEL (f);
9457 }
9458 return p->pixel;
9459}
9460
9461
9462/* Value is a vector of all pixel colors contained in the color table,
9463 allocated via xmalloc. Set *N to the number of colors. */
9464
9465static unsigned long *
9466colors_in_color_table (n)
9467 int *n;
9468{
9469 int i, j;
9470 struct ct_color *p;
9471 unsigned long *colors;
9472
9473 if (ct_colors_allocated == 0)
9474 {
9475 *n = 0;
9476 colors = NULL;
9477 }
9478 else
9479 {
9480 colors = (unsigned long *) xmalloc (ct_colors_allocated
9481 * sizeof *colors);
9482 *n = ct_colors_allocated;
7d0393cf 9483
6fc2811b
JR
9484 for (i = j = 0; i < CT_SIZE; ++i)
9485 for (p = ct_table[i]; p; p = p->next)
9486 colors[j++] = p->pixel;
9487 }
9488
9489 return colors;
9490}
9491
767b1ff0 9492#endif /* TODO */
6fc2811b
JR
9493
9494\f
9495/***********************************************************************
9496 Algorithms
9497 ***********************************************************************/
3cf3436e
JR
9498static XColor *x_to_xcolors P_ ((struct frame *, struct image *, int));
9499static void x_from_xcolors P_ ((struct frame *, struct image *, XColor *));
9500static void x_detect_edges P_ ((struct frame *, struct image *, int[9], int));
ac849ba4 9501static void XPutPixel (XImage *, int, int, COLORREF);
3cf3436e
JR
9502
9503/* Non-zero means draw a cross on images having `:conversion
9504 disabled'. */
6fc2811b 9505
3cf3436e 9506int cross_disabled_images;
6fc2811b 9507
3cf3436e
JR
9508/* Edge detection matrices for different edge-detection
9509 strategies. */
6fc2811b 9510
3cf3436e
JR
9511static int emboss_matrix[9] = {
9512 /* x - 1 x x + 1 */
9513 2, -1, 0, /* y - 1 */
9514 -1, 0, 1, /* y */
9515 0, 1, -2 /* y + 1 */
9516};
9517
9518static int laplace_matrix[9] = {
9519 /* x - 1 x x + 1 */
9520 1, 0, 0, /* y - 1 */
9521 0, 0, 0, /* y */
9522 0, 0, -1 /* y + 1 */
9523};
9524
9525/* Value is the intensity of the color whose red/green/blue values
9526 are R, G, and B. */
9527
9528#define COLOR_INTENSITY(R, G, B) ((2 * (R) + 3 * (G) + (B)) / 6)
9529
9530
9531/* On frame F, return an array of XColor structures describing image
9532 IMG->pixmap. Each XColor structure has its pixel color set. RGB_P
9533 non-zero means also fill the red/green/blue members of the XColor
9534 structures. Value is a pointer to the array of XColors structures,
9535 allocated with xmalloc; it must be freed by the caller. */
9536
9537static XColor *
9538x_to_xcolors (f, img, rgb_p)
9539 struct frame *f;
9540 struct image *img;
9541 int rgb_p;
9542{
9543 int x, y;
9544 XColor *colors, *p;
197edd35
JR
9545 HDC hdc, bmpdc;
9546 HGDIOBJ prev;
3cf3436e
JR
9547
9548 colors = (XColor *) xmalloc (img->width * img->height * sizeof *colors);
197edd35
JR
9549
9550 /* Load the image into a memory device context. */
9551 hdc = get_frame_dc (f);
9552 bmpdc = CreateCompatibleDC (hdc);
9553 release_frame_dc (f, hdc);
9554 prev = SelectObject (bmpdc, img->pixmap);
3cf3436e
JR
9555
9556 /* Fill the `pixel' members of the XColor array. I wished there
9557 were an easy and portable way to circumvent XGetPixel. */
9558 p = colors;
9559 for (y = 0; y < img->height; ++y)
9560 {
9561 XColor *row = p;
7d0393cf 9562
3cf3436e 9563 for (x = 0; x < img->width; ++x, ++p)
197edd35
JR
9564 {
9565 /* TODO: palette support needed here? */
9566 p->pixel = GetPixel (bmpdc, x, y);
3cf3436e 9567
197edd35
JR
9568 if (rgb_p)
9569 {
9570 p->red = 256 * GetRValue (p->pixel);
9571 p->green = 256 * GetGValue (p->pixel);
9572 p->blue = 256 * GetBValue (p->pixel);
9573 }
9574 }
3cf3436e
JR
9575 }
9576
197edd35
JR
9577 SelectObject (bmpdc, prev);
9578 DeleteDC (bmpdc);
9579
3cf3436e
JR
9580 return colors;
9581}
9582
ac849ba4
JR
9583/* Put a pixel of COLOR at position X, Y in XIMG. XIMG must have been
9584 created with CreateDIBSection, with the pointer to the bit values
9585 stored in ximg->data. */
9586
9587static void XPutPixel (ximg, x, y, color)
9588 XImage * ximg;
9589 int x, y;
9590 COLORREF color;
9591{
9592 int width = ximg->info.bmiHeader.biWidth;
9593 int height = ximg->info.bmiHeader.biHeight;
ac849ba4
JR
9594 unsigned char * pixel;
9595
54eefef1
JR
9596 /* True color images. */
9597 if (ximg->info.bmiHeader.biBitCount == 24)
9598 {
9599 int rowbytes = width * 3;
9600 /* Ensure scanlines are aligned on 4 byte boundaries. */
9601 if (rowbytes % 4)
9602 rowbytes += 4 - (rowbytes % 4);
9603
9604 pixel = ximg->data + y * rowbytes + x * 3;
9605 /* Windows bitmaps are in BGR order. */
9606 *pixel = GetBValue (color);
9607 *(pixel + 1) = GetGValue (color);
9608 *(pixel + 2) = GetRValue (color);
9609 }
9610 /* Monochrome images. */
9611 else if (ximg->info.bmiHeader.biBitCount == 1)
9612 {
9613 int rowbytes = width / 8;
9614 /* Ensure scanlines are aligned on 4 byte boundaries. */
9615 if (rowbytes % 4)
9616 rowbytes += 4 - (rowbytes % 4);
9617 pixel = ximg->data + y * rowbytes + x / 8;
9618 /* Filter out palette info. */
9619 if (color & 0x00ffffff)
9620 *pixel = *pixel | (1 << x % 8);
9621 else
9622 *pixel = *pixel & ~(1 << x % 8);
9623 }
9624 else
839b1909 9625 image_error ("XPutPixel: palette image not supported.", Qnil, Qnil);
ac849ba4
JR
9626}
9627
3cf3436e
JR
9628/* Create IMG->pixmap from an array COLORS of XColor structures, whose
9629 RGB members are set. F is the frame on which this all happens.
9630 COLORS will be freed; an existing IMG->pixmap will be freed, too. */
6fc2811b
JR
9631
9632static void
3cf3436e 9633x_from_xcolors (f, img, colors)
6fc2811b 9634 struct frame *f;
3cf3436e 9635 struct image *img;
6fc2811b 9636 XColor *colors;
6fc2811b 9637{
3cf3436e
JR
9638 int x, y;
9639 XImage *oimg;
9640 Pixmap pixmap;
9641 XColor *p;
ac849ba4 9642#if 0 /* TODO: color tables. */
3cf3436e 9643 init_color_table ();
ac849ba4 9644#endif
3cf3436e
JR
9645 x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9646 &oimg, &pixmap);
9647 p = colors;
9648 for (y = 0; y < img->height; ++y)
9649 for (x = 0; x < img->width; ++x, ++p)
9650 {
9651 unsigned long pixel;
ac849ba4 9652#if 0 /* TODO: color tables. */
3cf3436e 9653 pixel = lookup_rgb_color (f, p->red, p->green, p->blue);
ac849ba4 9654#else
197edd35 9655 pixel = PALETTERGB (p->red / 256, p->green / 256, p->blue / 256);
ac849ba4 9656#endif
3cf3436e
JR
9657 XPutPixel (oimg, x, y, pixel);
9658 }
6fc2811b 9659
3cf3436e
JR
9660 xfree (colors);
9661 x_clear_image_1 (f, img, 1, 0, 1);
6fc2811b 9662
3cf3436e
JR
9663 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9664 x_destroy_x_image (oimg);
9665 img->pixmap = pixmap;
ac849ba4 9666#if 0 /* TODO: color tables. */
3cf3436e
JR
9667 img->colors = colors_in_color_table (&img->ncolors);
9668 free_color_table ();
ac849ba4 9669#endif
6fc2811b
JR
9670}
9671
9672
3cf3436e
JR
9673/* On frame F, perform edge-detection on image IMG.
9674
9675 MATRIX is a nine-element array specifying the transformation
9676 matrix. See emboss_matrix for an example.
7d0393cf 9677
3cf3436e
JR
9678 COLOR_ADJUST is a color adjustment added to each pixel of the
9679 outgoing image. */
6fc2811b
JR
9680
9681static void
3cf3436e 9682x_detect_edges (f, img, matrix, color_adjust)
6fc2811b 9683 struct frame *f;
3cf3436e
JR
9684 struct image *img;
9685 int matrix[9], color_adjust;
6fc2811b 9686{
3cf3436e
JR
9687 XColor *colors = x_to_xcolors (f, img, 1);
9688 XColor *new, *p;
9689 int x, y, i, sum;
9690
9691 for (i = sum = 0; i < 9; ++i)
9692 sum += abs (matrix[i]);
9693
9694#define COLOR(A, X, Y) ((A) + (Y) * img->width + (X))
9695
9696 new = (XColor *) xmalloc (img->width * img->height * sizeof *new);
9697
9698 for (y = 0; y < img->height; ++y)
9699 {
9700 p = COLOR (new, 0, y);
9701 p->red = p->green = p->blue = 0xffff/2;
9702 p = COLOR (new, img->width - 1, y);
9703 p->red = p->green = p->blue = 0xffff/2;
9704 }
7d0393cf 9705
3cf3436e
JR
9706 for (x = 1; x < img->width - 1; ++x)
9707 {
9708 p = COLOR (new, x, 0);
9709 p->red = p->green = p->blue = 0xffff/2;
9710 p = COLOR (new, x, img->height - 1);
9711 p->red = p->green = p->blue = 0xffff/2;
9712 }
9713
9714 for (y = 1; y < img->height - 1; ++y)
9715 {
9716 p = COLOR (new, 1, y);
7d0393cf 9717
3cf3436e
JR
9718 for (x = 1; x < img->width - 1; ++x, ++p)
9719 {
9720 int r, g, b, y1, x1;
9721
9722 r = g = b = i = 0;
9723 for (y1 = y - 1; y1 < y + 2; ++y1)
9724 for (x1 = x - 1; x1 < x + 2; ++x1, ++i)
9725 if (matrix[i])
9726 {
9727 XColor *t = COLOR (colors, x1, y1);
9728 r += matrix[i] * t->red;
9729 g += matrix[i] * t->green;
9730 b += matrix[i] * t->blue;
9731 }
9732
9733 r = (r / sum + color_adjust) & 0xffff;
9734 g = (g / sum + color_adjust) & 0xffff;
9735 b = (b / sum + color_adjust) & 0xffff;
9736 p->red = p->green = p->blue = COLOR_INTENSITY (r, g, b);
9737 }
9738 }
9739
9740 xfree (colors);
9741 x_from_xcolors (f, img, new);
9742
9743#undef COLOR
9744}
9745
9746
9747/* Perform the pre-defined `emboss' edge-detection on image IMG
9748 on frame F. */
9749
9750static void
9751x_emboss (f, img)
9752 struct frame *f;
9753 struct image *img;
9754{
9755 x_detect_edges (f, img, emboss_matrix, 0xffff / 2);
6fc2811b 9756}
3cf3436e 9757
6fc2811b
JR
9758
9759/* Transform image IMG which is used on frame F with a Laplace
9760 edge-detection algorithm. The result is an image that can be used
9761 to draw disabled buttons, for example. */
9762
9763static void
9764x_laplace (f, img)
9765 struct frame *f;
9766 struct image *img;
9767{
3cf3436e
JR
9768 x_detect_edges (f, img, laplace_matrix, 45000);
9769}
6fc2811b 9770
6fc2811b 9771
3cf3436e
JR
9772/* Perform edge-detection on image IMG on frame F, with specified
9773 transformation matrix MATRIX and color-adjustment COLOR_ADJUST.
6fc2811b 9774
3cf3436e 9775 MATRIX must be either
6fc2811b 9776
3cf3436e
JR
9777 - a list of at least 9 numbers in row-major form
9778 - a vector of at least 9 numbers
6fc2811b 9779
3cf3436e
JR
9780 COLOR_ADJUST nil means use a default; otherwise it must be a
9781 number. */
6fc2811b 9782
3cf3436e
JR
9783static void
9784x_edge_detection (f, img, matrix, color_adjust)
9785 struct frame *f;
9786 struct image *img;
9787 Lisp_Object matrix, color_adjust;
9788{
9789 int i = 0;
9790 int trans[9];
7d0393cf 9791
3cf3436e 9792 if (CONSP (matrix))
6fc2811b 9793 {
3cf3436e
JR
9794 for (i = 0;
9795 i < 9 && CONSP (matrix) && NUMBERP (XCAR (matrix));
9796 ++i, matrix = XCDR (matrix))
9797 trans[i] = XFLOATINT (XCAR (matrix));
9798 }
9799 else if (VECTORP (matrix) && ASIZE (matrix) >= 9)
9800 {
9801 for (i = 0; i < 9 && NUMBERP (AREF (matrix, i)); ++i)
9802 trans[i] = XFLOATINT (AREF (matrix, i));
9803 }
9804
9805 if (NILP (color_adjust))
9806 color_adjust = make_number (0xffff / 2);
9807
9808 if (i == 9 && NUMBERP (color_adjust))
9809 x_detect_edges (f, img, trans, (int) XFLOATINT (color_adjust));
9810}
9811
6fc2811b 9812
3cf3436e 9813/* Transform image IMG on frame F so that it looks disabled. */
6fc2811b 9814
3cf3436e
JR
9815static void
9816x_disable_image (f, img)
9817 struct frame *f;
9818 struct image *img;
9819{
ac849ba4 9820 struct w32_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
3cf3436e 9821
ac849ba4 9822 if (dpyinfo->n_planes * dpyinfo->n_cbits >= 2)
3cf3436e
JR
9823 {
9824 /* Color (or grayscale). Convert to gray, and equalize. Just
9825 drawing such images with a stipple can look very odd, so
9826 we're using this method instead. */
9827 XColor *colors = x_to_xcolors (f, img, 1);
9828 XColor *p, *end;
9829 const int h = 15000;
9830 const int l = 30000;
9831
9832 for (p = colors, end = colors + img->width * img->height;
9833 p < end;
9834 ++p)
6fc2811b 9835 {
3cf3436e
JR
9836 int i = COLOR_INTENSITY (p->red, p->green, p->blue);
9837 int i2 = (0xffff - h - l) * i / 0xffff + l;
9838 p->red = p->green = p->blue = i2;
6fc2811b
JR
9839 }
9840
3cf3436e 9841 x_from_xcolors (f, img, colors);
6fc2811b
JR
9842 }
9843
3cf3436e
JR
9844 /* Draw a cross over the disabled image, if we must or if we
9845 should. */
ac849ba4 9846 if (dpyinfo->n_planes * dpyinfo->n_cbits < 2 || cross_disabled_images)
3cf3436e 9847 {
197edd35
JR
9848 HDC hdc, bmpdc;
9849 HGDIOBJ prev;
9850
9851 hdc = get_frame_dc (f);
9852 bmpdc = CreateCompatibleDC (hdc);
9853 release_frame_dc (f, hdc);
9854
9855 prev = SelectObject (bmpdc, img->pixmap);
6fc2811b 9856
197edd35
JR
9857 SetTextColor (bmpdc, BLACK_PIX_DEFAULT (f));
9858 MoveToEx (bmpdc, 0, 0, NULL);
9859 LineTo (bmpdc, img->width - 1, img->height - 1);
9860 MoveToEx (bmpdc, 0, img->height - 1, NULL);
9861 LineTo (bmpdc, img->width - 1, 0);
6fc2811b 9862
3cf3436e
JR
9863 if (img->mask)
9864 {
197edd35
JR
9865 SelectObject (bmpdc, img->mask);
9866 SetTextColor (bmpdc, WHITE_PIX_DEFAULT (f));
9867 MoveToEx (bmpdc, 0, 0, NULL);
9868 LineTo (bmpdc, img->width - 1, img->height - 1);
9869 MoveToEx (bmpdc, 0, img->height - 1, NULL);
9870 LineTo (bmpdc, img->width - 1, 0);
3cf3436e 9871 }
197edd35
JR
9872 SelectObject (bmpdc, prev);
9873 DeleteDC (bmpdc);
3cf3436e 9874 }
6fc2811b
JR
9875}
9876
9877
9878/* Build a mask for image IMG which is used on frame F. FILE is the
9879 name of an image file, for error messages. HOW determines how to
9880 determine the background color of IMG. If it is a list '(R G B)',
9881 with R, G, and B being integers >= 0, take that as the color of the
9882 background. Otherwise, determine the background color of IMG
9883 heuristically. Value is non-zero if successful. */
9884
9885static int
9886x_build_heuristic_mask (f, img, how)
9887 struct frame *f;
9888 struct image *img;
9889 Lisp_Object how;
9890{
197edd35
JR
9891 HDC img_dc, frame_dc;
9892 HGDIOBJ prev;
9893 char *mask_img;
a05e2bae
JR
9894 int x, y, rc, use_img_background;
9895 unsigned long bg = 0;
197edd35 9896 int row_width;
a05e2bae
JR
9897
9898 if (img->mask)
9899 {
197edd35
JR
9900 DeleteObject (img->mask);
9901 img->mask = NULL;
a05e2bae
JR
9902 img->background_transparent_valid = 0;
9903 }
6fc2811b 9904
197edd35
JR
9905 /* Create the bit array serving as mask. */
9906 row_width = (img->width + 7) / 8;
9907 mask_img = xmalloc (row_width * img->height);
9908 bzero (mask_img, row_width * img->height);
6fc2811b 9909
197edd35
JR
9910 /* Create a memory device context for IMG->pixmap. */
9911 frame_dc = get_frame_dc (f);
9912 img_dc = CreateCompatibleDC (frame_dc);
9913 release_frame_dc (f, frame_dc);
9914 prev = SelectObject (img_dc, img->pixmap);
6fc2811b 9915
197edd35 9916 /* Determine the background color of img_dc. If HOW is `(R G B)'
a05e2bae
JR
9917 take that as color. Otherwise, use the image's background color. */
9918 use_img_background = 1;
7d0393cf 9919
6fc2811b
JR
9920 if (CONSP (how))
9921 {
a05e2bae 9922 int rgb[3], i;
6fc2811b 9923
a05e2bae 9924 for (i = 0; i < 3 && CONSP (how) && NATNUMP (XCAR (how)); ++i)
6fc2811b
JR
9925 {
9926 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9927 how = XCDR (how);
9928 }
9929
9930 if (i == 3 && NILP (how))
9931 {
9932 char color_name[30];
6fc2811b 9933 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
0040b876 9934 bg = x_alloc_image_color (f, img, build_string (color_name), 0)
8f92c555 9935 & 0x00ffffff; /* Filter out palette info. */
a05e2bae 9936 use_img_background = 0;
6fc2811b
JR
9937 }
9938 }
7d0393cf 9939
a05e2bae 9940 if (use_img_background)
197edd35 9941 bg = four_corners_best (img_dc, img->width, img->height);
6fc2811b
JR
9942
9943 /* Set all bits in mask_img to 1 whose color in ximg is different
9944 from the background color bg. */
9945 for (y = 0; y < img->height; ++y)
9946 for (x = 0; x < img->width; ++x)
197edd35
JR
9947 {
9948 COLORREF p = GetPixel (img_dc, x, y);
9949 if (p != bg)
9950 mask_img[y * row_width + x / 8] |= 1 << (x % 8);
9951 }
9952
9953 /* Create the mask image. */
9954 img->mask = w32_create_pixmap_from_bitmap_data (img->width, img->height,
9955 mask_img);
6fc2811b 9956
a05e2bae 9957 /* Fill in the background_transparent field while we have the mask handy. */
197edd35
JR
9958 SelectObject (img_dc, img->mask);
9959
9960 image_background_transparent (img, f, img_dc);
a05e2bae 9961
6fc2811b 9962 /* Put mask_img into img->mask. */
54eefef1 9963 x_destroy_x_image ((XImage *)mask_img);
197edd35
JR
9964 SelectObject (img_dc, prev);
9965 DeleteDC (img_dc);
6fc2811b
JR
9966
9967 return 1;
9968}
217e5be0 9969
6fc2811b
JR
9970\f
9971/***********************************************************************
9972 PBM (mono, gray, color)
9973 ***********************************************************************/
6fc2811b
JR
9974
9975static int pbm_image_p P_ ((Lisp_Object object));
9976static int pbm_load P_ ((struct frame *f, struct image *img));
9977static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
9978
9979/* The symbol `pbm' identifying images of this type. */
9980
9981Lisp_Object Qpbm;
9982
9983/* Indices of image specification fields in gs_format, below. */
9984
9985enum pbm_keyword_index
9986{
9987 PBM_TYPE,
9988 PBM_FILE,
9989 PBM_DATA,
9990 PBM_ASCENT,
9991 PBM_MARGIN,
9992 PBM_RELIEF,
9993 PBM_ALGORITHM,
9994 PBM_HEURISTIC_MASK,
a05e2bae
JR
9995 PBM_MASK,
9996 PBM_FOREGROUND,
9997 PBM_BACKGROUND,
6fc2811b
JR
9998 PBM_LAST
9999};
10000
10001/* Vector of image_keyword structures describing the format
10002 of valid user-defined image specifications. */
10003
10004static struct image_keyword pbm_format[PBM_LAST] =
10005{
10006 {":type", IMAGE_SYMBOL_VALUE, 1},
10007 {":file", IMAGE_STRING_VALUE, 0},
10008 {":data", IMAGE_STRING_VALUE, 0},
8f92c555 10009 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 10010 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 10011 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 10012 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
3cf3436e
JR
10013 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10014 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10015 {":foreground", IMAGE_STRING_OR_NIL_VALUE, 0},
10016 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
10017};
10018
10019/* Structure describing the image type `pbm'. */
10020
10021static struct image_type pbm_type =
10022{
10023 &Qpbm,
10024 pbm_image_p,
10025 pbm_load,
10026 x_clear_image,
10027 NULL
10028};
10029
10030
10031/* Return non-zero if OBJECT is a valid PBM image specification. */
10032
10033static int
10034pbm_image_p (object)
10035 Lisp_Object object;
10036{
10037 struct image_keyword fmt[PBM_LAST];
7d0393cf 10038
6fc2811b 10039 bcopy (pbm_format, fmt, sizeof fmt);
7d0393cf 10040
8f92c555 10041 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm))
6fc2811b
JR
10042 return 0;
10043
10044 /* Must specify either :data or :file. */
10045 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
10046}
10047
10048
10049/* Scan a decimal number from *S and return it. Advance *S while
10050 reading the number. END is the end of the string. Value is -1 at
10051 end of input. */
10052
10053static int
10054pbm_scan_number (s, end)
10055 unsigned char **s, *end;
10056{
10057 int c, val = -1;
10058
10059 while (*s < end)
10060 {
10061 /* Skip white-space. */
10062 while (*s < end && (c = *(*s)++, isspace (c)))
10063 ;
10064
10065 if (c == '#')
10066 {
10067 /* Skip comment to end of line. */
10068 while (*s < end && (c = *(*s)++, c != '\n'))
10069 ;
10070 }
10071 else if (isdigit (c))
10072 {
10073 /* Read decimal number. */
10074 val = c - '0';
10075 while (*s < end && (c = *(*s)++, isdigit (c)))
10076 val = 10 * val + c - '0';
10077 break;
10078 }
10079 else
10080 break;
10081 }
10082
10083 return val;
10084}
10085
10086
10087/* Read FILE into memory. Value is a pointer to a buffer allocated
10088 with xmalloc holding FILE's contents. Value is null if an error
6f826971 10089 occurred. *SIZE is set to the size of the file. */
6fc2811b
JR
10090
10091static char *
10092pbm_read_file (file, size)
10093 Lisp_Object file;
10094 int *size;
10095{
10096 FILE *fp = NULL;
10097 char *buf = NULL;
10098 struct stat st;
10099
d5db4077 10100 if (stat (SDATA (file), &st) == 0
c45bb3b2 10101 && (fp = fopen (SDATA (file), "rb")) != NULL
6fc2811b
JR
10102 && (buf = (char *) xmalloc (st.st_size),
10103 fread (buf, 1, st.st_size, fp) == st.st_size))
10104 {
10105 *size = st.st_size;
10106 fclose (fp);
10107 }
10108 else
10109 {
10110 if (fp)
10111 fclose (fp);
10112 if (buf)
10113 {
10114 xfree (buf);
10115 buf = NULL;
10116 }
10117 }
7d0393cf 10118
6fc2811b
JR
10119 return buf;
10120}
10121
10122
10123/* Load PBM image IMG for use on frame F. */
10124
7d0393cf 10125static int
6fc2811b
JR
10126pbm_load (f, img)
10127 struct frame *f;
10128 struct image *img;
10129{
10130 int raw_p, x, y;
10131 int width, height, max_color_idx = 0;
10132 XImage *ximg;
10133 Lisp_Object file, specified_file;
10134 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
10135 struct gcpro gcpro1;
10136 unsigned char *contents = NULL;
10137 unsigned char *end, *p;
10138 int size;
10139
10140 specified_file = image_spec_value (img->spec, QCfile, NULL);
10141 file = Qnil;
10142 GCPRO1 (file);
10143
10144 if (STRINGP (specified_file))
10145 {
10146 file = x_find_image_file (specified_file);
10147 if (!STRINGP (file))
10148 {
10149 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10150 UNGCPRO;
10151 return 0;
10152 }
10153
d5db4077 10154 contents = slurp_file (SDATA (file), &size);
6fc2811b
JR
10155 if (contents == NULL)
10156 {
10157 image_error ("Error reading `%s'", file, Qnil);
10158 UNGCPRO;
10159 return 0;
10160 }
10161
10162 p = contents;
10163 end = contents + size;
10164 }
10165 else
10166 {
10167 Lisp_Object data;
10168 data = image_spec_value (img->spec, QCdata, NULL);
d5db4077
KR
10169 p = SDATA (data);
10170 end = p + SBYTES (data);
6fc2811b
JR
10171 }
10172
10173 /* Check magic number. */
10174 if (end - p < 2 || *p++ != 'P')
10175 {
10176 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10177 error:
10178 xfree (contents);
10179 UNGCPRO;
10180 return 0;
10181 }
10182
6fc2811b
JR
10183 switch (*p++)
10184 {
10185 case '1':
10186 raw_p = 0, type = PBM_MONO;
10187 break;
7d0393cf 10188
6fc2811b
JR
10189 case '2':
10190 raw_p = 0, type = PBM_GRAY;
10191 break;
10192
10193 case '3':
10194 raw_p = 0, type = PBM_COLOR;
10195 break;
10196
10197 case '4':
10198 raw_p = 1, type = PBM_MONO;
10199 break;
7d0393cf 10200
6fc2811b
JR
10201 case '5':
10202 raw_p = 1, type = PBM_GRAY;
10203 break;
7d0393cf 10204
6fc2811b
JR
10205 case '6':
10206 raw_p = 1, type = PBM_COLOR;
10207 break;
10208
10209 default:
10210 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
10211 goto error;
10212 }
10213
10214 /* Read width, height, maximum color-component. Characters
10215 starting with `#' up to the end of a line are ignored. */
10216 width = pbm_scan_number (&p, end);
10217 height = pbm_scan_number (&p, end);
10218
10219 if (type != PBM_MONO)
10220 {
10221 max_color_idx = pbm_scan_number (&p, end);
10222 if (raw_p && max_color_idx > 255)
10223 max_color_idx = 255;
10224 }
7d0393cf 10225
6fc2811b
JR
10226 if (width < 0
10227 || height < 0
10228 || (type != PBM_MONO && max_color_idx < 0))
10229 goto error;
10230
ac849ba4 10231 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
3cf3436e
JR
10232 goto error;
10233
ac849ba4 10234#if 0 /* TODO: color tables. */
6fc2811b
JR
10235 /* Initialize the color hash table. */
10236 init_color_table ();
ac849ba4 10237#endif
6fc2811b
JR
10238
10239 if (type == PBM_MONO)
10240 {
10241 int c = 0, g;
3cf3436e
JR
10242 struct image_keyword fmt[PBM_LAST];
10243 unsigned long fg = FRAME_FOREGROUND_PIXEL (f);
10244 unsigned long bg = FRAME_BACKGROUND_PIXEL (f);
10245
10246 /* Parse the image specification. */
10247 bcopy (pbm_format, fmt, sizeof fmt);
10248 parse_image_spec (img->spec, fmt, PBM_LAST, Qpbm);
7d0393cf 10249
3cf3436e
JR
10250 /* Get foreground and background colors, maybe allocate colors. */
10251 if (fmt[PBM_FOREGROUND].count
10252 && STRINGP (fmt[PBM_FOREGROUND].value))
10253 fg = x_alloc_image_color (f, img, fmt[PBM_FOREGROUND].value, fg);
10254 if (fmt[PBM_BACKGROUND].count
10255 && STRINGP (fmt[PBM_BACKGROUND].value))
a05e2bae
JR
10256 {
10257 bg = x_alloc_image_color (f, img, fmt[PBM_BACKGROUND].value, bg);
10258 img->background = bg;
10259 img->background_valid = 1;
10260 }
10261
6fc2811b
JR
10262 for (y = 0; y < height; ++y)
10263 for (x = 0; x < width; ++x)
10264 {
10265 if (raw_p)
10266 {
10267 if ((x & 7) == 0)
10268 c = *p++;
10269 g = c & 0x80;
10270 c <<= 1;
10271 }
10272 else
10273 g = pbm_scan_number (&p, end);
10274
3cf3436e 10275 XPutPixel (ximg, x, y, g ? fg : bg);
6fc2811b
JR
10276 }
10277 }
10278 else
10279 {
10280 for (y = 0; y < height; ++y)
10281 for (x = 0; x < width; ++x)
10282 {
10283 int r, g, b;
7d0393cf 10284
6fc2811b
JR
10285 if (type == PBM_GRAY)
10286 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
10287 else if (raw_p)
10288 {
10289 r = *p++;
10290 g = *p++;
10291 b = *p++;
10292 }
10293 else
10294 {
10295 r = pbm_scan_number (&p, end);
10296 g = pbm_scan_number (&p, end);
10297 b = pbm_scan_number (&p, end);
10298 }
7d0393cf 10299
6fc2811b
JR
10300 if (r < 0 || g < 0 || b < 0)
10301 {
ac849ba4 10302 x_destroy_x_image (ximg);
6fc2811b
JR
10303 image_error ("Invalid pixel value in image `%s'",
10304 img->spec, Qnil);
10305 goto error;
10306 }
7d0393cf 10307
6fc2811b 10308 /* RGB values are now in the range 0..max_color_idx.
ac849ba4
JR
10309 Scale this to the range 0..0xff supported by W32. */
10310 r = (int) ((double) r * 255 / max_color_idx);
10311 g = (int) ((double) g * 255 / max_color_idx);
10312 b = (int) ((double) b * 255 / max_color_idx);
10313 XPutPixel (ximg, x, y,
10314#if 0 /* TODO: color tables. */
10315 lookup_rgb_color (f, r, g, b));
10316#else
10317 PALETTERGB (r, g, b));
10318#endif
6fc2811b
JR
10319 }
10320 }
ac849ba4
JR
10321
10322#if 0 /* TODO: color tables. */
6fc2811b
JR
10323 /* Store in IMG->colors the colors allocated for the image, and
10324 free the color table. */
10325 img->colors = colors_in_color_table (&img->ncolors);
10326 free_color_table ();
ac849ba4 10327#endif
a05e2bae
JR
10328 /* Maybe fill in the background field while we have ximg handy. */
10329 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
10330 IMAGE_BACKGROUND (img, f, ximg);
7d0393cf 10331
6fc2811b
JR
10332 /* Put the image into a pixmap. */
10333 x_put_x_image (f, ximg, img->pixmap, width, height);
10334 x_destroy_x_image (ximg);
7d0393cf 10335
6fc2811b
JR
10336 img->width = width;
10337 img->height = height;
10338
10339 UNGCPRO;
10340 xfree (contents);
10341 return 1;
10342}
6fc2811b
JR
10343
10344\f
10345/***********************************************************************
10346 PNG
10347 ***********************************************************************/
10348
10349#if HAVE_PNG
10350
10351#include <png.h>
10352
10353/* Function prototypes. */
10354
10355static int png_image_p P_ ((Lisp_Object object));
10356static int png_load P_ ((struct frame *f, struct image *img));
10357
10358/* The symbol `png' identifying images of this type. */
10359
10360Lisp_Object Qpng;
10361
10362/* Indices of image specification fields in png_format, below. */
10363
10364enum png_keyword_index
10365{
10366 PNG_TYPE,
10367 PNG_DATA,
10368 PNG_FILE,
10369 PNG_ASCENT,
10370 PNG_MARGIN,
10371 PNG_RELIEF,
10372 PNG_ALGORITHM,
10373 PNG_HEURISTIC_MASK,
a05e2bae
JR
10374 PNG_MASK,
10375 PNG_BACKGROUND,
6fc2811b
JR
10376 PNG_LAST
10377};
10378
10379/* Vector of image_keyword structures describing the format
10380 of valid user-defined image specifications. */
10381
10382static struct image_keyword png_format[PNG_LAST] =
10383{
10384 {":type", IMAGE_SYMBOL_VALUE, 1},
10385 {":data", IMAGE_STRING_VALUE, 0},
10386 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 10387 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 10388 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 10389 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 10390 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
10391 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10392 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10393 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
10394};
10395
10396/* Structure describing the image type `png'. */
10397
10398static struct image_type png_type =
10399{
10400 &Qpng,
10401 png_image_p,
10402 png_load,
10403 x_clear_image,
10404 NULL
10405};
10406
839b1909
JR
10407/* PNG library details. */
10408
10409DEF_IMGLIB_FN (png_get_io_ptr);
10410DEF_IMGLIB_FN (png_check_sig);
10411DEF_IMGLIB_FN (png_create_read_struct);
10412DEF_IMGLIB_FN (png_create_info_struct);
10413DEF_IMGLIB_FN (png_destroy_read_struct);
10414DEF_IMGLIB_FN (png_set_read_fn);
c922a224 10415DEF_IMGLIB_FN (png_init_io);
839b1909
JR
10416DEF_IMGLIB_FN (png_set_sig_bytes);
10417DEF_IMGLIB_FN (png_read_info);
10418DEF_IMGLIB_FN (png_get_IHDR);
10419DEF_IMGLIB_FN (png_get_valid);
10420DEF_IMGLIB_FN (png_set_strip_16);
10421DEF_IMGLIB_FN (png_set_expand);
10422DEF_IMGLIB_FN (png_set_gray_to_rgb);
10423DEF_IMGLIB_FN (png_set_background);
10424DEF_IMGLIB_FN (png_get_bKGD);
10425DEF_IMGLIB_FN (png_read_update_info);
10426DEF_IMGLIB_FN (png_get_channels);
10427DEF_IMGLIB_FN (png_get_rowbytes);
10428DEF_IMGLIB_FN (png_read_image);
10429DEF_IMGLIB_FN (png_read_end);
10430DEF_IMGLIB_FN (png_error);
10431
10432static int
10433init_png_functions (library)
10434 HMODULE library;
10435{
10436 LOAD_IMGLIB_FN (library, png_get_io_ptr);
10437 LOAD_IMGLIB_FN (library, png_check_sig);
10438 LOAD_IMGLIB_FN (library, png_create_read_struct);
10439 LOAD_IMGLIB_FN (library, png_create_info_struct);
10440 LOAD_IMGLIB_FN (library, png_destroy_read_struct);
10441 LOAD_IMGLIB_FN (library, png_set_read_fn);
c922a224 10442 LOAD_IMGLIB_FN (library, png_init_io);
839b1909
JR
10443 LOAD_IMGLIB_FN (library, png_set_sig_bytes);
10444 LOAD_IMGLIB_FN (library, png_read_info);
10445 LOAD_IMGLIB_FN (library, png_get_IHDR);
10446 LOAD_IMGLIB_FN (library, png_get_valid);
10447 LOAD_IMGLIB_FN (library, png_set_strip_16);
10448 LOAD_IMGLIB_FN (library, png_set_expand);
10449 LOAD_IMGLIB_FN (library, png_set_gray_to_rgb);
10450 LOAD_IMGLIB_FN (library, png_set_background);
10451 LOAD_IMGLIB_FN (library, png_get_bKGD);
10452 LOAD_IMGLIB_FN (library, png_read_update_info);
10453 LOAD_IMGLIB_FN (library, png_get_channels);
10454 LOAD_IMGLIB_FN (library, png_get_rowbytes);
10455 LOAD_IMGLIB_FN (library, png_read_image);
10456 LOAD_IMGLIB_FN (library, png_read_end);
10457 LOAD_IMGLIB_FN (library, png_error);
10458 return 1;
10459}
6fc2811b
JR
10460
10461/* Return non-zero if OBJECT is a valid PNG image specification. */
10462
10463static int
10464png_image_p (object)
10465 Lisp_Object object;
10466{
10467 struct image_keyword fmt[PNG_LAST];
10468 bcopy (png_format, fmt, sizeof fmt);
c922a224 10469
8f92c555 10470 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng))
6fc2811b
JR
10471 return 0;
10472
10473 /* Must specify either the :data or :file keyword. */
10474 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
10475}
10476
10477
10478/* Error and warning handlers installed when the PNG library
10479 is initialized. */
10480
10481static void
10482my_png_error (png_ptr, msg)
10483 png_struct *png_ptr;
10484 char *msg;
10485{
10486 xassert (png_ptr != NULL);
10487 image_error ("PNG error: %s", build_string (msg), Qnil);
10488 longjmp (png_ptr->jmpbuf, 1);
10489}
10490
10491
10492static void
10493my_png_warning (png_ptr, msg)
10494 png_struct *png_ptr;
10495 char *msg;
10496{
10497 xassert (png_ptr != NULL);
10498 image_error ("PNG warning: %s", build_string (msg), Qnil);
10499}
10500
6fc2811b
JR
10501/* Memory source for PNG decoding. */
10502
10503struct png_memory_storage
10504{
10505 unsigned char *bytes; /* The data */
10506 size_t len; /* How big is it? */
10507 int index; /* Where are we? */
10508};
10509
10510
10511/* Function set as reader function when reading PNG image from memory.
10512 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
10513 bytes from the input to DATA. */
10514
10515static void
10516png_read_from_memory (png_ptr, data, length)
10517 png_structp png_ptr;
10518 png_bytep data;
10519 png_size_t length;
10520{
10521 struct png_memory_storage *tbr
839b1909 10522 = (struct png_memory_storage *) fn_png_get_io_ptr (png_ptr);
6fc2811b
JR
10523
10524 if (length > tbr->len - tbr->index)
839b1909 10525 fn_png_error (png_ptr, "Read error");
c922a224 10526
6fc2811b
JR
10527 bcopy (tbr->bytes + tbr->index, data, length);
10528 tbr->index = tbr->index + length;
10529}
10530
6fc2811b
JR
10531/* Load PNG image IMG for use on frame F. Value is non-zero if
10532 successful. */
10533
10534static int
10535png_load (f, img)
10536 struct frame *f;
10537 struct image *img;
10538{
10539 Lisp_Object file, specified_file;
10540 Lisp_Object specified_data;
10541 int x, y, i;
10542 XImage *ximg, *mask_img = NULL;
10543 struct gcpro gcpro1;
10544 png_struct *png_ptr = NULL;
10545 png_info *info_ptr = NULL, *end_info = NULL;
a05e2bae 10546 FILE *volatile fp = NULL;
6fc2811b 10547 png_byte sig[8];
54eefef1
JR
10548 png_byte * volatile pixels = NULL;
10549 png_byte ** volatile rows = NULL;
6fc2811b
JR
10550 png_uint_32 width, height;
10551 int bit_depth, color_type, interlace_type;
10552 png_byte channels;
10553 png_uint_32 row_bytes;
10554 int transparent_p;
6fc2811b
JR
10555 double screen_gamma, image_gamma;
10556 int intent;
10557 struct png_memory_storage tbr; /* Data to be read */
10558
10559 /* Find out what file to load. */
10560 specified_file = image_spec_value (img->spec, QCfile, NULL);
10561 specified_data = image_spec_value (img->spec, QCdata, NULL);
10562 file = Qnil;
10563 GCPRO1 (file);
10564
10565 if (NILP (specified_data))
10566 {
10567 file = x_find_image_file (specified_file);
10568 if (!STRINGP (file))
54eefef1
JR
10569 {
10570 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10571 UNGCPRO;
10572 return 0;
10573 }
6fc2811b
JR
10574
10575 /* Open the image file. */
d5db4077 10576 fp = fopen (SDATA (file), "rb");
6fc2811b 10577 if (!fp)
54eefef1
JR
10578 {
10579 image_error ("Cannot open image file `%s'", file, Qnil);
10580 UNGCPRO;
10581 fclose (fp);
10582 return 0;
10583 }
6fc2811b
JR
10584
10585 /* Check PNG signature. */
10586 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
839b1909 10587 || !fn_png_check_sig (sig, sizeof sig))
54eefef1
JR
10588 {
10589 image_error ("Not a PNG file: `%s'", file, Qnil);
10590 UNGCPRO;
10591 fclose (fp);
10592 return 0;
10593 }
6fc2811b
JR
10594 }
10595 else
10596 {
10597 /* Read from memory. */
d5db4077
KR
10598 tbr.bytes = SDATA (specified_data);
10599 tbr.len = SBYTES (specified_data);
6fc2811b
JR
10600 tbr.index = 0;
10601
10602 /* Check PNG signature. */
10603 if (tbr.len < sizeof sig
839b1909 10604 || !fn_png_check_sig (tbr.bytes, sizeof sig))
6fc2811b
JR
10605 {
10606 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
10607 UNGCPRO;
10608 return 0;
10609 }
10610
10611 /* Need to skip past the signature. */
10612 tbr.bytes += sizeof (sig);
10613 }
10614
6fc2811b 10615 /* Initialize read and info structs for PNG lib. */
839b1909
JR
10616 png_ptr = fn_png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
10617 my_png_error, my_png_warning);
6fc2811b
JR
10618 if (!png_ptr)
10619 {
10620 if (fp) fclose (fp);
10621 UNGCPRO;
10622 return 0;
10623 }
10624
839b1909 10625 info_ptr = fn_png_create_info_struct (png_ptr);
6fc2811b
JR
10626 if (!info_ptr)
10627 {
839b1909 10628 fn_png_destroy_read_struct (&png_ptr, NULL, NULL);
6fc2811b
JR
10629 if (fp) fclose (fp);
10630 UNGCPRO;
10631 return 0;
10632 }
10633
839b1909 10634 end_info = fn_png_create_info_struct (png_ptr);
6fc2811b
JR
10635 if (!end_info)
10636 {
839b1909 10637 fn_png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
6fc2811b
JR
10638 if (fp) fclose (fp);
10639 UNGCPRO;
10640 return 0;
10641 }
10642
10643 /* Set error jump-back. We come back here when the PNG library
10644 detects an error. */
10645 if (setjmp (png_ptr->jmpbuf))
10646 {
10647 error:
10648 if (png_ptr)
839b1909 10649 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6fc2811b
JR
10650 xfree (pixels);
10651 xfree (rows);
10652 if (fp) fclose (fp);
10653 UNGCPRO;
10654 return 0;
10655 }
10656
10657 /* Read image info. */
10658 if (!NILP (specified_data))
839b1909 10659 fn_png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
6fc2811b 10660 else
839b1909 10661 fn_png_init_io (png_ptr, fp);
6fc2811b 10662
839b1909
JR
10663 fn_png_set_sig_bytes (png_ptr, sizeof sig);
10664 fn_png_read_info (png_ptr, info_ptr);
10665 fn_png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
10666 &interlace_type, NULL, NULL);
6fc2811b 10667
c922a224 10668 /* If image contains simply transparency data, we prefer to
6fc2811b 10669 construct a clipping mask. */
839b1909 10670 if (fn_png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
6fc2811b
JR
10671 transparent_p = 1;
10672 else
10673 transparent_p = 0;
10674
c922a224 10675 /* This function is easier to write if we only have to handle
6fc2811b
JR
10676 one data format: RGB or RGBA with 8 bits per channel. Let's
10677 transform other formats into that format. */
10678
10679 /* Strip more than 8 bits per channel. */
10680 if (bit_depth == 16)
839b1909 10681 fn_png_set_strip_16 (png_ptr);
6fc2811b
JR
10682
10683 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10684 if available. */
839b1909 10685 fn_png_set_expand (png_ptr);
6fc2811b
JR
10686
10687 /* Convert grayscale images to RGB. */
c922a224 10688 if (color_type == PNG_COLOR_TYPE_GRAY
6fc2811b 10689 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
839b1909 10690 fn_png_set_gray_to_rgb (png_ptr);
6fc2811b 10691
54eefef1 10692 screen_gamma = (f->gamma ? 1 / f->gamma / 0.45455 : 2.2);
6fc2811b 10693
54eefef1 10694#if 0 /* Avoid double gamma correction for PNG images. */
6fc2811b 10695 /* Tell the PNG lib to handle gamma correction for us. */
6fc2811b
JR
10696#if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10697 if (png_get_sRGB (png_ptr, info_ptr, &intent))
54eefef1
JR
10698 /* The libpng documentation says this is right in this case. */
10699 png_set_gamma (png_ptr, screen_gamma, 0.45455);
6fc2811b
JR
10700 else
10701#endif
10702 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10703 /* Image contains gamma information. */
10704 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10705 else
54eefef1
JR
10706 /* Use the standard default for the image gamma. */
10707 png_set_gamma (png_ptr, screen_gamma, 0.45455);
10708#endif /* if 0 */
6fc2811b
JR
10709
10710 /* Handle alpha channel by combining the image with a background
10711 color. Do this only if a real alpha channel is supplied. For
10712 simple transparency, we prefer a clipping mask. */
10713 if (!transparent_p)
10714 {
54eefef1 10715 png_color_16 *image_bg;
a05e2bae
JR
10716 Lisp_Object specified_bg
10717 = image_spec_value (img->spec, QCbackground, NULL);
10718
a05e2bae
JR
10719 if (STRINGP (specified_bg))
10720 /* The user specified `:background', use that. */
10721 {
10722 COLORREF color;
d5db4077 10723 if (w32_defined_color (f, SDATA (specified_bg), &color, 0))
a05e2bae
JR
10724 {
10725 png_color_16 user_bg;
10726
10727 bzero (&user_bg, sizeof user_bg);
54eefef1
JR
10728 user_bg.red = 256 * GetRValue (color);
10729 user_bg.green = 256 * GetGValue (color);
10730 user_bg.blue = 256 * GetBValue (color);
6fc2811b 10731
839b1909
JR
10732 fn_png_set_background (png_ptr, &user_bg,
10733 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
a05e2bae
JR
10734 }
10735 }
839b1909 10736 else if (fn_png_get_bKGD (png_ptr, info_ptr, &image_bg))
c922a224 10737 /* Image contains a background color with which to
6fc2811b 10738 combine the image. */
839b1909
JR
10739 fn_png_set_background (png_ptr, image_bg,
10740 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
6fc2811b
JR
10741 else
10742 {
10743 /* Image does not contain a background color with which
c922a224 10744 to combine the image data via an alpha channel. Use
6fc2811b 10745 the frame's background instead. */
54eefef1 10746 COLORREF color;
6fc2811b 10747 png_color_16 frame_background;
54eefef1
JR
10748 color = FRAME_BACKGROUND_PIXEL (f);
10749#if 0 /* TODO : Colormap support. */
10750 Colormap cmap;
6fc2811b 10751
a05e2bae 10752 cmap = FRAME_X_COLORMAP (f);
a05e2bae 10753 x_query_color (f, &color);
54eefef1 10754#endif
6fc2811b
JR
10755
10756 bzero (&frame_background, sizeof frame_background);
54eefef1
JR
10757 frame_background.red = 256 * GetRValue (color);
10758 frame_background.green = 256 * GetGValue (color);
10759 frame_background.blue = 256 * GetBValue (color);
6fc2811b 10760
839b1909
JR
10761 fn_png_set_background (png_ptr, &frame_background,
10762 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
6fc2811b
JR
10763 }
10764 }
10765
10766 /* Update info structure. */
839b1909 10767 fn_png_read_update_info (png_ptr, info_ptr);
6fc2811b
JR
10768
10769 /* Get number of channels. Valid values are 1 for grayscale images
10770 and images with a palette, 2 for grayscale images with transparency
10771 information (alpha channel), 3 for RGB images, and 4 for RGB
10772 images with alpha channel, i.e. RGBA. If conversions above were
10773 sufficient we should only have 3 or 4 channels here. */
839b1909 10774 channels = fn_png_get_channels (png_ptr, info_ptr);
6fc2811b
JR
10775 xassert (channels == 3 || channels == 4);
10776
10777 /* Number of bytes needed for one row of the image. */
839b1909 10778 row_bytes = fn_png_get_rowbytes (png_ptr, info_ptr);
6fc2811b
JR
10779
10780 /* Allocate memory for the image. */
10781 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10782 rows = (png_byte **) xmalloc (height * sizeof *rows);
10783 for (i = 0; i < height; ++i)
10784 rows[i] = pixels + i * row_bytes;
10785
10786 /* Read the entire image. */
839b1909
JR
10787 fn_png_read_image (png_ptr, rows);
10788 fn_png_read_end (png_ptr, info_ptr);
6fc2811b
JR
10789 if (fp)
10790 {
10791 fclose (fp);
10792 fp = NULL;
10793 }
c922a224 10794
6fc2811b
JR
10795 /* Create the X image and pixmap. */
10796 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10797 &img->pixmap))
a05e2bae 10798 goto error;
c922a224 10799
6fc2811b
JR
10800 /* Create an image and pixmap serving as mask if the PNG image
10801 contains an alpha channel. */
10802 if (channels == 4
10803 && !transparent_p
10804 && !x_create_x_image_and_pixmap (f, width, height, 1,
10805 &mask_img, &img->mask))
10806 {
10807 x_destroy_x_image (ximg);
54eefef1 10808 DeleteObject (img->pixmap);
6fc2811b 10809 img->pixmap = 0;
6fc2811b
JR
10810 goto error;
10811 }
6fc2811b 10812 /* Fill the X image and mask from PNG data. */
54eefef1 10813#if 0 /* TODO: Color tables. */
6fc2811b 10814 init_color_table ();
54eefef1 10815#endif
6fc2811b
JR
10816
10817 for (y = 0; y < height; ++y)
10818 {
10819 png_byte *p = rows[y];
10820
10821 for (x = 0; x < width; ++x)
10822 {
10823 unsigned r, g, b;
10824
54eefef1
JR
10825 r = *p++;
10826 g = *p++;
10827 b = *p++;
10828#if 0 /* TODO: Color tables. */
6fc2811b 10829 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
54eefef1
JR
10830#else
10831 XPutPixel (ximg, x, y, PALETTERGB (r, g, b));
10832#endif
6fc2811b 10833 /* An alpha channel, aka mask channel, associates variable
c922a224
JB
10834 transparency with an image. Where other image formats
10835 support binary transparency---fully transparent or fully
6fc2811b
JR
10836 opaque---PNG allows up to 254 levels of partial transparency.
10837 The PNG library implements partial transparency by combining
10838 the image with a specified background color.
10839
10840 I'm not sure how to handle this here nicely: because the
10841 background on which the image is displayed may change, for
c922a224
JB
10842 real alpha channel support, it would be necessary to create
10843 a new image for each possible background.
6fc2811b
JR
10844
10845 What I'm doing now is that a mask is created if we have
10846 boolean transparency information. Otherwise I'm using
10847 the frame's background color to combine the image with. */
10848
10849 if (channels == 4)
10850 {
10851 if (mask_img)
10852 XPutPixel (mask_img, x, y, *p > 0);
10853 ++p;
10854 }
10855 }
10856 }
10857
a05e2bae
JR
10858 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
10859 /* Set IMG's background color from the PNG image, unless the user
10860 overrode it. */
10861 {
10862 png_color_16 *bg;
839b1909 10863 if (fn_png_get_bKGD (png_ptr, info_ptr, &bg))
a05e2bae 10864 {
54eefef1 10865#if 0 /* TODO: Color tables. */
a05e2bae 10866 img->background = lookup_rgb_color (f, bg->red, bg->green, bg->blue);
54eefef1
JR
10867#else
10868 img->background = PALETTERGB (bg->red / 256, bg->green / 256,
10869 bg->blue / 256);
10870#endif
a05e2bae
JR
10871 img->background_valid = 1;
10872 }
10873 }
10874
54eefef1 10875#if 0 /* TODO: Color tables. */
6fc2811b
JR
10876 /* Remember colors allocated for this image. */
10877 img->colors = colors_in_color_table (&img->ncolors);
10878 free_color_table ();
54eefef1 10879#endif
6fc2811b
JR
10880
10881 /* Clean up. */
839b1909 10882 fn_png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
6fc2811b
JR
10883 xfree (rows);
10884 xfree (pixels);
10885
10886 img->width = width;
10887 img->height = height;
10888
a05e2bae
JR
10889 /* Maybe fill in the background field while we have ximg handy. */
10890 IMAGE_BACKGROUND (img, f, ximg);
10891
6fc2811b
JR
10892 /* Put the image into the pixmap, then free the X image and its buffer. */
10893 x_put_x_image (f, ximg, img->pixmap, width, height);
10894 x_destroy_x_image (ximg);
10895
10896 /* Same for the mask. */
10897 if (mask_img)
10898 {
a05e2bae
JR
10899 /* Fill in the background_transparent field while we have the mask
10900 handy. */
10901 image_background_transparent (img, f, mask_img);
10902
6fc2811b
JR
10903 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10904 x_destroy_x_image (mask_img);
10905 }
10906
6fc2811b
JR
10907 UNGCPRO;
10908 return 1;
10909}
10910
10911#endif /* HAVE_PNG != 0 */
10912
10913
10914\f
10915/***********************************************************************
10916 JPEG
10917 ***********************************************************************/
10918
10919#if HAVE_JPEG
10920
10921/* Work around a warning about HAVE_STDLIB_H being redefined in
10922 jconfig.h. */
10923#ifdef HAVE_STDLIB_H
10924#define HAVE_STDLIB_H_1
10925#undef HAVE_STDLIB_H
10926#endif /* HAVE_STLIB_H */
10927
10928#include <jpeglib.h>
10929#include <jerror.h>
10930#include <setjmp.h>
10931
10932#ifdef HAVE_STLIB_H_1
10933#define HAVE_STDLIB_H 1
10934#endif
10935
10936static int jpeg_image_p P_ ((Lisp_Object object));
10937static int jpeg_load P_ ((struct frame *f, struct image *img));
10938
10939/* The symbol `jpeg' identifying images of this type. */
10940
10941Lisp_Object Qjpeg;
10942
10943/* Indices of image specification fields in gs_format, below. */
10944
10945enum jpeg_keyword_index
10946{
10947 JPEG_TYPE,
10948 JPEG_DATA,
10949 JPEG_FILE,
10950 JPEG_ASCENT,
10951 JPEG_MARGIN,
10952 JPEG_RELIEF,
10953 JPEG_ALGORITHM,
10954 JPEG_HEURISTIC_MASK,
a05e2bae
JR
10955 JPEG_MASK,
10956 JPEG_BACKGROUND,
6fc2811b
JR
10957 JPEG_LAST
10958};
10959
10960/* Vector of image_keyword structures describing the format
10961 of valid user-defined image specifications. */
10962
10963static struct image_keyword jpeg_format[JPEG_LAST] =
10964{
10965 {":type", IMAGE_SYMBOL_VALUE, 1},
10966 {":data", IMAGE_STRING_VALUE, 0},
10967 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 10968 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 10969 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 10970 {":relief", IMAGE_INTEGER_VALUE, 0},
a05e2bae
JR
10971 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10972 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10973 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10974 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
10975};
10976
10977/* Structure describing the image type `jpeg'. */
10978
10979static struct image_type jpeg_type =
10980{
10981 &Qjpeg,
10982 jpeg_image_p,
10983 jpeg_load,
10984 x_clear_image,
10985 NULL
10986};
10987
10988
afc390dc
JR
10989/* JPEG library details. */
10990DEF_IMGLIB_FN (jpeg_CreateDecompress);
10991DEF_IMGLIB_FN (jpeg_start_decompress);
10992DEF_IMGLIB_FN (jpeg_finish_decompress);
10993DEF_IMGLIB_FN (jpeg_destroy_decompress);
10994DEF_IMGLIB_FN (jpeg_read_header);
10995DEF_IMGLIB_FN (jpeg_read_scanlines);
10996DEF_IMGLIB_FN (jpeg_stdio_src);
10997DEF_IMGLIB_FN (jpeg_std_error);
10998DEF_IMGLIB_FN (jpeg_resync_to_restart);
10999
11000static int
11001init_jpeg_functions (library)
11002 HMODULE library;
11003{
11004 LOAD_IMGLIB_FN (library, jpeg_finish_decompress);
11005 LOAD_IMGLIB_FN (library, jpeg_read_scanlines);
11006 LOAD_IMGLIB_FN (library, jpeg_start_decompress);
11007 LOAD_IMGLIB_FN (library, jpeg_read_header);
11008 LOAD_IMGLIB_FN (library, jpeg_stdio_src);
11009 LOAD_IMGLIB_FN (library, jpeg_CreateDecompress);
11010 LOAD_IMGLIB_FN (library, jpeg_destroy_decompress);
11011 LOAD_IMGLIB_FN (library, jpeg_std_error);
11012 LOAD_IMGLIB_FN (library, jpeg_resync_to_restart);
11013 return 1;
11014}
11015
11016/* Wrapper since we can't directly assign the function pointer
11017 to another function pointer that was declared more completely easily. */
11018static boolean
11019jpeg_resync_to_restart_wrapper(cinfo, desired)
11020 j_decompress_ptr cinfo;
11021 int desired;
11022{
11023 return fn_jpeg_resync_to_restart (cinfo, desired);
11024}
11025
11026
6fc2811b
JR
11027/* Return non-zero if OBJECT is a valid JPEG image specification. */
11028
11029static int
11030jpeg_image_p (object)
11031 Lisp_Object object;
11032{
11033 struct image_keyword fmt[JPEG_LAST];
c922a224 11034
6fc2811b 11035 bcopy (jpeg_format, fmt, sizeof fmt);
c922a224 11036
8f92c555 11037 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg))
6fc2811b
JR
11038 return 0;
11039
11040 /* Must specify either the :data or :file keyword. */
11041 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
11042}
11043
11044
11045struct my_jpeg_error_mgr
11046{
11047 struct jpeg_error_mgr pub;
11048 jmp_buf setjmp_buffer;
11049};
11050
afc390dc 11051
6fc2811b
JR
11052static void
11053my_error_exit (cinfo)
11054 j_common_ptr cinfo;
11055{
11056 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
11057 longjmp (mgr->setjmp_buffer, 1);
11058}
11059
afc390dc 11060
6fc2811b
JR
11061/* Init source method for JPEG data source manager. Called by
11062 jpeg_read_header() before any data is actually read. See
11063 libjpeg.doc from the JPEG lib distribution. */
11064
11065static void
11066our_init_source (cinfo)
11067 j_decompress_ptr cinfo;
11068{
11069}
11070
11071
11072/* Fill input buffer method for JPEG data source manager. Called
11073 whenever more data is needed. We read the whole image in one step,
11074 so this only adds a fake end of input marker at the end. */
11075
11076static boolean
11077our_fill_input_buffer (cinfo)
11078 j_decompress_ptr cinfo;
11079{
11080 /* Insert a fake EOI marker. */
11081 struct jpeg_source_mgr *src = cinfo->src;
11082 static JOCTET buffer[2];
11083
11084 buffer[0] = (JOCTET) 0xFF;
11085 buffer[1] = (JOCTET) JPEG_EOI;
11086
11087 src->next_input_byte = buffer;
11088 src->bytes_in_buffer = 2;
11089 return TRUE;
11090}
11091
11092
11093/* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
11094 is the JPEG data source manager. */
11095
11096static void
11097our_skip_input_data (cinfo, num_bytes)
11098 j_decompress_ptr cinfo;
11099 long num_bytes;
11100{
11101 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
11102
11103 if (src)
11104 {
11105 if (num_bytes > src->bytes_in_buffer)
11106 ERREXIT (cinfo, JERR_INPUT_EOF);
c922a224 11107
6fc2811b
JR
11108 src->bytes_in_buffer -= num_bytes;
11109 src->next_input_byte += num_bytes;
11110 }
11111}
11112
11113
11114/* Method to terminate data source. Called by
11115 jpeg_finish_decompress() after all data has been processed. */
11116
11117static void
11118our_term_source (cinfo)
11119 j_decompress_ptr cinfo;
11120{
11121}
11122
11123
11124/* Set up the JPEG lib for reading an image from DATA which contains
11125 LEN bytes. CINFO is the decompression info structure created for
11126 reading the image. */
11127
11128static void
11129jpeg_memory_src (cinfo, data, len)
11130 j_decompress_ptr cinfo;
11131 JOCTET *data;
11132 unsigned int len;
11133{
11134 struct jpeg_source_mgr *src;
11135
11136 if (cinfo->src == NULL)
11137 {
11138 /* First time for this JPEG object? */
11139 cinfo->src = (struct jpeg_source_mgr *)
11140 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
11141 sizeof (struct jpeg_source_mgr));
11142 src = (struct jpeg_source_mgr *) cinfo->src;
11143 src->next_input_byte = data;
11144 }
c922a224 11145
6fc2811b
JR
11146 src = (struct jpeg_source_mgr *) cinfo->src;
11147 src->init_source = our_init_source;
11148 src->fill_input_buffer = our_fill_input_buffer;
11149 src->skip_input_data = our_skip_input_data;
afc390dc 11150 src->resync_to_restart = jpeg_resync_to_restart_wrapper; /* Use default method. */
6fc2811b
JR
11151 src->term_source = our_term_source;
11152 src->bytes_in_buffer = len;
11153 src->next_input_byte = data;
11154}
11155
11156
11157/* Load image IMG for use on frame F. Patterned after example.c
11158 from the JPEG lib. */
11159
c922a224 11160static int
6fc2811b
JR
11161jpeg_load (f, img)
11162 struct frame *f;
11163 struct image *img;
11164{
11165 struct jpeg_decompress_struct cinfo;
11166 struct my_jpeg_error_mgr mgr;
11167 Lisp_Object file, specified_file;
11168 Lisp_Object specified_data;
a05e2bae 11169 FILE * volatile fp = NULL;
6fc2811b
JR
11170 JSAMPARRAY buffer;
11171 int row_stride, x, y;
11172 XImage *ximg = NULL;
11173 int rc;
11174 unsigned long *colors;
11175 int width, height;
11176 struct gcpro gcpro1;
11177
11178 /* Open the JPEG file. */
11179 specified_file = image_spec_value (img->spec, QCfile, NULL);
11180 specified_data = image_spec_value (img->spec, QCdata, NULL);
11181 file = Qnil;
11182 GCPRO1 (file);
11183
6fc2811b
JR
11184 if (NILP (specified_data))
11185 {
11186 file = x_find_image_file (specified_file);
11187 if (!STRINGP (file))
afc390dc
JR
11188 {
11189 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11190 UNGCPRO;
11191 return 0;
11192 }
c922a224 11193
c45bb3b2 11194 fp = fopen (SDATA (file), "rb");
6fc2811b 11195 if (fp == NULL)
afc390dc
JR
11196 {
11197 image_error ("Cannot open `%s'", file, Qnil);
11198 UNGCPRO;
11199 return 0;
11200 }
6fc2811b 11201 }
7d0393cf 11202
6fc2811b 11203 /* Customize libjpeg's error handling to call my_error_exit when an
afc390dc
JR
11204 error is detected. This function will perform a longjmp. */
11205 cinfo.err = fn_jpeg_std_error (&mgr.pub);
a05e2bae 11206 mgr.pub.error_exit = my_error_exit;
c922a224 11207
6fc2811b
JR
11208 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
11209 {
11210 if (rc == 1)
11211 {
11212 /* Called from my_error_exit. Display a JPEG error. */
11213 char buffer[JMSG_LENGTH_MAX];
11214 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
11215 image_error ("Error reading JPEG image `%s': %s", img->spec,
11216 build_string (buffer));
11217 }
c922a224 11218
6fc2811b
JR
11219 /* Close the input file and destroy the JPEG object. */
11220 if (fp)
afc390dc
JR
11221 fclose ((FILE *) fp);
11222 fn_jpeg_destroy_decompress (&cinfo);
7d0393cf 11223
6fc2811b
JR
11224 /* If we already have an XImage, free that. */
11225 x_destroy_x_image (ximg);
11226
11227 /* Free pixmap and colors. */
11228 x_clear_image (f, img);
c922a224 11229
6fc2811b
JR
11230 UNGCPRO;
11231 return 0;
11232 }
11233
11234 /* Create the JPEG decompression object. Let it read from fp.
afc390dc
JR
11235 Read the JPEG image header. */
11236 fn_jpeg_CreateDecompress (&cinfo, JPEG_LIB_VERSION, sizeof (cinfo));
6fc2811b
JR
11237
11238 if (NILP (specified_data))
afc390dc 11239 fn_jpeg_stdio_src (&cinfo, (FILE *) fp);
6fc2811b 11240 else
d5db4077
KR
11241 jpeg_memory_src (&cinfo, SDATA (specified_data),
11242 SBYTES (specified_data));
6fc2811b 11243
afc390dc 11244 fn_jpeg_read_header (&cinfo, TRUE);
6fc2811b
JR
11245
11246 /* Customize decompression so that color quantization will be used.
afc390dc 11247 Start decompression. */
6fc2811b 11248 cinfo.quantize_colors = TRUE;
afc390dc 11249 fn_jpeg_start_decompress (&cinfo);
6fc2811b
JR
11250 width = img->width = cinfo.output_width;
11251 height = img->height = cinfo.output_height;
11252
6fc2811b 11253 /* Create X image and pixmap. */
afc390dc 11254 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
a05e2bae 11255 longjmp (mgr.setjmp_buffer, 2);
6fc2811b
JR
11256
11257 /* Allocate colors. When color quantization is used,
11258 cinfo.actual_number_of_colors has been set with the number of
11259 colors generated, and cinfo.colormap is a two-dimensional array
11260 of color indices in the range 0..cinfo.actual_number_of_colors.
11261 No more than 255 colors will be generated. */
11262 {
11263 int i, ir, ig, ib;
11264
11265 if (cinfo.out_color_components > 2)
11266 ir = 0, ig = 1, ib = 2;
11267 else if (cinfo.out_color_components > 1)
11268 ir = 0, ig = 1, ib = 0;
11269 else
11270 ir = 0, ig = 0, ib = 0;
11271
afc390dc 11272#if 0 /* TODO: Color tables. */
6fc2811b
JR
11273 /* Use the color table mechanism because it handles colors that
11274 cannot be allocated nicely. Such colors will be replaced with
11275 a default color, and we don't have to care about which colors
11276 can be freed safely, and which can't. */
11277 init_color_table ();
afc390dc 11278#endif
6fc2811b
JR
11279 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
11280 * sizeof *colors);
c922a224 11281
6fc2811b
JR
11282 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
11283 {
afc390dc
JR
11284 int r = cinfo.colormap[ir][i];
11285 int g = cinfo.colormap[ig][i];
11286 int b = cinfo.colormap[ib][i];
11287#if 0 /* TODO: Color tables. */
6fc2811b 11288 colors[i] = lookup_rgb_color (f, r, g, b);
afc390dc
JR
11289#else
11290 colors[i] = PALETTERGB (r, g, b);
11291#endif
6fc2811b
JR
11292 }
11293
afc390dc 11294#if 0 /* TODO: Color tables. */
6fc2811b
JR
11295 /* Remember those colors actually allocated. */
11296 img->colors = colors_in_color_table (&img->ncolors);
11297 free_color_table ();
afc390dc 11298#endif
6fc2811b
JR
11299 }
11300
11301 /* Read pixels. */
11302 row_stride = width * cinfo.output_components;
11303 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
11304 row_stride, 1);
11305 for (y = 0; y < height; ++y)
11306 {
afc390dc 11307 fn_jpeg_read_scanlines (&cinfo, buffer, 1);
6fc2811b
JR
11308 for (x = 0; x < cinfo.output_width; ++x)
11309 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
11310 }
11311
11312 /* Clean up. */
afc390dc
JR
11313 fn_jpeg_finish_decompress (&cinfo);
11314 fn_jpeg_destroy_decompress (&cinfo);
6fc2811b 11315 if (fp)
afc390dc 11316 fclose ((FILE *) fp);
7d0393cf 11317
a05e2bae
JR
11318 /* Maybe fill in the background field while we have ximg handy. */
11319 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11320 IMAGE_BACKGROUND (img, f, ximg);
c922a224 11321
6fc2811b
JR
11322 /* Put the image into the pixmap. */
11323 x_put_x_image (f, ximg, img->pixmap, width, height);
11324 x_destroy_x_image (ximg);
6fc2811b
JR
11325 UNGCPRO;
11326 return 1;
11327}
11328
11329#endif /* HAVE_JPEG */
11330
11331
11332\f
11333/***********************************************************************
11334 TIFF
11335 ***********************************************************************/
11336
11337#if HAVE_TIFF
11338
11339#include <tiffio.h>
11340
11341static int tiff_image_p P_ ((Lisp_Object object));
11342static int tiff_load P_ ((struct frame *f, struct image *img));
11343
11344/* The symbol `tiff' identifying images of this type. */
11345
11346Lisp_Object Qtiff;
11347
11348/* Indices of image specification fields in tiff_format, below. */
11349
11350enum tiff_keyword_index
11351{
11352 TIFF_TYPE,
11353 TIFF_DATA,
11354 TIFF_FILE,
11355 TIFF_ASCENT,
11356 TIFF_MARGIN,
11357 TIFF_RELIEF,
11358 TIFF_ALGORITHM,
11359 TIFF_HEURISTIC_MASK,
a05e2bae
JR
11360 TIFF_MASK,
11361 TIFF_BACKGROUND,
6fc2811b
JR
11362 TIFF_LAST
11363};
11364
11365/* Vector of image_keyword structures describing the format
11366 of valid user-defined image specifications. */
11367
11368static struct image_keyword tiff_format[TIFF_LAST] =
11369{
11370 {":type", IMAGE_SYMBOL_VALUE, 1},
11371 {":data", IMAGE_STRING_VALUE, 0},
11372 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 11373 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 11374 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 11375 {":relief", IMAGE_INTEGER_VALUE, 0},
a05e2bae
JR
11376 {":conversions", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11377 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11378 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11379 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
11380};
11381
11382/* Structure describing the image type `tiff'. */
11383
11384static struct image_type tiff_type =
11385{
11386 &Qtiff,
11387 tiff_image_p,
11388 tiff_load,
11389 x_clear_image,
11390 NULL
11391};
11392
12b918b2
JB
11393/* TIFF library details. */
11394DEF_IMGLIB_FN (TIFFSetErrorHandler);
11395DEF_IMGLIB_FN (TIFFSetWarningHandler);
11396DEF_IMGLIB_FN (TIFFOpen);
11397DEF_IMGLIB_FN (TIFFClientOpen);
11398DEF_IMGLIB_FN (TIFFGetField);
11399DEF_IMGLIB_FN (TIFFReadRGBAImage);
11400DEF_IMGLIB_FN (TIFFClose);
11401
11402static int
11403init_tiff_functions (library)
11404 HMODULE library;
11405{
11406 LOAD_IMGLIB_FN (library, TIFFSetErrorHandler);
11407 LOAD_IMGLIB_FN (library, TIFFSetWarningHandler);
11408 LOAD_IMGLIB_FN (library, TIFFOpen);
11409 LOAD_IMGLIB_FN (library, TIFFClientOpen);
11410 LOAD_IMGLIB_FN (library, TIFFGetField);
11411 LOAD_IMGLIB_FN (library, TIFFReadRGBAImage);
11412 LOAD_IMGLIB_FN (library, TIFFClose);
11413 return 1;
11414}
6fc2811b
JR
11415
11416/* Return non-zero if OBJECT is a valid TIFF image specification. */
11417
11418static int
11419tiff_image_p (object)
11420 Lisp_Object object;
11421{
11422 struct image_keyword fmt[TIFF_LAST];
11423 bcopy (tiff_format, fmt, sizeof fmt);
7d0393cf 11424
8f92c555 11425 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff))
6fc2811b 11426 return 0;
7d0393cf 11427
6fc2811b
JR
11428 /* Must specify either the :data or :file keyword. */
11429 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
11430}
11431
11432
11433/* Reading from a memory buffer for TIFF images Based on the PNG
11434 memory source, but we have to provide a lot of extra functions.
11435 Blah.
11436
11437 We really only need to implement read and seek, but I am not
11438 convinced that the TIFF library is smart enough not to destroy
11439 itself if we only hand it the function pointers we need to
11440 override. */
11441
11442typedef struct
11443{
11444 unsigned char *bytes;
11445 size_t len;
11446 int index;
11447}
11448tiff_memory_source;
11449
11450static size_t
11451tiff_read_from_memory (data, buf, size)
11452 thandle_t data;
11453 tdata_t buf;
11454 tsize_t size;
11455{
11456 tiff_memory_source *src = (tiff_memory_source *) data;
11457
11458 if (size > src->len - src->index)
11459 return (size_t) -1;
11460 bcopy (src->bytes + src->index, buf, size);
11461 src->index += size;
11462 return size;
11463}
11464
11465static size_t
11466tiff_write_from_memory (data, buf, size)
11467 thandle_t data;
11468 tdata_t buf;
11469 tsize_t size;
11470{
11471 return (size_t) -1;
11472}
11473
11474static toff_t
11475tiff_seek_in_memory (data, off, whence)
11476 thandle_t data;
11477 toff_t off;
11478 int whence;
11479{
11480 tiff_memory_source *src = (tiff_memory_source *) data;
11481 int idx;
11482
11483 switch (whence)
11484 {
11485 case SEEK_SET: /* Go from beginning of source. */
11486 idx = off;
11487 break;
7d0393cf 11488
6fc2811b
JR
11489 case SEEK_END: /* Go from end of source. */
11490 idx = src->len + off;
11491 break;
7d0393cf 11492
6fc2811b
JR
11493 case SEEK_CUR: /* Go from current position. */
11494 idx = src->index + off;
11495 break;
7d0393cf 11496
6fc2811b
JR
11497 default: /* Invalid `whence'. */
11498 return -1;
11499 }
7d0393cf 11500
6fc2811b
JR
11501 if (idx > src->len || idx < 0)
11502 return -1;
7d0393cf 11503
6fc2811b
JR
11504 src->index = idx;
11505 return src->index;
11506}
11507
11508static int
11509tiff_close_memory (data)
11510 thandle_t data;
11511{
11512 /* NOOP */
11513 return 0;
11514}
11515
11516static int
11517tiff_mmap_memory (data, pbase, psize)
11518 thandle_t data;
11519 tdata_t *pbase;
11520 toff_t *psize;
11521{
11522 /* It is already _IN_ memory. */
11523 return 0;
11524}
11525
11526static void
11527tiff_unmap_memory (data, base, size)
11528 thandle_t data;
11529 tdata_t base;
11530 toff_t size;
11531{
11532 /* We don't need to do this. */
11533}
11534
11535static toff_t
11536tiff_size_of_memory (data)
11537 thandle_t data;
11538{
11539 return ((tiff_memory_source *) data)->len;
11540}
11541
3cf3436e
JR
11542
11543static void
11544tiff_error_handler (title, format, ap)
11545 const char *title, *format;
11546 va_list ap;
11547{
11548 char buf[512];
11549 int len;
7d0393cf 11550
3cf3436e
JR
11551 len = sprintf (buf, "TIFF error: %s ", title);
11552 vsprintf (buf + len, format, ap);
11553 add_to_log (buf, Qnil, Qnil);
11554}
11555
11556
11557static void
11558tiff_warning_handler (title, format, ap)
11559 const char *title, *format;
11560 va_list ap;
11561{
11562 char buf[512];
11563 int len;
7d0393cf 11564
3cf3436e
JR
11565 len = sprintf (buf, "TIFF warning: %s ", title);
11566 vsprintf (buf + len, format, ap);
11567 add_to_log (buf, Qnil, Qnil);
11568}
11569
11570
6fc2811b
JR
11571/* Load TIFF image IMG for use on frame F. Value is non-zero if
11572 successful. */
11573
11574static int
11575tiff_load (f, img)
11576 struct frame *f;
11577 struct image *img;
11578{
11579 Lisp_Object file, specified_file;
11580 Lisp_Object specified_data;
11581 TIFF *tiff;
11582 int width, height, x, y;
11583 uint32 *buf;
11584 int rc;
11585 XImage *ximg;
11586 struct gcpro gcpro1;
11587 tiff_memory_source memsrc;
11588
11589 specified_file = image_spec_value (img->spec, QCfile, NULL);
11590 specified_data = image_spec_value (img->spec, QCdata, NULL);
11591 file = Qnil;
11592 GCPRO1 (file);
11593
12b918b2
JB
11594 fn_TIFFSetErrorHandler (tiff_error_handler);
11595 fn_TIFFSetWarningHandler (tiff_warning_handler);
3cf3436e 11596
6fc2811b
JR
11597 if (NILP (specified_data))
11598 {
11599 /* Read from a file */
11600 file = x_find_image_file (specified_file);
11601 if (!STRINGP (file))
3cf3436e
JR
11602 {
11603 image_error ("Cannot find image file `%s'", file, Qnil);
11604 UNGCPRO;
11605 return 0;
11606 }
7d0393cf 11607
6fc2811b 11608 /* Try to open the image file. */
12b918b2 11609 tiff = fn_TIFFOpen (SDATA (file), "r");
6fc2811b 11610 if (tiff == NULL)
3cf3436e
JR
11611 {
11612 image_error ("Cannot open `%s'", file, Qnil);
11613 UNGCPRO;
11614 return 0;
11615 }
6fc2811b
JR
11616 }
11617 else
11618 {
11619 /* Memory source! */
d5db4077
KR
11620 memsrc.bytes = SDATA (specified_data);
11621 memsrc.len = SBYTES (specified_data);
6fc2811b
JR
11622 memsrc.index = 0;
11623
12b918b2
JB
11624 tiff = fn_TIFFClientOpen ("memory_source", "r", &memsrc,
11625 (TIFFReadWriteProc) tiff_read_from_memory,
11626 (TIFFReadWriteProc) tiff_write_from_memory,
11627 tiff_seek_in_memory,
11628 tiff_close_memory,
11629 tiff_size_of_memory,
11630 tiff_mmap_memory,
11631 tiff_unmap_memory);
6fc2811b
JR
11632
11633 if (!tiff)
11634 {
11635 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
11636 UNGCPRO;
11637 return 0;
11638 }
11639 }
11640
11641 /* Get width and height of the image, and allocate a raster buffer
11642 of width x height 32-bit values. */
12b918b2
JB
11643 fn_TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
11644 fn_TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
6fc2811b 11645 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
7d0393cf 11646
12b918b2
JB
11647 rc = fn_TIFFReadRGBAImage (tiff, width, height, buf, 0);
11648 fn_TIFFClose (tiff);
6fc2811b
JR
11649 if (!rc)
11650 {
11651 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
11652 xfree (buf);
11653 UNGCPRO;
11654 return 0;
11655 }
11656
6fc2811b
JR
11657 /* Create the X image and pixmap. */
11658 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11659 {
6fc2811b
JR
11660 xfree (buf);
11661 UNGCPRO;
11662 return 0;
11663 }
11664
12b918b2 11665#if 0 /* TODO: Color tables. */
6fc2811b
JR
11666 /* Initialize the color table. */
11667 init_color_table ();
12b918b2 11668#endif
6fc2811b
JR
11669
11670 /* Process the pixel raster. Origin is in the lower-left corner. */
11671 for (y = 0; y < height; ++y)
11672 {
11673 uint32 *row = buf + y * width;
7d0393cf 11674
6fc2811b
JR
11675 for (x = 0; x < width; ++x)
11676 {
11677 uint32 abgr = row[x];
12b918b2
JB
11678 int r = TIFFGetR (abgr);
11679 int g = TIFFGetG (abgr);
11680 int b = TIFFGetB (abgr);
11681#if 0 /* TODO: Color tables. */
7d0393cf 11682 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
12b918b2
JB
11683#else
11684 XPutPixel (ximg, x, height - 1 - y, PALETTERGB (r, g, b));
11685#endif
6fc2811b
JR
11686 }
11687 }
11688
12b918b2 11689#if 0 /* TODO: Color tables. */
6fc2811b
JR
11690 /* Remember the colors allocated for the image. Free the color table. */
11691 img->colors = colors_in_color_table (&img->ncolors);
11692 free_color_table ();
12b918b2 11693#endif
6fc2811b 11694
a05e2bae
JR
11695 img->width = width;
11696 img->height = height;
11697
11698 /* Maybe fill in the background field while we have ximg handy. */
11699 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
11700 IMAGE_BACKGROUND (img, f, ximg);
11701
6fc2811b
JR
11702 /* Put the image into the pixmap, then free the X image and its buffer. */
11703 x_put_x_image (f, ximg, img->pixmap, width, height);
11704 x_destroy_x_image (ximg);
11705 xfree (buf);
6fc2811b
JR
11706
11707 UNGCPRO;
11708 return 1;
11709}
11710
11711#endif /* HAVE_TIFF != 0 */
11712
11713
11714\f
11715/***********************************************************************
11716 GIF
11717 ***********************************************************************/
11718
11719#if HAVE_GIF
11720
1ffb278b 11721#define DrawText gif_DrawText
6fc2811b 11722#include <gif_lib.h>
1ffb278b 11723#undef DrawText
6fc2811b
JR
11724
11725static int gif_image_p P_ ((Lisp_Object object));
11726static int gif_load P_ ((struct frame *f, struct image *img));
11727
11728/* The symbol `gif' identifying images of this type. */
11729
11730Lisp_Object Qgif;
11731
11732/* Indices of image specification fields in gif_format, below. */
11733
11734enum gif_keyword_index
11735{
11736 GIF_TYPE,
11737 GIF_DATA,
11738 GIF_FILE,
11739 GIF_ASCENT,
11740 GIF_MARGIN,
11741 GIF_RELIEF,
11742 GIF_ALGORITHM,
11743 GIF_HEURISTIC_MASK,
a05e2bae 11744 GIF_MASK,
6fc2811b 11745 GIF_IMAGE,
a05e2bae 11746 GIF_BACKGROUND,
6fc2811b
JR
11747 GIF_LAST
11748};
11749
11750/* Vector of image_keyword structures describing the format
11751 of valid user-defined image specifications. */
11752
11753static struct image_keyword gif_format[GIF_LAST] =
11754{
11755 {":type", IMAGE_SYMBOL_VALUE, 1},
11756 {":data", IMAGE_STRING_VALUE, 0},
11757 {":file", IMAGE_STRING_VALUE, 0},
8f92c555 11758 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 11759 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 11760 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 11761 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
6fc2811b 11762 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
11763 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11764 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11765 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
11766};
11767
11768/* Structure describing the image type `gif'. */
11769
11770static struct image_type gif_type =
11771{
11772 &Qgif,
11773 gif_image_p,
11774 gif_load,
11775 x_clear_image,
11776 NULL
11777};
11778
1ffb278b
JB
11779
11780/* GIF library details. */
11781DEF_IMGLIB_FN (DGifCloseFile);
11782DEF_IMGLIB_FN (DGifSlurp);
11783DEF_IMGLIB_FN (DGifOpen);
11784DEF_IMGLIB_FN (DGifOpenFileName);
11785
11786static int
11787init_gif_functions (library)
11788 HMODULE library;
11789{
11790 LOAD_IMGLIB_FN (library, DGifCloseFile);
11791 LOAD_IMGLIB_FN (library, DGifSlurp);
11792 LOAD_IMGLIB_FN (library, DGifOpen);
11793 LOAD_IMGLIB_FN (library, DGifOpenFileName);
11794 return 1;
11795}
11796
11797
6fc2811b
JR
11798/* Return non-zero if OBJECT is a valid GIF image specification. */
11799
11800static int
11801gif_image_p (object)
11802 Lisp_Object object;
11803{
11804 struct image_keyword fmt[GIF_LAST];
11805 bcopy (gif_format, fmt, sizeof fmt);
7d0393cf 11806
8f92c555 11807 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif))
6fc2811b 11808 return 0;
7d0393cf 11809
6fc2811b
JR
11810 /* Must specify either the :data or :file keyword. */
11811 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
11812}
11813
11814/* Reading a GIF image from memory
11815 Based on the PNG memory stuff to a certain extent. */
11816
11817typedef struct
11818{
11819 unsigned char *bytes;
11820 size_t len;
11821 int index;
11822}
11823gif_memory_source;
11824
11825/* Make the current memory source available to gif_read_from_memory.
11826 It's done this way because not all versions of libungif support
11827 a UserData field in the GifFileType structure. */
11828static gif_memory_source *current_gif_memory_src;
11829
11830static int
11831gif_read_from_memory (file, buf, len)
11832 GifFileType *file;
11833 GifByteType *buf;
11834 int len;
11835{
11836 gif_memory_source *src = current_gif_memory_src;
11837
11838 if (len > src->len - src->index)
11839 return -1;
11840
11841 bcopy (src->bytes + src->index, buf, len);
11842 src->index += len;
11843 return len;
11844}
11845
11846
11847/* Load GIF image IMG for use on frame F. Value is non-zero if
11848 successful. */
11849
11850static int
11851gif_load (f, img)
11852 struct frame *f;
11853 struct image *img;
11854{
11855 Lisp_Object file, specified_file;
11856 Lisp_Object specified_data;
11857 int rc, width, height, x, y, i;
11858 XImage *ximg;
11859 ColorMapObject *gif_color_map;
11860 unsigned long pixel_colors[256];
11861 GifFileType *gif;
11862 struct gcpro gcpro1;
11863 Lisp_Object image;
11864 int ino, image_left, image_top, image_width, image_height;
11865 gif_memory_source memsrc;
11866 unsigned char *raster;
11867
11868 specified_file = image_spec_value (img->spec, QCfile, NULL);
11869 specified_data = image_spec_value (img->spec, QCdata, NULL);
11870 file = Qnil;
dfff8a69 11871 GCPRO1 (file);
6fc2811b
JR
11872
11873 if (NILP (specified_data))
11874 {
11875 file = x_find_image_file (specified_file);
6fc2811b
JR
11876 if (!STRINGP (file))
11877 {
11878 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11879 UNGCPRO;
11880 return 0;
11881 }
7d0393cf 11882
6fc2811b 11883 /* Open the GIF file. */
1ffb278b 11884 gif = fn_DGifOpenFileName (SDATA (file));
6fc2811b
JR
11885 if (gif == NULL)
11886 {
11887 image_error ("Cannot open `%s'", file, Qnil);
11888 UNGCPRO;
11889 return 0;
11890 }
11891 }
11892 else
11893 {
11894 /* Read from memory! */
11895 current_gif_memory_src = &memsrc;
d5db4077
KR
11896 memsrc.bytes = SDATA (specified_data);
11897 memsrc.len = SBYTES (specified_data);
6fc2811b
JR
11898 memsrc.index = 0;
11899
1ffb278b 11900 gif = fn_DGifOpen(&memsrc, gif_read_from_memory);
6fc2811b
JR
11901 if (!gif)
11902 {
11903 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11904 UNGCPRO;
11905 return 0;
11906 }
11907 }
11908
11909 /* Read entire contents. */
1ffb278b 11910 rc = fn_DGifSlurp (gif);
6fc2811b
JR
11911 if (rc == GIF_ERROR)
11912 {
11913 image_error ("Error reading `%s'", img->spec, Qnil);
1ffb278b 11914 fn_DGifCloseFile (gif);
6fc2811b
JR
11915 UNGCPRO;
11916 return 0;
11917 }
11918
11919 image = image_spec_value (img->spec, QCindex, NULL);
11920 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11921 if (ino >= gif->ImageCount)
11922 {
11923 image_error ("Invalid image number `%s' in image `%s'",
11924 image, img->spec);
1ffb278b 11925 fn_DGifCloseFile (gif);
6fc2811b
JR
11926 UNGCPRO;
11927 return 0;
11928 }
11929
1ffb278b
JB
11930 width = img->width = max (gif->SWidth, gif->Image.Left + gif->Image.Width);
11931 height = img->height = max (gif->SHeight, gif->Image.Top + gif->Image.Height);
6fc2811b 11932
6fc2811b
JR
11933 /* Create the X image and pixmap. */
11934 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11935 {
1ffb278b 11936 fn_DGifCloseFile (gif);
6fc2811b
JR
11937 UNGCPRO;
11938 return 0;
11939 }
7d0393cf 11940
6fc2811b
JR
11941 /* Allocate colors. */
11942 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11943 if (!gif_color_map)
11944 gif_color_map = gif->SColorMap;
1ffb278b 11945#if 0 /* TODO: Color tables */
6fc2811b 11946 init_color_table ();
1ffb278b 11947#endif
6fc2811b 11948 bzero (pixel_colors, sizeof pixel_colors);
7d0393cf 11949
6fc2811b
JR
11950 for (i = 0; i < gif_color_map->ColorCount; ++i)
11951 {
1ffb278b
JB
11952 int r = gif_color_map->Colors[i].Red;
11953 int g = gif_color_map->Colors[i].Green;
11954 int b = gif_color_map->Colors[i].Blue;
11955#if 0 /* TODO: Color tables */
6fc2811b 11956 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
1ffb278b
JB
11957#else
11958 pixel_colors[i] = PALETTERGB (r, g, b);
11959#endif
6fc2811b
JR
11960 }
11961
1ffb278b 11962#if 0 /* TODO: Color tables */
6fc2811b
JR
11963 img->colors = colors_in_color_table (&img->ncolors);
11964 free_color_table ();
1ffb278b 11965#endif
6fc2811b
JR
11966
11967 /* Clear the part of the screen image that are not covered by
7d0393cf 11968 the image from the GIF file. Full animated GIF support
6fc2811b
JR
11969 requires more than can be done here (see the gif89 spec,
11970 disposal methods). Let's simply assume that the part
11971 not covered by a sub-image is in the frame's background color. */
11972 image_top = gif->SavedImages[ino].ImageDesc.Top;
11973 image_left = gif->SavedImages[ino].ImageDesc.Left;
11974 image_width = gif->SavedImages[ino].ImageDesc.Width;
11975 image_height = gif->SavedImages[ino].ImageDesc.Height;
11976
11977 for (y = 0; y < image_top; ++y)
11978 for (x = 0; x < width; ++x)
11979 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11980
11981 for (y = image_top + image_height; y < height; ++y)
11982 for (x = 0; x < width; ++x)
11983 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11984
11985 for (y = image_top; y < image_top + image_height; ++y)
11986 {
11987 for (x = 0; x < image_left; ++x)
11988 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11989 for (x = image_left + image_width; x < width; ++x)
11990 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11991 }
11992
11993 /* Read the GIF image into the X image. We use a local variable
11994 `raster' here because RasterBits below is a char *, and invites
11995 problems with bytes >= 0x80. */
11996 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
11997
11998 if (gif->SavedImages[ino].ImageDesc.Interlace)
11999 {
12000 static int interlace_start[] = {0, 4, 2, 1};
12001 static int interlace_increment[] = {8, 8, 4, 2};
a05e2bae 12002 int pass;
6fc2811b
JR
12003 int row = interlace_start[0];
12004
12005 pass = 0;
12006
12007 for (y = 0; y < image_height; y++)
12008 {
12009 if (row >= image_height)
12010 {
12011 row = interlace_start[++pass];
12012 while (row >= image_height)
12013 row = interlace_start[++pass];
12014 }
7d0393cf 12015
6fc2811b
JR
12016 for (x = 0; x < image_width; x++)
12017 {
12018 int i = raster[(y * image_width) + x];
12019 XPutPixel (ximg, x + image_left, row + image_top,
12020 pixel_colors[i]);
12021 }
7d0393cf 12022
6fc2811b
JR
12023 row += interlace_increment[pass];
12024 }
12025 }
12026 else
12027 {
12028 for (y = 0; y < image_height; ++y)
12029 for (x = 0; x < image_width; ++x)
12030 {
12031 int i = raster[y* image_width + x];
12032 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
12033 }
12034 }
7d0393cf 12035
1ffb278b 12036 fn_DGifCloseFile (gif);
a05e2bae
JR
12037
12038 /* Maybe fill in the background field while we have ximg handy. */
12039 if (NILP (image_spec_value (img->spec, QCbackground, NULL)))
12040 IMAGE_BACKGROUND (img, f, ximg);
12041
6fc2811b
JR
12042 /* Put the image into the pixmap, then free the X image and its buffer. */
12043 x_put_x_image (f, ximg, img->pixmap, width, height);
12044 x_destroy_x_image (ximg);
7d0393cf 12045
6fc2811b
JR
12046 UNGCPRO;
12047 return 1;
12048}
12049
12050#endif /* HAVE_GIF != 0 */
12051
12052
12053\f
12054/***********************************************************************
12055 Ghostscript
12056 ***********************************************************************/
12057
3cf3436e
JR
12058Lisp_Object Qpostscript;
12059
839b1909
JR
12060/* Keyword symbols. */
12061
12062Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12063
6fc2811b
JR
12064#ifdef HAVE_GHOSTSCRIPT
12065static int gs_image_p P_ ((Lisp_Object object));
12066static int gs_load P_ ((struct frame *f, struct image *img));
12067static void gs_clear_image P_ ((struct frame *f, struct image *img));
12068
12069/* The symbol `postscript' identifying images of this type. */
12070
6fc2811b
JR
12071/* Keyword symbols. */
12072
12073Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
12074
12075/* Indices of image specification fields in gs_format, below. */
12076
12077enum gs_keyword_index
12078{
12079 GS_TYPE,
12080 GS_PT_WIDTH,
12081 GS_PT_HEIGHT,
12082 GS_FILE,
12083 GS_LOADER,
12084 GS_BOUNDING_BOX,
12085 GS_ASCENT,
12086 GS_MARGIN,
12087 GS_RELIEF,
12088 GS_ALGORITHM,
12089 GS_HEURISTIC_MASK,
a05e2bae
JR
12090 GS_MASK,
12091 GS_BACKGROUND,
6fc2811b
JR
12092 GS_LAST
12093};
12094
12095/* Vector of image_keyword structures describing the format
12096 of valid user-defined image specifications. */
12097
12098static struct image_keyword gs_format[GS_LAST] =
12099{
12100 {":type", IMAGE_SYMBOL_VALUE, 1},
12101 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12102 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
12103 {":file", IMAGE_STRING_VALUE, 1},
12104 {":loader", IMAGE_FUNCTION_VALUE, 0},
12105 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
8f92c555 12106 {":ascent", IMAGE_ASCENT_VALUE, 0},
8edb0a6f 12107 {":margin", IMAGE_POSITIVE_INTEGER_VALUE_OR_PAIR, 0},
6fc2811b 12108 {":relief", IMAGE_INTEGER_VALUE, 0},
a93f4566 12109 {":conversion", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
a05e2bae
JR
12110 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12111 {":mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
12112 {":background", IMAGE_STRING_OR_NIL_VALUE, 0}
6fc2811b
JR
12113};
12114
12115/* Structure describing the image type `ghostscript'. */
12116
12117static struct image_type gs_type =
12118{
12119 &Qpostscript,
12120 gs_image_p,
12121 gs_load,
12122 gs_clear_image,
12123 NULL
12124};
12125
12126
12127/* Free X resources of Ghostscript image IMG which is used on frame F. */
12128
12129static void
12130gs_clear_image (f, img)
12131 struct frame *f;
12132 struct image *img;
12133{
12134 /* IMG->data.ptr_val may contain a recorded colormap. */
12135 xfree (img->data.ptr_val);
12136 x_clear_image (f, img);
12137}
12138
12139
12140/* Return non-zero if OBJECT is a valid Ghostscript image
12141 specification. */
12142
12143static int
12144gs_image_p (object)
12145 Lisp_Object object;
12146{
12147 struct image_keyword fmt[GS_LAST];
12148 Lisp_Object tem;
12149 int i;
7d0393cf 12150
6fc2811b 12151 bcopy (gs_format, fmt, sizeof fmt);
7d0393cf 12152
8f92c555 12153 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript))
6fc2811b
JR
12154 return 0;
12155
12156 /* Bounding box must be a list or vector containing 4 integers. */
12157 tem = fmt[GS_BOUNDING_BOX].value;
12158 if (CONSP (tem))
12159 {
12160 for (i = 0; i < 4; ++i, tem = XCDR (tem))
12161 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
12162 return 0;
12163 if (!NILP (tem))
12164 return 0;
12165 }
12166 else if (VECTORP (tem))
12167 {
12168 if (XVECTOR (tem)->size != 4)
12169 return 0;
12170 for (i = 0; i < 4; ++i)
12171 if (!INTEGERP (XVECTOR (tem)->contents[i]))
12172 return 0;
12173 }
12174 else
12175 return 0;
12176
12177 return 1;
12178}
12179
12180
12181/* Load Ghostscript image IMG for use on frame F. Value is non-zero
12182 if successful. */
12183
12184static int
12185gs_load (f, img)
12186 struct frame *f;
12187 struct image *img;
12188{
12189 char buffer[100];
12190 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
12191 struct gcpro gcpro1, gcpro2;
12192 Lisp_Object frame;
12193 double in_width, in_height;
12194 Lisp_Object pixel_colors = Qnil;
12195
12196 /* Compute pixel size of pixmap needed from the given size in the
12197 image specification. Sizes in the specification are in pt. 1 pt
12198 = 1/72 in, xdpi and ydpi are stored in the frame's X display
12199 info. */
12200 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
12201 in_width = XFASTINT (pt_width) / 72.0;
12202 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
12203 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
12204 in_height = XFASTINT (pt_height) / 72.0;
12205 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
12206
12207 /* Create the pixmap. */
12208 BLOCK_INPUT;
12209 xassert (img->pixmap == 0);
12210 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12211 img->width, img->height,
a05e2bae 12212 one_w32_display_info.n_cbits);
6fc2811b
JR
12213 UNBLOCK_INPUT;
12214
12215 if (!img->pixmap)
12216 {
12217 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
12218 return 0;
12219 }
7d0393cf 12220
6fc2811b
JR
12221 /* Call the loader to fill the pixmap. It returns a process object
12222 if successful. We do not record_unwind_protect here because
12223 other places in redisplay like calling window scroll functions
12224 don't either. Let the Lisp loader use `unwind-protect' instead. */
12225 GCPRO2 (window_and_pixmap_id, pixel_colors);
12226
12227 sprintf (buffer, "%lu %lu",
12228 (unsigned long) FRAME_W32_WINDOW (f),
12229 (unsigned long) img->pixmap);
12230 window_and_pixmap_id = build_string (buffer);
7d0393cf 12231
6fc2811b
JR
12232 sprintf (buffer, "%lu %lu",
12233 FRAME_FOREGROUND_PIXEL (f),
12234 FRAME_BACKGROUND_PIXEL (f));
12235 pixel_colors = build_string (buffer);
7d0393cf 12236
6fc2811b
JR
12237 XSETFRAME (frame, f);
12238 loader = image_spec_value (img->spec, QCloader, NULL);
12239 if (NILP (loader))
12240 loader = intern ("gs-load-image");
12241
12242 img->data.lisp_val = call6 (loader, frame, img->spec,
12243 make_number (img->width),
12244 make_number (img->height),
12245 window_and_pixmap_id,
12246 pixel_colors);
12247 UNGCPRO;
12248 return PROCESSP (img->data.lisp_val);
12249}
12250
12251
12252/* Kill the Ghostscript process that was started to fill PIXMAP on
12253 frame F. Called from XTread_socket when receiving an event
12254 telling Emacs that Ghostscript has finished drawing. */
12255
12256void
12257x_kill_gs_process (pixmap, f)
12258 Pixmap pixmap;
12259 struct frame *f;
12260{
12261 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
12262 int class, i;
12263 struct image *img;
12264
12265 /* Find the image containing PIXMAP. */
12266 for (i = 0; i < c->used; ++i)
12267 if (c->images[i]->pixmap == pixmap)
12268 break;
12269
3cf3436e
JR
12270 /* Should someone in between have cleared the image cache, for
12271 instance, give up. */
12272 if (i == c->used)
12273 return;
12274
6fc2811b
JR
12275 /* Kill the GS process. We should have found PIXMAP in the image
12276 cache and its image should contain a process object. */
6fc2811b
JR
12277 img = c->images[i];
12278 xassert (PROCESSP (img->data.lisp_val));
12279 Fkill_process (img->data.lisp_val, Qnil);
12280 img->data.lisp_val = Qnil;
12281
12282 /* On displays with a mutable colormap, figure out the colors
12283 allocated for the image by looking at the pixels of an XImage for
12284 img->pixmap. */
12285 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
12286 if (class != StaticColor && class != StaticGray && class != TrueColor)
12287 {
12288 XImage *ximg;
12289
12290 BLOCK_INPUT;
12291
12292 /* Try to get an XImage for img->pixmep. */
12293 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
12294 0, 0, img->width, img->height, ~0, ZPixmap);
12295 if (ximg)
12296 {
12297 int x, y;
7d0393cf 12298
6fc2811b
JR
12299 /* Initialize the color table. */
12300 init_color_table ();
7d0393cf 12301
6fc2811b
JR
12302 /* For each pixel of the image, look its color up in the
12303 color table. After having done so, the color table will
12304 contain an entry for each color used by the image. */
12305 for (y = 0; y < img->height; ++y)
12306 for (x = 0; x < img->width; ++x)
12307 {
12308 unsigned long pixel = XGetPixel (ximg, x, y);
12309 lookup_pixel_color (f, pixel);
12310 }
12311
12312 /* Record colors in the image. Free color table and XImage. */
12313 img->colors = colors_in_color_table (&img->ncolors);
12314 free_color_table ();
12315 XDestroyImage (ximg);
12316
12317#if 0 /* This doesn't seem to be the case. If we free the colors
12318 here, we get a BadAccess later in x_clear_image when
12319 freeing the colors. */
12320 /* We have allocated colors once, but Ghostscript has also
12321 allocated colors on behalf of us. So, to get the
12322 reference counts right, free them once. */
12323 if (img->ncolors)
3cf3436e 12324 x_free_colors (FRAME_W32_DISPLAY (f), cmap,
6fc2811b 12325 img->colors, img->ncolors, 0);
6fc2811b
JR
12326#endif
12327 }
12328 else
12329 image_error ("Cannot get X image of `%s'; colors will not be freed",
12330 img->spec, Qnil);
7d0393cf 12331
6fc2811b
JR
12332 UNBLOCK_INPUT;
12333 }
3cf3436e
JR
12334
12335 /* Now that we have the pixmap, compute mask and transform the
12336 image if requested. */
12337 BLOCK_INPUT;
12338 postprocess_image (f, img);
12339 UNBLOCK_INPUT;
6fc2811b
JR
12340}
12341
12342#endif /* HAVE_GHOSTSCRIPT */
12343
12344\f
12345/***********************************************************************
12346 Window properties
12347 ***********************************************************************/
12348
12349DEFUN ("x-change-window-property", Fx_change_window_property,
12350 Sx_change_window_property, 2, 3, 0,
74e1aeec
JR
12351 doc: /* Change window property PROP to VALUE on the X window of FRAME.
12352PROP and VALUE must be strings. FRAME nil or omitted means use the
12353selected frame. Value is VALUE. */)
6fc2811b
JR
12354 (prop, value, frame)
12355 Lisp_Object frame, prop, value;
12356{
767b1ff0 12357#if 0 /* TODO : port window properties to W32 */
6fc2811b
JR
12358 struct frame *f = check_x_frame (frame);
12359 Atom prop_atom;
12360
b7826503
PJ
12361 CHECK_STRING (prop);
12362 CHECK_STRING (value);
6fc2811b
JR
12363
12364 BLOCK_INPUT;
d5db4077 12365 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6fc2811b
JR
12366 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12367 prop_atom, XA_STRING, 8, PropModeReplace,
d5db4077 12368 SDATA (value), SCHARS (value));
6fc2811b
JR
12369
12370 /* Make sure the property is set when we return. */
12371 XFlush (FRAME_W32_DISPLAY (f));
12372 UNBLOCK_INPUT;
12373
767b1ff0 12374#endif /* TODO */
6fc2811b
JR
12375
12376 return value;
12377}
12378
12379
12380DEFUN ("x-delete-window-property", Fx_delete_window_property,
12381 Sx_delete_window_property, 1, 2, 0,
74e1aeec
JR
12382 doc: /* Remove window property PROP from X window of FRAME.
12383FRAME nil or omitted means use the selected frame. Value is PROP. */)
6fc2811b
JR
12384 (prop, frame)
12385 Lisp_Object prop, frame;
12386{
767b1ff0 12387#if 0 /* TODO : port window properties to W32 */
6fc2811b
JR
12388
12389 struct frame *f = check_x_frame (frame);
12390 Atom prop_atom;
12391
b7826503 12392 CHECK_STRING (prop);
6fc2811b 12393 BLOCK_INPUT;
d5db4077 12394 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6fc2811b
JR
12395 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
12396
12397 /* Make sure the property is removed when we return. */
12398 XFlush (FRAME_W32_DISPLAY (f));
12399 UNBLOCK_INPUT;
767b1ff0 12400#endif /* TODO */
6fc2811b
JR
12401
12402 return prop;
12403}
12404
12405
12406DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
12407 1, 2, 0,
74e1aeec
JR
12408 doc: /* Value is the value of window property PROP on FRAME.
12409If FRAME is nil or omitted, use the selected frame. Value is nil
12410if FRAME hasn't a property with name PROP or if PROP has no string
12411value. */)
6fc2811b
JR
12412 (prop, frame)
12413 Lisp_Object prop, frame;
12414{
767b1ff0 12415#if 0 /* TODO : port window properties to W32 */
6fc2811b
JR
12416
12417 struct frame *f = check_x_frame (frame);
12418 Atom prop_atom;
12419 int rc;
12420 Lisp_Object prop_value = Qnil;
12421 char *tmp_data = NULL;
12422 Atom actual_type;
12423 int actual_format;
12424 unsigned long actual_size, bytes_remaining;
12425
b7826503 12426 CHECK_STRING (prop);
6fc2811b 12427 BLOCK_INPUT;
d5db4077 12428 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6fc2811b
JR
12429 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12430 prop_atom, 0, 0, False, XA_STRING,
12431 &actual_type, &actual_format, &actual_size,
12432 &bytes_remaining, (unsigned char **) &tmp_data);
12433 if (rc == Success)
12434 {
12435 int size = bytes_remaining;
12436
12437 XFree (tmp_data);
12438 tmp_data = NULL;
12439
12440 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12441 prop_atom, 0, bytes_remaining,
12442 False, XA_STRING,
7d0393cf
JB
12443 &actual_type, &actual_format,
12444 &actual_size, &bytes_remaining,
6fc2811b
JR
12445 (unsigned char **) &tmp_data);
12446 if (rc == Success)
12447 prop_value = make_string (tmp_data, size);
12448
12449 XFree (tmp_data);
12450 }
12451
12452 UNBLOCK_INPUT;
12453
12454 return prop_value;
12455
767b1ff0 12456#endif /* TODO */
6fc2811b
JR
12457 return Qnil;
12458}
12459
12460
12461\f
12462/***********************************************************************
12463 Busy cursor
12464 ***********************************************************************/
12465
f79e6790 12466/* If non-null, an asynchronous timer that, when it expires, displays
0af913d7 12467 an hourglass cursor on all frames. */
6fc2811b 12468
0af913d7 12469static struct atimer *hourglass_atimer;
6fc2811b 12470
0af913d7 12471/* Non-zero means an hourglass cursor is currently shown. */
6fc2811b 12472
0af913d7 12473static int hourglass_shown_p;
6fc2811b 12474
0af913d7 12475/* Number of seconds to wait before displaying an hourglass cursor. */
6fc2811b 12476
0af913d7 12477static Lisp_Object Vhourglass_delay;
6fc2811b 12478
0af913d7 12479/* Default number of seconds to wait before displaying an hourglass
f79e6790
JR
12480 cursor. */
12481
0af913d7 12482#define DEFAULT_HOURGLASS_DELAY 1
f79e6790
JR
12483
12484/* Function prototypes. */
12485
0af913d7
GM
12486static void show_hourglass P_ ((struct atimer *));
12487static void hide_hourglass P_ ((void));
f79e6790
JR
12488
12489
0af913d7 12490/* Cancel a currently active hourglass timer, and start a new one. */
f79e6790
JR
12491
12492void
0af913d7 12493start_hourglass ()
f79e6790 12494{
767b1ff0 12495#if 0 /* TODO: cursor shape changes. */
f79e6790 12496 EMACS_TIME delay;
dfff8a69 12497 int secs, usecs = 0;
7d0393cf 12498
0af913d7 12499 cancel_hourglass ();
f79e6790 12500
0af913d7
GM
12501 if (INTEGERP (Vhourglass_delay)
12502 && XINT (Vhourglass_delay) > 0)
12503 secs = XFASTINT (Vhourglass_delay);
12504 else if (FLOATP (Vhourglass_delay)
12505 && XFLOAT_DATA (Vhourglass_delay) > 0)
dfff8a69
JR
12506 {
12507 Lisp_Object tem;
0af913d7 12508 tem = Ftruncate (Vhourglass_delay, Qnil);
dfff8a69 12509 secs = XFASTINT (tem);
0af913d7 12510 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
dfff8a69 12511 }
f79e6790 12512 else
0af913d7 12513 secs = DEFAULT_HOURGLASS_DELAY;
7d0393cf 12514
dfff8a69 12515 EMACS_SET_SECS_USECS (delay, secs, usecs);
0af913d7
GM
12516 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
12517 show_hourglass, NULL);
f79e6790
JR
12518#endif
12519}
12520
12521
0af913d7
GM
12522/* Cancel the hourglass cursor timer if active, hide an hourglass
12523 cursor if shown. */
f79e6790
JR
12524
12525void
0af913d7 12526cancel_hourglass ()
f79e6790 12527{
0af913d7 12528 if (hourglass_atimer)
dfff8a69 12529 {
0af913d7
GM
12530 cancel_atimer (hourglass_atimer);
12531 hourglass_atimer = NULL;
dfff8a69 12532 }
7d0393cf 12533
0af913d7
GM
12534 if (hourglass_shown_p)
12535 hide_hourglass ();
f79e6790
JR
12536}
12537
12538
0af913d7
GM
12539/* Timer function of hourglass_atimer. TIMER is equal to
12540 hourglass_atimer.
f79e6790 12541
0af913d7
GM
12542 Display an hourglass cursor on all frames by mapping the frames'
12543 hourglass_window. Set the hourglass_p flag in the frames'
12544 output_data.x structure to indicate that an hourglass cursor is
12545 shown on the frames. */
f79e6790
JR
12546
12547static void
0af913d7 12548show_hourglass (timer)
f79e6790 12549 struct atimer *timer;
6fc2811b 12550{
767b1ff0 12551#if 0 /* TODO: cursor shape changes. */
f79e6790 12552 /* The timer implementation will cancel this timer automatically
0af913d7 12553 after this function has run. Set hourglass_atimer to null
f79e6790 12554 so that we know the timer doesn't have to be canceled. */
0af913d7 12555 hourglass_atimer = NULL;
f79e6790 12556
0af913d7 12557 if (!hourglass_shown_p)
6fc2811b
JR
12558 {
12559 Lisp_Object rest, frame;
7d0393cf 12560
f79e6790 12561 BLOCK_INPUT;
7d0393cf 12562
6fc2811b 12563 FOR_EACH_FRAME (rest, frame)
dc220243 12564 if (FRAME_W32_P (XFRAME (frame)))
6fc2811b
JR
12565 {
12566 struct frame *f = XFRAME (frame);
7d0393cf 12567
0af913d7 12568 f->output_data.w32->hourglass_p = 1;
7d0393cf 12569
0af913d7 12570 if (!f->output_data.w32->hourglass_window)
6fc2811b
JR
12571 {
12572 unsigned long mask = CWCursor;
12573 XSetWindowAttributes attrs;
7d0393cf 12574
0af913d7 12575 attrs.cursor = f->output_data.w32->hourglass_cursor;
7d0393cf 12576
0af913d7 12577 f->output_data.w32->hourglass_window
f79e6790 12578 = XCreateWindow (FRAME_X_DISPLAY (f),
6fc2811b
JR
12579 FRAME_OUTER_WINDOW (f),
12580 0, 0, 32000, 32000, 0, 0,
f79e6790
JR
12581 InputOnly,
12582 CopyFromParent,
6fc2811b
JR
12583 mask, &attrs);
12584 }
7d0393cf 12585
0af913d7
GM
12586 XMapRaised (FRAME_X_DISPLAY (f),
12587 f->output_data.w32->hourglass_window);
f79e6790 12588 XFlush (FRAME_X_DISPLAY (f));
6fc2811b 12589 }
6fc2811b 12590
0af913d7 12591 hourglass_shown_p = 1;
f79e6790
JR
12592 UNBLOCK_INPUT;
12593 }
12594#endif
6fc2811b
JR
12595}
12596
12597
0af913d7 12598/* Hide the hourglass cursor on all frames, if it is currently shown. */
6fc2811b 12599
f79e6790 12600static void
0af913d7 12601hide_hourglass ()
f79e6790 12602{
767b1ff0 12603#if 0 /* TODO: cursor shape changes. */
0af913d7 12604 if (hourglass_shown_p)
6fc2811b 12605 {
f79e6790
JR
12606 Lisp_Object rest, frame;
12607
12608 BLOCK_INPUT;
12609 FOR_EACH_FRAME (rest, frame)
6fc2811b 12610 {
f79e6790 12611 struct frame *f = XFRAME (frame);
7d0393cf 12612
dc220243 12613 if (FRAME_W32_P (f)
f79e6790 12614 /* Watch out for newly created frames. */
0af913d7 12615 && f->output_data.x->hourglass_window)
f79e6790 12616 {
0af913d7
GM
12617 XUnmapWindow (FRAME_X_DISPLAY (f),
12618 f->output_data.x->hourglass_window);
12619 /* Sync here because XTread_socket looks at the
12620 hourglass_p flag that is reset to zero below. */
f79e6790 12621 XSync (FRAME_X_DISPLAY (f), False);
0af913d7 12622 f->output_data.x->hourglass_p = 0;
f79e6790 12623 }
6fc2811b 12624 }
6fc2811b 12625
0af913d7 12626 hourglass_shown_p = 0;
f79e6790
JR
12627 UNBLOCK_INPUT;
12628 }
12629#endif
6fc2811b
JR
12630}
12631
12632
12633\f
12634/***********************************************************************
12635 Tool tips
12636 ***********************************************************************/
12637
12638static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
3cf3436e
JR
12639 Lisp_Object, Lisp_Object));
12640static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
12641 Lisp_Object, int, int, int *, int *));
7d0393cf 12642
3cf3436e 12643/* The frame of a currently visible tooltip. */
6fc2811b 12644
937e601e 12645Lisp_Object tip_frame;
6fc2811b
JR
12646
12647/* If non-nil, a timer started that hides the last tooltip when it
12648 fires. */
12649
12650Lisp_Object tip_timer;
12651Window tip_window;
12652
3cf3436e
JR
12653/* If non-nil, a vector of 3 elements containing the last args
12654 with which x-show-tip was called. See there. */
12655
12656Lisp_Object last_show_tip_args;
12657
12658/* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
12659
12660Lisp_Object Vx_max_tooltip_size;
12661
12662
937e601e
AI
12663static Lisp_Object
12664unwind_create_tip_frame (frame)
12665 Lisp_Object frame;
12666{
c844a81a
GM
12667 Lisp_Object deleted;
12668
12669 deleted = unwind_create_frame (frame);
12670 if (EQ (deleted, Qt))
12671 {
12672 tip_window = NULL;
12673 tip_frame = Qnil;
12674 }
7d0393cf 12675
c844a81a 12676 return deleted;
937e601e
AI
12677}
12678
12679
6fc2811b 12680/* Create a frame for a tooltip on the display described by DPYINFO.
3cf3436e
JR
12681 PARMS is a list of frame parameters. TEXT is the string to
12682 display in the tip frame. Value is the frame.
937e601e
AI
12683
12684 Note that functions called here, esp. x_default_parameter can
12685 signal errors, for instance when a specified color name is
12686 undefined. We have to make sure that we're in a consistent state
12687 when this happens. */
6fc2811b
JR
12688
12689static Lisp_Object
3cf3436e 12690x_create_tip_frame (dpyinfo, parms, text)
6fc2811b 12691 struct w32_display_info *dpyinfo;
3cf3436e 12692 Lisp_Object parms, text;
6fc2811b 12693{
6fc2811b
JR
12694 struct frame *f;
12695 Lisp_Object frame, tem;
12696 Lisp_Object name;
12697 long window_prompting = 0;
12698 int width, height;
331379bf 12699 int count = SPECPDL_INDEX ();
6fc2811b
JR
12700 struct gcpro gcpro1, gcpro2, gcpro3;
12701 struct kboard *kb;
3cf3436e
JR
12702 int face_change_count_before = face_change_count;
12703 Lisp_Object buffer;
12704 struct buffer *old_buffer;
6fc2811b 12705
ca56d953 12706 check_w32 ();
6fc2811b
JR
12707
12708 /* Use this general default value to start with until we know if
12709 this frame has a specified name. */
12710 Vx_resource_name = Vinvocation_name;
12711
12712#ifdef MULTI_KBOARD
12713 kb = dpyinfo->kboard;
12714#else
12715 kb = &the_only_kboard;
12716#endif
12717
12718 /* Get the name of the frame to use for resource lookup. */
12719 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
12720 if (!STRINGP (name)
12721 && !EQ (name, Qunbound)
12722 && !NILP (name))
12723 error ("Invalid frame name--not a string or nil");
12724 Vx_resource_name = name;
12725
12726 frame = Qnil;
12727 GCPRO3 (parms, name, frame);
9eb16b62
JR
12728 /* Make a frame without minibuffer nor mode-line. */
12729 f = make_frame (0);
12730 f->wants_modeline = 0;
6fc2811b 12731 XSETFRAME (frame, f);
3cf3436e
JR
12732
12733 buffer = Fget_buffer_create (build_string (" *tip*"));
12734 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
12735 old_buffer = current_buffer;
12736 set_buffer_internal_1 (XBUFFER (buffer));
12737 current_buffer->truncate_lines = Qnil;
12738 Ferase_buffer ();
12739 Finsert (1, &text);
12740 set_buffer_internal_1 (old_buffer);
7d0393cf 12741
6fc2811b 12742 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
937e601e 12743 record_unwind_protect (unwind_create_tip_frame, frame);
6fc2811b 12744
3cf3436e
JR
12745 /* By setting the output method, we're essentially saying that
12746 the frame is live, as per FRAME_LIVE_P. If we get a signal
12747 from this point on, x_destroy_window might screw up reference
12748 counts etc. */
d88c567c 12749 f->output_method = output_w32;
6fc2811b
JR
12750 f->output_data.w32 =
12751 (struct w32_output *) xmalloc (sizeof (struct w32_output));
12752 bzero (f->output_data.w32, sizeof (struct w32_output));
ca56d953
JR
12753
12754 FRAME_FONTSET (f) = -1;
6fc2811b
JR
12755 f->icon_name = Qnil;
12756
ca56d953 12757#if 0 /* GLYPH_DEBUG TODO: image support. */
937e601e
AI
12758 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
12759 dpyinfo_refcount = dpyinfo->reference_count;
12760#endif /* GLYPH_DEBUG */
6fc2811b
JR
12761#ifdef MULTI_KBOARD
12762 FRAME_KBOARD (f) = kb;
12763#endif
12764 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
12765 f->output_data.w32->explicit_parent = 0;
12766
12767 /* Set the name; the functions to which we pass f expect the name to
12768 be set. */
12769 if (EQ (name, Qunbound) || NILP (name))
12770 {
ca56d953 12771 f->name = build_string (dpyinfo->w32_id_name);
6fc2811b
JR
12772 f->explicit_name = 0;
12773 }
12774 else
12775 {
12776 f->name = name;
12777 f->explicit_name = 1;
12778 /* use the frame's title when getting resources for this frame. */
12779 specbind (Qx_resource_name, name);
12780 }
12781
6fc2811b
JR
12782 /* Extract the window parameters from the supplied values
12783 that are needed to determine window geometry. */
12784 {
12785 Lisp_Object font;
12786
12787 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
12788
12789 BLOCK_INPUT;
12790 /* First, try whatever font the caller has specified. */
12791 if (STRINGP (font))
12792 {
12793 tem = Fquery_fontset (font, Qnil);
12794 if (STRINGP (tem))
d5db4077 12795 font = x_new_fontset (f, SDATA (tem));
6fc2811b 12796 else
d5db4077 12797 font = x_new_font (f, SDATA (font));
6fc2811b 12798 }
7d0393cf 12799
6fc2811b
JR
12800 /* Try out a font which we hope has bold and italic variations. */
12801 if (!STRINGP (font))
ca56d953 12802 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
6fc2811b 12803 if (! STRINGP (font))
ca56d953 12804 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
6fc2811b
JR
12805 /* If those didn't work, look for something which will at least work. */
12806 if (! STRINGP (font))
ca56d953 12807 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
6fc2811b
JR
12808 UNBLOCK_INPUT;
12809 if (! STRINGP (font))
ca56d953 12810 font = build_string ("Fixedsys");
6fc2811b
JR
12811
12812 x_default_parameter (f, parms, Qfont, font,
12813 "font", "Font", RES_TYPE_STRING);
12814 }
12815
12816 x_default_parameter (f, parms, Qborder_width, make_number (2),
12817 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6fc2811b
JR
12818 /* This defaults to 2 in order to match xterm. We recognize either
12819 internalBorderWidth or internalBorder (which is what xterm calls
12820 it). */
12821 if (NILP (Fassq (Qinternal_border_width, parms)))
12822 {
12823 Lisp_Object value;
12824
12825 value = w32_get_arg (parms, Qinternal_border_width,
12826 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
12827 if (! EQ (value, Qunbound))
12828 parms = Fcons (Fcons (Qinternal_border_width, value),
12829 parms);
12830 }
bfd6edcc 12831 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6fc2811b
JR
12832 "internalBorderWidth", "internalBorderWidth",
12833 RES_TYPE_NUMBER);
12834
12835 /* Also do the stuff which must be set before the window exists. */
12836 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
12837 "foreground", "Foreground", RES_TYPE_STRING);
12838 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
12839 "background", "Background", RES_TYPE_STRING);
12840 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
12841 "pointerColor", "Foreground", RES_TYPE_STRING);
12842 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
12843 "cursorColor", "Foreground", RES_TYPE_STRING);
12844 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
12845 "borderColor", "BorderColor", RES_TYPE_STRING);
12846
12847 /* Init faces before x_default_parameter is called for scroll-bar
12848 parameters because that function calls x_set_scroll_bar_width,
12849 which calls change_frame_size, which calls Fset_window_buffer,
12850 which runs hooks, which call Fvertical_motion. At the end, we
12851 end up in init_iterator with a null face cache, which should not
12852 happen. */
12853 init_frame_faces (f);
ca56d953
JR
12854
12855 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6fc2811b 12856 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
9eb16b62 12857
6d906347 12858 window_prompting = x_figure_window_size (f, parms, 0);
6fc2811b 12859
9eb16b62
JR
12860 /* No fringes on tip frame. */
12861 f->output_data.w32->fringes_extra = 0;
12862 f->output_data.w32->fringe_cols = 0;
12863 f->output_data.w32->left_fringe_width = 0;
12864 f->output_data.w32->right_fringe_width = 0;
12865
ca56d953
JR
12866 BLOCK_INPUT;
12867 my_create_tip_window (f);
12868 UNBLOCK_INPUT;
6fc2811b
JR
12869
12870 x_make_gc (f);
12871
12872 x_default_parameter (f, parms, Qauto_raise, Qnil,
12873 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12874 x_default_parameter (f, parms, Qauto_lower, Qnil,
12875 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
12876 x_default_parameter (f, parms, Qcursor_type, Qbox,
12877 "cursorType", "CursorType", RES_TYPE_SYMBOL);
12878
12879 /* Dimensions, especially f->height, must be done via change_frame_size.
12880 Change will not be effected unless different from the current
12881 f->height. */
12882 width = f->width;
12883 height = f->height;
12884 f->height = 0;
12885 SET_FRAME_WIDTH (f, 0);
12886 change_frame_size (f, height, width, 1, 0, 0);
12887
cd1d850f
JPW
12888 /* Add `tooltip' frame parameter's default value. */
12889 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
12890 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
12891 Qnil));
7d0393cf 12892
3cf3436e
JR
12893 /* Set up faces after all frame parameters are known. This call
12894 also merges in face attributes specified for new frames.
12895
12896 Frame parameters may be changed if .Xdefaults contains
12897 specifications for the default font. For example, if there is an
12898 `Emacs.default.attributeBackground: pink', the `background-color'
12899 attribute of the frame get's set, which let's the internal border
12900 of the tooltip frame appear in pink. Prevent this. */
12901 {
12902 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
12903
12904 /* Set tip_frame here, so that */
12905 tip_frame = frame;
12906 call1 (Qface_set_after_frame_default, frame);
7d0393cf 12907
3cf3436e
JR
12908 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
12909 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
12910 Qnil));
12911 }
7d0393cf 12912
6fc2811b
JR
12913 f->no_split = 1;
12914
12915 UNGCPRO;
12916
12917 /* It is now ok to make the frame official even if we get an error
12918 below. And the frame needs to be on Vframe_list or making it
12919 visible won't work. */
12920 Vframe_list = Fcons (frame, Vframe_list);
12921
12922 /* Now that the frame is official, it counts as a reference to
12923 its display. */
12924 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
ee78dc32 12925
3cf3436e
JR
12926 /* Setting attributes of faces of the tooltip frame from resources
12927 and similar will increment face_change_count, which leads to the
12928 clearing of all current matrices. Since this isn't necessary
12929 here, avoid it by resetting face_change_count to the value it
12930 had before we created the tip frame. */
12931 face_change_count = face_change_count_before;
12932
12933 /* Discard the unwind_protect. */
6fc2811b 12934 return unbind_to (count, frame);
ee78dc32
GV
12935}
12936
3cf3436e
JR
12937
12938/* Compute where to display tip frame F. PARMS is the list of frame
12939 parameters for F. DX and DY are specified offsets from the current
12940 location of the mouse. WIDTH and HEIGHT are the width and height
12941 of the tooltip. Return coordinates relative to the root window of
12942 the display in *ROOT_X, and *ROOT_Y. */
12943
12944static void
12945compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
12946 struct frame *f;
12947 Lisp_Object parms, dx, dy;
12948 int width, height;
12949 int *root_x, *root_y;
12950{
3cf3436e 12951 Lisp_Object left, top;
7d0393cf 12952
3cf3436e
JR
12953 /* User-specified position? */
12954 left = Fcdr (Fassq (Qleft, parms));
12955 top = Fcdr (Fassq (Qtop, parms));
7d0393cf 12956
3cf3436e
JR
12957 /* Move the tooltip window where the mouse pointer is. Resize and
12958 show it. */
ca56d953 12959 if (!INTEGERP (left) || !INTEGERP (top))
3cf3436e 12960 {
ca56d953
JR
12961 POINT pt;
12962
3cf3436e 12963 BLOCK_INPUT;
ca56d953
JR
12964 GetCursorPos (&pt);
12965 *root_x = pt.x;
12966 *root_y = pt.y;
3cf3436e
JR
12967 UNBLOCK_INPUT;
12968 }
12969
12970 if (INTEGERP (top))
12971 *root_y = XINT (top);
12972 else if (*root_y + XINT (dy) - height < 0)
12973 *root_y -= XINT (dy);
12974 else
12975 {
12976 *root_y -= height;
12977 *root_y += XINT (dy);
12978 }
12979
12980 if (INTEGERP (left))
12981 *root_x = XINT (left);
72e4adef
JR
12982 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
12983 /* It fits to the right of the pointer. */
12984 *root_x += XINT (dx);
12985 else if (width + XINT (dx) <= *root_x)
12986 /* It fits to the left of the pointer. */
3cf3436e
JR
12987 *root_x -= width + XINT (dx);
12988 else
72e4adef
JR
12989 /* Put it left justified on the screen -- it ought to fit that way. */
12990 *root_x = 0;
3cf3436e
JR
12991}
12992
12993
71eab8d1 12994DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
74e1aeec
JR
12995 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
12996A tooltip window is a small window displaying a string.
12997
12998FRAME nil or omitted means use the selected frame.
12999
13000PARMS is an optional list of frame parameters which can be
13001used to change the tooltip's appearance.
13002
ca56d953
JR
13003Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
13004means use the default timeout of 5 seconds.
74e1aeec 13005
ca56d953 13006If the list of frame parameters PARAMS contains a `left' parameter,
74e1aeec
JR
13007the tooltip is displayed at that x-position. Otherwise it is
13008displayed at the mouse position, with offset DX added (default is 5 if
13009DX isn't specified). Likewise for the y-position; if a `top' frame
13010parameter is specified, it determines the y-position of the tooltip
13011window, otherwise it is displayed at the mouse position, with offset
13012DY added (default is -10).
13013
13014A tooltip's maximum size is specified by `x-max-tooltip-size'.
13015Text larger than the specified size is clipped. */)
71eab8d1
AI
13016 (string, frame, parms, timeout, dx, dy)
13017 Lisp_Object string, frame, parms, timeout, dx, dy;
ee78dc32 13018{
6fc2811b
JR
13019 struct frame *f;
13020 struct window *w;
3cf3436e 13021 int root_x, root_y;
6fc2811b
JR
13022 struct buffer *old_buffer;
13023 struct text_pos pos;
13024 int i, width, height;
6fc2811b
JR
13025 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
13026 int old_windows_or_buffers_changed = windows_or_buffers_changed;
331379bf 13027 int count = SPECPDL_INDEX ();
7d0393cf 13028
6fc2811b 13029 specbind (Qinhibit_redisplay, Qt);
ee78dc32 13030
dfff8a69 13031 GCPRO4 (string, parms, frame, timeout);
ee78dc32 13032
b7826503 13033 CHECK_STRING (string);
6fc2811b
JR
13034 f = check_x_frame (frame);
13035 if (NILP (timeout))
13036 timeout = make_number (5);
13037 else
b7826503 13038 CHECK_NATNUM (timeout);
ee78dc32 13039
71eab8d1
AI
13040 if (NILP (dx))
13041 dx = make_number (5);
13042 else
b7826503 13043 CHECK_NUMBER (dx);
7d0393cf 13044
71eab8d1 13045 if (NILP (dy))
dc220243 13046 dy = make_number (-10);
71eab8d1 13047 else
b7826503 13048 CHECK_NUMBER (dy);
71eab8d1 13049
dc220243
JR
13050 if (NILP (last_show_tip_args))
13051 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
13052
13053 if (!NILP (tip_frame))
13054 {
13055 Lisp_Object last_string = AREF (last_show_tip_args, 0);
13056 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
13057 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
13058
13059 if (EQ (frame, last_frame)
13060 && !NILP (Fequal (last_string, string))
13061 && !NILP (Fequal (last_parms, parms)))
13062 {
13063 struct frame *f = XFRAME (tip_frame);
7d0393cf 13064
dc220243
JR
13065 /* Only DX and DY have changed. */
13066 if (!NILP (tip_timer))
13067 {
13068 Lisp_Object timer = tip_timer;
13069 tip_timer = Qnil;
13070 call1 (Qcancel_timer, timer);
13071 }
13072
13073 BLOCK_INPUT;
ca56d953
JR
13074 compute_tip_xy (f, parms, dx, dy, PIXEL_WIDTH (f),
13075 PIXEL_HEIGHT (f), &root_x, &root_y);
d65a9cdc
JR
13076
13077 /* Put tooltip in topmost group and in position. */
ca56d953
JR
13078 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13079 root_x, root_y, 0, 0,
13080 SWP_NOSIZE | SWP_NOACTIVATE);
d65a9cdc
JR
13081
13082 /* Ensure tooltip is on top of other topmost windows (eg menus). */
13083 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
13084 0, 0, 0, 0,
13085 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
13086
dc220243
JR
13087 UNBLOCK_INPUT;
13088 goto start_timer;
13089 }
13090 }
13091
6fc2811b
JR
13092 /* Hide a previous tip, if any. */
13093 Fx_hide_tip ();
ee78dc32 13094
dc220243
JR
13095 ASET (last_show_tip_args, 0, string);
13096 ASET (last_show_tip_args, 1, frame);
13097 ASET (last_show_tip_args, 2, parms);
13098
6fc2811b
JR
13099 /* Add default values to frame parameters. */
13100 if (NILP (Fassq (Qname, parms)))
13101 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
13102 if (NILP (Fassq (Qinternal_border_width, parms)))
13103 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
13104 if (NILP (Fassq (Qborder_width, parms)))
13105 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
13106 if (NILP (Fassq (Qborder_color, parms)))
13107 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
13108 if (NILP (Fassq (Qbackground_color, parms)))
13109 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
13110 parms);
13111
0e3fcdef
JR
13112 /* Block input until the tip has been fully drawn, to avoid crashes
13113 when drawing tips in menus. */
13114 BLOCK_INPUT;
13115
6fc2811b
JR
13116 /* Create a frame for the tooltip, and record it in the global
13117 variable tip_frame. */
ca56d953 13118 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
937e601e 13119 f = XFRAME (frame);
6fc2811b 13120
3cf3436e 13121 /* Set up the frame's root window. */
6fc2811b
JR
13122 w = XWINDOW (FRAME_ROOT_WINDOW (f));
13123 w->left = w->top = make_number (0);
3cf3436e
JR
13124
13125 if (CONSP (Vx_max_tooltip_size)
13126 && INTEGERP (XCAR (Vx_max_tooltip_size))
13127 && XINT (XCAR (Vx_max_tooltip_size)) > 0
13128 && INTEGERP (XCDR (Vx_max_tooltip_size))
13129 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
13130 {
13131 w->width = XCAR (Vx_max_tooltip_size);
13132 w->height = XCDR (Vx_max_tooltip_size);
13133 }
13134 else
13135 {
13136 w->width = make_number (80);
13137 w->height = make_number (40);
13138 }
7d0393cf 13139
3cf3436e 13140 f->window_width = XINT (w->width);
6fc2811b
JR
13141 adjust_glyphs (f);
13142 w->pseudo_window_p = 1;
13143
13144 /* Display the tooltip text in a temporary buffer. */
6fc2811b 13145 old_buffer = current_buffer;
3cf3436e
JR
13146 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
13147 current_buffer->truncate_lines = Qnil;
6fc2811b
JR
13148 clear_glyph_matrix (w->desired_matrix);
13149 clear_glyph_matrix (w->current_matrix);
13150 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
13151 try_window (FRAME_ROOT_WINDOW (f), pos);
13152
13153 /* Compute width and height of the tooltip. */
13154 width = height = 0;
13155 for (i = 0; i < w->desired_matrix->nrows; ++i)
ee78dc32 13156 {
6fc2811b
JR
13157 struct glyph_row *row = &w->desired_matrix->rows[i];
13158 struct glyph *last;
13159 int row_width;
13160
13161 /* Stop at the first empty row at the end. */
13162 if (!row->enabled_p || !row->displays_text_p)
13163 break;
13164
13165 /* Let the row go over the full width of the frame. */
13166 row->full_width_p = 1;
13167
4e3a1c61
JR
13168#ifdef TODO /* Investigate why some fonts need more width than is
13169 calculated for some tooltips. */
6fc2811b
JR
13170 /* There's a glyph at the end of rows that is use to place
13171 the cursor there. Don't include the width of this glyph. */
13172 if (row->used[TEXT_AREA])
13173 {
13174 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
13175 row_width = row->pixel_width - last->pixel_width;
13176 }
13177 else
4e3a1c61 13178#endif
6fc2811b 13179 row_width = row->pixel_width;
7d0393cf 13180
ca56d953 13181 /* TODO: find why tips do not draw along baseline as instructed. */
bfd6edcc 13182 height += row->height;
6fc2811b 13183 width = max (width, row_width);
ee78dc32
GV
13184 }
13185
6fc2811b
JR
13186 /* Add the frame's internal border to the width and height the X
13187 window should have. */
13188 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
13189 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
ee78dc32 13190
6fc2811b
JR
13191 /* Move the tooltip window where the mouse pointer is. Resize and
13192 show it. */
3cf3436e 13193 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
71eab8d1 13194
bfd6edcc
JR
13195 {
13196 /* Adjust Window size to take border into account. */
13197 RECT rect;
13198 rect.left = rect.top = 0;
13199 rect.right = width;
13200 rect.bottom = height;
13201 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
13202 FRAME_EXTERNAL_MENU_BAR (f));
13203
d65a9cdc 13204 /* Position and size tooltip, and put it in the topmost group. */
bfd6edcc
JR
13205 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
13206 root_x, root_y, rect.right - rect.left,
13207 rect.bottom - rect.top, SWP_NOACTIVATE);
13208
d65a9cdc
JR
13209 /* Ensure tooltip is on top of other topmost windows (eg menus). */
13210 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
13211 0, 0, 0, 0,
13212 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
13213
bfd6edcc
JR
13214 /* Let redisplay know that we have made the frame visible already. */
13215 f->async_visible = 1;
13216
13217 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
13218 }
ee78dc32 13219
6fc2811b
JR
13220 /* Draw into the window. */
13221 w->must_be_updated_p = 1;
13222 update_single_window (w, 1);
ee78dc32 13223
0e3fcdef
JR
13224 UNBLOCK_INPUT;
13225
6fc2811b
JR
13226 /* Restore original current buffer. */
13227 set_buffer_internal_1 (old_buffer);
13228 windows_or_buffers_changed = old_windows_or_buffers_changed;
ee78dc32 13229
dc220243 13230 start_timer:
6fc2811b
JR
13231 /* Let the tip disappear after timeout seconds. */
13232 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
13233 intern ("x-hide-tip"));
ee78dc32 13234
dfff8a69 13235 UNGCPRO;
6fc2811b 13236 return unbind_to (count, Qnil);
ee78dc32
GV
13237}
13238
ee78dc32 13239
6fc2811b 13240DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
74e1aeec
JR
13241 doc: /* Hide the current tooltip window, if there is any.
13242Value is t if tooltip was open, nil otherwise. */)
6fc2811b
JR
13243 ()
13244{
937e601e
AI
13245 int count;
13246 Lisp_Object deleted, frame, timer;
13247 struct gcpro gcpro1, gcpro2;
13248
13249 /* Return quickly if nothing to do. */
13250 if (NILP (tip_timer) && NILP (tip_frame))
13251 return Qnil;
7d0393cf 13252
937e601e
AI
13253 frame = tip_frame;
13254 timer = tip_timer;
13255 GCPRO2 (frame, timer);
13256 tip_frame = tip_timer = deleted = Qnil;
7d0393cf 13257
331379bf 13258 count = SPECPDL_INDEX ();
6fc2811b 13259 specbind (Qinhibit_redisplay, Qt);
937e601e 13260 specbind (Qinhibit_quit, Qt);
7d0393cf 13261
937e601e 13262 if (!NILP (timer))
dc220243 13263 call1 (Qcancel_timer, timer);
ee78dc32 13264
937e601e 13265 if (FRAMEP (frame))
6fc2811b 13266 {
937e601e
AI
13267 Fdelete_frame (frame, Qnil);
13268 deleted = Qt;
6fc2811b 13269 }
1edf84e7 13270
937e601e
AI
13271 UNGCPRO;
13272 return unbind_to (count, deleted);
6fc2811b 13273}
5ac45f98 13274
5ac45f98 13275
6fc2811b
JR
13276\f
13277/***********************************************************************
13278 File selection dialog
13279 ***********************************************************************/
6fc2811b
JR
13280extern Lisp_Object Qfile_name_history;
13281
1030b26b
JR
13282/* Callback for altering the behaviour of the Open File dialog.
13283 Makes the Filename text field contain "Current Directory" and be
13284 read-only when "Directories" is selected in the filter. This
13285 allows us to work around the fact that the standard Open File
13286 dialog does not support directories. */
13287UINT CALLBACK
13288file_dialog_callback (hwnd, msg, wParam, lParam)
13289 HWND hwnd;
13290 UINT msg;
13291 WPARAM wParam;
13292 LPARAM lParam;
13293{
13294 if (msg == WM_NOTIFY)
13295 {
13296 OFNOTIFY * notify = (OFNOTIFY *)lParam;
13297 /* Detect when the Filter dropdown is changed. */
13298 if (notify->hdr.code == CDN_TYPECHANGE)
13299 {
13300 HWND dialog = GetParent (hwnd);
13301 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
13302
13303 /* Directories is in index 2. */
13304 if (notify->lpOFN->nFilterIndex == 2)
13305 {
13306 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
13307 "Current Directory");
13308 EnableWindow (edit_control, FALSE);
13309 }
13310 else
13311 {
13312 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
13313 "");
13314 EnableWindow (edit_control, TRUE);
13315 }
13316 }
13317 }
13318 return 0;
13319}
13320
6fc2811b 13321DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
74e1aeec
JR
13322 doc: /* Read file name, prompting with PROMPT in directory DIR.
13323Use a file selection dialog.
13324Select DEFAULT-FILENAME in the dialog's file selection box, if
13325specified. Ensure that file exists if MUSTMATCH is non-nil. */)
6fc2811b
JR
13326 (prompt, dir, default_filename, mustmatch)
13327 Lisp_Object prompt, dir, default_filename, mustmatch;
13328{
13329 struct frame *f = SELECTED_FRAME ();
13330 Lisp_Object file = Qnil;
aed13378 13331 int count = SPECPDL_INDEX ();
6fc2811b
JR
13332 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
13333 char filename[MAX_PATH + 1];
13334 char init_dir[MAX_PATH + 1];
6fc2811b
JR
13335
13336 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
b7826503
PJ
13337 CHECK_STRING (prompt);
13338 CHECK_STRING (dir);
6fc2811b
JR
13339
13340 /* Create the dialog with PROMPT as title, using DIR as initial
13341 directory and using "*" as pattern. */
13342 dir = Fexpand_file_name (dir, Qnil);
d5db4077 13343 strncpy (init_dir, SDATA (dir), MAX_PATH);
6fc2811b
JR
13344 init_dir[MAX_PATH] = '\0';
13345 unixtodos_filename (init_dir);
13346
13347 if (STRINGP (default_filename))
13348 {
13349 char *file_name_only;
d5db4077 13350 char *full_path_name = SDATA (default_filename);
5ac45f98 13351
6fc2811b 13352 unixtodos_filename (full_path_name);
5ac45f98 13353
6fc2811b
JR
13354 file_name_only = strrchr (full_path_name, '\\');
13355 if (!file_name_only)
13356 file_name_only = full_path_name;
13357 else
13358 {
13359 file_name_only++;
6fc2811b 13360 }
ee78dc32 13361
6fc2811b
JR
13362 strncpy (filename, file_name_only, MAX_PATH);
13363 filename[MAX_PATH] = '\0';
13364 }
ee78dc32 13365 else
6fc2811b 13366 filename[0] = '\0';
ee78dc32 13367
1030b26b
JR
13368 {
13369 OPENFILENAME file_details;
5ac45f98 13370
1030b26b
JR
13371 /* Prevent redisplay. */
13372 specbind (Qinhibit_redisplay, Qt);
13373 BLOCK_INPUT;
ee78dc32 13374
1030b26b
JR
13375 bzero (&file_details, sizeof (file_details));
13376 file_details.lStructSize = sizeof (file_details);
13377 file_details.hwndOwner = FRAME_W32_WINDOW (f);
13378 /* Undocumented Bug in Common File Dialog:
13379 If a filter is not specified, shell links are not resolved. */
13380 file_details.lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
13381 file_details.lpstrFile = filename;
13382 file_details.nMaxFile = sizeof (filename);
13383 file_details.lpstrInitialDir = init_dir;
d5db4077 13384 file_details.lpstrTitle = SDATA (prompt);
1030b26b
JR
13385 file_details.Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
13386 | OFN_EXPLORER | OFN_ENABLEHOOK);
13387 if (!NILP (mustmatch))
13388 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
13389
13390 file_details.lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
13391
13392 if (GetOpenFileName (&file_details))
13393 {
13394 dostounix_filename (filename);
13395 if (file_details.nFilterIndex == 2)
13396 {
13397 /* "Folder Only" selected - strip dummy file name. */
13398 char * last = strrchr (filename, '/');
13399 *last = '\0';
13400 }
6fc2811b 13401
1030b26b
JR
13402 file = DECODE_FILE(build_string (filename));
13403 }
13404 /* User cancelled the dialog without making a selection. */
13405 else if (!CommDlgExtendedError ())
13406 file = Qnil;
13407 /* An error occurred, fallback on reading from the mini-buffer. */
13408 else
13409 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
13410 dir, mustmatch, dir, Qfile_name_history,
13411 default_filename, Qnil);
13412
13413 UNBLOCK_INPUT;
13414 file = unbind_to (count, file);
13415 }
ee78dc32 13416
6fc2811b 13417 UNGCPRO;
1edf84e7 13418
6fc2811b
JR
13419 /* Make "Cancel" equivalent to C-g. */
13420 if (NILP (file))
13421 Fsignal (Qquit, Qnil);
ee78dc32 13422
dfff8a69 13423 return unbind_to (count, file);
6fc2811b 13424}
ee78dc32 13425
ee78dc32 13426
6fc2811b 13427\f
6fc2811b
JR
13428/***********************************************************************
13429 w32 specialized functions
13430 ***********************************************************************/
ee78dc32 13431
d84b082d 13432DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
74e1aeec
JR
13433 doc: /* Select a font using the W32 font dialog.
13434Returns an X font string corresponding to the selection. */)
d84b082d
JR
13435 (frame, include_proportional)
13436 Lisp_Object frame, include_proportional;
ee78dc32
GV
13437{
13438 FRAME_PTR f = check_x_frame (frame);
13439 CHOOSEFONT cf;
13440 LOGFONT lf;
f46e6225
GV
13441 TEXTMETRIC tm;
13442 HDC hdc;
13443 HANDLE oldobj;
ee78dc32
GV
13444 char buf[100];
13445
13446 bzero (&cf, sizeof (cf));
f46e6225 13447 bzero (&lf, sizeof (lf));
ee78dc32
GV
13448
13449 cf.lStructSize = sizeof (cf);
fbd6baed 13450 cf.hwndOwner = FRAME_W32_WINDOW (f);
d84b082d
JR
13451 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
13452
13453 /* Unless include_proportional is non-nil, limit the selection to
13454 monospaced fonts. */
13455 if (NILP (include_proportional))
13456 cf.Flags |= CF_FIXEDPITCHONLY;
13457
ee78dc32
GV
13458 cf.lpLogFont = &lf;
13459
f46e6225
GV
13460 /* Initialize as much of the font details as we can from the current
13461 default font. */
13462 hdc = GetDC (FRAME_W32_WINDOW (f));
13463 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
13464 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
13465 if (GetTextMetrics (hdc, &tm))
13466 {
13467 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
13468 lf.lfWeight = tm.tmWeight;
13469 lf.lfItalic = tm.tmItalic;
13470 lf.lfUnderline = tm.tmUnderlined;
13471 lf.lfStrikeOut = tm.tmStruckOut;
f46e6225
GV
13472 lf.lfCharSet = tm.tmCharSet;
13473 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
13474 }
13475 SelectObject (hdc, oldobj);
6fc2811b 13476 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
f46e6225 13477
767b1ff0 13478 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
3c190163 13479 return Qnil;
ee78dc32
GV
13480
13481 return build_string (buf);
13482}
13483
74e1aeec
JR
13484DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
13485 Sw32_send_sys_command, 1, 2, 0,
13486 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
d84b082d
JR
13487Some useful values for command are #xf030 to maximise frame (#xf020
13488to minimize), #xf120 to restore frame to original size, and #xf100
13489to activate the menubar for keyboard access. #xf140 activates the
74e1aeec
JR
13490screen saver if defined.
13491
13492If optional parameter FRAME is not specified, use selected frame. */)
1edf84e7
GV
13493 (command, frame)
13494 Lisp_Object command, frame;
13495{
1edf84e7
GV
13496 FRAME_PTR f = check_x_frame (frame);
13497
b7826503 13498 CHECK_NUMBER (command);
1edf84e7 13499
ce6059da 13500 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
1edf84e7
GV
13501
13502 return Qnil;
13503}
13504
55dcfc15 13505DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
74e1aeec
JR
13506 doc: /* Get Windows to perform OPERATION on DOCUMENT.
13507This is a wrapper around the ShellExecute system function, which
13508invokes the application registered to handle OPERATION for DOCUMENT.
13509OPERATION is typically \"open\", \"print\" or \"explore\" (but can be
13510nil for the default action), and DOCUMENT is typically the name of a
13511document file or URL, but can also be a program executable to run or
13512a directory to open in the Windows Explorer.
13513
13514If DOCUMENT is a program executable, PARAMETERS can be a string
13515containing command line parameters, but otherwise should be nil.
13516
13517SHOW-FLAG can be used to control whether the invoked application is hidden
13518or minimized. If SHOW-FLAG is nil, the application is displayed normally,
13519otherwise it is an integer representing a ShowWindow flag:
13520
13521 0 - start hidden
13522 1 - start normally
13523 3 - start maximized
13524 6 - start minimized */)
55dcfc15
AI
13525 (operation, document, parameters, show_flag)
13526 Lisp_Object operation, document, parameters, show_flag;
13527{
13528 Lisp_Object current_dir;
13529
b7826503 13530 CHECK_STRING (document);
55dcfc15
AI
13531
13532 /* Encode filename and current directory. */
13533 current_dir = ENCODE_FILE (current_buffer->directory);
13534 document = ENCODE_FILE (document);
13535 if ((int) ShellExecute (NULL,
6fc2811b 13536 (STRINGP (operation) ?
d5db4077
KR
13537 SDATA (operation) : NULL),
13538 SDATA (document),
55dcfc15 13539 (STRINGP (parameters) ?
d5db4077
KR
13540 SDATA (parameters) : NULL),
13541 SDATA (current_dir),
55dcfc15
AI
13542 (INTEGERP (show_flag) ?
13543 XINT (show_flag) : SW_SHOWDEFAULT))
13544 > 32)
13545 return Qt;
90d97e64 13546 error ("ShellExecute failed: %s", w32_strerror (0));
55dcfc15
AI
13547}
13548
ccc2d29c
GV
13549/* Lookup virtual keycode from string representing the name of a
13550 non-ascii keystroke into the corresponding virtual key, using
13551 lispy_function_keys. */
13552static int
13553lookup_vk_code (char *key)
13554{
13555 int i;
13556
13557 for (i = 0; i < 256; i++)
13558 if (lispy_function_keys[i] != 0
13559 && strcmp (lispy_function_keys[i], key) == 0)
13560 return i;
13561
13562 return -1;
13563}
13564
13565/* Convert a one-element vector style key sequence to a hot key
13566 definition. */
13567static int
13568w32_parse_hot_key (key)
13569 Lisp_Object key;
13570{
13571 /* Copied from Fdefine_key and store_in_keymap. */
13572 register Lisp_Object c;
13573 int vk_code;
13574 int lisp_modifiers;
13575 int w32_modifiers;
13576 struct gcpro gcpro1;
13577
b7826503 13578 CHECK_VECTOR (key);
ccc2d29c
GV
13579
13580 if (XFASTINT (Flength (key)) != 1)
13581 return Qnil;
13582
13583 GCPRO1 (key);
13584
13585 c = Faref (key, make_number (0));
13586
13587 if (CONSP (c) && lucid_event_type_list_p (c))
13588 c = Fevent_convert_list (c);
13589
13590 UNGCPRO;
13591
13592 if (! INTEGERP (c) && ! SYMBOLP (c))
13593 error ("Key definition is invalid");
13594
13595 /* Work out the base key and the modifiers. */
13596 if (SYMBOLP (c))
13597 {
13598 c = parse_modifiers (c);
13599 lisp_modifiers = Fcar (Fcdr (c));
13600 c = Fcar (c);
13601 if (!SYMBOLP (c))
13602 abort ();
d5db4077 13603 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
ccc2d29c
GV
13604 }
13605 else if (INTEGERP (c))
13606 {
13607 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
13608 /* Many ascii characters are their own virtual key code. */
13609 vk_code = XINT (c) & CHARACTERBITS;
13610 }
13611
13612 if (vk_code < 0 || vk_code > 255)
13613 return Qnil;
13614
13615 if ((lisp_modifiers & meta_modifier) != 0
13616 && !NILP (Vw32_alt_is_meta))
13617 lisp_modifiers |= alt_modifier;
13618
71eab8d1
AI
13619 /* Supply defs missing from mingw32. */
13620#ifndef MOD_ALT
13621#define MOD_ALT 0x0001
13622#define MOD_CONTROL 0x0002
13623#define MOD_SHIFT 0x0004
13624#define MOD_WIN 0x0008
13625#endif
13626
ccc2d29c
GV
13627 /* Convert lisp modifiers to Windows hot-key form. */
13628 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
13629 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
13630 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
13631 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
13632
13633 return HOTKEY (vk_code, w32_modifiers);
13634}
13635
74e1aeec
JR
13636DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
13637 Sw32_register_hot_key, 1, 1, 0,
13638 doc: /* Register KEY as a hot-key combination.
13639Certain key combinations like Alt-Tab are reserved for system use on
13640Windows, and therefore are normally intercepted by the system. However,
13641most of these key combinations can be received by registering them as
13642hot-keys, overriding their special meaning.
13643
13644KEY must be a one element key definition in vector form that would be
13645acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
13646modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
13647is always interpreted as the Windows modifier keys.
13648
13649The return value is the hotkey-id if registered, otherwise nil. */)
ccc2d29c
GV
13650 (key)
13651 Lisp_Object key;
13652{
13653 key = w32_parse_hot_key (key);
13654
13655 if (NILP (Fmemq (key, w32_grabbed_keys)))
13656 {
13657 /* Reuse an empty slot if possible. */
13658 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
13659
13660 /* Safe to add new key to list, even if we have focus. */
13661 if (NILP (item))
13662 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
13663 else
f3fbd155 13664 XSETCAR (item, key);
ccc2d29c
GV
13665
13666 /* Notify input thread about new hot-key definition, so that it
13667 takes effect without needing to switch focus. */
13668 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
13669 (WPARAM) key, 0);
13670 }
13671
13672 return key;
13673}
13674
74e1aeec
JR
13675DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
13676 Sw32_unregister_hot_key, 1, 1, 0,
13677 doc: /* Unregister HOTKEY as a hot-key combination. */)
ccc2d29c
GV
13678 (key)
13679 Lisp_Object key;
13680{
13681 Lisp_Object item;
13682
13683 if (!INTEGERP (key))
13684 key = w32_parse_hot_key (key);
13685
13686 item = Fmemq (key, w32_grabbed_keys);
13687
13688 if (!NILP (item))
13689 {
13690 /* Notify input thread about hot-key definition being removed, so
13691 that it takes effect without needing focus switch. */
13692 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
13693 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
13694 {
13695 MSG msg;
13696 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13697 }
13698 return Qt;
13699 }
13700 return Qnil;
13701}
13702
74e1aeec
JR
13703DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
13704 Sw32_registered_hot_keys, 0, 0, 0,
13705 doc: /* Return list of registered hot-key IDs. */)
ccc2d29c
GV
13706 ()
13707{
13708 return Fcopy_sequence (w32_grabbed_keys);
13709}
13710
74e1aeec
JR
13711DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
13712 Sw32_reconstruct_hot_key, 1, 1, 0,
13713 doc: /* Convert hot-key ID to a lisp key combination. */)
ccc2d29c
GV
13714 (hotkeyid)
13715 Lisp_Object hotkeyid;
13716{
13717 int vk_code, w32_modifiers;
13718 Lisp_Object key;
13719
b7826503 13720 CHECK_NUMBER (hotkeyid);
ccc2d29c
GV
13721
13722 vk_code = HOTKEY_VK_CODE (hotkeyid);
13723 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
13724
13725 if (lispy_function_keys[vk_code])
13726 key = intern (lispy_function_keys[vk_code]);
13727 else
13728 key = make_number (vk_code);
13729
13730 key = Fcons (key, Qnil);
13731 if (w32_modifiers & MOD_SHIFT)
3ef68e6b 13732 key = Fcons (Qshift, key);
ccc2d29c 13733 if (w32_modifiers & MOD_CONTROL)
3ef68e6b 13734 key = Fcons (Qctrl, key);
ccc2d29c 13735 if (w32_modifiers & MOD_ALT)
3ef68e6b 13736 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
ccc2d29c 13737 if (w32_modifiers & MOD_WIN)
3ef68e6b 13738 key = Fcons (Qhyper, key);
ccc2d29c
GV
13739
13740 return key;
13741}
adcc3809 13742
74e1aeec
JR
13743DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
13744 Sw32_toggle_lock_key, 1, 2, 0,
13745 doc: /* Toggle the state of the lock key KEY.
13746KEY can be `capslock', `kp-numlock', or `scroll'.
13747If the optional parameter NEW-STATE is a number, then the state of KEY
13748is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
adcc3809
GV
13749 (key, new_state)
13750 Lisp_Object key, new_state;
13751{
13752 int vk_code;
adcc3809
GV
13753
13754 if (EQ (key, intern ("capslock")))
13755 vk_code = VK_CAPITAL;
13756 else if (EQ (key, intern ("kp-numlock")))
13757 vk_code = VK_NUMLOCK;
13758 else if (EQ (key, intern ("scroll")))
13759 vk_code = VK_SCROLL;
13760 else
13761 return Qnil;
13762
13763 if (!dwWindowsThreadId)
13764 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
13765
13766 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
13767 (WPARAM) vk_code, (LPARAM) new_state))
13768 {
13769 MSG msg;
13770 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
13771 return make_number (msg.wParam);
13772 }
13773 return Qnil;
13774}
ee78dc32 13775\f
2254bcde 13776DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
74e1aeec
JR
13777 doc: /* Return storage information about the file system FILENAME is on.
13778Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
13779storage of the file system, FREE is the free storage, and AVAIL is the
13780storage available to a non-superuser. All 3 numbers are in bytes.
13781If the underlying system call fails, value is nil. */)
2254bcde
AI
13782 (filename)
13783 Lisp_Object filename;
13784{
13785 Lisp_Object encoded, value;
13786
b7826503 13787 CHECK_STRING (filename);
2254bcde
AI
13788 filename = Fexpand_file_name (filename, Qnil);
13789 encoded = ENCODE_FILE (filename);
13790
13791 value = Qnil;
13792
13793 /* Determining the required information on Windows turns out, sadly,
13794 to be more involved than one would hope. The original Win32 api
13795 call for this will return bogus information on some systems, but we
13796 must dynamically probe for the replacement api, since that was
13797 added rather late on. */
13798 {
13799 HMODULE hKernel = GetModuleHandle ("kernel32");
13800 BOOL (*pfn_GetDiskFreeSpaceEx)
13801 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
13802 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
13803
13804 /* On Windows, we may need to specify the root directory of the
13805 volume holding FILENAME. */
13806 char rootname[MAX_PATH];
d5db4077 13807 char *name = SDATA (encoded);
2254bcde
AI
13808
13809 /* find the root name of the volume if given */
13810 if (isalpha (name[0]) && name[1] == ':')
13811 {
13812 rootname[0] = name[0];
13813 rootname[1] = name[1];
13814 rootname[2] = '\\';
13815 rootname[3] = 0;
13816 }
13817 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
13818 {
13819 char *str = rootname;
13820 int slashes = 4;
13821 do
13822 {
13823 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
13824 break;
13825 *str++ = *name++;
13826 }
13827 while ( *name );
13828
13829 *str++ = '\\';
13830 *str = 0;
13831 }
13832
13833 if (pfn_GetDiskFreeSpaceEx)
13834 {
ac849ba4
JR
13835 /* Unsigned large integers cannot be cast to double, so
13836 use signed ones instead. */
2254bcde
AI
13837 LARGE_INTEGER availbytes;
13838 LARGE_INTEGER freebytes;
13839 LARGE_INTEGER totalbytes;
13840
13841 if (pfn_GetDiskFreeSpaceEx(rootname,
ac849ba4
JR
13842 (ULARGE_INTEGER *)&availbytes,
13843 (ULARGE_INTEGER *)&totalbytes,
13844 (ULARGE_INTEGER *)&freebytes))
2254bcde
AI
13845 value = list3 (make_float ((double) totalbytes.QuadPart),
13846 make_float ((double) freebytes.QuadPart),
13847 make_float ((double) availbytes.QuadPart));
13848 }
13849 else
13850 {
13851 DWORD sectors_per_cluster;
13852 DWORD bytes_per_sector;
13853 DWORD free_clusters;
13854 DWORD total_clusters;
13855
13856 if (GetDiskFreeSpace(rootname,
13857 &sectors_per_cluster,
13858 &bytes_per_sector,
13859 &free_clusters,
13860 &total_clusters))
13861 value = list3 (make_float ((double) total_clusters
13862 * sectors_per_cluster * bytes_per_sector),
13863 make_float ((double) free_clusters
13864 * sectors_per_cluster * bytes_per_sector),
13865 make_float ((double) free_clusters
13866 * sectors_per_cluster * bytes_per_sector));
13867 }
13868 }
13869
13870 return value;
13871}
13872\f
0e3fcdef
JR
13873/***********************************************************************
13874 Initialization
13875 ***********************************************************************/
13876
6d906347
KS
13877/* Keep this list in the same order as frame_parms in frame.c.
13878 Use 0 for unsupported frame parameters. */
13879
13880frame_parm_handler w32_frame_parm_handlers[] =
13881{
13882 x_set_autoraise,
13883 x_set_autolower,
13884 x_set_background_color,
13885 x_set_border_color,
13886 x_set_border_width,
13887 x_set_cursor_color,
13888 x_set_cursor_type,
13889 x_set_font,
13890 x_set_foreground_color,
13891 x_set_icon_name,
13892 x_set_icon_type,
13893 x_set_internal_border_width,
13894 x_set_menu_bar_lines,
13895 x_set_mouse_color,
13896 x_explicitly_set_name,
13897 x_set_scroll_bar_width,
13898 x_set_title,
13899 x_set_unsplittable,
13900 x_set_vertical_scroll_bars,
13901 x_set_visibility,
13902 x_set_tool_bar_lines,
13903 0, /* x_set_scroll_bar_foreground, */
13904 0, /* x_set_scroll_bar_background, */
13905 x_set_screen_gamma,
13906 x_set_line_spacing,
13907 x_set_fringe_width,
13908 x_set_fringe_width,
13909 0, /* x_set_wait_for_wm, */
13910 x_set_fullscreen,
13911};
13912
0e3fcdef 13913void
fbd6baed 13914syms_of_w32fns ()
ee78dc32 13915{
afc390dc
JR
13916 globals_of_w32fns ();
13917 /* This is zero if not using MS-Windows. */
1edf84e7 13918 w32_in_use = 0;
9eb16b62
JR
13919 track_mouse_window = NULL;
13920
d285988b
JR
13921 w32_visible_system_caret_hwnd = NULL;
13922
ee78dc32
GV
13923 Qnone = intern ("none");
13924 staticpro (&Qnone);
ee78dc32
GV
13925 Qsuppress_icon = intern ("suppress-icon");
13926 staticpro (&Qsuppress_icon);
ee78dc32
GV
13927 Qundefined_color = intern ("undefined-color");
13928 staticpro (&Qundefined_color);
dfff8a69
JR
13929 Qcenter = intern ("center");
13930 staticpro (&Qcenter);
dc220243
JR
13931 Qcancel_timer = intern ("cancel-timer");
13932 staticpro (&Qcancel_timer);
ee78dc32 13933
adcc3809
GV
13934 Qhyper = intern ("hyper");
13935 staticpro (&Qhyper);
13936 Qsuper = intern ("super");
13937 staticpro (&Qsuper);
13938 Qmeta = intern ("meta");
13939 staticpro (&Qmeta);
13940 Qalt = intern ("alt");
13941 staticpro (&Qalt);
13942 Qctrl = intern ("ctrl");
13943 staticpro (&Qctrl);
13944 Qcontrol = intern ("control");
13945 staticpro (&Qcontrol);
13946 Qshift = intern ("shift");
13947 staticpro (&Qshift);
f7b9d4d1 13948 /* This is the end of symbol initialization. */
adcc3809 13949
6fc2811b
JR
13950 /* Text property `display' should be nonsticky by default. */
13951 Vtext_property_default_nonsticky
13952 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
13953
13954
13955 Qlaplace = intern ("laplace");
13956 staticpro (&Qlaplace);
3cf3436e
JR
13957 Qemboss = intern ("emboss");
13958 staticpro (&Qemboss);
13959 Qedge_detection = intern ("edge-detection");
13960 staticpro (&Qedge_detection);
13961 Qheuristic = intern ("heuristic");
13962 staticpro (&Qheuristic);
13963 QCmatrix = intern (":matrix");
13964 staticpro (&QCmatrix);
13965 QCcolor_adjustment = intern (":color-adjustment");
13966 staticpro (&QCcolor_adjustment);
13967 QCmask = intern (":mask");
13968 staticpro (&QCmask);
6fc2811b 13969
ee78dc32
GV
13970 Fput (Qundefined_color, Qerror_conditions,
13971 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
13972 Fput (Qundefined_color, Qerror_message,
13973 build_string ("Undefined color"));
13974
ccc2d29c
GV
13975 staticpro (&w32_grabbed_keys);
13976 w32_grabbed_keys = Qnil;
13977
fbd6baed 13978 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
74e1aeec 13979 doc: /* An array of color name mappings for windows. */);
fbd6baed 13980 Vw32_color_map = Qnil;
ee78dc32 13981
fbd6baed 13982 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
74e1aeec
JR
13983 doc: /* Non-nil if alt key presses are passed on to Windows.
13984When non-nil, for example, alt pressed and released and then space will
13985open the System menu. When nil, Emacs silently swallows alt key events. */);
fbd6baed 13986 Vw32_pass_alt_to_system = Qnil;
da36a4d6 13987
fbd6baed 13988 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
74e1aeec
JR
13989 doc: /* Non-nil if the alt key is to be considered the same as the meta key.
13990When nil, Emacs will translate the alt key to the Alt modifier, and not Meta. */);
fbd6baed 13991 Vw32_alt_is_meta = Qt;
8c205c63 13992
7d081355 13993 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
74e1aeec 13994 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
7d081355
AI
13995 XSETINT (Vw32_quit_key, 0);
13996
7d0393cf 13997 DEFVAR_LISP ("w32-pass-lwindow-to-system",
ccc2d29c 13998 &Vw32_pass_lwindow_to_system,
74e1aeec
JR
13999 doc: /* Non-nil if the left \"Windows\" key is passed on to Windows.
14000When non-nil, the Start menu is opened by tapping the key. */);
ccc2d29c
GV
14001 Vw32_pass_lwindow_to_system = Qt;
14002
7d0393cf 14003 DEFVAR_LISP ("w32-pass-rwindow-to-system",
ccc2d29c 14004 &Vw32_pass_rwindow_to_system,
74e1aeec
JR
14005 doc: /* Non-nil if the right \"Windows\" key is passed on to Windows.
14006When non-nil, the Start menu is opened by tapping the key. */);
ccc2d29c
GV
14007 Vw32_pass_rwindow_to_system = Qt;
14008
adcc3809
GV
14009 DEFVAR_INT ("w32-phantom-key-code",
14010 &Vw32_phantom_key_code,
74e1aeec
JR
14011 doc: /* Virtual key code used to generate \"phantom\" key presses.
14012Value is a number between 0 and 255.
14013
14014Phantom key presses are generated in order to stop the system from
14015acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
14016`w32-pass-rwindow-to-system' is nil. */);
ce6059da
AI
14017 /* Although 255 is technically not a valid key code, it works and
14018 means that this hack won't interfere with any real key code. */
14019 Vw32_phantom_key_code = 255;
adcc3809 14020
7d0393cf 14021 DEFVAR_LISP ("w32-enable-num-lock",
ccc2d29c 14022 &Vw32_enable_num_lock,
74e1aeec
JR
14023 doc: /* Non-nil if Num Lock should act normally.
14024Set to nil to see Num Lock as the key `kp-numlock'. */);
ccc2d29c
GV
14025 Vw32_enable_num_lock = Qt;
14026
7d0393cf 14027 DEFVAR_LISP ("w32-enable-caps-lock",
ccc2d29c 14028 &Vw32_enable_caps_lock,
74e1aeec
JR
14029 doc: /* Non-nil if Caps Lock should act normally.
14030Set to nil to see Caps Lock as the key `capslock'. */);
ccc2d29c
GV
14031 Vw32_enable_caps_lock = Qt;
14032
14033 DEFVAR_LISP ("w32-scroll-lock-modifier",
14034 &Vw32_scroll_lock_modifier,
74e1aeec
JR
14035 doc: /* Modifier to use for the Scroll Lock on state.
14036The value can be hyper, super, meta, alt, control or shift for the
14037respective modifier, or nil to see Scroll Lock as the key `scroll'.
14038Any other value will cause the key to be ignored. */);
ccc2d29c
GV
14039 Vw32_scroll_lock_modifier = Qt;
14040
14041 DEFVAR_LISP ("w32-lwindow-modifier",
14042 &Vw32_lwindow_modifier,
74e1aeec
JR
14043 doc: /* Modifier to use for the left \"Windows\" key.
14044The value can be hyper, super, meta, alt, control or shift for the
14045respective modifier, or nil to appear as the key `lwindow'.
14046Any other value will cause the key to be ignored. */);
ccc2d29c
GV
14047 Vw32_lwindow_modifier = Qnil;
14048
14049 DEFVAR_LISP ("w32-rwindow-modifier",
14050 &Vw32_rwindow_modifier,
74e1aeec
JR
14051 doc: /* Modifier to use for the right \"Windows\" key.
14052The value can be hyper, super, meta, alt, control or shift for the
14053respective modifier, or nil to appear as the key `rwindow'.
14054Any other value will cause the key to be ignored. */);
ccc2d29c
GV
14055 Vw32_rwindow_modifier = Qnil;
14056
14057 DEFVAR_LISP ("w32-apps-modifier",
14058 &Vw32_apps_modifier,
74e1aeec
JR
14059 doc: /* Modifier to use for the \"Apps\" key.
14060The value can be hyper, super, meta, alt, control or shift for the
14061respective modifier, or nil to appear as the key `apps'.
14062Any other value will cause the key to be ignored. */);
ccc2d29c 14063 Vw32_apps_modifier = Qnil;
da36a4d6 14064
d84b082d 14065 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
74e1aeec 14066 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
d84b082d 14067 w32_enable_synthesized_fonts = 0;
5ac45f98 14068
fbd6baed 14069 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
74e1aeec 14070 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
fbd6baed 14071 Vw32_enable_palette = Qt;
5ac45f98 14072
fbd6baed
GV
14073 DEFVAR_INT ("w32-mouse-button-tolerance",
14074 &Vw32_mouse_button_tolerance,
74e1aeec
JR
14075 doc: /* Analogue of double click interval for faking middle mouse events.
14076The value is the minimum time in milliseconds that must elapse between
14077left/right button down events before they are considered distinct events.
14078If both mouse buttons are depressed within this interval, a middle mouse
14079button down event is generated instead. */);
fbd6baed 14080 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
5ac45f98 14081
fbd6baed
GV
14082 DEFVAR_INT ("w32-mouse-move-interval",
14083 &Vw32_mouse_move_interval,
74e1aeec
JR
14084 doc: /* Minimum interval between mouse move events.
14085The value is the minimum time in milliseconds that must elapse between
14086successive mouse move (or scroll bar drag) events before they are
14087reported as lisp events. */);
247be837 14088 XSETINT (Vw32_mouse_move_interval, 0);
84fb1139 14089
74214547
JR
14090 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
14091 &w32_pass_extra_mouse_buttons_to_system,
14092 doc: /* Non-nil if the fourth and fifth mouse buttons are passed to Windows.
14093Recent versions of Windows support mice with up to five buttons.
14094Since most applications don't support these extra buttons, most mouse
14095drivers will allow you to map them to functions at the system level.
14096If this variable is non-nil, Emacs will pass them on, allowing the
14097system to handle them. */);
14098 w32_pass_extra_mouse_buttons_to_system = 0;
14099
ee78dc32 14100 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
6e2d67d8 14101 doc: /* List of directories to search for window system bitmap files. */);
ee78dc32
GV
14102 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
14103
14104 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
74e1aeec
JR
14105 doc: /* The shape of the pointer when over text.
14106Changing the value does not affect existing frames
14107unless you set the mouse color. */);
ee78dc32
GV
14108 Vx_pointer_shape = Qnil;
14109
ee78dc32
GV
14110 Vx_nontext_pointer_shape = Qnil;
14111
14112 Vx_mode_pointer_shape = Qnil;
14113
0af913d7 14114 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
74e1aeec
JR
14115 doc: /* The shape of the pointer when Emacs is busy.
14116This variable takes effect when you create a new frame
14117or when you set the mouse color. */);
0af913d7 14118 Vx_hourglass_pointer_shape = Qnil;
6fc2811b 14119
0af913d7 14120 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
74e1aeec 14121 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
0af913d7 14122 display_hourglass_p = 1;
7d0393cf 14123
0af913d7 14124 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
74e1aeec
JR
14125 doc: /* *Seconds to wait before displaying an hourglass pointer.
14126Value must be an integer or float. */);
0af913d7 14127 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
f79e6790 14128
6fc2811b 14129 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
ee78dc32 14130 &Vx_sensitive_text_pointer_shape,
74e1aeec
JR
14131 doc: /* The shape of the pointer when over mouse-sensitive text.
14132This variable takes effect when you create a new frame
14133or when you set the mouse color. */);
ee78dc32
GV
14134 Vx_sensitive_text_pointer_shape = Qnil;
14135
4694d762
JR
14136 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
14137 &Vx_window_horizontal_drag_shape,
74e1aeec
JR
14138 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
14139This variable takes effect when you create a new frame
14140or when you set the mouse color. */);
4694d762
JR
14141 Vx_window_horizontal_drag_shape = Qnil;
14142
ee78dc32 14143 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
74e1aeec 14144 doc: /* A string indicating the foreground color of the cursor box. */);
ee78dc32
GV
14145 Vx_cursor_fore_pixel = Qnil;
14146
3cf3436e 14147 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
b3700ae7
JR
14148 doc: /* Maximum size for tooltips.
14149Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
3cf3436e 14150 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
7d0393cf 14151
ee78dc32 14152 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
74e1aeec
JR
14153 doc: /* Non-nil if no window manager is in use.
14154Emacs doesn't try to figure this out; this is always nil
14155unless you set it to something else. */);
ee78dc32
GV
14156 /* We don't have any way to find this out, so set it to nil
14157 and maybe the user would like to set it to t. */
14158 Vx_no_window_manager = Qnil;
14159
4587b026
GV
14160 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
14161 &Vx_pixel_size_width_font_regexp,
74e1aeec
JR
14162 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
14163
14164Since Emacs gets width of a font matching with this regexp from
14165PIXEL_SIZE field of the name, font finding mechanism gets faster for
14166such a font. This is especially effective for such large fonts as
14167Chinese, Japanese, and Korean. */);
4587b026
GV
14168 Vx_pixel_size_width_font_regexp = Qnil;
14169
6fc2811b 14170 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
74e1aeec
JR
14171 doc: /* Time after which cached images are removed from the cache.
14172When an image has not been displayed this many seconds, remove it
14173from the image cache. Value must be an integer or nil with nil
14174meaning don't clear the cache. */);
6fc2811b
JR
14175 Vimage_cache_eviction_delay = make_number (30 * 60);
14176
33d52f9c
GV
14177 DEFVAR_LISP ("w32-bdf-filename-alist",
14178 &Vw32_bdf_filename_alist,
74e1aeec 14179 doc: /* List of bdf fonts and their corresponding filenames. */);
33d52f9c
GV
14180 Vw32_bdf_filename_alist = Qnil;
14181
1075afa9
GV
14182 DEFVAR_BOOL ("w32-strict-fontnames",
14183 &w32_strict_fontnames,
74e1aeec
JR
14184 doc: /* Non-nil means only use fonts that are exact matches for those requested.
14185Default is nil, which allows old fontnames that are not XLFD compliant,
14186and allows third-party CJK display to work by specifying false charset
14187fields to trick Emacs into translating to Big5, SJIS etc.
14188Setting this to t will prevent wrong fonts being selected when
14189fontsets are automatically created. */);
1075afa9
GV
14190 w32_strict_fontnames = 0;
14191
c0611964
AI
14192 DEFVAR_BOOL ("w32-strict-painting",
14193 &w32_strict_painting,
74e1aeec
JR
14194 doc: /* Non-nil means use strict rules for repainting frames.
14195Set this to nil to get the old behaviour for repainting; this should
14196only be necessary if the default setting causes problems. */);
c0611964
AI
14197 w32_strict_painting = 1;
14198
dfff8a69
JR
14199 DEFVAR_LISP ("w32-charset-info-alist",
14200 &Vw32_charset_info_alist,
b3700ae7
JR
14201 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
14202Each entry should be of the form:
74e1aeec
JR
14203
14204 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
14205
14206where CHARSET_NAME is a string used in font names to identify the charset,
14207WINDOWS_CHARSET is a symbol that can be one of:
14208w32-charset-ansi, w32-charset-default, w32-charset-symbol,
14209w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
14210w32-charset-chinesebig5,
dfff8a69 14211#ifdef JOHAB_CHARSET
74e1aeec
JR
14212w32-charset-johab, w32-charset-hebrew,
14213w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
14214w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
14215w32-charset-russian, w32-charset-mac, w32-charset-baltic,
dfff8a69
JR
14216#endif
14217#ifdef UNICODE_CHARSET
74e1aeec 14218w32-charset-unicode,
dfff8a69 14219#endif
74e1aeec
JR
14220or w32-charset-oem.
14221CODEPAGE should be an integer specifying the codepage that should be used
14222to display the character set, t to do no translation and output as Unicode,
14223or nil to do no translation and output as 8 bit (or multibyte on far-east
14224versions of Windows) characters. */);
dfff8a69
JR
14225 Vw32_charset_info_alist = Qnil;
14226
14227 staticpro (&Qw32_charset_ansi);
14228 Qw32_charset_ansi = intern ("w32-charset-ansi");
14229 staticpro (&Qw32_charset_symbol);
14230 Qw32_charset_symbol = intern ("w32-charset-symbol");
14231 staticpro (&Qw32_charset_shiftjis);
14232 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
767b1ff0
JR
14233 staticpro (&Qw32_charset_hangeul);
14234 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
dfff8a69
JR
14235 staticpro (&Qw32_charset_chinesebig5);
14236 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
14237 staticpro (&Qw32_charset_gb2312);
14238 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
14239 staticpro (&Qw32_charset_oem);
14240 Qw32_charset_oem = intern ("w32-charset-oem");
14241
14242#ifdef JOHAB_CHARSET
14243 {
14244 static int w32_extra_charsets_defined = 1;
74e1aeec
JR
14245 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
14246 doc: /* Internal variable. */);
dfff8a69
JR
14247
14248 staticpro (&Qw32_charset_johab);
14249 Qw32_charset_johab = intern ("w32-charset-johab");
14250 staticpro (&Qw32_charset_easteurope);
14251 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
14252 staticpro (&Qw32_charset_turkish);
14253 Qw32_charset_turkish = intern ("w32-charset-turkish");
14254 staticpro (&Qw32_charset_baltic);
14255 Qw32_charset_baltic = intern ("w32-charset-baltic");
14256 staticpro (&Qw32_charset_russian);
14257 Qw32_charset_russian = intern ("w32-charset-russian");
14258 staticpro (&Qw32_charset_arabic);
14259 Qw32_charset_arabic = intern ("w32-charset-arabic");
14260 staticpro (&Qw32_charset_greek);
14261 Qw32_charset_greek = intern ("w32-charset-greek");
14262 staticpro (&Qw32_charset_hebrew);
14263 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
767b1ff0
JR
14264 staticpro (&Qw32_charset_vietnamese);
14265 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
dfff8a69
JR
14266 staticpro (&Qw32_charset_thai);
14267 Qw32_charset_thai = intern ("w32-charset-thai");
14268 staticpro (&Qw32_charset_mac);
14269 Qw32_charset_mac = intern ("w32-charset-mac");
14270 }
14271#endif
14272
14273#ifdef UNICODE_CHARSET
14274 {
14275 static int w32_unicode_charset_defined = 1;
14276 DEFVAR_BOOL ("w32-unicode-charset-defined",
74e1aeec
JR
14277 &w32_unicode_charset_defined,
14278 doc: /* Internal variable. */);
dfff8a69
JR
14279
14280 staticpro (&Qw32_charset_unicode);
14281 Qw32_charset_unicode = intern ("w32-charset-unicode");
14282#endif
14283
767b1ff0 14284#if 0 /* TODO: Port to W32 */
6fc2811b
JR
14285 defsubr (&Sx_change_window_property);
14286 defsubr (&Sx_delete_window_property);
14287 defsubr (&Sx_window_property);
14288#endif
2d764c78 14289 defsubr (&Sxw_display_color_p);
ee78dc32 14290 defsubr (&Sx_display_grayscale_p);
2d764c78
EZ
14291 defsubr (&Sxw_color_defined_p);
14292 defsubr (&Sxw_color_values);
ee78dc32
GV
14293 defsubr (&Sx_server_max_request_size);
14294 defsubr (&Sx_server_vendor);
14295 defsubr (&Sx_server_version);
14296 defsubr (&Sx_display_pixel_width);
14297 defsubr (&Sx_display_pixel_height);
14298 defsubr (&Sx_display_mm_width);
14299 defsubr (&Sx_display_mm_height);
14300 defsubr (&Sx_display_screens);
14301 defsubr (&Sx_display_planes);
14302 defsubr (&Sx_display_color_cells);
14303 defsubr (&Sx_display_visual_class);
14304 defsubr (&Sx_display_backing_store);
14305 defsubr (&Sx_display_save_under);
ee78dc32 14306 defsubr (&Sx_create_frame);
ee78dc32
GV
14307 defsubr (&Sx_open_connection);
14308 defsubr (&Sx_close_connection);
14309 defsubr (&Sx_display_list);
14310 defsubr (&Sx_synchronize);
14311
fbd6baed 14312 /* W32 specific functions */
ee78dc32 14313
1edf84e7 14314 defsubr (&Sw32_focus_frame);
fbd6baed
GV
14315 defsubr (&Sw32_select_font);
14316 defsubr (&Sw32_define_rgb_color);
14317 defsubr (&Sw32_default_color_map);
14318 defsubr (&Sw32_load_color_file);
1edf84e7 14319 defsubr (&Sw32_send_sys_command);
55dcfc15 14320 defsubr (&Sw32_shell_execute);
ccc2d29c
GV
14321 defsubr (&Sw32_register_hot_key);
14322 defsubr (&Sw32_unregister_hot_key);
14323 defsubr (&Sw32_registered_hot_keys);
14324 defsubr (&Sw32_reconstruct_hot_key);
adcc3809 14325 defsubr (&Sw32_toggle_lock_key);
33d52f9c 14326 defsubr (&Sw32_find_bdf_fonts);
4587b026 14327
2254bcde
AI
14328 defsubr (&Sfile_system_info);
14329
4587b026
GV
14330 /* Setting callback functions for fontset handler. */
14331 get_font_info_func = w32_get_font_info;
6fc2811b
JR
14332
14333#if 0 /* This function pointer doesn't seem to be used anywhere.
14334 And the pointer assigned has the wrong type, anyway. */
4587b026 14335 list_fonts_func = w32_list_fonts;
6fc2811b
JR
14336#endif
14337
4587b026
GV
14338 load_font_func = w32_load_font;
14339 find_ccl_program_func = w32_find_ccl_program;
14340 query_font_func = w32_query_font;
14341 set_frame_fontset_func = x_set_font;
14342 check_window_system_func = check_w32;
6fc2811b 14343
6fc2811b
JR
14344 /* Images. */
14345 Qxbm = intern ("xbm");
14346 staticpro (&Qxbm);
a93f4566
GM
14347 QCconversion = intern (":conversion");
14348 staticpro (&QCconversion);
6fc2811b
JR
14349 QCheuristic_mask = intern (":heuristic-mask");
14350 staticpro (&QCheuristic_mask);
14351 QCcolor_symbols = intern (":color-symbols");
14352 staticpro (&QCcolor_symbols);
6fc2811b
JR
14353 QCascent = intern (":ascent");
14354 staticpro (&QCascent);
14355 QCmargin = intern (":margin");
14356 staticpro (&QCmargin);
14357 QCrelief = intern (":relief");
14358 staticpro (&QCrelief);
14359 Qpostscript = intern ("postscript");
14360 staticpro (&Qpostscript);
14361 QCloader = intern (":loader");
14362 staticpro (&QCloader);
14363 QCbounding_box = intern (":bounding-box");
14364 staticpro (&QCbounding_box);
14365 QCpt_width = intern (":pt-width");
14366 staticpro (&QCpt_width);
14367 QCpt_height = intern (":pt-height");
14368 staticpro (&QCpt_height);
14369 QCindex = intern (":index");
14370 staticpro (&QCindex);
14371 Qpbm = intern ("pbm");
14372 staticpro (&Qpbm);
14373
14374#if HAVE_XPM
14375 Qxpm = intern ("xpm");
14376 staticpro (&Qxpm);
14377#endif
7d0393cf 14378
6fc2811b
JR
14379#if HAVE_JPEG
14380 Qjpeg = intern ("jpeg");
14381 staticpro (&Qjpeg);
7d0393cf 14382#endif
6fc2811b
JR
14383
14384#if HAVE_TIFF
14385 Qtiff = intern ("tiff");
14386 staticpro (&Qtiff);
7d0393cf 14387#endif
6fc2811b
JR
14388
14389#if HAVE_GIF
14390 Qgif = intern ("gif");
14391 staticpro (&Qgif);
14392#endif
14393
14394#if HAVE_PNG
14395 Qpng = intern ("png");
14396 staticpro (&Qpng);
14397#endif
14398
14399 defsubr (&Sclear_image_cache);
ac849ba4
JR
14400 defsubr (&Simage_size);
14401 defsubr (&Simage_mask_p);
6fc2811b
JR
14402
14403#if GLYPH_DEBUG
14404 defsubr (&Simagep);
14405 defsubr (&Slookup_image);
14406#endif
6fc2811b 14407
0af913d7
GM
14408 hourglass_atimer = NULL;
14409 hourglass_shown_p = 0;
6fc2811b
JR
14410 defsubr (&Sx_show_tip);
14411 defsubr (&Sx_hide_tip);
6fc2811b 14412 tip_timer = Qnil;
57fa2774
JR
14413 staticpro (&tip_timer);
14414 tip_frame = Qnil;
14415 staticpro (&tip_frame);
6fc2811b 14416
ca56d953
JR
14417 last_show_tip_args = Qnil;
14418 staticpro (&last_show_tip_args);
14419
6fc2811b
JR
14420 defsubr (&Sx_file_dialog);
14421}
14422
c922a224 14423
9785d95b
BK
14424/*
14425 globals_of_w32fns is used to initialize those global variables that
14426 must always be initialized on startup even when the global variable
14427 initialized is non zero (see the function main in emacs.c).
14428 globals_of_w32fns is called from syms_of_w32fns when the global
14429 variable initialized is 0 and directly from main when initialized
14430 is non zero.
14431 */
14432void globals_of_w32fns ()
14433{
14434 HMODULE user32_lib = GetModuleHandle ("user32.dll");
14435 /*
14436 TrackMouseEvent not available in all versions of Windows, so must load
14437 it dynamically. Do it once, here, instead of every time it is used.
14438 */
14439 track_mouse_event_fn = (TrackMouseEvent_Proc) GetProcAddress (user32_lib, "TrackMouseEvent");
14440}
6fc2811b 14441
839b1909
JR
14442/* Initialize image types. Based on which libraries are available. */
14443static void
14444init_external_image_libraries ()
6fc2811b 14445{
afc390dc 14446 HINSTANCE library;
7d0393cf 14447
6fc2811b 14448#if HAVE_XPM
c736ffda
JR
14449 if ((library = LoadLibrary ("libXpm.dll")))
14450 {
14451 if (init_xpm_functions (library))
14452 define_image_type (&xpm_type);
14453 }
14454
6fc2811b 14455#endif
7d0393cf 14456
6fc2811b 14457#if HAVE_JPEG
afc390dc 14458 /* Try loading jpeg library under probable names. */
c922a224 14459 if ((library = LoadLibrary ("libjpeg.dll"))
100dcd40 14460 || (library = LoadLibrary ("jpeg-62.dll"))
c922a224 14461 || (library = LoadLibrary ("jpeg.dll")))
afc390dc
JR
14462 {
14463 if (init_jpeg_functions (library))
14464 define_image_type (&jpeg_type);
14465 }
6fc2811b 14466#endif
7d0393cf 14467
6fc2811b 14468#if HAVE_TIFF
12b918b2
JB
14469 if (library = LoadLibrary ("libtiff.dll"))
14470 {
14471 if (init_tiff_functions (library))
14472 define_image_type (&tiff_type);
14473 }
6fc2811b 14474#endif
919f1e88 14475
6fc2811b 14476#if HAVE_GIF
1ffb278b
JB
14477 if (library = LoadLibrary ("libungif.dll"))
14478 {
14479 if (init_gif_functions (library))
14480 define_image_type (&gif_type);
14481 }
6fc2811b 14482#endif
7d0393cf 14483
6fc2811b 14484#if HAVE_PNG
839b1909
JR
14485 /* Ensure zlib is loaded. Try debug version first. */
14486 if (!LoadLibrary ("zlibd.dll"))
14487 LoadLibrary ("zlib.dll");
14488
14489 /* Try loading libpng under probable names. */
afc390dc
JR
14490 if ((library = LoadLibrary ("libpng13d.dll"))
14491 || (library = LoadLibrary ("libpng13.dll"))
14492 || (library = LoadLibrary ("libpng12d.dll"))
14493 || (library = LoadLibrary ("libpng12.dll"))
14494 || (library = LoadLibrary ("libpng.dll")))
839b1909 14495 {
afc390dc 14496 if (init_png_functions (library))
839b1909
JR
14497 define_image_type (&png_type);
14498 }
6fc2811b 14499#endif
ee78dc32
GV
14500}
14501
839b1909
JR
14502void
14503init_xfns ()
14504{
14505 image_types = NULL;
14506 Vimage_types = Qnil;
14507
14508 define_image_type (&pbm_type);
14509 define_image_type (&xbm_type);
14510
14511#if 0 /* TODO : Ghostscript support for W32 */
14512 define_image_type (&gs_type);
14513#endif
14514
14515 /* Image types that rely on external libraries are loaded dynamically
14516 if the library is available. */
14517 init_external_image_libraries ();
14518}
14519
ee78dc32
GV
14520#undef abort
14521
7d0393cf 14522void
fbd6baed 14523w32_abort()
ee78dc32 14524{
5ac45f98
GV
14525 int button;
14526 button = MessageBox (NULL,
14527 "A fatal error has occurred!\n\n"
14528 "Select Abort to exit, Retry to debug, Ignore to continue",
14529 "Emacs Abort Dialog",
14530 MB_ICONEXCLAMATION | MB_TASKMODAL
14531 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
14532 switch (button)
14533 {
14534 case IDRETRY:
14535 DebugBreak ();
14536 break;
14537 case IDIGNORE:
14538 break;
14539 case IDABORT:
14540 default:
14541 abort ();
14542 break;
14543 }
ee78dc32 14544}
d573caac 14545
83c75055
GV
14546/* For convenience when debugging. */
14547int
14548w32_last_error()
14549{
14550 return GetLastError ();
14551}