(font-lock-support-mode): Doc fix.
[emacs.git] / src / macterm.c
blob362da7f77c7caa07fd5b6a0e75e723c68441d8c7
1 /* Implementation of GUI terminal on the Mac OS.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004,
3 2005 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 /* Contributed by Andrew Choi (akochoi@mac.com). */
24 #include <config.h>
25 #include <signal.h>
27 #include <stdio.h>
29 #include "lisp.h"
30 #include "blockinput.h"
32 #include "macterm.h"
34 #ifndef MAC_OSX
35 #include <alloca.h>
36 #endif
38 #if TARGET_API_MAC_CARBON
39 /* USE_CARBON_EVENTS determines if the Carbon Event Manager is used to
40 obtain events from the event queue. If set to 0, WaitNextEvent is
41 used instead. */
42 #define USE_CARBON_EVENTS 1
43 #else /* not TARGET_API_MAC_CARBON */
44 #include <Quickdraw.h>
45 #include <ToolUtils.h>
46 #include <Sound.h>
47 #include <Events.h>
48 #include <Script.h>
49 #include <Resources.h>
50 #include <Fonts.h>
51 #include <TextUtils.h>
52 #include <LowMem.h>
53 #include <Controls.h>
54 #include <Windows.h>
55 #if defined (__MRC__) || (__MSL__ >= 0x6000)
56 #include <ControlDefinitions.h>
57 #endif
59 #if __profile__
60 #include <profiler.h>
61 #endif
62 #endif /* not TARGET_API_MAC_CARBON */
64 #include "systty.h"
65 #include "systime.h"
67 #include <ctype.h>
68 #include <errno.h>
69 #include <setjmp.h>
70 #include <sys/stat.h>
71 #include <sys/param.h>
73 #include "charset.h"
74 #include "coding.h"
75 #include "frame.h"
76 #include "dispextern.h"
77 #include "fontset.h"
78 #include "termhooks.h"
79 #include "termopts.h"
80 #include "termchar.h"
81 #include "gnu.h"
82 #include "disptab.h"
83 #include "buffer.h"
84 #include "window.h"
85 #include "keyboard.h"
86 #include "intervals.h"
87 #include "atimer.h"
88 #include "keymap.h"
90 /* Set of macros that handle mapping of Mac modifier keys to emacs. */
91 #define macCtrlKey (NILP (Vmac_reverse_ctrl_meta) ? controlKey : \
92 (NILP (Vmac_command_key_is_meta) ? optionKey : cmdKey))
93 #define macShiftKey (shiftKey)
94 #define macMetaKey (NILP (Vmac_reverse_ctrl_meta) ? \
95 (NILP (Vmac_command_key_is_meta) ? optionKey : cmdKey) \
96 : controlKey)
97 #define macAltKey (NILP (Vmac_command_key_is_meta) ? cmdKey : optionKey)
100 /* Non-nil means Emacs uses toolkit scroll bars. */
102 Lisp_Object Vx_toolkit_scroll_bars;
104 /* If Non-nil, the text will be rendered using Core Graphics text rendering which may anti-alias the text. */
105 Lisp_Object Vmac_use_core_graphics;
108 /* Non-zero means that a HELP_EVENT has been generated since Emacs
109 start. */
111 static int any_help_event_p;
113 /* Last window where we saw the mouse. Used by mouse-autoselect-window. */
114 static Lisp_Object last_window;
116 /* This is a chain of structures for all the X displays currently in
117 use. */
119 struct x_display_info *x_display_list;
121 /* This is a list of cons cells, each of the form (NAME
122 FONT-LIST-CACHE . RESOURCE-DATABASE), one for each element of
123 x_display_list and in the same order. NAME is the name of the
124 frame. FONT-LIST-CACHE records previous values returned by
125 x-list-fonts. RESOURCE-DATABASE preserves the X Resource Database
126 equivalent, which is implemented with a Lisp object, for the
127 display. */
129 Lisp_Object x_display_name_list;
131 /* This is display since Mac does not support multiple ones. */
132 struct mac_display_info one_mac_display_info;
134 /* Frame being updated by update_frame. This is declared in term.c.
135 This is set by update_begin and looked at by all the XT functions.
136 It is zero while not inside an update. In that case, the XT
137 functions assume that `selected_frame' is the frame to apply to. */
139 extern struct frame *updating_frame;
141 /* This is a frame waiting to be auto-raised, within XTread_socket. */
143 struct frame *pending_autoraise_frame;
145 /* Mouse movement.
147 Formerly, we used PointerMotionHintMask (in standard_event_mask)
148 so that we would have to call XQueryPointer after each MotionNotify
149 event to ask for another such event. However, this made mouse tracking
150 slow, and there was a bug that made it eventually stop.
152 Simply asking for MotionNotify all the time seems to work better.
154 In order to avoid asking for motion events and then throwing most
155 of them away or busy-polling the server for mouse positions, we ask
156 the server for pointer motion hints. This means that we get only
157 one event per group of mouse movements. "Groups" are delimited by
158 other kinds of events (focus changes and button clicks, for
159 example), or by XQueryPointer calls; when one of these happens, we
160 get another MotionNotify event the next time the mouse moves. This
161 is at least as efficient as getting motion events when mouse
162 tracking is on, and I suspect only negligibly worse when tracking
163 is off. */
165 /* Where the mouse was last time we reported a mouse event. */
167 static Rect last_mouse_glyph;
169 /* The scroll bar in which the last X motion event occurred.
171 If the last X motion event occurred in a scroll bar, we set this so
172 XTmouse_position can know whether to report a scroll bar motion or
173 an ordinary motion.
175 If the last X motion event didn't occur in a scroll bar, we set
176 this to Qnil, to tell XTmouse_position to return an ordinary motion
177 event. */
179 static Lisp_Object last_mouse_scroll_bar;
181 /* This is a hack. We would really prefer that XTmouse_position would
182 return the time associated with the position it returns, but there
183 doesn't seem to be any way to wrest the time-stamp from the server
184 along with the position query. So, we just keep track of the time
185 of the last movement we received, and return that in hopes that
186 it's somewhat accurate. */
188 static Time last_mouse_movement_time;
190 struct scroll_bar *tracked_scroll_bar = NULL;
192 /* Incremented by XTread_socket whenever it really tries to read
193 events. */
195 #ifdef __STDC__
196 static int volatile input_signal_count;
197 #else
198 static int input_signal_count;
199 #endif
201 extern Lisp_Object Vsystem_name;
203 /* A mask of extra modifier bits to put into every keyboard char. */
205 extern EMACS_INT extra_keyboard_modifiers;
207 /* The keysyms to use for the various modifiers. */
209 static Lisp_Object Qalt, Qhyper, Qsuper, Qmodifier_value;
211 extern int inhibit_window_system;
213 #if __MRC__ && !TARGET_API_MAC_CARBON
214 QDGlobals qd; /* QuickDraw global information structure. */
215 #endif
217 #define mac_window_to_frame(wp) (((mac_output *) GetWRefCon (wp))->mFP)
219 struct mac_display_info *mac_display_info_for_display (Display *);
220 static void x_update_window_end P_ ((struct window *, int, int));
221 static int x_io_error_quitter P_ ((Display *));
222 int x_catch_errors P_ ((Display *));
223 void x_uncatch_errors P_ ((Display *, int));
224 void x_lower_frame P_ ((struct frame *));
225 void x_scroll_bar_clear P_ ((struct frame *));
226 int x_had_errors_p P_ ((Display *));
227 void x_wm_set_size_hint P_ ((struct frame *, long, int));
228 void x_raise_frame P_ ((struct frame *));
229 void x_set_window_size P_ ((struct frame *, int, int, int));
230 void x_wm_set_window_state P_ ((struct frame *, int));
231 void x_wm_set_icon_pixmap P_ ((struct frame *, int));
232 void mac_initialize P_ ((void));
233 static void x_font_min_bounds P_ ((XFontStruct *, int *, int *));
234 static int x_compute_min_glyph_bounds P_ ((struct frame *));
235 static void x_update_end P_ ((struct frame *));
236 static void XTframe_up_to_date P_ ((struct frame *));
237 static void XTset_terminal_modes P_ ((void));
238 static void XTreset_terminal_modes P_ ((void));
239 static void x_clear_frame P_ ((void));
240 static void frame_highlight P_ ((struct frame *));
241 static void frame_unhighlight P_ ((struct frame *));
242 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
243 static void mac_focus_changed P_ ((int, struct mac_display_info *,
244 struct frame *, struct input_event *));
245 static void x_detect_focus_change P_ ((struct mac_display_info *,
246 EventRecord *, struct input_event *));
247 static void XTframe_rehighlight P_ ((struct frame *));
248 static void x_frame_rehighlight P_ ((struct x_display_info *));
249 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
250 static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
251 enum text_cursor_kinds));
253 static void x_clip_to_row P_ ((struct window *, struct glyph_row *, int, GC));
254 static void x_flush P_ ((struct frame *f));
255 static void x_update_begin P_ ((struct frame *));
256 static void x_update_window_begin P_ ((struct window *));
257 static void x_after_update_window_line P_ ((struct glyph_row *));
258 static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
259 enum scroll_bar_part *,
260 Lisp_Object *, Lisp_Object *,
261 unsigned long *));
263 static int is_emacs_window P_ ((WindowPtr));
265 static void XSetFont P_ ((Display *, GC, XFontStruct *));
267 /* Defined in macmenu.h. */
268 extern void menubar_selection_callback (FRAME_PTR, int);
270 #define GC_FORE_COLOR(gc) (&(gc)->fore_color)
271 #define GC_BACK_COLOR(gc) (&(gc)->back_color)
272 #define GC_FONT(gc) ((gc)->xgcv.font)
273 #define MAC_WINDOW_NORMAL_GC(w) (((mac_output *) GetWRefCon (w))->normal_gc)
276 /* X display function emulation */
278 void
279 XFreePixmap (display, pixmap)
280 Display *display; /* not used */
281 Pixmap pixmap;
283 DisposeGWorld (pixmap);
287 /* Mac version of XDrawLine. */
289 static void
290 XDrawLine (display, w, gc, x1, y1, x2, y2)
291 Display *display;
292 WindowPtr w;
293 GC gc;
294 int x1, y1, x2, y2;
296 SetPortWindowPort (w);
298 RGBForeColor (GC_FORE_COLOR (gc));
300 MoveTo (x1, y1);
301 LineTo (x2, y2);
304 void
305 mac_draw_line_to_pixmap (display, p, gc, x1, y1, x2, y2)
306 Display *display;
307 Pixmap p;
308 GC gc;
309 int x1, y1, x2, y2;
311 CGrafPtr old_port;
312 GDHandle old_gdh;
314 GetGWorld (&old_port, &old_gdh);
315 SetGWorld (p, NULL);
317 RGBForeColor (GC_FORE_COLOR (gc));
319 LockPixels (GetGWorldPixMap (p));
320 MoveTo (x1, y1);
321 LineTo (x2, y2);
322 UnlockPixels (GetGWorldPixMap (p));
324 SetGWorld (old_port, old_gdh);
328 static void
329 mac_erase_rectangle (w, gc, x, y, width, height)
330 WindowPtr w;
331 GC gc;
332 int x, y;
333 unsigned int width, height;
335 Rect r;
337 SetPortWindowPort (w);
339 RGBBackColor (GC_BACK_COLOR (gc));
340 SetRect (&r, x, y, x + width, y + height);
342 EraseRect (&r);
344 RGBBackColor (GC_BACK_COLOR (MAC_WINDOW_NORMAL_GC (w)));
348 /* Mac version of XClearArea. */
350 void
351 XClearArea (display, w, x, y, width, height, exposures)
352 Display *display;
353 WindowPtr w;
354 int x, y;
355 unsigned int width, height;
356 int exposures;
358 mac_erase_rectangle (w, MAC_WINDOW_NORMAL_GC (w), x, y, width, height);
361 /* Mac version of XClearWindow. */
363 static void
364 XClearWindow (display, w)
365 Display *display;
366 WindowPtr w;
368 SetPortWindowPort (w);
370 RGBBackColor (GC_BACK_COLOR (MAC_WINDOW_NORMAL_GC (w)));
372 #if TARGET_API_MAC_CARBON
374 Rect r;
376 GetWindowPortBounds (w, &r);
377 EraseRect (&r);
379 #else /* not TARGET_API_MAC_CARBON */
380 EraseRect (&(w->portRect));
381 #endif /* not TARGET_API_MAC_CARBON */
385 /* Mac replacement for XCopyArea. */
387 static void
388 mac_draw_bitmap (display, w, gc, x, y, width, height, bits, overlay_p)
389 Display *display;
390 WindowPtr w;
391 GC gc;
392 int x, y, width, height;
393 unsigned short *bits;
394 int overlay_p;
396 BitMap bitmap;
397 Rect r;
399 bitmap.rowBytes = sizeof(unsigned short);
400 bitmap.baseAddr = (char *)bits;
401 SetRect (&(bitmap.bounds), 0, 0, width, height);
403 SetPortWindowPort (w);
405 RGBForeColor (GC_FORE_COLOR (gc));
406 RGBBackColor (GC_BACK_COLOR (gc));
407 SetRect (&r, x, y, x + width, y + height);
409 #if TARGET_API_MAC_CARBON
410 LockPortBits (GetWindowPort (w));
411 CopyBits (&bitmap, GetPortBitMapForCopyBits (GetWindowPort (w)),
412 &(bitmap.bounds), &r, overlay_p ? srcOr : srcCopy, 0);
413 UnlockPortBits (GetWindowPort (w));
414 #else /* not TARGET_API_MAC_CARBON */
415 CopyBits (&bitmap, &(w->portBits), &(bitmap.bounds), &r,
416 overlay_p ? srcOr : srcCopy, 0);
417 #endif /* not TARGET_API_MAC_CARBON */
419 RGBBackColor (GC_BACK_COLOR (MAC_WINDOW_NORMAL_GC (w)));
423 /* Mac replacement for XSetClipRectangles. */
425 static void
426 mac_set_clip_rectangle (display, w, r)
427 Display *display;
428 WindowPtr w;
429 Rect *r;
431 SetPortWindowPort (w);
433 ClipRect (r);
437 /* Mac replacement for XSetClipMask. */
439 static void
440 mac_reset_clipping (display, w)
441 Display *display;
442 WindowPtr w;
444 Rect r;
446 SetPortWindowPort (w);
448 SetRect (&r, -32767, -32767, 32767, 32767);
449 ClipRect (&r);
453 /* Mac replacement for XCreateBitmapFromBitmapData. */
455 static void
456 mac_create_bitmap_from_bitmap_data (bitmap, bits, w, h)
457 BitMap *bitmap;
458 char *bits;
459 int w, h;
461 static unsigned char swap_nibble[16]
462 = { 0x0, 0x8, 0x4, 0xc, /* 0000 1000 0100 1100 */
463 0x2, 0xa, 0x6, 0xe, /* 0010 1010 0110 1110 */
464 0x1, 0x9, 0x5, 0xd, /* 0001 1001 0101 1101 */
465 0x3, 0xb, 0x7, 0xf }; /* 0011 1011 0111 1111 */
466 int i, j, w1;
467 char *p;
469 w1 = (w + 7) / 8; /* nb of 8bits elt in X bitmap */
470 bitmap->rowBytes = ((w + 15) / 16) * 2; /* nb of 16bits elt in Mac bitmap */
471 bitmap->baseAddr = xmalloc (bitmap->rowBytes * h);
472 bzero (bitmap->baseAddr, bitmap->rowBytes * h);
473 for (i = 0; i < h; i++)
475 p = bitmap->baseAddr + i * bitmap->rowBytes;
476 for (j = 0; j < w1; j++)
478 /* Bitswap XBM bytes to match how Mac does things. */
479 unsigned char c = *bits++;
480 *p++ = (unsigned char)((swap_nibble[c & 0xf] << 4)
481 | (swap_nibble[(c>>4) & 0xf]));;
485 SetRect (&(bitmap->bounds), 0, 0, w, h);
489 static void
490 mac_free_bitmap (bitmap)
491 BitMap *bitmap;
493 xfree (bitmap->baseAddr);
497 Pixmap
498 XCreatePixmap (display, w, width, height, depth)
499 Display *display; /* not used */
500 WindowPtr w;
501 unsigned int width, height;
502 unsigned int depth;
504 Pixmap pixmap;
505 Rect r;
506 QDErr err;
508 SetPortWindowPort (w);
510 SetRect (&r, 0, 0, width, height);
511 err = NewGWorld (&pixmap, depth, &r, NULL, NULL, 0);
512 if (err != noErr)
513 return NULL;
514 return pixmap;
518 Pixmap
519 XCreatePixmapFromBitmapData (display, w, data, width, height, fg, bg, depth)
520 Display *display; /* not used */
521 WindowPtr w;
522 char *data;
523 unsigned int width, height;
524 unsigned long fg, bg;
525 unsigned int depth;
527 Pixmap pixmap;
528 BitMap bitmap;
529 CGrafPtr old_port;
530 GDHandle old_gdh;
531 static GC gc = NULL; /* not reentrant */
533 if (gc == NULL)
534 gc = XCreateGC (display, w, 0, NULL);
536 pixmap = XCreatePixmap (display, w, width, height, depth);
537 if (pixmap == NULL)
538 return NULL;
540 GetGWorld (&old_port, &old_gdh);
541 SetGWorld (pixmap, NULL);
542 mac_create_bitmap_from_bitmap_data (&bitmap, data, width, height);
543 XSetForeground (display, gc, fg);
544 XSetBackground (display, gc, bg);
545 RGBForeColor (GC_FORE_COLOR (gc));
546 RGBBackColor (GC_BACK_COLOR (gc));
547 LockPixels (GetGWorldPixMap (pixmap));
548 #if TARGET_API_MAC_CARBON
549 CopyBits (&bitmap, GetPortBitMapForCopyBits (pixmap),
550 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
551 #else /* not TARGET_API_MAC_CARBON */
552 CopyBits (&bitmap, &(((GrafPtr)pixmap)->portBits),
553 &bitmap.bounds, &bitmap.bounds, srcCopy, 0);
554 #endif /* not TARGET_API_MAC_CARBON */
555 UnlockPixels (GetGWorldPixMap (pixmap));
556 SetGWorld (old_port, old_gdh);
557 mac_free_bitmap (&bitmap);
559 return pixmap;
563 /* Mac replacement for XFillRectangle. */
565 static void
566 XFillRectangle (display, w, gc, x, y, width, height)
567 Display *display;
568 WindowPtr w;
569 GC gc;
570 int x, y;
571 unsigned int width, height;
573 Rect r;
575 SetPortWindowPort (w);
577 RGBForeColor (GC_FORE_COLOR (gc));
578 SetRect (&r, x, y, x + width, y + height);
580 PaintRect (&r); /* using foreground color of gc */
584 #if 0 /* TODO: figure out if we need to do this on Mac. */
585 static void
586 mac_fill_rectangle_to_pixmap (display, p, gc, x, y, width, height)
587 Display *display;
588 Pixmap p;
589 GC gc;
590 int x, y;
591 unsigned int width, height;
593 CGrafPtr old_port;
594 GDHandle old_gdh;
595 Rect r;
597 GetGWorld (&old_port, &old_gdh);
598 SetGWorld (p, NULL);
599 RGBForeColor (GC_FORE_COLOR (gc));
600 SetRect (&r, x, y, x + width, y + height);
602 LockPixels (GetGWorldPixMap (p));
603 PaintRect (&r); /* using foreground color of gc */
604 UnlockPixels (GetGWorldPixMap (p));
606 SetGWorld (old_port, old_gdh);
608 #endif
611 /* Mac replacement for XDrawRectangle: dest is a window. */
613 static void
614 mac_draw_rectangle (display, w, gc, x, y, width, height)
615 Display *display;
616 WindowPtr w;
617 GC gc;
618 int x, y;
619 unsigned int width, height;
621 Rect r;
623 SetPortWindowPort (w);
625 RGBForeColor (GC_FORE_COLOR (gc));
626 SetRect (&r, x, y, x + width + 1, y + height + 1);
628 FrameRect (&r); /* using foreground color of gc */
632 #if 0 /* TODO: figure out if we need to do this on Mac. */
633 /* Mac replacement for XDrawRectangle: dest is a Pixmap. */
635 static void
636 mac_draw_rectangle_to_pixmap (display, p, gc, x, y, width, height)
637 Display *display;
638 Pixmap p;
639 GC gc;
640 int x, y;
641 unsigned int width, height;
643 CGrafPtr old_port;
644 GDHandle old_gdh;
645 Rect r;
647 GetGWorld (&old_port, &old_gdh);
648 SetGWorld (p, NULL);
649 RGBForeColor (GC_FORE_COLOR (gc));
650 SetRect (&r, x, y, x + width + 1, y + height + 1);
652 LockPixels (GetGWorldPixMap (p));
653 FrameRect (&r); /* using foreground color of gc */
654 UnlockPixels (GetGWorldPixMap (p));
656 SetGWorld (old_port, old_gdh);
658 #endif
661 static void
662 mac_draw_string_common (display, w, gc, x, y, buf, nchars, mode,
663 bytes_per_char)
664 Display *display;
665 WindowPtr w;
666 GC gc;
667 int x, y;
668 char *buf;
669 int nchars, mode, bytes_per_char;
671 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
672 UInt32 textFlags, savedFlags;
673 if (!NILP(Vmac_use_core_graphics)) {
674 textFlags = kQDUseCGTextRendering;
675 savedFlags = SwapQDTextFlags(textFlags);
677 #endif
679 SetPortWindowPort (w);
681 RGBForeColor (GC_FORE_COLOR (gc));
682 if (mode != srcOr)
683 RGBBackColor (GC_BACK_COLOR (gc));
685 TextFont (GC_FONT (gc)->mac_fontnum);
686 TextSize (GC_FONT (gc)->mac_fontsize);
687 TextFace (GC_FONT (gc)->mac_fontface);
688 TextMode (mode);
690 MoveTo (x, y);
691 DrawText (buf, 0, nchars * bytes_per_char);
693 if (mode != srcOr)
694 RGBBackColor (GC_BACK_COLOR (MAC_WINDOW_NORMAL_GC (w)));
695 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
696 if (!NILP(Vmac_use_core_graphics))
697 SwapQDTextFlags(savedFlags);
698 #endif
702 /* Mac replacement for XDrawString. */
704 static void
705 XDrawString (display, w, gc, x, y, buf, nchars)
706 Display *display;
707 WindowPtr w;
708 GC gc;
709 int x, y;
710 char *buf;
711 int nchars;
713 mac_draw_string_common (display, w, gc, x, y, buf, nchars, srcOr, 1);
717 /* Mac replacement for XDrawString16. */
719 static void
720 XDrawString16 (display, w, gc, x, y, buf, nchars)
721 Display *display;
722 WindowPtr w;
723 GC gc;
724 int x, y;
725 XChar2b *buf;
726 int nchars;
728 mac_draw_string_common (display, w, gc, x, y, (char *) buf, nchars, srcOr,
733 /* Mac replacement for XDrawImageString. */
735 static void
736 XDrawImageString (display, w, gc, x, y, buf, nchars)
737 Display *display;
738 WindowPtr w;
739 GC gc;
740 int x, y;
741 char *buf;
742 int nchars;
744 mac_draw_string_common (display, w, gc, x, y, buf, nchars, srcCopy, 1);
748 /* Mac replacement for XDrawString16. */
750 static void
751 XDrawImageString16 (display, w, gc, x, y, buf, nchars)
752 Display *display;
753 WindowPtr w;
754 GC gc;
755 int x, y;
756 XChar2b *buf;
757 int nchars;
759 mac_draw_string_common (display, w, gc, x, y, (char *) buf, nchars, srcCopy,
764 /* Mac replacement for XCopyArea: dest must be window. */
766 static void
767 mac_copy_area (display, src, dest, gc, src_x, src_y, width, height, dest_x,
768 dest_y)
769 Display *display;
770 Pixmap src;
771 WindowPtr dest;
772 GC gc;
773 int src_x, src_y;
774 unsigned int width, height;
775 int dest_x, dest_y;
777 Rect src_r, dest_r;
779 SetPortWindowPort (dest);
781 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
782 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
784 ForeColor (blackColor);
785 BackColor (whiteColor);
787 LockPixels (GetGWorldPixMap (src));
788 #if TARGET_API_MAC_CARBON
789 LockPortBits (GetWindowPort (dest));
790 CopyBits (GetPortBitMapForCopyBits (src),
791 GetPortBitMapForCopyBits (GetWindowPort (dest)),
792 &src_r, &dest_r, srcCopy, 0);
793 UnlockPortBits (GetWindowPort (dest));
794 #else /* not TARGET_API_MAC_CARBON */
795 CopyBits (&(((GrafPtr)src)->portBits), &(dest->portBits),
796 &src_r, &dest_r, srcCopy, 0);
797 #endif /* not TARGET_API_MAC_CARBON */
798 UnlockPixels (GetGWorldPixMap (src));
800 RGBBackColor (GC_BACK_COLOR (MAC_WINDOW_NORMAL_GC (dest)));
804 static void
805 mac_copy_area_with_mask (display, src, mask, dest, gc, src_x, src_y,
806 width, height, dest_x, dest_y)
807 Display *display;
808 Pixmap src, mask;
809 WindowPtr dest;
810 GC gc;
811 int src_x, src_y;
812 unsigned int width, height;
813 int dest_x, dest_y;
815 Rect src_r, dest_r;
817 SetPortWindowPort (dest);
819 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
820 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
822 ForeColor (blackColor);
823 BackColor (whiteColor);
825 LockPixels (GetGWorldPixMap (src));
826 LockPixels (GetGWorldPixMap (mask));
827 #if TARGET_API_MAC_CARBON
828 LockPortBits (GetWindowPort (dest));
829 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
830 GetPortBitMapForCopyBits (GetWindowPort (dest)),
831 &src_r, &src_r, &dest_r);
832 UnlockPortBits (GetWindowPort (dest));
833 #else /* not TARGET_API_MAC_CARBON */
834 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
835 &(dest->portBits), &src_r, &src_r, &dest_r);
836 #endif /* not TARGET_API_MAC_CARBON */
837 UnlockPixels (GetGWorldPixMap (mask));
838 UnlockPixels (GetGWorldPixMap (src));
840 RGBBackColor (GC_BACK_COLOR (MAC_WINDOW_NORMAL_GC (dest)));
844 /* Mac replacement for XCopyArea: used only for scrolling. */
846 static void
847 mac_scroll_area (display, w, gc, src_x, src_y, width, height, dest_x, dest_y)
848 Display *display;
849 WindowPtr w;
850 GC gc;
851 int src_x, src_y;
852 unsigned int width, height;
853 int dest_x, dest_y;
855 #if TARGET_API_MAC_CARBON
856 Rect src_r;
857 RgnHandle dummy = NewRgn (); /* For avoiding update events. */
859 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
860 ScrollWindowRect (w, &src_r, dest_x - src_x, dest_y - src_y,
861 kScrollWindowNoOptions, dummy);
862 DisposeRgn (dummy);
863 #else /* not TARGET_API_MAC_CARBON */
864 Rect src_r, dest_r;
866 SetPort (w);
868 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
869 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
871 /* In Color QuickDraw, set ForeColor and BackColor as follows to avoid
872 color mapping in CopyBits. Otherwise, it will be slow. */
873 ForeColor (blackColor);
874 BackColor (whiteColor);
875 CopyBits (&(w->portBits), &(w->portBits), &src_r, &dest_r, srcCopy, 0);
877 RGBBackColor (GC_BACK_COLOR (MAC_WINDOW_NORMAL_GC (w)));
878 #endif /* not TARGET_API_MAC_CARBON */
882 #if 0 /* TODO: figure out if we need to do this on Mac. */
883 /* Mac replacement for XCopyArea: dest must be Pixmap. */
885 static void
886 mac_copy_area_to_pixmap (display, src, dest, gc, src_x, src_y, width, height,
887 dest_x, dest_y)
888 Display *display;
889 Pixmap src, dest;
890 GC gc;
891 int src_x, src_y;
892 unsigned int width, height;
893 int dest_x, dest_y;
895 CGrafPtr old_port;
896 GDHandle old_gdh;
897 Rect src_r, dest_r;
899 GetGWorld (&old_port, &old_gdh);
900 SetGWorld (dest, NULL);
901 ForeColor (blackColor);
902 BackColor (whiteColor);
904 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
905 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
907 LockPixels (GetGWorldPixMap (src));
908 LockPixels (GetGWorldPixMap (dest));
909 #if TARGET_API_MAC_CARBON
910 CopyBits (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (dest),
911 &src_r, &dest_r, srcCopy, 0);
912 #else /* not TARGET_API_MAC_CARBON */
913 CopyBits (&(((GrafPtr)src)->portBits), &(((GrafPtr)dest)->portBits),
914 &src_r, &dest_r, srcCopy, 0);
915 #endif /* not TARGET_API_MAC_CARBON */
916 UnlockPixels (GetGWorldPixMap (dest));
917 UnlockPixels (GetGWorldPixMap (src));
919 SetGWorld (old_port, old_gdh);
923 static void
924 mac_copy_area_with_mask_to_pixmap (display, src, mask, dest, gc, src_x, src_y,
925 width, height, dest_x, dest_y)
926 Display *display;
927 Pixmap src, mask, dest;
928 GC gc;
929 int src_x, src_y;
930 unsigned int width, height;
931 int dest_x, dest_y;
933 CGrafPtr old_port;
934 GDHandle old_gdh;
935 Rect src_r, dest_r;
937 GetGWorld (&old_port, &old_gdh);
938 SetGWorld (dest, NULL);
939 ForeColor (blackColor);
940 BackColor (whiteColor);
942 SetRect (&src_r, src_x, src_y, src_x + width, src_y + height);
943 SetRect (&dest_r, dest_x, dest_y, dest_x + width, dest_y + height);
945 LockPixels (GetGWorldPixMap (src));
946 LockPixels (GetGWorldPixMap (mask));
947 LockPixels (GetGWorldPixMap (dest));
948 #if TARGET_API_MAC_CARBON
949 CopyMask (GetPortBitMapForCopyBits (src), GetPortBitMapForCopyBits (mask),
950 GetPortBitMapForCopyBits (dest), &src_r, &src_r, &dest_r);
951 #else /* not TARGET_API_MAC_CARBON */
952 CopyMask (&(((GrafPtr)src)->portBits), &(((GrafPtr)mask)->portBits),
953 &(((GrafPtr)dest)->portBits), &src_r, &src_r, &dest_r);
954 #endif /* not TARGET_API_MAC_CARBON */
955 UnlockPixels (GetGWorldPixMap (dest));
956 UnlockPixels (GetGWorldPixMap (mask));
957 UnlockPixels (GetGWorldPixMap (src));
959 SetGWorld (old_port, old_gdh);
961 #endif
964 /* Mac replacement for XChangeGC. */
966 static void
967 XChangeGC (display, gc, mask, xgcv)
968 Display *display;
969 GC gc;
970 unsigned long mask;
971 XGCValues *xgcv;
973 if (mask & GCForeground)
974 XSetForeground (display, gc, xgcv->foreground);
975 if (mask & GCBackground)
976 XSetBackground (display, gc, xgcv->background);
977 if (mask & GCFont)
978 XSetFont (display, gc, xgcv->font);
982 /* Mac replacement for XCreateGC. */
985 XCreateGC (display, window, mask, xgcv)
986 Display *display;
987 Window window;
988 unsigned long mask;
989 XGCValues *xgcv;
991 GC gc = xmalloc (sizeof (*gc));
993 if (gc)
995 bzero (gc, sizeof (*gc));
996 XChangeGC (display, gc, mask, xgcv);
999 return gc;
1003 /* Used in xfaces.c. */
1005 void
1006 XFreeGC (display, gc)
1007 Display *display;
1008 GC gc;
1010 xfree (gc);
1014 /* Mac replacement for XGetGCValues. */
1016 static void
1017 XGetGCValues (display, gc, mask, xgcv)
1018 Display *display;
1019 GC gc;
1020 unsigned long mask;
1021 XGCValues *xgcv;
1023 if (mask & GCForeground)
1024 xgcv->foreground = gc->xgcv.foreground;
1025 if (mask & GCBackground)
1026 xgcv->background = gc->xgcv.background;
1027 if (mask & GCFont)
1028 xgcv->font = gc->xgcv.font;
1032 /* Mac replacement for XSetForeground. */
1034 void
1035 XSetForeground (display, gc, color)
1036 Display *display;
1037 GC gc;
1038 unsigned long color;
1040 if (gc->xgcv.foreground != color)
1042 gc->xgcv.foreground = color;
1043 gc->fore_color.red = RED16_FROM_ULONG (color);
1044 gc->fore_color.green = GREEN16_FROM_ULONG (color);
1045 gc->fore_color.blue = BLUE16_FROM_ULONG (color);
1050 /* Mac replacement for XSetBackground. */
1052 void
1053 XSetBackground (display, gc, color)
1054 Display *display;
1055 GC gc;
1056 unsigned long color;
1058 if (gc->xgcv.background != color)
1060 gc->xgcv.background = color;
1061 gc->back_color.red = RED16_FROM_ULONG (color);
1062 gc->back_color.green = GREEN16_FROM_ULONG (color);
1063 gc->back_color.blue = BLUE16_FROM_ULONG (color);
1068 /* Mac replacement for XSetFont. */
1070 static void
1071 XSetFont (display, gc, font)
1072 Display *display;
1073 GC gc;
1074 XFontStruct *font;
1076 gc->xgcv.font = font;
1080 /* Mac replacement for XSetWindowBackground. */
1082 void
1083 XSetWindowBackground (display, w, color)
1084 Display *display;
1085 WindowPtr w;
1086 unsigned long color;
1088 #if !TARGET_API_MAC_CARBON
1089 AuxWinHandle aw_handle;
1090 CTabHandle ctab_handle;
1091 ColorSpecPtr ct_table;
1092 short ct_size;
1093 #endif
1094 RGBColor bg_color;
1096 bg_color.red = RED16_FROM_ULONG (color);
1097 bg_color.green = GREEN16_FROM_ULONG (color);
1098 bg_color.blue = BLUE16_FROM_ULONG (color);
1100 #if TARGET_API_MAC_CARBON
1101 SetWindowContentColor (w, &bg_color);
1102 #else
1103 if (GetAuxWin (w, &aw_handle))
1105 ctab_handle = (*aw_handle)->awCTable;
1106 HandToHand ((Handle *) &ctab_handle);
1107 ct_table = (*ctab_handle)->ctTable;
1108 ct_size = (*ctab_handle)->ctSize;
1109 while (ct_size > -1)
1111 if (ct_table->value == 0)
1113 ct_table->rgb = bg_color;
1114 CTabChanged (ctab_handle);
1115 SetWinColor (w, (WCTabHandle) ctab_handle);
1117 ct_size--;
1120 #endif
1123 /* x_sync is a no-op on Mac. */
1124 void
1125 x_sync (f)
1126 void *f;
1131 /* Flush display of frame F, or of all frames if F is null. */
1133 static void
1134 x_flush (f)
1135 struct frame *f;
1137 #if TARGET_API_MAC_CARBON
1138 BLOCK_INPUT;
1139 if (f)
1140 QDFlushPortBuffer (GetWindowPort (FRAME_MAC_WINDOW (f)), NULL);
1141 else
1142 QDFlushPortBuffer (GetQDGlobalsThePort (), NULL);
1143 UNBLOCK_INPUT;
1144 #endif
1148 /* Remove calls to XFlush by defining XFlush to an empty replacement.
1149 Calls to XFlush should be unnecessary because the X output buffer
1150 is flushed automatically as needed by calls to XPending,
1151 XNextEvent, or XWindowEvent according to the XFlush man page.
1152 XTread_socket calls XPending. Removing XFlush improves
1153 performance. */
1155 #define XFlush(DISPLAY) (void) 0
1158 /* Return the struct mac_display_info corresponding to DPY. There's
1159 only one. */
1161 struct mac_display_info *
1162 mac_display_info_for_display (dpy)
1163 Display *dpy;
1165 return &one_mac_display_info;
1170 /***********************************************************************
1171 Starting and ending an update
1172 ***********************************************************************/
1174 /* Start an update of frame F. This function is installed as a hook
1175 for update_begin, i.e. it is called when update_begin is called.
1176 This function is called prior to calls to x_update_window_begin for
1177 each window being updated. */
1179 static void
1180 x_update_begin (f)
1181 struct frame *f;
1183 #if TARGET_API_MAC_CARBON
1184 /* During update of a frame, availability of input events is
1185 periodically checked with ReceiveNextEvent if
1186 redisplay-dont-pause is nil. That normally flushes window buffer
1187 changes for every check, and thus screen update looks waving even
1188 if no input is available. So we disable screen updates during
1189 update of a frame. */
1190 BLOCK_INPUT;
1191 DisableScreenUpdates ();
1192 UNBLOCK_INPUT;
1193 #endif
1197 /* Start update of window W. Set the global variable updated_window
1198 to the window being updated and set output_cursor to the cursor
1199 position of W. */
1201 static void
1202 x_update_window_begin (w)
1203 struct window *w;
1205 struct frame *f = XFRAME (WINDOW_FRAME (w));
1206 struct mac_display_info *display_info = FRAME_MAC_DISPLAY_INFO (f);
1208 updated_window = w;
1209 set_output_cursor (&w->cursor);
1211 BLOCK_INPUT;
1213 if (f == display_info->mouse_face_mouse_frame)
1215 /* Don't do highlighting for mouse motion during the update. */
1216 display_info->mouse_face_defer = 1;
1218 /* If F needs to be redrawn, simply forget about any prior mouse
1219 highlighting. */
1220 if (FRAME_GARBAGED_P (f))
1221 display_info->mouse_face_window = Qnil;
1223 #if 0 /* Rows in a current matrix containing glyphs in mouse-face have
1224 their mouse_face_p flag set, which means that they are always
1225 unequal to rows in a desired matrix which never have that
1226 flag set. So, rows containing mouse-face glyphs are never
1227 scrolled, and we don't have to switch the mouse highlight off
1228 here to prevent it from being scrolled. */
1230 /* Can we tell that this update does not affect the window
1231 where the mouse highlight is? If so, no need to turn off.
1232 Likewise, don't do anything if the frame is garbaged;
1233 in that case, the frame's current matrix that we would use
1234 is all wrong, and we will redisplay that line anyway. */
1235 if (!NILP (display_info->mouse_face_window)
1236 && w == XWINDOW (display_info->mouse_face_window))
1238 int i;
1240 for (i = 0; i < w->desired_matrix->nrows; ++i)
1241 if (MATRIX_ROW_ENABLED_P (w->desired_matrix, i))
1242 break;
1244 if (i < w->desired_matrix->nrows)
1245 clear_mouse_face (display_info);
1247 #endif /* 0 */
1250 UNBLOCK_INPUT;
1254 /* Draw a vertical window border from (x,y0) to (x,y1) */
1256 static void
1257 mac_draw_vertical_window_border (w, x, y0, y1)
1258 struct window *w;
1259 int x, y0, y1;
1261 struct frame *f = XFRAME (WINDOW_FRAME (w));
1262 struct face *face;
1264 face = FACE_FROM_ID (f, VERTICAL_BORDER_FACE_ID);
1265 if (face)
1266 XSetForeground (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
1267 face->foreground);
1269 XDrawLine (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
1270 f->output_data.mac->normal_gc, x, y0, x, y1);
1273 /* End update of window W (which is equal to updated_window).
1275 Draw vertical borders between horizontally adjacent windows, and
1276 display W's cursor if CURSOR_ON_P is non-zero.
1278 MOUSE_FACE_OVERWRITTEN_P non-zero means that some row containing
1279 glyphs in mouse-face were overwritten. In that case we have to
1280 make sure that the mouse-highlight is properly redrawn.
1282 W may be a menu bar pseudo-window in case we don't have X toolkit
1283 support. Such windows don't have a cursor, so don't display it
1284 here. */
1286 static void
1287 x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
1288 struct window *w;
1289 int cursor_on_p, mouse_face_overwritten_p;
1291 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (XFRAME (w->frame));
1293 if (!w->pseudo_window_p)
1295 BLOCK_INPUT;
1297 if (cursor_on_p)
1298 display_and_set_cursor (w, 1, output_cursor.hpos,
1299 output_cursor.vpos,
1300 output_cursor.x, output_cursor.y);
1302 if (draw_window_fringes (w, 1))
1303 x_draw_vertical_border (w);
1305 UNBLOCK_INPUT;
1308 /* If a row with mouse-face was overwritten, arrange for
1309 XTframe_up_to_date to redisplay the mouse highlight. */
1310 if (mouse_face_overwritten_p)
1312 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
1313 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
1314 dpyinfo->mouse_face_window = Qnil;
1317 updated_window = NULL;
1321 /* End update of frame F. This function is installed as a hook in
1322 update_end. */
1324 static void
1325 x_update_end (f)
1326 struct frame *f;
1328 /* Mouse highlight may be displayed again. */
1329 FRAME_MAC_DISPLAY_INFO (f)->mouse_face_defer = 0;
1331 BLOCK_INPUT;
1332 #if TARGET_API_MAC_CARBON
1333 EnableScreenUpdates ();
1334 #endif
1335 XFlush (FRAME_MAC_DISPLAY (f));
1336 UNBLOCK_INPUT;
1340 /* This function is called from various places in xdisp.c whenever a
1341 complete update has been performed. The global variable
1342 updated_window is not available here. */
1344 static void
1345 XTframe_up_to_date (f)
1346 struct frame *f;
1348 if (FRAME_MAC_P (f))
1350 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
1352 if (dpyinfo->mouse_face_deferred_gc
1353 || f == dpyinfo->mouse_face_mouse_frame)
1355 BLOCK_INPUT;
1356 if (dpyinfo->mouse_face_mouse_frame)
1357 note_mouse_highlight (dpyinfo->mouse_face_mouse_frame,
1358 dpyinfo->mouse_face_mouse_x,
1359 dpyinfo->mouse_face_mouse_y);
1360 dpyinfo->mouse_face_deferred_gc = 0;
1361 UNBLOCK_INPUT;
1367 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
1368 arrow bitmaps, or clear the fringes if no bitmaps are required
1369 before DESIRED_ROW is made current. The window being updated is
1370 found in updated_window. This function is called from
1371 update_window_line only if it is known that there are differences
1372 between bitmaps to be drawn between current row and DESIRED_ROW. */
1374 static void
1375 x_after_update_window_line (desired_row)
1376 struct glyph_row *desired_row;
1378 struct window *w = updated_window;
1379 struct frame *f;
1380 int width, height;
1382 xassert (w);
1384 if (!desired_row->mode_line_p && !w->pseudo_window_p)
1385 desired_row->redraw_fringe_bitmaps_p = 1;
1387 /* When a window has disappeared, make sure that no rest of
1388 full-width rows stays visible in the internal border. Could
1389 check here if updated_window is the leftmost/rightmost window,
1390 but I guess it's not worth doing since vertically split windows
1391 are almost never used, internal border is rarely set, and the
1392 overhead is very small. */
1393 if (windows_or_buffers_changed
1394 && desired_row->full_width_p
1395 && (f = XFRAME (w->frame),
1396 width = FRAME_INTERNAL_BORDER_WIDTH (f),
1397 width != 0)
1398 && (height = desired_row->visible_height,
1399 height > 0))
1401 int y = WINDOW_TO_FRAME_PIXEL_Y (w, max (0, desired_row->y));
1403 /* Internal border is drawn below the tool bar. */
1404 if (WINDOWP (f->tool_bar_window)
1405 && w == XWINDOW (f->tool_bar_window))
1406 y -= width;
1408 BLOCK_INPUT;
1409 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
1410 0, y, width, height, 0);
1411 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
1412 FRAME_PIXEL_WIDTH (f) - width, y,
1413 width, height, 0);
1414 UNBLOCK_INPUT;
1419 /* Draw the bitmap WHICH in one of the left or right fringes of
1420 window W. ROW is the glyph row for which to display the bitmap; it
1421 determines the vertical position at which the bitmap has to be
1422 drawn. */
1424 static void
1425 x_draw_fringe_bitmap (w, row, p)
1426 struct window *w;
1427 struct glyph_row *row;
1428 struct draw_fringe_bitmap_params *p;
1430 struct frame *f = XFRAME (WINDOW_FRAME (w));
1431 Display *display = FRAME_MAC_DISPLAY (f);
1432 WindowPtr window = FRAME_MAC_WINDOW (f);
1433 GC gc = f->output_data.mac->normal_gc;
1434 struct face *face = p->face;
1435 int rowY;
1437 /* Must clip because of partially visible lines. */
1438 rowY = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
1439 if (p->y < rowY)
1441 /* Adjust position of "bottom aligned" bitmap on partially
1442 visible last row. */
1443 int oldY = row->y;
1444 int oldVH = row->visible_height;
1445 row->visible_height = p->h;
1446 row->y -= rowY - p->y;
1447 x_clip_to_row (w, row, -1, gc);
1448 row->y = oldY;
1449 row->visible_height = oldVH;
1451 else
1452 x_clip_to_row (w, row, -1, gc);
1454 if (p->bx >= 0 && !p->overlay_p)
1456 #if 0 /* MAC_TODO: stipple */
1457 /* In case the same realized face is used for fringes and
1458 for something displayed in the text (e.g. face `region' on
1459 mono-displays, the fill style may have been changed to
1460 FillSolid in x_draw_glyph_string_background. */
1461 if (face->stipple)
1462 XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
1463 else
1464 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
1465 #endif
1467 mac_erase_rectangle (window, face->gc, p->bx, p->by, p->nx, p->ny);
1469 #if 0 /* MAC_TODO: stipple */
1470 if (!face->stipple)
1471 XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
1472 #endif
1475 if (p->which)
1477 unsigned short *bits = p->bits + p->dh;
1478 XGCValues gcv;
1480 XGetGCValues (display, face->gc, GCForeground, &gcv);
1481 XSetForeground (display, face->gc,
1482 (p->cursor_p
1483 ? (p->overlay_p ? face->background
1484 : f->output_data.mac->cursor_pixel)
1485 : face->foreground));
1486 mac_draw_bitmap (display, window, face->gc, p->x, p->y,
1487 p->wd, p->h, bits, p->overlay_p);
1488 XSetForeground (display, face->gc, gcv.foreground);
1491 mac_reset_clipping (display, window);
1496 /* This is called when starting Emacs and when restarting after
1497 suspend. When starting Emacs, no window is mapped. And nothing
1498 must be done to Emacs's own window if it is suspended (though that
1499 rarely happens). */
1501 static void
1502 XTset_terminal_modes ()
1506 /* This is called when exiting or suspending Emacs. Exiting will make
1507 the windows go away, and suspending requires no action. */
1509 static void
1510 XTreset_terminal_modes ()
1516 /***********************************************************************
1517 Display Iterator
1518 ***********************************************************************/
1520 /* Function prototypes of this page. */
1522 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
1523 static int mac_encode_char P_ ((int, XChar2b *, struct font_info *, int *));
1526 /* Return a pointer to per-char metric information in FONT of a
1527 character pointed by B which is a pointer to an XChar2b. */
1529 #define PER_CHAR_METRIC(font, b) \
1530 ((font)->per_char \
1531 ? ((font)->per_char + (b)->byte2 - (font)->min_char_or_byte2 \
1532 + (((font)->min_byte1 || (font)->max_byte1) \
1533 ? (((b)->byte1 - (font)->min_byte1) \
1534 * ((font)->max_char_or_byte2 - (font)->min_char_or_byte2 + 1)) \
1535 : 0)) \
1536 : &((font)->max_bounds))
1539 /* Get metrics of character CHAR2B in FONT. Value is null if CHAR2B
1540 is not contained in the font. */
1542 static INLINE XCharStruct *
1543 x_per_char_metric (font, char2b)
1544 XFontStruct *font;
1545 XChar2b *char2b;
1547 /* The result metric information. */
1548 XCharStruct *pcm = NULL;
1550 xassert (font && char2b);
1552 if (font->per_char != NULL)
1554 if (font->min_byte1 == 0 && font->max_byte1 == 0)
1556 /* min_char_or_byte2 specifies the linear character index
1557 corresponding to the first element of the per_char array,
1558 max_char_or_byte2 is the index of the last character. A
1559 character with non-zero CHAR2B->byte1 is not in the font.
1560 A character with byte2 less than min_char_or_byte2 or
1561 greater max_char_or_byte2 is not in the font. */
1562 if (char2b->byte1 == 0
1563 && char2b->byte2 >= font->min_char_or_byte2
1564 && char2b->byte2 <= font->max_char_or_byte2)
1565 pcm = font->per_char + char2b->byte2 - font->min_char_or_byte2;
1567 else
1569 /* If either min_byte1 or max_byte1 are nonzero, both
1570 min_char_or_byte2 and max_char_or_byte2 are less than
1571 256, and the 2-byte character index values corresponding
1572 to the per_char array element N (counting from 0) are:
1574 byte1 = N/D + min_byte1
1575 byte2 = N\D + min_char_or_byte2
1577 where:
1579 D = max_char_or_byte2 - min_char_or_byte2 + 1
1580 / = integer division
1581 \ = integer modulus */
1582 if (char2b->byte1 >= font->min_byte1
1583 && char2b->byte1 <= font->max_byte1
1584 && char2b->byte2 >= font->min_char_or_byte2
1585 && char2b->byte2 <= font->max_char_or_byte2)
1587 pcm = (font->per_char
1588 + ((font->max_char_or_byte2 - font->min_char_or_byte2 + 1)
1589 * (char2b->byte1 - font->min_byte1))
1590 + (char2b->byte2 - font->min_char_or_byte2));
1594 else
1596 /* If the per_char pointer is null, all glyphs between the first
1597 and last character indexes inclusive have the same
1598 information, as given by both min_bounds and max_bounds. */
1599 if (char2b->byte2 >= font->min_char_or_byte2
1600 && char2b->byte2 <= font->max_char_or_byte2)
1601 pcm = &font->max_bounds;
1604 return ((pcm == NULL
1605 || (pcm->width == 0 && (pcm->rbearing - pcm->lbearing) == 0))
1606 ? NULL : pcm);
1609 /* RIF:
1612 static XCharStruct *
1613 mac_per_char_metric (font, char2b, font_type)
1614 XFontStruct *font;
1615 XChar2b *char2b;
1616 int font_type;
1618 return x_per_char_metric (font, char2b);
1621 /* RIF:
1622 Encode CHAR2B using encoding information from FONT_INFO. CHAR2B is
1623 the two-byte form of C. Encoding is returned in *CHAR2B. */
1625 static int
1626 mac_encode_char (c, char2b, font_info, two_byte_p)
1627 int c;
1628 XChar2b *char2b;
1629 struct font_info *font_info;
1630 int *two_byte_p;
1632 int charset = CHAR_CHARSET (c);
1633 XFontStruct *font = font_info->font;
1635 /* FONT_INFO may define a scheme by which to encode byte1 and byte2.
1636 This may be either a program in a special encoder language or a
1637 fixed encoding. */
1638 if (font_info->font_encoder)
1640 /* It's a program. */
1641 struct ccl_program *ccl = font_info->font_encoder;
1643 check_ccl_update (ccl);
1644 if (CHARSET_DIMENSION (charset) == 1)
1646 ccl->reg[0] = charset;
1647 ccl->reg[1] = char2b->byte2;
1648 ccl->reg[2] = -1;
1650 else
1652 ccl->reg[0] = charset;
1653 ccl->reg[1] = char2b->byte1;
1654 ccl->reg[2] = char2b->byte2;
1657 ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
1659 /* We assume that MSBs are appropriately set/reset by CCL
1660 program. */
1661 if (font->max_byte1 == 0) /* 1-byte font */
1662 char2b->byte1 = 0, char2b->byte2 = ccl->reg[1];
1663 else
1664 char2b->byte1 = ccl->reg[1], char2b->byte2 = ccl->reg[2];
1666 else if (font_info->encoding[charset])
1668 /* Fixed encoding scheme. See fontset.h for the meaning of the
1669 encoding numbers. */
1670 int enc = font_info->encoding[charset];
1672 if ((enc == 1 || enc == 2)
1673 && CHARSET_DIMENSION (charset) == 2)
1674 char2b->byte1 |= 0x80;
1676 if (enc == 1 || enc == 3)
1677 char2b->byte2 |= 0x80;
1679 if (enc == 4)
1681 int sjis1, sjis2;
1683 ENCODE_SJIS (char2b->byte1, char2b->byte2, sjis1, sjis2);
1684 char2b->byte1 = sjis1;
1685 char2b->byte2 = sjis2;
1689 if (two_byte_p)
1690 *two_byte_p = ((XFontStruct *) (font_info->font))->max_byte1 > 0;
1692 return FONT_TYPE_UNKNOWN;
1697 /***********************************************************************
1698 Glyph display
1699 ***********************************************************************/
1703 static void x_set_glyph_string_clipping P_ ((struct glyph_string *));
1704 static void x_set_glyph_string_gc P_ ((struct glyph_string *));
1705 static void x_draw_glyph_string_background P_ ((struct glyph_string *,
1706 int));
1707 static void x_draw_glyph_string_foreground P_ ((struct glyph_string *));
1708 static void x_draw_composite_glyph_string_foreground P_ ((struct glyph_string *));
1709 static void x_draw_glyph_string_box P_ ((struct glyph_string *));
1710 static void x_draw_glyph_string P_ ((struct glyph_string *));
1711 static void mac_compute_glyph_string_overhangs P_ ((struct glyph_string *));
1712 static void x_set_cursor_gc P_ ((struct glyph_string *));
1713 static void x_set_mode_line_face_gc P_ ((struct glyph_string *));
1714 static void x_set_mouse_face_gc P_ ((struct glyph_string *));
1715 /*static int x_alloc_lighter_color P_ ((struct frame *, Display *, Colormap,
1716 unsigned long *, double, int));*/
1717 static void x_setup_relief_color P_ ((struct frame *, struct relief *,
1718 double, int, unsigned long));
1719 static void x_setup_relief_colors P_ ((struct glyph_string *));
1720 static void x_draw_image_glyph_string P_ ((struct glyph_string *));
1721 static void x_draw_image_relief P_ ((struct glyph_string *));
1722 static void x_draw_image_foreground P_ ((struct glyph_string *));
1723 static void x_draw_image_foreground_1 P_ ((struct glyph_string *, Pixmap));
1724 static void x_clear_glyph_string_rect P_ ((struct glyph_string *, int,
1725 int, int, int));
1726 static void x_draw_relief_rect P_ ((struct frame *, int, int, int, int,
1727 int, int, int, int, int, int,
1728 Rect *));
1729 static void x_draw_box_rect P_ ((struct glyph_string *, int, int, int, int,
1730 int, int, int, Rect *));
1732 #if GLYPH_DEBUG
1733 static void x_check_font P_ ((struct frame *, XFontStruct *));
1734 #endif
1737 /* Set S->gc to a suitable GC for drawing glyph string S in cursor
1738 face. */
1740 static void
1741 x_set_cursor_gc (s)
1742 struct glyph_string *s;
1744 if (s->font == FRAME_FONT (s->f)
1745 && s->face->background == FRAME_BACKGROUND_PIXEL (s->f)
1746 && s->face->foreground == FRAME_FOREGROUND_PIXEL (s->f)
1747 && !s->cmp)
1748 s->gc = s->f->output_data.mac->cursor_gc;
1749 else
1751 /* Cursor on non-default face: must merge. */
1752 XGCValues xgcv;
1753 unsigned long mask;
1755 xgcv.background = s->f->output_data.mac->cursor_pixel;
1756 xgcv.foreground = s->face->background;
1758 /* If the glyph would be invisible, try a different foreground. */
1759 if (xgcv.foreground == xgcv.background)
1760 xgcv.foreground = s->face->foreground;
1761 if (xgcv.foreground == xgcv.background)
1762 xgcv.foreground = s->f->output_data.mac->cursor_foreground_pixel;
1763 if (xgcv.foreground == xgcv.background)
1764 xgcv.foreground = s->face->foreground;
1766 /* Make sure the cursor is distinct from text in this face. */
1767 if (xgcv.background == s->face->background
1768 && xgcv.foreground == s->face->foreground)
1770 xgcv.background = s->face->foreground;
1771 xgcv.foreground = s->face->background;
1774 IF_DEBUG (x_check_font (s->f, s->font));
1775 xgcv.font = s->font;
1776 mask = GCForeground | GCBackground | GCFont;
1778 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1779 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1780 mask, &xgcv);
1781 else
1782 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
1783 = XCreateGC (s->display, s->window, mask, &xgcv);
1785 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1790 /* Set up S->gc of glyph string S for drawing text in mouse face. */
1792 static void
1793 x_set_mouse_face_gc (s)
1794 struct glyph_string *s;
1796 int face_id;
1797 struct face *face;
1799 /* What face has to be used last for the mouse face? */
1800 face_id = FRAME_X_DISPLAY_INFO (s->f)->mouse_face_face_id;
1801 face = FACE_FROM_ID (s->f, face_id);
1802 if (face == NULL)
1803 face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
1805 if (s->first_glyph->type == CHAR_GLYPH)
1806 face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
1807 else
1808 face_id = FACE_FOR_CHAR (s->f, face, 0);
1809 s->face = FACE_FROM_ID (s->f, face_id);
1810 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1812 /* If font in this face is same as S->font, use it. */
1813 if (s->font == s->face->font)
1814 s->gc = s->face->gc;
1815 else
1817 /* Otherwise construct scratch_cursor_gc with values from FACE
1818 but font FONT. */
1819 XGCValues xgcv;
1820 unsigned long mask;
1822 xgcv.background = s->face->background;
1823 xgcv.foreground = s->face->foreground;
1824 IF_DEBUG (x_check_font (s->f, s->font));
1825 xgcv.font = s->font;
1826 mask = GCForeground | GCBackground | GCFont;
1828 if (FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc)
1829 XChangeGC (s->display, FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc,
1830 mask, &xgcv);
1831 else
1832 FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc
1833 = XCreateGC (s->display, s->window, mask, &xgcv);
1835 s->gc = FRAME_MAC_DISPLAY_INFO (s->f)->scratch_cursor_gc;
1838 xassert (s->gc != 0);
1842 /* Set S->gc of glyph string S to a GC suitable for drawing a mode line.
1843 Faces to use in the mode line have already been computed when the
1844 matrix was built, so there isn't much to do, here. */
1846 static INLINE void
1847 x_set_mode_line_face_gc (s)
1848 struct glyph_string *s;
1850 s->gc = s->face->gc;
1854 /* Set S->gc of glyph string S for drawing that glyph string. Set
1855 S->stippled_p to a non-zero value if the face of S has a stipple
1856 pattern. */
1858 static INLINE void
1859 x_set_glyph_string_gc (s)
1860 struct glyph_string *s;
1862 PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
1864 if (s->hl == DRAW_NORMAL_TEXT)
1866 s->gc = s->face->gc;
1867 s->stippled_p = s->face->stipple != 0;
1869 else if (s->hl == DRAW_INVERSE_VIDEO)
1871 x_set_mode_line_face_gc (s);
1872 s->stippled_p = s->face->stipple != 0;
1874 else if (s->hl == DRAW_CURSOR)
1876 x_set_cursor_gc (s);
1877 s->stippled_p = 0;
1879 else if (s->hl == DRAW_MOUSE_FACE)
1881 x_set_mouse_face_gc (s);
1882 s->stippled_p = s->face->stipple != 0;
1884 else if (s->hl == DRAW_IMAGE_RAISED
1885 || s->hl == DRAW_IMAGE_SUNKEN)
1887 s->gc = s->face->gc;
1888 s->stippled_p = s->face->stipple != 0;
1890 else
1892 s->gc = s->face->gc;
1893 s->stippled_p = s->face->stipple != 0;
1896 /* GC must have been set. */
1897 xassert (s->gc != 0);
1901 /* Set clipping for output of glyph string S. S may be part of a mode
1902 line or menu if we don't have X toolkit support. */
1904 static INLINE void
1905 x_set_glyph_string_clipping (s)
1906 struct glyph_string *s;
1908 Rect r;
1909 get_glyph_string_clip_rect (s, &r);
1910 mac_set_clip_rectangle (s->display, s->window, &r);
1914 /* RIF:
1915 Compute left and right overhang of glyph string S. If S is a glyph
1916 string for a composition, assume overhangs don't exist. */
1918 static void
1919 mac_compute_glyph_string_overhangs (s)
1920 struct glyph_string *s;
1922 if (s->cmp == NULL
1923 && s->first_glyph->type == CHAR_GLYPH)
1925 Rect r;
1926 MacFontStruct *font = s->font;
1928 TextFont (font->mac_fontnum);
1929 TextSize (font->mac_fontsize);
1930 TextFace (font->mac_fontface);
1932 if (s->two_byte_p)
1933 QDTextBounds (s->nchars * 2, (char *)s->char2b, &r);
1934 else
1936 int i;
1937 char *buf = xmalloc (s->nchars);
1939 if (buf == NULL)
1940 SetRect (&r, 0, 0, 0, 0);
1941 else
1943 for (i = 0; i < s->nchars; ++i)
1944 buf[i] = s->char2b[i].byte2;
1945 QDTextBounds (s->nchars, buf, &r);
1946 xfree (buf);
1950 s->right_overhang = r.right > s->width ? r.right - s->width : 0;
1951 s->left_overhang = r.left < 0 ? -r.left : 0;
1956 /* Fill rectangle X, Y, W, H with background color of glyph string S. */
1958 static INLINE void
1959 x_clear_glyph_string_rect (s, x, y, w, h)
1960 struct glyph_string *s;
1961 int x, y, w, h;
1963 mac_erase_rectangle (s->window, s->gc, x, y, w, h);
1967 /* We prefer not to use XDrawImageString (srcCopy text transfer mode)
1968 on Mac OS X because:
1969 - Screen is double-buffered. (In srcCopy mode, a text is drawn
1970 into an offscreen graphics world first. So performance gain
1971 cannot be expected.)
1972 - It lowers rendering quality.
1973 - Some fonts leave garbage on cursor movement. */
1975 /* Draw the background of glyph_string S. If S->background_filled_p
1976 is non-zero don't draw it. FORCE_P non-zero means draw the
1977 background even if it wouldn't be drawn normally. This is used
1978 when a string preceding S draws into the background of S, or S
1979 contains the first component of a composition. */
1981 static void
1982 x_draw_glyph_string_background (s, force_p)
1983 struct glyph_string *s;
1984 int force_p;
1986 /* Nothing to do if background has already been drawn or if it
1987 shouldn't be drawn in the first place. */
1988 if (!s->background_filled_p)
1990 int box_line_width = max (s->face->box_line_width, 0);
1992 #if 0 /* MAC_TODO: stipple */
1993 if (s->stippled_p)
1995 /* Fill background with a stipple pattern. */
1996 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
1997 XFillRectangle (s->display, s->window, s->gc, s->x,
1998 s->y + box_line_width,
1999 s->background_width,
2000 s->height - 2 * box_line_width);
2001 XSetFillStyle (s->display, s->gc, FillSolid);
2002 s->background_filled_p = 1;
2004 else
2005 #endif
2006 #ifdef MAC_OS8
2007 if (FONT_HEIGHT (s->font) < s->height - 2 * box_line_width
2008 || s->font_not_found_p
2009 || s->extends_to_end_of_line_p
2010 || force_p)
2011 #endif
2013 x_clear_glyph_string_rect (s, s->x, s->y + box_line_width,
2014 s->background_width,
2015 s->height - 2 * box_line_width);
2016 s->background_filled_p = 1;
2022 /* Draw the foreground of glyph string S. */
2024 static void
2025 x_draw_glyph_string_foreground (s)
2026 struct glyph_string *s;
2028 int i, x;
2030 /* If first glyph of S has a left box line, start drawing the text
2031 of S to the right of that box line. */
2032 if (s->face->box != FACE_NO_BOX
2033 && s->first_glyph->left_box_line_p)
2034 x = s->x + abs (s->face->box_line_width);
2035 else
2036 x = s->x;
2038 /* Draw characters of S as rectangles if S's font could not be
2039 loaded. */
2040 if (s->font_not_found_p)
2042 for (i = 0; i < s->nchars; ++i)
2044 struct glyph *g = s->first_glyph + i;
2045 mac_draw_rectangle (s->display, s->window,
2046 s->gc, x, s->y, g->pixel_width - 1,
2047 s->height - 1);
2048 x += g->pixel_width;
2051 else
2053 char *char1b = (char *) s->char2b;
2054 int boff = s->font_info->baseline_offset;
2056 if (s->font_info->vertical_centering)
2057 boff = VCENTER_BASELINE_OFFSET (s->font, s->f) - boff;
2059 /* If we can use 8-bit functions, condense S->char2b. */
2060 if (!s->two_byte_p)
2061 for (i = 0; i < s->nchars; ++i)
2062 char1b[i] = s->char2b[i].byte2;
2064 #ifdef MAC_OS8
2065 /* Draw text with XDrawString if background has already been
2066 filled. Otherwise, use XDrawImageString. (Note that
2067 XDrawImageString is usually faster than XDrawString.) Always
2068 use XDrawImageString when drawing the cursor so that there is
2069 no chance that characters under a box cursor are invisible. */
2070 if (s->for_overlaps_p
2071 || (s->background_filled_p && s->hl != DRAW_CURSOR))
2072 #endif
2074 /* Draw characters with 16-bit or 8-bit functions. */
2075 if (s->two_byte_p)
2076 XDrawString16 (s->display, s->window, s->gc, x,
2077 s->ybase - boff, s->char2b, s->nchars);
2078 else
2079 XDrawString (s->display, s->window, s->gc, x,
2080 s->ybase - boff, char1b, s->nchars);
2082 #ifdef MAC_OS8
2083 else
2085 if (s->two_byte_p)
2086 XDrawImageString16 (s->display, s->window, s->gc, x,
2087 s->ybase - boff, s->char2b, s->nchars);
2088 else
2089 XDrawImageString (s->display, s->window, s->gc, x,
2090 s->ybase - boff, char1b, s->nchars);
2092 #endif
2096 /* Draw the foreground of composite glyph string S. */
2098 static void
2099 x_draw_composite_glyph_string_foreground (s)
2100 struct glyph_string *s;
2102 int i, x;
2104 /* If first glyph of S has a left box line, start drawing the text
2105 of S to the right of that box line. */
2106 if (s->face->box != FACE_NO_BOX
2107 && s->first_glyph->left_box_line_p)
2108 x = s->x + abs (s->face->box_line_width);
2109 else
2110 x = s->x;
2112 /* S is a glyph string for a composition. S->gidx is the index of
2113 the first character drawn for glyphs of this composition.
2114 S->gidx == 0 means we are drawing the very first character of
2115 this composition. */
2117 /* Draw a rectangle for the composition if the font for the very
2118 first character of the composition could not be loaded. */
2119 if (s->font_not_found_p)
2121 if (s->gidx == 0)
2122 mac_draw_rectangle (s->display, s->window, s->gc, x, s->y,
2123 s->width - 1, s->height - 1);
2125 else
2127 for (i = 0; i < s->nchars; i++, ++s->gidx)
2128 XDrawString16 (s->display, s->window, s->gc,
2129 x + s->cmp->offsets[s->gidx * 2],
2130 s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
2131 s->char2b + i, 1);
2136 #ifdef USE_X_TOOLKIT
2138 static struct frame *x_frame_of_widget P_ ((Widget));
2141 /* Return the frame on which widget WIDGET is used.. Abort if frame
2142 cannot be determined. */
2144 static struct frame *
2145 x_frame_of_widget (widget)
2146 Widget widget;
2148 struct x_display_info *dpyinfo;
2149 Lisp_Object tail;
2150 struct frame *f;
2152 dpyinfo = x_display_info_for_display (XtDisplay (widget));
2154 /* Find the top-level shell of the widget. Note that this function
2155 can be called when the widget is not yet realized, so XtWindow
2156 (widget) == 0. That's the reason we can't simply use
2157 x_any_window_to_frame. */
2158 while (!XtIsTopLevelShell (widget))
2159 widget = XtParent (widget);
2161 /* Look for a frame with that top-level widget. Allocate the color
2162 on that frame to get the right gamma correction value. */
2163 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
2164 if (GC_FRAMEP (XCAR (tail))
2165 && (f = XFRAME (XCAR (tail)),
2166 (f->output_data.nothing != 1
2167 && FRAME_X_DISPLAY_INFO (f) == dpyinfo))
2168 && f->output_data.x->widget == widget)
2169 return f;
2171 abort ();
2175 /* Allocate the color COLOR->pixel on the screen and display of
2176 widget WIDGET in colormap CMAP. If an exact match cannot be
2177 allocated, try the nearest color available. Value is non-zero
2178 if successful. This is called from lwlib. */
2181 x_alloc_nearest_color_for_widget (widget, cmap, color)
2182 Widget widget;
2183 Colormap cmap;
2184 XColor *color;
2186 struct frame *f = x_frame_of_widget (widget);
2187 return x_alloc_nearest_color (f, cmap, color);
2191 #endif /* USE_X_TOOLKIT */
2193 #if 0 /* MAC_TODO */
2195 /* Allocate the color COLOR->pixel on SCREEN of DISPLAY, colormap
2196 CMAP. If an exact match can't be allocated, try the nearest color
2197 available. Value is non-zero if successful. Set *COLOR to the
2198 color allocated. */
2201 x_alloc_nearest_color (f, cmap, color)
2202 struct frame *f;
2203 Colormap cmap;
2204 XColor *color;
2206 Display *display = FRAME_X_DISPLAY (f);
2207 Screen *screen = FRAME_X_SCREEN (f);
2208 int rc;
2210 gamma_correct (f, color);
2211 rc = XAllocColor (display, cmap, color);
2212 if (rc == 0)
2214 /* If we got to this point, the colormap is full, so we're going
2215 to try to get the next closest color. The algorithm used is
2216 a least-squares matching, which is what X uses for closest
2217 color matching with StaticColor visuals. */
2218 int nearest, i;
2219 unsigned long nearest_delta = ~0;
2220 int ncells = XDisplayCells (display, XScreenNumberOfScreen (screen));
2221 XColor *cells = (XColor *) alloca (ncells * sizeof *cells);
2223 for (i = 0; i < ncells; ++i)
2224 cells[i].pixel = i;
2225 XQueryColors (display, cmap, cells, ncells);
2227 for (nearest = i = 0; i < ncells; ++i)
2229 long dred = (color->red >> 8) - (cells[i].red >> 8);
2230 long dgreen = (color->green >> 8) - (cells[i].green >> 8);
2231 long dblue = (color->blue >> 8) - (cells[i].blue >> 8);
2232 unsigned long delta = dred * dred + dgreen * dgreen + dblue * dblue;
2234 if (delta < nearest_delta)
2236 nearest = i;
2237 nearest_delta = delta;
2241 color->red = cells[nearest].red;
2242 color->green = cells[nearest].green;
2243 color->blue = cells[nearest].blue;
2244 rc = XAllocColor (display, cmap, color);
2247 #ifdef DEBUG_X_COLORS
2248 if (rc)
2249 register_color (color->pixel);
2250 #endif /* DEBUG_X_COLORS */
2252 return rc;
2256 /* Allocate color PIXEL on frame F. PIXEL must already be allocated.
2257 It's necessary to do this instead of just using PIXEL directly to
2258 get color reference counts right. */
2260 unsigned long
2261 x_copy_color (f, pixel)
2262 struct frame *f;
2263 unsigned long pixel;
2265 XColor color;
2267 color.pixel = pixel;
2268 BLOCK_INPUT;
2269 XQueryColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2270 XAllocColor (FRAME_X_DISPLAY (f), FRAME_X_COLORMAP (f), &color);
2271 UNBLOCK_INPUT;
2272 #ifdef DEBUG_X_COLORS
2273 register_color (pixel);
2274 #endif
2275 return color.pixel;
2279 /* Allocate color PIXEL on display DPY. PIXEL must already be allocated.
2280 It's necessary to do this instead of just using PIXEL directly to
2281 get color reference counts right. */
2283 unsigned long
2284 x_copy_dpy_color (dpy, cmap, pixel)
2285 Display *dpy;
2286 Colormap cmap;
2287 unsigned long pixel;
2289 XColor color;
2291 color.pixel = pixel;
2292 BLOCK_INPUT;
2293 XQueryColor (dpy, cmap, &color);
2294 XAllocColor (dpy, cmap, &color);
2295 UNBLOCK_INPUT;
2296 #ifdef DEBUG_X_COLORS
2297 register_color (pixel);
2298 #endif
2299 return color.pixel;
2302 #endif /* MAC_TODO */
2305 /* Brightness beyond which a color won't have its highlight brightness
2306 boosted.
2308 Nominally, highlight colors for `3d' faces are calculated by
2309 brightening an object's color by a constant scale factor, but this
2310 doesn't yield good results for dark colors, so for colors who's
2311 brightness is less than this value (on a scale of 0-255) have to
2312 use an additional additive factor.
2314 The value here is set so that the default menu-bar/mode-line color
2315 (grey75) will not have its highlights changed at all. */
2316 #define HIGHLIGHT_COLOR_DARK_BOOST_LIMIT 187
2319 /* Allocate a color which is lighter or darker than *COLOR by FACTOR
2320 or DELTA. Try a color with RGB values multiplied by FACTOR first.
2321 If this produces the same color as COLOR, try a color where all RGB
2322 values have DELTA added. Return the allocated color in *COLOR.
2323 DISPLAY is the X display, CMAP is the colormap to operate on.
2324 Value is non-zero if successful. */
2326 static int
2327 mac_alloc_lighter_color (f, color, factor, delta)
2328 struct frame *f;
2329 unsigned long *color;
2330 double factor;
2331 int delta;
2333 unsigned long new;
2334 long bright;
2336 /* On Mac, RGB values are 0-255, not 0-65535, so scale delta. */
2337 delta /= 256;
2339 /* Change RGB values by specified FACTOR. Avoid overflow! */
2340 xassert (factor >= 0);
2341 new = RGB_TO_ULONG (min (0xff, (int) (factor * RED_FROM_ULONG (*color))),
2342 min (0xff, (int) (factor * GREEN_FROM_ULONG (*color))),
2343 min (0xff, (int) (factor * BLUE_FROM_ULONG (*color))));
2345 /* Calculate brightness of COLOR. */
2346 bright = (2 * RED_FROM_ULONG (*color) + 3 * GREEN_FROM_ULONG (*color)
2347 + BLUE_FROM_ULONG (*color)) / 6;
2349 /* We only boost colors that are darker than
2350 HIGHLIGHT_COLOR_DARK_BOOST_LIMIT. */
2351 if (bright < HIGHLIGHT_COLOR_DARK_BOOST_LIMIT)
2352 /* Make an additive adjustment to NEW, because it's dark enough so
2353 that scaling by FACTOR alone isn't enough. */
2355 /* How far below the limit this color is (0 - 1, 1 being darker). */
2356 double dimness = 1 - (double)bright / HIGHLIGHT_COLOR_DARK_BOOST_LIMIT;
2357 /* The additive adjustment. */
2358 int min_delta = delta * dimness * factor / 2;
2360 if (factor < 1)
2361 new = RGB_TO_ULONG (max (0, min (0xff, (int) (RED_FROM_ULONG (*color)) - min_delta)),
2362 max (0, min (0xff, (int) (GREEN_FROM_ULONG (*color)) - min_delta)),
2363 max (0, min (0xff, (int) (BLUE_FROM_ULONG (*color)) - min_delta)));
2364 else
2365 new = RGB_TO_ULONG (max (0, min (0xff, (int) (min_delta + RED_FROM_ULONG (*color)))),
2366 max (0, min (0xff, (int) (min_delta + GREEN_FROM_ULONG (*color)))),
2367 max (0, min (0xff, (int) (min_delta + BLUE_FROM_ULONG (*color)))));
2370 if (new == *color)
2371 new = RGB_TO_ULONG (max (0, min (0xff, (int) (delta + RED_FROM_ULONG (*color)))),
2372 max (0, min (0xff, (int) (delta + GREEN_FROM_ULONG (*color)))),
2373 max (0, min (0xff, (int) (delta + BLUE_FROM_ULONG (*color)))));
2375 /* MAC_TODO: Map to palette and retry with delta if same? */
2376 /* MAC_TODO: Free colors (if using palette)? */
2378 if (new == *color)
2379 return 0;
2381 *color = new;
2383 return 1;
2387 /* Set up the foreground color for drawing relief lines of glyph
2388 string S. RELIEF is a pointer to a struct relief containing the GC
2389 with which lines will be drawn. Use a color that is FACTOR or
2390 DELTA lighter or darker than the relief's background which is found
2391 in S->f->output_data.x->relief_background. If such a color cannot
2392 be allocated, use DEFAULT_PIXEL, instead. */
2394 static void
2395 x_setup_relief_color (f, relief, factor, delta, default_pixel)
2396 struct frame *f;
2397 struct relief *relief;
2398 double factor;
2399 int delta;
2400 unsigned long default_pixel;
2402 XGCValues xgcv;
2403 struct mac_output *di = f->output_data.mac;
2404 unsigned long mask = GCForeground;
2405 unsigned long pixel;
2406 unsigned long background = di->relief_background;
2407 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
2409 /* MAC_TODO: Free colors (if using palette)? */
2411 /* Allocate new color. */
2412 xgcv.foreground = default_pixel;
2413 pixel = background;
2414 if (dpyinfo->n_planes != 1
2415 && mac_alloc_lighter_color (f, &pixel, factor, delta))
2417 relief->allocated_p = 1;
2418 xgcv.foreground = relief->pixel = pixel;
2421 if (relief->gc == 0)
2423 #if 0 /* MAC_TODO: stipple */
2424 xgcv.stipple = dpyinfo->gray;
2425 mask |= GCStipple;
2426 #endif
2427 relief->gc = XCreateGC (NULL, FRAME_MAC_WINDOW (f), mask, &xgcv);
2429 else
2430 XChangeGC (NULL, relief->gc, mask, &xgcv);
2434 /* Set up colors for the relief lines around glyph string S. */
2436 static void
2437 x_setup_relief_colors (s)
2438 struct glyph_string *s;
2440 struct mac_output *di = s->f->output_data.mac;
2441 unsigned long color;
2443 if (s->face->use_box_color_for_shadows_p)
2444 color = s->face->box_color;
2445 else if (s->first_glyph->type == IMAGE_GLYPH
2446 && s->img->pixmap
2447 && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
2448 color = IMAGE_BACKGROUND (s->img, s->f, 0);
2449 else
2451 XGCValues xgcv;
2453 /* Get the background color of the face. */
2454 XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
2455 color = xgcv.background;
2458 if (di->white_relief.gc == 0
2459 || color != di->relief_background)
2461 di->relief_background = color;
2462 x_setup_relief_color (s->f, &di->white_relief, 1.2, 0x8000,
2463 WHITE_PIX_DEFAULT (s->f));
2464 x_setup_relief_color (s->f, &di->black_relief, 0.6, 0x4000,
2465 BLACK_PIX_DEFAULT (s->f));
2470 /* Draw a relief on frame F inside the rectangle given by LEFT_X,
2471 TOP_Y, RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the relief
2472 to draw, it must be >= 0. RAISED_P non-zero means draw a raised
2473 relief. LEFT_P non-zero means draw a relief on the left side of
2474 the rectangle. RIGHT_P non-zero means draw a relief on the right
2475 side of the rectangle. CLIP_RECT is the clipping rectangle to use
2476 when drawing. */
2478 static void
2479 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
2480 raised_p, top_p, bot_p, left_p, right_p, clip_rect)
2481 struct frame *f;
2482 int left_x, top_y, right_x, bottom_y, width;
2483 int top_p, bot_p, left_p, right_p, raised_p;
2484 Rect *clip_rect;
2486 Display *dpy = FRAME_MAC_DISPLAY (f);
2487 Window window = FRAME_MAC_WINDOW (f);
2488 int i;
2489 GC gc;
2491 if (raised_p)
2492 gc = f->output_data.mac->white_relief.gc;
2493 else
2494 gc = f->output_data.mac->black_relief.gc;
2495 mac_set_clip_rectangle (dpy, window, clip_rect);
2497 /* Top. */
2498 if (top_p)
2499 for (i = 0; i < width; ++i)
2500 XDrawLine (dpy, window, gc,
2501 left_x + i * left_p, top_y + i,
2502 right_x - i * right_p, top_y + i);
2504 /* Left. */
2505 if (left_p)
2506 for (i = 0; i < width; ++i)
2507 XDrawLine (dpy, window, gc,
2508 left_x + i, top_y + i, left_x + i, bottom_y - i);
2510 mac_reset_clipping (dpy, window);
2511 if (raised_p)
2512 gc = f->output_data.mac->black_relief.gc;
2513 else
2514 gc = f->output_data.mac->white_relief.gc;
2515 mac_set_clip_rectangle (dpy, window,
2516 clip_rect);
2518 /* Bottom. */
2519 if (bot_p)
2520 for (i = 0; i < width; ++i)
2521 XDrawLine (dpy, window, gc,
2522 left_x + i * left_p, bottom_y - i,
2523 right_x - i * right_p, bottom_y - i);
2525 /* Right. */
2526 if (right_p)
2527 for (i = 0; i < width; ++i)
2528 XDrawLine (dpy, window, gc,
2529 right_x - i, top_y + i + 1, right_x - i, bottom_y - i - 1);
2531 mac_reset_clipping (dpy, window);
2535 /* Draw a box on frame F inside the rectangle given by LEFT_X, TOP_Y,
2536 RIGHT_X, and BOTTOM_Y. WIDTH is the thickness of the lines to
2537 draw, it must be >= 0. LEFT_P non-zero means draw a line on the
2538 left side of the rectangle. RIGHT_P non-zero means draw a line
2539 on the right side of the rectangle. CLIP_RECT is the clipping
2540 rectangle to use when drawing. */
2542 static void
2543 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2544 left_p, right_p, clip_rect)
2545 struct glyph_string *s;
2546 int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
2547 Rect *clip_rect;
2549 XGCValues xgcv;
2551 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
2552 XSetForeground (s->display, s->gc, s->face->box_color);
2553 mac_set_clip_rectangle (s->display, s->window, clip_rect);
2555 /* Top. */
2556 XFillRectangle (s->display, s->window, s->gc,
2557 left_x, top_y, right_x - left_x + 1, width);
2559 /* Left. */
2560 if (left_p)
2561 XFillRectangle (s->display, s->window, s->gc,
2562 left_x, top_y, width, bottom_y - top_y + 1);
2564 /* Bottom. */
2565 XFillRectangle (s->display, s->window, s->gc,
2566 left_x, bottom_y - width + 1, right_x - left_x + 1, width);
2568 /* Right. */
2569 if (right_p)
2570 XFillRectangle (s->display, s->window, s->gc,
2571 right_x - width + 1, top_y, width, bottom_y - top_y + 1);
2573 XSetForeground (s->display, s->gc, xgcv.foreground);
2574 mac_reset_clipping (s->display, s->window);
2578 /* Draw a box around glyph string S. */
2580 static void
2581 x_draw_glyph_string_box (s)
2582 struct glyph_string *s;
2584 int width, left_x, right_x, top_y, bottom_y, last_x, raised_p;
2585 int left_p, right_p;
2586 struct glyph *last_glyph;
2587 Rect clip_rect;
2589 last_x = ((s->row->full_width_p && !s->w->pseudo_window_p)
2590 ? WINDOW_RIGHT_EDGE_X (s->w)
2591 : window_box_right (s->w, s->area));
2593 /* The glyph that may have a right box line. */
2594 last_glyph = (s->cmp || s->img
2595 ? s->first_glyph
2596 : s->first_glyph + s->nchars - 1);
2598 width = abs (s->face->box_line_width);
2599 raised_p = s->face->box == FACE_RAISED_BOX;
2600 left_x = s->x;
2601 right_x = (s->row->full_width_p && s->extends_to_end_of_line_p
2602 ? last_x - 1
2603 : min (last_x, s->x + s->background_width) - 1);
2604 top_y = s->y;
2605 bottom_y = top_y + s->height - 1;
2607 left_p = (s->first_glyph->left_box_line_p
2608 || (s->hl == DRAW_MOUSE_FACE
2609 && (s->prev == NULL
2610 || s->prev->hl != s->hl)));
2611 right_p = (last_glyph->right_box_line_p
2612 || (s->hl == DRAW_MOUSE_FACE
2613 && (s->next == NULL
2614 || s->next->hl != s->hl)));
2616 get_glyph_string_clip_rect (s, &clip_rect);
2618 if (s->face->box == FACE_SIMPLE_BOX)
2619 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
2620 left_p, right_p, &clip_rect);
2621 else
2623 x_setup_relief_colors (s);
2624 x_draw_relief_rect (s->f, left_x, top_y, right_x, bottom_y,
2625 width, raised_p, 1, 1, left_p, right_p, &clip_rect);
2630 /* Draw foreground of image glyph string S. */
2632 static void
2633 x_draw_image_foreground (s)
2634 struct glyph_string *s;
2636 int x = s->x;
2637 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2639 /* If first glyph of S has a left box line, start drawing it to the
2640 right of that line. */
2641 if (s->face->box != FACE_NO_BOX
2642 && s->first_glyph->left_box_line_p
2643 && s->slice.x == 0)
2644 x += abs (s->face->box_line_width);
2646 /* If there is a margin around the image, adjust x- and y-position
2647 by that margin. */
2648 if (s->slice.x == 0)
2649 x += s->img->hmargin;
2650 if (s->slice.y == 0)
2651 y += s->img->vmargin;
2653 if (s->img->pixmap)
2655 x_set_glyph_string_clipping (s);
2657 if (s->img->mask)
2658 mac_copy_area_with_mask (s->display, s->img->pixmap, s->img->mask,
2659 s->window, s->gc, s->slice.x, s->slice.y,
2660 s->slice.width, s->slice.height, x, y);
2661 else
2663 mac_copy_area (s->display, s->img->pixmap,
2664 s->window, s->gc, s->slice.x, s->slice.y,
2665 s->slice.width, s->slice.height, x, y);
2667 /* When the image has a mask, we can expect that at
2668 least part of a mouse highlight or a block cursor will
2669 be visible. If the image doesn't have a mask, make
2670 a block cursor visible by drawing a rectangle around
2671 the image. I believe it's looking better if we do
2672 nothing here for mouse-face. */
2673 if (s->hl == DRAW_CURSOR)
2675 int r = s->img->relief;
2676 if (r < 0) r = -r;
2677 mac_draw_rectangle (s->display, s->window, s->gc,
2678 x - r, y - r,
2679 s->slice.width + r*2 - 1,
2680 s->slice.height + r*2 - 1);
2684 else
2685 /* Draw a rectangle if image could not be loaded. */
2686 mac_draw_rectangle (s->display, s->window, s->gc, x, y,
2687 s->slice.width - 1, s->slice.height - 1);
2691 /* Draw a relief around the image glyph string S. */
2693 static void
2694 x_draw_image_relief (s)
2695 struct glyph_string *s;
2697 int x0, y0, x1, y1, thick, raised_p;
2698 Rect r;
2699 int x = s->x;
2700 int y = s->ybase - image_ascent (s->img, s->face, &s->slice);
2702 /* If first glyph of S has a left box line, start drawing it to the
2703 right of that line. */
2704 if (s->face->box != FACE_NO_BOX
2705 && s->first_glyph->left_box_line_p
2706 && s->slice.x == 0)
2707 x += abs (s->face->box_line_width);
2709 /* If there is a margin around the image, adjust x- and y-position
2710 by that margin. */
2711 if (s->slice.x == 0)
2712 x += s->img->hmargin;
2713 if (s->slice.y == 0)
2714 y += s->img->vmargin;
2716 if (s->hl == DRAW_IMAGE_SUNKEN
2717 || s->hl == DRAW_IMAGE_RAISED)
2719 thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
2720 raised_p = s->hl == DRAW_IMAGE_RAISED;
2722 else
2724 thick = abs (s->img->relief);
2725 raised_p = s->img->relief > 0;
2728 x0 = x - thick;
2729 y0 = y - thick;
2730 x1 = x + s->slice.width + thick - 1;
2731 y1 = y + s->slice.height + thick - 1;
2733 x_setup_relief_colors (s);
2734 get_glyph_string_clip_rect (s, &r);
2735 x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p,
2736 s->slice.y == 0,
2737 s->slice.y + s->slice.height == s->img->height,
2738 s->slice.x == 0,
2739 s->slice.x + s->slice.width == s->img->width,
2740 &r);
2744 #if 0 /* TODO: figure out if we need to do this on Mac. */
2745 /* Draw the foreground of image glyph string S to PIXMAP. */
2747 static void
2748 x_draw_image_foreground_1 (s, pixmap)
2749 struct glyph_string *s;
2750 Pixmap pixmap;
2752 int x = 0;
2753 int y = s->ybase - s->y - image_ascent (s->img, s->face, &s->slice);
2755 /* If first glyph of S has a left box line, start drawing it to the
2756 right of that line. */
2757 if (s->face->box != FACE_NO_BOX
2758 && s->first_glyph->left_box_line_p
2759 && s->slice.x == 0)
2760 x += abs (s->face->box_line_width);
2762 /* If there is a margin around the image, adjust x- and y-position
2763 by that margin. */
2764 if (s->slice.x == 0)
2765 x += s->img->hmargin;
2766 if (s->slice.y == 0)
2767 y += s->img->vmargin;
2769 if (s->img->pixmap)
2771 if (s->img->mask)
2772 mac_copy_area_with_mask_to_pixmap (s->display, s->img->pixmap,
2773 s->img->mask, pixmap, s->gc,
2774 s->slice.x, s->slice.y,
2775 s->slice.width, s->slice.height,
2776 x, y);
2777 else
2779 mac_copy_area_to_pixmap (s->display, s->img->pixmap, pixmap, s->gc,
2780 s->slice.x, s->slice.y,
2781 s->slice.width, s->slice.height,
2782 x, y);
2784 /* When the image has a mask, we can expect that at
2785 least part of a mouse highlight or a block cursor will
2786 be visible. If the image doesn't have a mask, make
2787 a block cursor visible by drawing a rectangle around
2788 the image. I believe it's looking better if we do
2789 nothing here for mouse-face. */
2790 if (s->hl == DRAW_CURSOR)
2792 int r = s->img->relief;
2793 if (r < 0) r = -r;
2794 mac_draw_rectangle (s->display, s->window, s->gc, x - r, y - r,
2795 s->slice.width + r*2 - 1,
2796 s->slice.height + r*2 - 1);
2800 else
2801 /* Draw a rectangle if image could not be loaded. */
2802 mac_draw_rectangle_to_pixmap (s->display, pixmap, s->gc, x, y,
2803 s->slice.width - 1, s->slice.height - 1);
2805 #endif
2808 /* Draw part of the background of glyph string S. X, Y, W, and H
2809 give the rectangle to draw. */
2811 static void
2812 x_draw_glyph_string_bg_rect (s, x, y, w, h)
2813 struct glyph_string *s;
2814 int x, y, w, h;
2816 #if 0 /* MAC_TODO: stipple */
2817 if (s->stippled_p)
2819 /* Fill background with a stipple pattern. */
2820 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2821 XFillRectangle (s->display, s->window, s->gc, x, y, w, h);
2822 XSetFillStyle (s->display, s->gc, FillSolid);
2824 else
2825 #endif /* MAC_TODO */
2826 x_clear_glyph_string_rect (s, x, y, w, h);
2830 /* Draw image glyph string S.
2832 s->y
2833 s->x +-------------------------
2834 | s->face->box
2836 | +-------------------------
2837 | | s->img->margin
2839 | | +-------------------
2840 | | | the image
2844 static void
2845 x_draw_image_glyph_string (s)
2846 struct glyph_string *s;
2848 int x, y;
2849 int box_line_hwidth = abs (s->face->box_line_width);
2850 int box_line_vwidth = max (s->face->box_line_width, 0);
2851 int height;
2852 Pixmap pixmap = 0;
2854 height = s->height - 2 * box_line_vwidth;
2857 /* Fill background with face under the image. Do it only if row is
2858 taller than image or if image has a clip mask to reduce
2859 flickering. */
2860 s->stippled_p = s->face->stipple != 0;
2861 if (height > s->slice.height
2862 || s->img->hmargin
2863 || s->img->vmargin
2864 || s->img->mask
2865 || s->img->pixmap == 0
2866 || s->width != s->background_width)
2868 x = s->x;
2869 if (s->first_glyph->left_box_line_p
2870 && s->slice.x == 0)
2871 x += box_line_hwidth;
2873 y = s->y;
2874 if (s->slice.y == 0)
2875 y += box_line_vwidth;
2877 #if 0 /* TODO: figure out if we need to do this on Mac. */
2878 if (s->img->mask)
2880 /* Create a pixmap as large as the glyph string. Fill it
2881 with the background color. Copy the image to it, using
2882 its mask. Copy the temporary pixmap to the display. */
2883 int depth = one_mac_display_info.n_planes;
2885 /* Create a pixmap as large as the glyph string. */
2886 pixmap = XCreatePixmap (s->display, s->window,
2887 s->background_width,
2888 s->height, depth);
2890 /* Fill the pixmap with the background color/stipple. */
2891 #if 0 /* TODO: stipple */
2892 if (s->stippled_p)
2894 /* Fill background with a stipple pattern. */
2895 XSetFillStyle (s->display, s->gc, FillOpaqueStippled);
2896 XFillRectangle (s->display, pixmap, s->gc,
2897 0, 0, s->background_width, s->height);
2898 XSetFillStyle (s->display, s->gc, FillSolid);
2900 else
2901 #endif
2903 XGCValues xgcv;
2904 XGetGCValues (s->display, s->gc, GCForeground | GCBackground,
2905 &xgcv);
2906 XSetForeground (s->display, s->gc, xgcv.background);
2907 mac_fill_rectangle_to_pixmap (s->display, pixmap, s->gc,
2908 0, 0, s->background_width,
2909 s->height);
2910 XSetForeground (s->display, s->gc, xgcv.foreground);
2913 else
2914 #endif
2915 x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
2917 s->background_filled_p = 1;
2920 /* Draw the foreground. */
2921 #if 0 /* TODO: figure out if we need to do this on Mac. */
2922 if (pixmap != 0)
2924 x_draw_image_foreground_1 (s, pixmap);
2925 x_set_glyph_string_clipping (s);
2926 mac_copy_area (s->display, pixmap, s->window, s->gc,
2927 0, 0, s->background_width, s->height, s->x, s->y);
2928 mac_reset_clipping (s->display, s->window);
2929 XFreePixmap (s->display, pixmap);
2931 else
2932 #endif
2933 x_draw_image_foreground (s);
2935 /* If we must draw a relief around the image, do it. */
2936 if (s->img->relief
2937 || s->hl == DRAW_IMAGE_RAISED
2938 || s->hl == DRAW_IMAGE_SUNKEN)
2939 x_draw_image_relief (s);
2943 /* Draw stretch glyph string S. */
2945 static void
2946 x_draw_stretch_glyph_string (s)
2947 struct glyph_string *s;
2949 xassert (s->first_glyph->type == STRETCH_GLYPH);
2950 s->stippled_p = s->face->stipple != 0;
2952 if (s->hl == DRAW_CURSOR
2953 && !x_stretch_cursor_p)
2955 /* If `x-stretch-block-cursor' is nil, don't draw a block cursor
2956 as wide as the stretch glyph. */
2957 int width = min (FRAME_COLUMN_WIDTH (s->f), s->background_width);
2959 /* Draw cursor. */
2960 x_draw_glyph_string_bg_rect (s, s->x, s->y, width, s->height);
2962 /* Clear rest using the GC of the original non-cursor face. */
2963 if (width < s->background_width)
2965 int x = s->x + width, y = s->y;
2966 int w = s->background_width - width, h = s->height;
2967 Rect r;
2968 GC gc;
2970 if (s->row->mouse_face_p
2971 && cursor_in_mouse_face_p (s->w))
2973 x_set_mouse_face_gc (s);
2974 gc = s->gc;
2976 else
2977 gc = s->face->gc;
2979 get_glyph_string_clip_rect (s, &r);
2980 mac_set_clip_rectangle (s->display, s->window, &r);
2982 #if 0 /* MAC_TODO: stipple */
2983 if (s->face->stipple)
2985 /* Fill background with a stipple pattern. */
2986 XSetFillStyle (s->display, gc, FillOpaqueStippled);
2987 XFillRectangle (s->display, s->window, gc, x, y, w, h);
2988 XSetFillStyle (s->display, gc, FillSolid);
2990 else
2991 #endif /* MAC_TODO */
2992 mac_erase_rectangle (s->window, gc, x, y, w, h);
2994 mac_reset_clipping (s->display, s->window);
2997 else if (!s->background_filled_p)
2998 x_draw_glyph_string_bg_rect (s, s->x, s->y, s->background_width,
2999 s->height);
3001 s->background_filled_p = 1;
3005 /* Draw glyph string S. */
3007 static void
3008 x_draw_glyph_string (s)
3009 struct glyph_string *s;
3011 int relief_drawn_p = 0;
3013 /* If S draws into the background of its successor that does not
3014 draw a cursor, draw the background of the successor first so that
3015 S can draw into it. This makes S->next use XDrawString instead
3016 of XDrawImageString. */
3017 if (s->next && s->right_overhang && !s->for_overlaps_p
3018 && s->next->hl != DRAW_CURSOR)
3020 xassert (s->next->img == NULL);
3021 x_set_glyph_string_gc (s->next);
3022 x_set_glyph_string_clipping (s->next);
3023 x_draw_glyph_string_background (s->next, 1);
3026 /* Set up S->gc, set clipping and draw S. */
3027 x_set_glyph_string_gc (s);
3029 /* Draw relief (if any) in advance for char/composition so that the
3030 glyph string can be drawn over it. */
3031 if (!s->for_overlaps_p
3032 && s->face->box != FACE_NO_BOX
3033 && (s->first_glyph->type == CHAR_GLYPH
3034 || s->first_glyph->type == COMPOSITE_GLYPH))
3037 x_set_glyph_string_clipping (s);
3038 x_draw_glyph_string_background (s, 1);
3039 x_draw_glyph_string_box (s);
3040 x_set_glyph_string_clipping (s);
3041 relief_drawn_p = 1;
3043 else
3044 x_set_glyph_string_clipping (s);
3046 switch (s->first_glyph->type)
3048 case IMAGE_GLYPH:
3049 x_draw_image_glyph_string (s);
3050 break;
3052 case STRETCH_GLYPH:
3053 x_draw_stretch_glyph_string (s);
3054 break;
3056 case CHAR_GLYPH:
3057 if (s->for_overlaps_p)
3058 s->background_filled_p = 1;
3059 else
3060 x_draw_glyph_string_background (s, 0);
3061 x_draw_glyph_string_foreground (s);
3062 break;
3064 case COMPOSITE_GLYPH:
3065 if (s->for_overlaps_p || s->gidx > 0)
3066 s->background_filled_p = 1;
3067 else
3068 x_draw_glyph_string_background (s, 1);
3069 x_draw_composite_glyph_string_foreground (s);
3070 break;
3072 default:
3073 abort ();
3076 if (!s->for_overlaps_p)
3078 /* Draw underline. */
3079 if (s->face->underline_p)
3081 unsigned long h = 1;
3082 unsigned long dy = s->height - h;
3084 if (s->face->underline_defaulted_p)
3085 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3086 s->width, h);
3087 else
3089 XGCValues xgcv;
3090 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3091 XSetForeground (s->display, s->gc, s->face->underline_color);
3092 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3093 s->width, h);
3094 XSetForeground (s->display, s->gc, xgcv.foreground);
3098 /* Draw overline. */
3099 if (s->face->overline_p)
3101 unsigned long dy = 0, h = 1;
3103 if (s->face->overline_color_defaulted_p)
3104 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3105 s->width, h);
3106 else
3108 XGCValues xgcv;
3109 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3110 XSetForeground (s->display, s->gc, s->face->overline_color);
3111 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3112 s->width, h);
3113 XSetForeground (s->display, s->gc, xgcv.foreground);
3117 /* Draw strike-through. */
3118 if (s->face->strike_through_p)
3120 unsigned long h = 1;
3121 unsigned long dy = (s->height - h) / 2;
3123 if (s->face->strike_through_color_defaulted_p)
3124 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3125 s->width, h);
3126 else
3128 XGCValues xgcv;
3129 XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
3130 XSetForeground (s->display, s->gc, s->face->strike_through_color);
3131 XFillRectangle (s->display, s->window, s->gc, s->x, s->y + dy,
3132 s->width, h);
3133 XSetForeground (s->display, s->gc, xgcv.foreground);
3137 /* Draw relief if not yet drawn. */
3138 if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
3139 x_draw_glyph_string_box (s);
3142 /* Reset clipping. */
3143 mac_reset_clipping (s->display, s->window);
3146 /* Shift display to make room for inserted glyphs. */
3148 void
3149 mac_shift_glyphs_for_insert (f, x, y, width, height, shift_by)
3150 struct frame *f;
3151 int x, y, width, height, shift_by;
3153 mac_scroll_area (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
3154 f->output_data.mac->normal_gc,
3155 x, y, width, height,
3156 x + shift_by, y);
3159 /* Delete N glyphs at the nominal cursor position. Not implemented
3160 for X frames. */
3162 static void
3163 x_delete_glyphs (n)
3164 register int n;
3166 abort ();
3170 /* Clear entire frame. If updating_frame is non-null, clear that
3171 frame. Otherwise clear the selected frame. */
3173 static void
3174 x_clear_frame ()
3176 struct frame *f;
3178 if (updating_frame)
3179 f = updating_frame;
3180 else
3181 f = SELECTED_FRAME ();
3183 /* Clearing the frame will erase any cursor, so mark them all as no
3184 longer visible. */
3185 mark_window_cursors_off (XWINDOW (FRAME_ROOT_WINDOW (f)));
3186 output_cursor.hpos = output_cursor.vpos = 0;
3187 output_cursor.x = -1;
3189 /* We don't set the output cursor here because there will always
3190 follow an explicit cursor_to. */
3191 BLOCK_INPUT;
3192 XClearWindow (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f));
3194 /* We have to clear the scroll bars, too. If we have changed
3195 colors or something like that, then they should be notified. */
3196 x_scroll_bar_clear (f);
3198 XFlush (FRAME_MAC_DISPLAY (f));
3199 UNBLOCK_INPUT;
3204 /* Invert the middle quarter of the frame for .15 sec. */
3206 /* We use the select system call to do the waiting, so we have to make
3207 sure it's available. If it isn't, we just won't do visual bells. */
3209 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3212 /* Subtract the `struct timeval' values X and Y, storing the result in
3213 *RESULT. Return 1 if the difference is negative, otherwise 0. */
3215 static int
3216 timeval_subtract (result, x, y)
3217 struct timeval *result, x, y;
3219 /* Perform the carry for the later subtraction by updating y. This
3220 is safer because on some systems the tv_sec member is unsigned. */
3221 if (x.tv_usec < y.tv_usec)
3223 int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
3224 y.tv_usec -= 1000000 * nsec;
3225 y.tv_sec += nsec;
3228 if (x.tv_usec - y.tv_usec > 1000000)
3230 int nsec = (y.tv_usec - x.tv_usec) / 1000000;
3231 y.tv_usec += 1000000 * nsec;
3232 y.tv_sec -= nsec;
3235 /* Compute the time remaining to wait. tv_usec is certainly
3236 positive. */
3237 result->tv_sec = x.tv_sec - y.tv_sec;
3238 result->tv_usec = x.tv_usec - y.tv_usec;
3240 /* Return indication of whether the result should be considered
3241 negative. */
3242 return x.tv_sec < y.tv_sec;
3245 void
3246 XTflash (f)
3247 struct frame *f;
3249 BLOCK_INPUT;
3251 FlashMenuBar (0);
3254 struct timeval wakeup;
3256 EMACS_GET_TIME (wakeup);
3258 /* Compute time to wait until, propagating carry from usecs. */
3259 wakeup.tv_usec += 150000;
3260 wakeup.tv_sec += (wakeup.tv_usec / 1000000);
3261 wakeup.tv_usec %= 1000000;
3263 /* Keep waiting until past the time wakeup. */
3264 while (1)
3266 struct timeval timeout;
3268 EMACS_GET_TIME (timeout);
3270 /* In effect, timeout = wakeup - timeout.
3271 Break if result would be negative. */
3272 if (timeval_subtract (&timeout, wakeup, timeout))
3273 break;
3275 /* Try to wait that long--but we might wake up sooner. */
3276 select (0, NULL, NULL, NULL, &timeout);
3280 FlashMenuBar (0);
3282 UNBLOCK_INPUT;
3285 #endif /* defined (HAVE_TIMEVAL) && defined (HAVE_SELECT) */
3288 /* Make audible bell. */
3290 void
3291 XTring_bell ()
3293 struct frame *f = SELECTED_FRAME ();
3295 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
3296 if (visible_bell)
3297 XTflash (f);
3298 else
3299 #endif
3301 BLOCK_INPUT;
3302 SysBeep (1);
3303 XFlush (FRAME_MAC_DISPLAY (f));
3304 UNBLOCK_INPUT;
3309 /* Specify how many text lines, from the top of the window,
3310 should be affected by insert-lines and delete-lines operations.
3311 This, and those operations, are used only within an update
3312 that is bounded by calls to x_update_begin and x_update_end. */
3314 static void
3315 XTset_terminal_window (n)
3316 register int n;
3318 /* This function intentionally left blank. */
3323 /***********************************************************************
3324 Line Dance
3325 ***********************************************************************/
3327 /* Perform an insert-lines or delete-lines operation, inserting N
3328 lines or deleting -N lines at vertical position VPOS. */
3330 static void
3331 x_ins_del_lines (vpos, n)
3332 int vpos, n;
3334 abort ();
3338 /* Scroll part of the display as described by RUN. */
3340 static void
3341 x_scroll_run (w, run)
3342 struct window *w;
3343 struct run *run;
3345 struct frame *f = XFRAME (w->frame);
3346 int x, y, width, height, from_y, to_y, bottom_y;
3348 /* Get frame-relative bounding box of the text display area of W,
3349 without mode lines. Include in this box the left and right
3350 fringe of W. */
3351 window_box (w, -1, &x, &y, &width, &height);
3353 from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
3354 to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
3355 bottom_y = y + height;
3357 if (to_y < from_y)
3359 /* Scrolling up. Make sure we don't copy part of the mode
3360 line at the bottom. */
3361 if (from_y + run->height > bottom_y)
3362 height = bottom_y - from_y;
3363 else
3364 height = run->height;
3366 else
3368 /* Scolling down. Make sure we don't copy over the mode line.
3369 at the bottom. */
3370 if (to_y + run->height > bottom_y)
3371 height = bottom_y - to_y;
3372 else
3373 height = run->height;
3376 BLOCK_INPUT;
3378 /* Cursor off. Will be switched on again in x_update_window_end. */
3379 updated_window = w;
3380 x_clear_cursor (w);
3382 mac_scroll_area (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
3383 f->output_data.mac->normal_gc,
3384 x, from_y,
3385 width, height,
3386 x, to_y);
3388 UNBLOCK_INPUT;
3393 /***********************************************************************
3394 Exposure Events
3395 ***********************************************************************/
3398 static void
3399 frame_highlight (f)
3400 struct frame *f;
3402 OSErr err;
3403 ControlRef root_control;
3405 BLOCK_INPUT;
3406 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3407 if (err == noErr)
3408 ActivateControl (root_control);
3409 UNBLOCK_INPUT;
3410 x_update_cursor (f, 1);
3413 static void
3414 frame_unhighlight (f)
3415 struct frame *f;
3417 OSErr err;
3418 ControlRef root_control;
3420 BLOCK_INPUT;
3421 err = GetRootControl (FRAME_MAC_WINDOW (f), &root_control);
3422 if (err == noErr)
3423 DeactivateControl (root_control);
3424 UNBLOCK_INPUT;
3425 x_update_cursor (f, 1);
3428 /* The focus has changed. Update the frames as necessary to reflect
3429 the new situation. Note that we can't change the selected frame
3430 here, because the Lisp code we are interrupting might become confused.
3431 Each event gets marked with the frame in which it occurred, so the
3432 Lisp code can tell when the switch took place by examining the events. */
3434 static void
3435 x_new_focus_frame (dpyinfo, frame)
3436 struct x_display_info *dpyinfo;
3437 struct frame *frame;
3439 struct frame *old_focus = dpyinfo->x_focus_frame;
3441 if (frame != dpyinfo->x_focus_frame)
3443 /* Set this before calling other routines, so that they see
3444 the correct value of x_focus_frame. */
3445 dpyinfo->x_focus_frame = frame;
3447 if (old_focus && old_focus->auto_lower)
3448 x_lower_frame (old_focus);
3450 #if 0
3451 selected_frame = frame;
3452 XSETFRAME (XWINDOW (selected_frame->selected_window)->frame,
3453 selected_frame);
3454 Fselect_window (selected_frame->selected_window, Qnil);
3455 choose_minibuf_frame ();
3456 #endif /* ! 0 */
3458 if (dpyinfo->x_focus_frame && dpyinfo->x_focus_frame->auto_raise)
3459 pending_autoraise_frame = dpyinfo->x_focus_frame;
3460 else
3461 pending_autoraise_frame = 0;
3464 x_frame_rehighlight (dpyinfo);
3467 /* Handle FocusIn and FocusOut state changes for FRAME.
3468 If FRAME has focus and there exists more than one frame, puts
3469 a FOCUS_IN_EVENT into *BUFP. */
3471 static void
3472 mac_focus_changed (type, dpyinfo, frame, bufp)
3473 int type;
3474 struct mac_display_info *dpyinfo;
3475 struct frame *frame;
3476 struct input_event *bufp;
3478 if (type == activeFlag)
3480 if (dpyinfo->x_focus_event_frame != frame)
3482 x_new_focus_frame (dpyinfo, frame);
3483 dpyinfo->x_focus_event_frame = frame;
3485 /* Don't stop displaying the initial startup message
3486 for a switch-frame event we don't need. */
3487 if (GC_NILP (Vterminal_frame)
3488 && GC_CONSP (Vframe_list)
3489 && !GC_NILP (XCDR (Vframe_list)))
3491 bufp->kind = FOCUS_IN_EVENT;
3492 XSETFRAME (bufp->frame_or_window, frame);
3496 else
3498 if (dpyinfo->x_focus_event_frame == frame)
3500 dpyinfo->x_focus_event_frame = 0;
3501 x_new_focus_frame (dpyinfo, 0);
3506 /* The focus may have changed. Figure out if it is a real focus change,
3507 by checking both FocusIn/Out and Enter/LeaveNotify events.
3509 Returns FOCUS_IN_EVENT event in *BUFP. */
3511 static void
3512 x_detect_focus_change (dpyinfo, event, bufp)
3513 struct mac_display_info *dpyinfo;
3514 EventRecord *event;
3515 struct input_event *bufp;
3517 struct frame *frame;
3519 frame = mac_window_to_frame ((WindowPtr) event->message);
3520 if (! frame)
3521 return;
3523 /* On Mac, this is only called from focus events, so no switch needed. */
3524 mac_focus_changed ((event->modifiers & activeFlag),
3525 dpyinfo, frame, bufp);
3529 /* Handle an event saying the mouse has moved out of an Emacs frame. */
3531 void
3532 x_mouse_leave (dpyinfo)
3533 struct x_display_info *dpyinfo;
3535 x_new_focus_frame (dpyinfo, dpyinfo->x_focus_event_frame);
3538 /* The focus has changed, or we have redirected a frame's focus to
3539 another frame (this happens when a frame uses a surrogate
3540 mini-buffer frame). Shift the highlight as appropriate.
3542 The FRAME argument doesn't necessarily have anything to do with which
3543 frame is being highlighted or un-highlighted; we only use it to find
3544 the appropriate X display info. */
3546 static void
3547 XTframe_rehighlight (frame)
3548 struct frame *frame;
3550 x_frame_rehighlight (FRAME_X_DISPLAY_INFO (frame));
3553 static void
3554 x_frame_rehighlight (dpyinfo)
3555 struct x_display_info *dpyinfo;
3557 struct frame *old_highlight = dpyinfo->x_highlight_frame;
3559 if (dpyinfo->x_focus_frame)
3561 dpyinfo->x_highlight_frame
3562 = ((GC_FRAMEP (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame)))
3563 ? XFRAME (FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame))
3564 : dpyinfo->x_focus_frame);
3565 if (! FRAME_LIVE_P (dpyinfo->x_highlight_frame))
3567 FRAME_FOCUS_FRAME (dpyinfo->x_focus_frame) = Qnil;
3568 dpyinfo->x_highlight_frame = dpyinfo->x_focus_frame;
3571 else
3572 dpyinfo->x_highlight_frame = 0;
3574 if (dpyinfo->x_highlight_frame != old_highlight)
3576 if (old_highlight)
3577 frame_unhighlight (old_highlight);
3578 if (dpyinfo->x_highlight_frame)
3579 frame_highlight (dpyinfo->x_highlight_frame);
3585 /* Keyboard processing - modifier keys, vendor-specific keysyms, etc. */
3587 #if 0 /* MAC_TODO */
3588 /* Initialize mode_switch_bit and modifier_meaning. */
3589 static void
3590 x_find_modifier_meanings (dpyinfo)
3591 struct x_display_info *dpyinfo;
3593 int min_code, max_code;
3594 KeySym *syms;
3595 int syms_per_code;
3596 XModifierKeymap *mods;
3598 dpyinfo->meta_mod_mask = 0;
3599 dpyinfo->shift_lock_mask = 0;
3600 dpyinfo->alt_mod_mask = 0;
3601 dpyinfo->super_mod_mask = 0;
3602 dpyinfo->hyper_mod_mask = 0;
3604 #ifdef HAVE_X11R4
3605 XDisplayKeycodes (dpyinfo->display, &min_code, &max_code);
3606 #else
3607 min_code = dpyinfo->display->min_keycode;
3608 max_code = dpyinfo->display->max_keycode;
3609 #endif
3611 syms = XGetKeyboardMapping (dpyinfo->display,
3612 min_code, max_code - min_code + 1,
3613 &syms_per_code);
3614 mods = XGetModifierMapping (dpyinfo->display);
3616 /* Scan the modifier table to see which modifier bits the Meta and
3617 Alt keysyms are on. */
3619 int row, col; /* The row and column in the modifier table. */
3621 for (row = 3; row < 8; row++)
3622 for (col = 0; col < mods->max_keypermod; col++)
3624 KeyCode code
3625 = mods->modifiermap[(row * mods->max_keypermod) + col];
3627 /* Zeroes are used for filler. Skip them. */
3628 if (code == 0)
3629 continue;
3631 /* Are any of this keycode's keysyms a meta key? */
3633 int code_col;
3635 for (code_col = 0; code_col < syms_per_code; code_col++)
3637 int sym = syms[((code - min_code) * syms_per_code) + code_col];
3639 switch (sym)
3641 case XK_Meta_L:
3642 case XK_Meta_R:
3643 dpyinfo->meta_mod_mask |= (1 << row);
3644 break;
3646 case XK_Alt_L:
3647 case XK_Alt_R:
3648 dpyinfo->alt_mod_mask |= (1 << row);
3649 break;
3651 case XK_Hyper_L:
3652 case XK_Hyper_R:
3653 dpyinfo->hyper_mod_mask |= (1 << row);
3654 break;
3656 case XK_Super_L:
3657 case XK_Super_R:
3658 dpyinfo->super_mod_mask |= (1 << row);
3659 break;
3661 case XK_Shift_Lock:
3662 /* Ignore this if it's not on the lock modifier. */
3663 if ((1 << row) == LockMask)
3664 dpyinfo->shift_lock_mask = LockMask;
3665 break;
3672 /* If we couldn't find any meta keys, accept any alt keys as meta keys. */
3673 if (! dpyinfo->meta_mod_mask)
3675 dpyinfo->meta_mod_mask = dpyinfo->alt_mod_mask;
3676 dpyinfo->alt_mod_mask = 0;
3679 /* If some keys are both alt and meta,
3680 make them just meta, not alt. */
3681 if (dpyinfo->alt_mod_mask & dpyinfo->meta_mod_mask)
3683 dpyinfo->alt_mod_mask &= ~dpyinfo->meta_mod_mask;
3686 XFree ((char *) syms);
3687 XFreeModifiermap (mods);
3690 #endif /* MAC_TODO */
3692 /* Convert between the modifier bits X uses and the modifier bits
3693 Emacs uses. */
3695 static unsigned int
3696 x_mac_to_emacs_modifiers (dpyinfo, state)
3697 struct x_display_info *dpyinfo;
3698 unsigned short state;
3700 return (((state & shiftKey) ? shift_modifier : 0)
3701 | ((state & controlKey) ? ctrl_modifier : 0)
3702 | ((state & cmdKey) ? meta_modifier : 0)
3703 | ((state & optionKey) ? alt_modifier : 0));
3706 #if 0 /* MAC_TODO */
3707 static unsigned short
3708 x_emacs_to_x_modifiers (dpyinfo, state)
3709 struct x_display_info *dpyinfo;
3710 unsigned int state;
3712 return ( ((state & alt_modifier) ? dpyinfo->alt_mod_mask : 0)
3713 | ((state & super_modifier) ? dpyinfo->super_mod_mask : 0)
3714 | ((state & hyper_modifier) ? dpyinfo->hyper_mod_mask : 0)
3715 | ((state & shift_modifier) ? ShiftMask : 0)
3716 | ((state & ctrl_modifier) ? ControlMask : 0)
3717 | ((state & meta_modifier) ? dpyinfo->meta_mod_mask : 0));
3719 #endif /* MAC_TODO */
3721 /* Convert a keysym to its name. */
3723 char *
3724 x_get_keysym_name (keysym)
3725 int keysym;
3727 char *value;
3729 BLOCK_INPUT;
3730 #if 0
3731 value = XKeysymToString (keysym);
3732 #else
3733 value = 0;
3734 #endif
3735 UNBLOCK_INPUT;
3737 return value;
3742 /* Function to report a mouse movement to the mainstream Emacs code.
3743 The input handler calls this.
3745 We have received a mouse movement event, which is given in *event.
3746 If the mouse is over a different glyph than it was last time, tell
3747 the mainstream emacs code by setting mouse_moved. If not, ask for
3748 another motion event, so we can check again the next time it moves. */
3750 static Point last_mouse_motion_position;
3751 static Lisp_Object last_mouse_motion_frame;
3753 static void
3754 note_mouse_movement (frame, pos)
3755 FRAME_PTR frame;
3756 Point *pos;
3758 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (frame);
3759 #if TARGET_API_MAC_CARBON
3760 Rect r;
3761 #endif
3763 last_mouse_movement_time = TickCount () * (1000 / 60); /* to milliseconds */
3764 last_mouse_motion_position = *pos;
3765 XSETFRAME (last_mouse_motion_frame, frame);
3767 #if TARGET_API_MAC_CARBON
3768 if (!PtInRect (*pos, GetWindowPortBounds (FRAME_MAC_WINDOW (frame), &r)))
3769 #else
3770 if (!PtInRect (*pos, &FRAME_MAC_WINDOW (frame)->portRect))
3771 #endif
3773 if (frame == dpyinfo->mouse_face_mouse_frame)
3774 /* This case corresponds to LeaveNotify in X11. */
3776 /* If we move outside the frame, then we're certainly no
3777 longer on any text in the frame. */
3778 clear_mouse_face (dpyinfo);
3779 dpyinfo->mouse_face_mouse_frame = 0;
3780 if (!dpyinfo->grabbed)
3781 rif->define_frame_cursor (frame,
3782 frame->output_data.mac->nontext_cursor);
3785 /* Has the mouse moved off the glyph it was on at the last sighting? */
3786 else if (pos->h < last_mouse_glyph.left
3787 || pos->h >= last_mouse_glyph.right
3788 || pos->v < last_mouse_glyph.top
3789 || pos->v >= last_mouse_glyph.bottom)
3791 frame->mouse_moved = 1;
3792 last_mouse_scroll_bar = Qnil;
3793 note_mouse_highlight (frame, pos->h, pos->v);
3798 /************************************************************************
3799 Mouse Face
3800 ************************************************************************/
3802 static int glyph_rect P_ ((struct frame *f, int, int, Rect *));
3805 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
3807 static void
3808 redo_mouse_highlight ()
3810 if (!NILP (last_mouse_motion_frame)
3811 && FRAME_LIVE_P (XFRAME (last_mouse_motion_frame)))
3812 note_mouse_highlight (XFRAME (last_mouse_motion_frame),
3813 last_mouse_motion_position.h,
3814 last_mouse_motion_position.v);
3818 /* Try to determine frame pixel position and size of the glyph under
3819 frame pixel coordinates X/Y on frame F . Return the position and
3820 size in *RECT. Value is non-zero if we could compute these
3821 values. */
3823 static int
3824 glyph_rect (f, x, y, rect)
3825 struct frame *f;
3826 int x, y;
3827 Rect *rect;
3829 Lisp_Object window;
3831 window = window_from_coordinates (f, x, y, 0, &x, &y, 0);
3833 if (!NILP (window))
3835 struct window *w = XWINDOW (window);
3836 struct glyph_row *r = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
3837 struct glyph_row *end = r + w->current_matrix->nrows - 1;
3839 for (; r < end && r->enabled_p; ++r)
3840 if (r->y <= y && r->y + r->height > y)
3842 /* Found the row at y. */
3843 struct glyph *g = r->glyphs[TEXT_AREA];
3844 struct glyph *end = g + r->used[TEXT_AREA];
3845 int gx;
3847 rect->top = WINDOW_TO_FRAME_PIXEL_Y (w, r->y);
3848 rect->bottom = rect->top + r->height;
3850 if (x < r->x)
3852 /* x is to the left of the first glyph in the row. */
3853 /* Shouldn't this be a pixel value?
3854 WINDOW_LEFT_EDGE_X (w) seems to be the right value.
3855 ++KFS */
3856 rect->left = WINDOW_LEFT_EDGE_COL (w);
3857 rect->right = WINDOW_TO_FRAME_PIXEL_X (w, r->x);
3858 return 1;
3861 for (gx = r->x; g < end; gx += g->pixel_width, ++g)
3862 if (gx <= x && gx + g->pixel_width > x)
3864 /* x is on a glyph. */
3865 rect->left = WINDOW_TO_FRAME_PIXEL_X (w, gx);
3866 rect->right = rect->left + g->pixel_width;
3867 return 1;
3870 /* x is to the right of the last glyph in the row. */
3871 rect->left = WINDOW_TO_FRAME_PIXEL_X (w, gx);
3872 /* Shouldn't this be a pixel value?
3873 WINDOW_RIGHT_EDGE_X (w) seems to be the right value.
3874 ++KFS */
3875 rect->right = WINDOW_RIGHT_EDGE_COL (w);
3876 return 1;
3880 /* The y is not on any row. */
3881 return 0;
3884 /* MAC TODO: This should be called from somewhere (or removed) ++KFS */
3886 /* Record the position of the mouse in last_mouse_glyph. */
3887 static void
3888 remember_mouse_glyph (f1, gx, gy)
3889 struct frame * f1;
3890 int gx, gy;
3892 if (!glyph_rect (f1, gx, gy, &last_mouse_glyph))
3894 int width = FRAME_SMALLEST_CHAR_WIDTH (f1);
3895 int height = FRAME_SMALLEST_FONT_HEIGHT (f1);
3897 /* Arrange for the division in FRAME_PIXEL_X_TO_COL etc. to
3898 round down even for negative values. */
3899 if (gx < 0)
3900 gx -= width - 1;
3901 if (gy < 0)
3902 gy -= height - 1;
3903 #if 0
3904 /* This was the original code from XTmouse_position, but it seems
3905 to give the position of the glyph diagonally next to the one
3906 the mouse is over. */
3907 gx = (gx + width - 1) / width * width;
3908 gy = (gy + height - 1) / height * height;
3909 #else
3910 gx = gx / width * width;
3911 gy = gy / height * height;
3912 #endif
3914 last_mouse_glyph.left = gx;
3915 last_mouse_glyph.top = gy;
3916 last_mouse_glyph.right = gx + width;
3917 last_mouse_glyph.bottom = gy + height;
3922 static struct frame *
3923 mac_focus_frame (dpyinfo)
3924 struct mac_display_info *dpyinfo;
3926 if (dpyinfo->x_focus_frame)
3927 return dpyinfo->x_focus_frame;
3928 else
3929 /* Mac version may get events, such as a menu bar click, even when
3930 all the frames are invisible. In this case, we regard the
3931 event came to the selected frame. */
3932 return SELECTED_FRAME ();
3936 /* Return the current position of the mouse.
3937 *fp should be a frame which indicates which display to ask about.
3939 If the mouse movement started in a scroll bar, set *fp, *bar_window,
3940 and *part to the frame, window, and scroll bar part that the mouse
3941 is over. Set *x and *y to the portion and whole of the mouse's
3942 position on the scroll bar.
3944 If the mouse movement started elsewhere, set *fp to the frame the
3945 mouse is on, *bar_window to nil, and *x and *y to the character cell
3946 the mouse is over.
3948 Set *time to the server time-stamp for the time at which the mouse
3949 was at this position.
3951 Don't store anything if we don't have a valid set of values to report.
3953 This clears the mouse_moved flag, so we can wait for the next mouse
3954 movement. */
3956 static void
3957 XTmouse_position (fp, insist, bar_window, part, x, y, time)
3958 FRAME_PTR *fp;
3959 int insist;
3960 Lisp_Object *bar_window;
3961 enum scroll_bar_part *part;
3962 Lisp_Object *x, *y;
3963 unsigned long *time;
3965 Point mouse_pos;
3966 int ignore1, ignore2;
3967 struct frame *f = mac_focus_frame (FRAME_MAC_DISPLAY_INFO (*fp));
3968 WindowPtr wp = FRAME_MAC_WINDOW (f);
3969 Lisp_Object frame, tail;
3971 BLOCK_INPUT;
3973 if (! NILP (last_mouse_scroll_bar) && insist == 0)
3974 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
3975 else
3977 /* Clear the mouse-moved flag for every frame on this display. */
3978 FOR_EACH_FRAME (tail, frame)
3979 XFRAME (frame)->mouse_moved = 0;
3981 last_mouse_scroll_bar = Qnil;
3983 SetPortWindowPort (wp);
3985 GetMouse (&mouse_pos);
3987 pixel_to_glyph_coords (f, mouse_pos.h, mouse_pos.v, &ignore1, &ignore2,
3988 &last_mouse_glyph, insist);
3990 *bar_window = Qnil;
3991 *part = scroll_bar_handle;
3992 *fp = f;
3993 XSETINT (*x, mouse_pos.h);
3994 XSETINT (*y, mouse_pos.v);
3995 *time = last_mouse_movement_time;
3998 UNBLOCK_INPUT;
4002 /************************************************************************
4003 Toolkit scroll bars
4004 ************************************************************************/
4006 #ifdef USE_TOOLKIT_SCROLL_BARS
4008 static pascal void scroll_bar_timer_callback P_ ((EventLoopTimerRef, void *));
4009 static OSStatus install_scroll_bar_timer P_ ((void));
4010 static OSStatus set_scroll_bar_timer P_ ((EventTimerInterval));
4011 static int control_part_code_to_scroll_bar_part P_ ((ControlPartCode));
4012 static void construct_scroll_bar_click P_ ((struct scroll_bar *, int,
4013 struct input_event *));
4014 static OSErr get_control_part_bounds P_ ((ControlHandle, ControlPartCode,
4015 Rect *));
4016 static void x_scroll_bar_handle_press P_ ((struct scroll_bar *,
4017 ControlPartCode,
4018 struct input_event *));
4019 static void x_scroll_bar_handle_release P_ ((struct scroll_bar *,
4020 struct input_event *));
4021 static void x_scroll_bar_handle_drag P_ ((WindowPtr, struct scroll_bar *,
4022 Point, struct input_event *));
4023 static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
4024 int, int, int));
4026 /* Last scroll bar part sent in x_scroll_bar_handle_*. */
4028 static int last_scroll_bar_part;
4030 static EventLoopTimerRef scroll_bar_timer;
4032 static int scroll_bar_timer_event_posted_p;
4034 #define SCROLL_BAR_FIRST_DELAY 0.5
4035 #define SCROLL_BAR_CONTINUOUS_DELAY (1.0 / 15)
4037 static pascal void
4038 scroll_bar_timer_callback (timer, data)
4039 EventLoopTimerRef timer;
4040 void *data;
4042 EventRef event = NULL;
4043 OSErr err;
4045 err = CreateEvent (NULL, kEventClassMouse, kEventMouseMoved, 0,
4046 kEventAttributeNone, &event);
4047 if (err == noErr)
4049 Point mouse_pos;
4051 GetMouse (&mouse_pos);
4052 LocalToGlobal (&mouse_pos);
4053 err = SetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
4054 sizeof (Point), &mouse_pos);
4056 if (err == noErr)
4058 UInt32 modifiers = GetCurrentKeyModifiers ();
4060 err = SetEventParameter (event, kEventParamKeyModifiers, typeUInt32,
4061 sizeof (UInt32), &modifiers);
4063 if (err == noErr)
4064 err = PostEventToQueue (GetCurrentEventQueue (), event,
4065 kEventPriorityStandard);
4066 if (err == noErr)
4067 scroll_bar_timer_event_posted_p = 1;
4069 if (event)
4070 ReleaseEvent (event);
4073 static OSStatus
4074 install_scroll_bar_timer ()
4076 static EventLoopTimerUPP scroll_bar_timer_callbackUPP = NULL;
4078 if (scroll_bar_timer_callbackUPP == NULL)
4079 scroll_bar_timer_callbackUPP =
4080 NewEventLoopTimerUPP (scroll_bar_timer_callback);
4082 if (scroll_bar_timer == NULL)
4083 /* Mac OS X and CarbonLib 1.5 and later allow us to specify
4084 kEventDurationForever as delays. */
4085 return
4086 InstallEventLoopTimer (GetCurrentEventLoop (),
4087 kEventDurationForever, kEventDurationForever,
4088 scroll_bar_timer_callbackUPP, NULL,
4089 &scroll_bar_timer);
4092 static OSStatus
4093 set_scroll_bar_timer (delay)
4094 EventTimerInterval delay;
4096 if (scroll_bar_timer == NULL)
4097 install_scroll_bar_timer ();
4099 scroll_bar_timer_event_posted_p = 0;
4101 return SetEventLoopTimerNextFireTime (scroll_bar_timer, delay);
4104 static int
4105 control_part_code_to_scroll_bar_part (part_code)
4106 ControlPartCode part_code;
4108 switch (part_code)
4110 case kControlUpButtonPart: return scroll_bar_up_arrow;
4111 case kControlDownButtonPart: return scroll_bar_down_arrow;
4112 case kControlPageUpPart: return scroll_bar_above_handle;
4113 case kControlPageDownPart: return scroll_bar_below_handle;
4114 case kControlIndicatorPart: return scroll_bar_handle;
4117 return -1;
4120 static void
4121 construct_scroll_bar_click (bar, part, bufp)
4122 struct scroll_bar *bar;
4123 int part;
4124 struct input_event *bufp;
4126 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4127 bufp->frame_or_window = bar->window;
4128 bufp->arg = Qnil;
4129 bufp->part = part;
4130 bufp->code = 0;
4131 XSETINT (bufp->x, 0);
4132 XSETINT (bufp->y, 0);
4133 bufp->modifiers = 0;
4136 static OSErr
4137 get_control_part_bounds (ch, part_code, rect)
4138 ControlHandle ch;
4139 ControlPartCode part_code;
4140 Rect *rect;
4142 RgnHandle region = NewRgn ();
4143 OSStatus err;
4145 err = GetControlRegion (ch, part_code, region);
4146 if (err == noErr)
4147 GetRegionBounds (region, rect);
4148 DisposeRgn (region);
4150 return err;
4153 static void
4154 x_scroll_bar_handle_press (bar, part_code, bufp)
4155 struct scroll_bar *bar;
4156 ControlPartCode part_code;
4157 struct input_event *bufp;
4159 int part = control_part_code_to_scroll_bar_part (part_code);
4161 if (part < 0)
4162 return;
4164 if (part != scroll_bar_handle)
4166 construct_scroll_bar_click (bar, part, bufp);
4167 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4168 set_scroll_bar_timer (SCROLL_BAR_FIRST_DELAY);
4171 last_scroll_bar_part = part;
4172 bar->dragging = Qnil;
4173 tracked_scroll_bar = bar;
4176 static void
4177 x_scroll_bar_handle_release (bar, bufp)
4178 struct scroll_bar *bar;
4179 struct input_event *bufp;
4181 if (last_scroll_bar_part != scroll_bar_handle
4182 || !GC_NILP (bar->dragging))
4183 construct_scroll_bar_click (bar, scroll_bar_end_scroll, bufp);
4185 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4186 set_scroll_bar_timer (kEventDurationForever);
4188 last_scroll_bar_part = -1;
4189 bar->dragging = Qnil;
4190 tracked_scroll_bar = NULL;
4193 static void
4194 x_scroll_bar_handle_drag (win, bar, mouse_pos, bufp)
4195 WindowPtr win;
4196 struct scroll_bar *bar;
4197 Point mouse_pos;
4198 struct input_event *bufp;
4200 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4202 if (last_scroll_bar_part == scroll_bar_handle)
4204 int top, top_range;
4205 Rect r;
4207 get_control_part_bounds (SCROLL_BAR_CONTROL_HANDLE (bar),
4208 kControlIndicatorPart, &r);
4210 if (GC_NILP (bar->dragging))
4211 XSETINT (bar->dragging, mouse_pos.v - r.top);
4213 top = mouse_pos.v - XINT (bar->dragging) - XINT (bar->track_top);
4214 top_range = (XINT (bar->track_height) - (r.bottom - r.top)) *
4215 (1.0 + (float) GetControlViewSize (ch) / GetControl32BitMaximum (ch))
4216 + .5;
4218 if (top < 0)
4219 top = 0;
4220 if (top > top_range)
4221 top = top_range;
4223 construct_scroll_bar_click (bar, scroll_bar_handle, bufp);
4224 XSETINT (bufp->x, top);
4225 XSETINT (bufp->y, top_range);
4227 else
4229 ControlPartCode part_code;
4230 int unhilite_p = 0, part;
4232 if (ch != FindControlUnderMouse (mouse_pos, win, &part_code))
4233 unhilite_p = 1;
4234 else
4236 part = control_part_code_to_scroll_bar_part (part_code);
4238 switch (last_scroll_bar_part)
4240 case scroll_bar_above_handle:
4241 case scroll_bar_below_handle:
4242 if (part != scroll_bar_above_handle
4243 && part != scroll_bar_below_handle)
4244 unhilite_p = 1;
4245 break;
4247 case scroll_bar_up_arrow:
4248 case scroll_bar_down_arrow:
4249 if (part != scroll_bar_up_arrow
4250 && part != scroll_bar_down_arrow)
4251 unhilite_p = 1;
4252 break;
4256 if (unhilite_p)
4257 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), 0);
4258 else if (part != last_scroll_bar_part
4259 || scroll_bar_timer_event_posted_p)
4261 construct_scroll_bar_click (bar, part, bufp);
4262 last_scroll_bar_part = part;
4263 HiliteControl (SCROLL_BAR_CONTROL_HANDLE (bar), part_code);
4264 set_scroll_bar_timer (SCROLL_BAR_CONTINUOUS_DELAY);
4269 /* Set the thumb size and position of scroll bar BAR. We are currently
4270 displaying PORTION out of a whole WHOLE, and our position POSITION. */
4272 static void
4273 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
4274 struct scroll_bar *bar;
4275 int portion, position, whole;
4277 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4279 int value, viewsize, maximum;
4281 if (whole == 0 || XINT (bar->track_height) == 0)
4282 value = 0, viewsize = 1, maximum = 0;
4283 else
4285 value = position;
4286 viewsize = portion;
4287 maximum = max (0, whole - portion);
4290 BLOCK_INPUT;
4292 SetControl32BitMinimum (ch, 0);
4293 SetControl32BitMaximum (ch, maximum);
4294 SetControl32BitValue (ch, value);
4295 SetControlViewSize (ch, viewsize);
4297 UNBLOCK_INPUT;
4300 #endif /* USE_TOOLKIT_SCROLL_BARS */
4304 /************************************************************************
4305 Scroll bars, general
4306 ************************************************************************/
4308 /* Create a scroll bar and return the scroll bar vector for it. W is
4309 the Emacs window on which to create the scroll bar. TOP, LEFT,
4310 WIDTH and HEIGHT are the pixel coordinates and dimensions of the
4311 scroll bar. */
4313 static struct scroll_bar *
4314 x_scroll_bar_create (w, top, left, width, height, disp_top, disp_height)
4315 struct window *w;
4316 int top, left, width, height, disp_top, disp_height;
4318 struct frame *f = XFRAME (w->frame);
4319 struct scroll_bar *bar
4320 = XSCROLL_BAR (Fmake_vector (make_number (SCROLL_BAR_VEC_SIZE), Qnil));
4321 Rect r;
4322 ControlHandle ch;
4324 BLOCK_INPUT;
4326 r.left = left;
4327 r.top = disp_top;
4328 r.right = left + width;
4329 r.bottom = disp_top + disp_height;
4331 #if TARGET_API_MAC_CARBON
4332 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4333 0, 0, 0, kControlScrollBarProc, (long) bar);
4334 #else
4335 ch = NewControl (FRAME_MAC_WINDOW (f), &r, "\p", width < disp_height,
4336 0, 0, 0, scrollBarProc, (long) bar);
4337 #endif
4338 SET_SCROLL_BAR_CONTROL_HANDLE (bar, ch);
4340 XSETWINDOW (bar->window, w);
4341 XSETINT (bar->top, top);
4342 XSETINT (bar->left, left);
4343 XSETINT (bar->width, width);
4344 XSETINT (bar->height, height);
4345 XSETINT (bar->start, 0);
4346 XSETINT (bar->end, 0);
4347 bar->dragging = Qnil;
4348 #ifdef USE_TOOLKIT_SCROLL_BARS
4349 bar->track_top = Qnil;
4350 bar->track_height = Qnil;
4351 #endif
4353 /* Add bar to its frame's list of scroll bars. */
4354 bar->next = FRAME_SCROLL_BARS (f);
4355 bar->prev = Qnil;
4356 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4357 if (!NILP (bar->next))
4358 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4360 UNBLOCK_INPUT;
4361 return bar;
4365 /* Draw BAR's handle in the proper position.
4367 If the handle is already drawn from START to END, don't bother
4368 redrawing it, unless REBUILD is non-zero; in that case, always
4369 redraw it. (REBUILD is handy for drawing the handle after expose
4370 events.)
4372 Normally, we want to constrain the start and end of the handle to
4373 fit inside its rectangle, but if the user is dragging the scroll
4374 bar handle, we want to let them drag it down all the way, so that
4375 the bar's top is as far down as it goes; otherwise, there's no way
4376 to move to the very end of the buffer. */
4378 #ifndef USE_TOOLKIT_SCROLL_BARS
4380 static void
4381 x_scroll_bar_set_handle (bar, start, end, rebuild)
4382 struct scroll_bar *bar;
4383 int start, end;
4384 int rebuild;
4386 int dragging = ! NILP (bar->dragging);
4387 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4388 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4389 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4390 int length = end - start;
4392 /* If the display is already accurate, do nothing. */
4393 if (! rebuild
4394 && start == XINT (bar->start)
4395 && end == XINT (bar->end))
4396 return;
4398 BLOCK_INPUT;
4400 /* Make sure the values are reasonable, and try to preserve the
4401 distance between start and end. */
4402 if (start < 0)
4403 start = 0;
4404 else if (start > top_range)
4405 start = top_range;
4406 end = start + length;
4408 if (end < start)
4409 end = start;
4410 else if (end > top_range && ! dragging)
4411 end = top_range;
4413 /* Store the adjusted setting in the scroll bar. */
4414 XSETINT (bar->start, start);
4415 XSETINT (bar->end, end);
4417 /* Clip the end position, just for display. */
4418 if (end > top_range)
4419 end = top_range;
4421 /* Draw bottom positions VERTICAL_SCROLL_BAR_MIN_HANDLE pixels below
4422 top positions, to make sure the handle is always at least that
4423 many pixels tall. */
4424 end += VERTICAL_SCROLL_BAR_MIN_HANDLE;
4426 SetControlMinimum (ch, 0);
4427 /* Don't inadvertently activate deactivated scroll bars */
4428 if (GetControlMaximum (ch) != -1)
4429 SetControlMaximum (ch, top_range + VERTICAL_SCROLL_BAR_MIN_HANDLE
4430 - (end - start));
4431 SetControlValue (ch, start);
4432 #if TARGET_API_MAC_CARBON
4433 SetControlViewSize (ch, end - start);
4434 #endif
4436 UNBLOCK_INPUT;
4439 #endif /* !USE_TOOLKIT_SCROLL_BARS */
4441 /* Destroy scroll bar BAR, and set its Emacs window's scroll bar to
4442 nil. */
4444 static void
4445 x_scroll_bar_remove (bar)
4446 struct scroll_bar *bar;
4448 FRAME_PTR f = XFRAME (WINDOW_FRAME (XWINDOW (bar->window)));
4450 BLOCK_INPUT;
4452 /* Destroy the Mac scroll bar control */
4453 DisposeControl (SCROLL_BAR_CONTROL_HANDLE (bar));
4455 /* Disassociate this scroll bar from its window. */
4456 XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
4458 UNBLOCK_INPUT;
4462 /* Set the handle of the vertical scroll bar for WINDOW to indicate
4463 that we are displaying PORTION characters out of a total of WHOLE
4464 characters, starting at POSITION. If WINDOW has no scroll bar,
4465 create one. */
4467 static void
4468 XTset_vertical_scroll_bar (w, portion, whole, position)
4469 struct window *w;
4470 int portion, whole, position;
4472 struct frame *f = XFRAME (w->frame);
4473 struct scroll_bar *bar;
4474 int top, height, left, sb_left, width, sb_width, disp_top, disp_height;
4475 int window_y, window_height;
4477 /* Get window dimensions. */
4478 window_box (w, -1, 0, &window_y, 0, &window_height);
4479 top = window_y;
4480 width = WINDOW_CONFIG_SCROLL_BAR_COLS (w) * FRAME_COLUMN_WIDTH (f);
4481 height = window_height;
4483 /* Compute the left edge of the scroll bar area. */
4484 left = WINDOW_SCROLL_BAR_AREA_X (w);
4486 /* Compute the width of the scroll bar which might be less than
4487 the width of the area reserved for the scroll bar. */
4488 if (WINDOW_CONFIG_SCROLL_BAR_WIDTH (w) > 0)
4489 sb_width = WINDOW_CONFIG_SCROLL_BAR_WIDTH (w);
4490 else
4491 sb_width = width;
4493 /* Compute the left edge of the scroll bar. */
4494 if (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
4495 sb_left = left;
4496 else
4497 sb_left = left + width - sb_width;
4499 /* Adjustments according to Inside Macintosh to make it look nice */
4500 disp_top = top;
4501 disp_height = height;
4502 if (disp_top == 0)
4504 disp_top = -1;
4505 disp_height++;
4507 else if (disp_top == FRAME_PIXEL_HEIGHT (f) - 16)
4509 disp_top++;
4510 disp_height--;
4513 if (sb_left + sb_width == FRAME_PIXEL_WIDTH (f))
4514 sb_left++;
4516 /* Does the scroll bar exist yet? */
4517 if (NILP (w->vertical_scroll_bar))
4519 BLOCK_INPUT;
4520 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
4521 left, top, width, height, 0);
4522 UNBLOCK_INPUT;
4523 bar = x_scroll_bar_create (w, top, sb_left, sb_width, height, disp_top,
4524 disp_height);
4525 XSETVECTOR (w->vertical_scroll_bar, bar);
4527 else
4529 /* It may just need to be moved and resized. */
4530 ControlHandle ch;
4532 bar = XSCROLL_BAR (w->vertical_scroll_bar);
4533 ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4535 BLOCK_INPUT;
4537 /* If already correctly positioned, do nothing. */
4538 if (!(XINT (bar->left) == sb_left
4539 && XINT (bar->top) == top
4540 && XINT (bar->width) == sb_width
4541 && XINT (bar->height) == height))
4543 /* Since toolkit scroll bars are smaller than the space reserved
4544 for them on the frame, we have to clear "under" them. */
4545 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
4546 left, top, width, height, 0);
4548 #if 0
4549 if (sb_left + sb_width >= FRAME_PIXEL_WIDTH (f))
4550 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
4551 sb_left - 1, top, 1, height, 0);
4552 #endif
4554 HideControl (ch);
4555 MoveControl (ch, sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM, disp_top);
4556 SizeControl (ch, sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
4557 disp_height);
4558 if (sb_width < disp_height)
4559 ShowControl (ch);
4561 /* Remember new settings. */
4562 XSETINT (bar->left, sb_left);
4563 XSETINT (bar->top, top);
4564 XSETINT (bar->width, sb_width);
4565 XSETINT (bar->height, height);
4566 #ifdef USE_TOOLKIT_SCROLL_BARS
4567 bar->track_top = Qnil;
4568 bar->track_height = Qnil;
4569 #endif
4572 UNBLOCK_INPUT;
4575 #ifdef USE_TOOLKIT_SCROLL_BARS
4576 if (NILP (bar->track_top))
4578 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4579 Rect r0, r1;
4581 BLOCK_INPUT;
4583 SetControl32BitMinimum (ch, 0);
4584 SetControl32BitMaximum (ch, 1);
4585 SetControlViewSize (ch, 1);
4587 /* Move the scroll bar thumb to the top. */
4588 SetControl32BitValue (ch, 0);
4589 get_control_part_bounds (ch, kControlIndicatorPart, &r0);
4591 /* Move the scroll bar thumb to the bottom. */
4592 SetControl32BitValue (ch, 1);
4593 get_control_part_bounds (ch, kControlIndicatorPart, &r1);
4595 UnionRect (&r0, &r1, &r0);
4596 XSETINT (bar->track_top, r0.top);
4597 XSETINT (bar->track_height, r0.bottom - r0.top);
4599 UNBLOCK_INPUT;
4602 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
4603 #else /* not USE_TOOLKIT_SCROLL_BARS */
4604 /* Set the scroll bar's current state, unless we're currently being
4605 dragged. */
4606 if (NILP (bar->dragging))
4608 int top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, height);
4610 if (whole == 0)
4611 x_scroll_bar_set_handle (bar, 0, top_range, 0);
4612 else
4614 int start = ((double) position * top_range) / whole;
4615 int end = ((double) (position + portion) * top_range) / whole;
4616 x_scroll_bar_set_handle (bar, start, end, 0);
4619 #endif /* not USE_TOOLKIT_SCROLL_BARS */
4623 /* The following three hooks are used when we're doing a thorough
4624 redisplay of the frame. We don't explicitly know which scroll bars
4625 are going to be deleted, because keeping track of when windows go
4626 away is a real pain - "Can you say set-window-configuration, boys
4627 and girls?" Instead, we just assert at the beginning of redisplay
4628 that *all* scroll bars are to be removed, and then save a scroll bar
4629 from the fiery pit when we actually redisplay its window. */
4631 /* Arrange for all scroll bars on FRAME to be removed at the next call
4632 to `*judge_scroll_bars_hook'. A scroll bar may be spared if
4633 `*redeem_scroll_bar_hook' is applied to its window before the judgment. */
4635 static void
4636 XTcondemn_scroll_bars (frame)
4637 FRAME_PTR frame;
4639 /* Transfer all the scroll bars to FRAME_CONDEMNED_SCROLL_BARS. */
4640 while (! NILP (FRAME_SCROLL_BARS (frame)))
4642 Lisp_Object bar;
4643 bar = FRAME_SCROLL_BARS (frame);
4644 FRAME_SCROLL_BARS (frame) = XSCROLL_BAR (bar)->next;
4645 XSCROLL_BAR (bar)->next = FRAME_CONDEMNED_SCROLL_BARS (frame);
4646 XSCROLL_BAR (bar)->prev = Qnil;
4647 if (! NILP (FRAME_CONDEMNED_SCROLL_BARS (frame)))
4648 XSCROLL_BAR (FRAME_CONDEMNED_SCROLL_BARS (frame))->prev = bar;
4649 FRAME_CONDEMNED_SCROLL_BARS (frame) = bar;
4654 /* Un-mark WINDOW's scroll bar for deletion in this judgment cycle.
4655 Note that WINDOW isn't necessarily condemned at all. */
4657 static void
4658 XTredeem_scroll_bar (window)
4659 struct window *window;
4661 struct scroll_bar *bar;
4662 struct frame *f;
4664 /* We can't redeem this window's scroll bar if it doesn't have one. */
4665 if (NILP (window->vertical_scroll_bar))
4666 abort ();
4668 bar = XSCROLL_BAR (window->vertical_scroll_bar);
4670 /* Unlink it from the condemned list. */
4671 f = XFRAME (WINDOW_FRAME (window));
4672 if (NILP (bar->prev))
4674 /* If the prev pointer is nil, it must be the first in one of
4675 the lists. */
4676 if (EQ (FRAME_SCROLL_BARS (f), window->vertical_scroll_bar))
4677 /* It's not condemned. Everything's fine. */
4678 return;
4679 else if (EQ (FRAME_CONDEMNED_SCROLL_BARS (f),
4680 window->vertical_scroll_bar))
4681 FRAME_CONDEMNED_SCROLL_BARS (f) = bar->next;
4682 else
4683 /* If its prev pointer is nil, it must be at the front of
4684 one or the other! */
4685 abort ();
4687 else
4688 XSCROLL_BAR (bar->prev)->next = bar->next;
4690 if (! NILP (bar->next))
4691 XSCROLL_BAR (bar->next)->prev = bar->prev;
4693 bar->next = FRAME_SCROLL_BARS (f);
4694 bar->prev = Qnil;
4695 XSETVECTOR (FRAME_SCROLL_BARS (f), bar);
4696 if (! NILP (bar->next))
4697 XSETVECTOR (XSCROLL_BAR (bar->next)->prev, bar);
4700 /* Remove all scroll bars on FRAME that haven't been saved since the
4701 last call to `*condemn_scroll_bars_hook'. */
4703 static void
4704 XTjudge_scroll_bars (f)
4705 FRAME_PTR f;
4707 Lisp_Object bar, next;
4709 bar = FRAME_CONDEMNED_SCROLL_BARS (f);
4711 /* Clear out the condemned list now so we won't try to process any
4712 more events on the hapless scroll bars. */
4713 FRAME_CONDEMNED_SCROLL_BARS (f) = Qnil;
4715 for (; ! NILP (bar); bar = next)
4717 struct scroll_bar *b = XSCROLL_BAR (bar);
4719 x_scroll_bar_remove (b);
4721 next = b->next;
4722 b->next = b->prev = Qnil;
4725 /* Now there should be no references to the condemned scroll bars,
4726 and they should get garbage-collected. */
4730 /* Handle a mouse click on the scroll bar BAR. If *EMACS_EVENT's kind
4731 is set to something other than NO_EVENT, it is enqueued.
4733 This may be called from a signal handler, so we have to ignore GC
4734 mark bits. */
4736 static void
4737 x_scroll_bar_handle_click (bar, part_code, er, bufp)
4738 struct scroll_bar *bar;
4739 ControlPartCode part_code;
4740 EventRecord *er;
4741 struct input_event *bufp;
4743 int win_y, top_range;
4745 if (! GC_WINDOWP (bar->window))
4746 abort ();
4748 bufp->kind = SCROLL_BAR_CLICK_EVENT;
4749 bufp->frame_or_window = bar->window;
4750 bufp->arg = Qnil;
4752 bar->dragging = Qnil;
4754 switch (part_code)
4756 case kControlUpButtonPart:
4757 bufp->part = scroll_bar_up_arrow;
4758 break;
4759 case kControlDownButtonPart:
4760 bufp->part = scroll_bar_down_arrow;
4761 break;
4762 case kControlPageUpPart:
4763 bufp->part = scroll_bar_above_handle;
4764 break;
4765 case kControlPageDownPart:
4766 bufp->part = scroll_bar_below_handle;
4767 break;
4768 #if TARGET_API_MAC_CARBON
4769 default:
4770 #else
4771 case kControlIndicatorPart:
4772 #endif
4773 if (er->what == mouseDown)
4774 bar->dragging = make_number (0);
4775 XSETVECTOR (last_mouse_scroll_bar, bar);
4776 bufp->part = scroll_bar_handle;
4777 break;
4780 win_y = XINT (bufp->y) - XINT (bar->top);
4781 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (0/*dummy*/, XINT (bar->height));
4783 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
4785 win_y -= 24;
4787 if (! NILP (bar->dragging))
4788 win_y -= XINT (bar->dragging);
4790 if (win_y < 0)
4791 win_y = 0;
4792 if (win_y > top_range)
4793 win_y = top_range;
4795 XSETINT (bufp->x, win_y);
4796 XSETINT (bufp->y, top_range);
4799 #ifndef USE_TOOLKIT_SCROLL_BARS
4801 /* Handle some mouse motion while someone is dragging the scroll bar.
4803 This may be called from a signal handler, so we have to ignore GC
4804 mark bits. */
4806 static void
4807 x_scroll_bar_note_movement (bar, y_pos, t)
4808 struct scroll_bar *bar;
4809 int y_pos;
4810 Time t;
4812 FRAME_PTR f = XFRAME (XWINDOW (bar->window)->frame);
4814 last_mouse_movement_time = t;
4816 f->mouse_moved = 1;
4817 XSETVECTOR (last_mouse_scroll_bar, bar);
4819 /* If we're dragging the bar, display it. */
4820 if (! GC_NILP (bar->dragging))
4822 /* Where should the handle be now? */
4823 int new_start = y_pos - 24;
4825 if (new_start != XINT (bar->start))
4827 int new_end = new_start + (XINT (bar->end) - XINT (bar->start));
4829 x_scroll_bar_set_handle (bar, new_start, new_end, 0);
4834 #endif /* !USE_TOOLKIT_SCROLL_BARS */
4836 /* Return information to the user about the current position of the mouse
4837 on the scroll bar. */
4839 static void
4840 x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
4841 FRAME_PTR *fp;
4842 Lisp_Object *bar_window;
4843 enum scroll_bar_part *part;
4844 Lisp_Object *x, *y;
4845 unsigned long *time;
4847 struct scroll_bar *bar = XSCROLL_BAR (last_mouse_scroll_bar);
4848 ControlHandle ch = SCROLL_BAR_CONTROL_HANDLE (bar);
4849 #if TARGET_API_MAC_CARBON
4850 WindowPtr wp = GetControlOwner (ch);
4851 #else
4852 WindowPtr wp = (*ch)->contrlOwner;
4853 #endif
4854 Point mouse_pos;
4855 struct frame *f = mac_window_to_frame (wp);
4856 int win_y, top_range;
4858 SetPortWindowPort (wp);
4860 GetMouse (&mouse_pos);
4862 win_y = mouse_pos.v - XINT (bar->top);
4863 top_range = VERTICAL_SCROLL_BAR_TOP_RANGE (f, XINT (bar->height));
4865 win_y -= VERTICAL_SCROLL_BAR_TOP_BORDER;
4867 win_y -= 24;
4869 if (! NILP (bar->dragging))
4870 win_y -= XINT (bar->dragging);
4872 if (win_y < 0)
4873 win_y = 0;
4874 if (win_y > top_range)
4875 win_y = top_range;
4877 *fp = f;
4878 *bar_window = bar->window;
4880 if (! NILP (bar->dragging))
4881 *part = scroll_bar_handle;
4882 else if (win_y < XINT (bar->start))
4883 *part = scroll_bar_above_handle;
4884 else if (win_y < XINT (bar->end) + VERTICAL_SCROLL_BAR_MIN_HANDLE)
4885 *part = scroll_bar_handle;
4886 else
4887 *part = scroll_bar_below_handle;
4889 XSETINT (*x, win_y);
4890 XSETINT (*y, top_range);
4892 f->mouse_moved = 0;
4893 last_mouse_scroll_bar = Qnil;
4895 *time = last_mouse_movement_time;
4899 /* The screen has been cleared so we may have changed foreground or
4900 background colors, and the scroll bars may need to be redrawn.
4901 Clear out the scroll bars, and ask for expose events, so we can
4902 redraw them. */
4904 void
4905 x_scroll_bar_clear (f)
4906 FRAME_PTR f;
4908 XTcondemn_scroll_bars (f);
4909 XTjudge_scroll_bars (f);
4913 /***********************************************************************
4914 Text Cursor
4915 ***********************************************************************/
4917 /* Set clipping for output in glyph row ROW. W is the window in which
4918 we operate. GC is the graphics context to set clipping in.
4920 ROW may be a text row or, e.g., a mode line. Text rows must be
4921 clipped to the interior of the window dedicated to text display,
4922 mode lines must be clipped to the whole window. */
4924 static void
4925 x_clip_to_row (w, row, area, gc)
4926 struct window *w;
4927 struct glyph_row *row;
4928 int area;
4929 GC gc;
4931 struct frame *f = XFRAME (WINDOW_FRAME (w));
4932 Rect clip_rect;
4933 int window_x, window_y, window_width;
4935 window_box (w, area, &window_x, &window_y, &window_width, 0);
4937 clip_rect.left = window_x;
4938 clip_rect.top = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
4939 clip_rect.top = max (clip_rect.top, window_y);
4940 clip_rect.right = clip_rect.left + window_width;
4941 clip_rect.bottom = clip_rect.top + row->visible_height;
4943 mac_set_clip_rectangle (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f), &clip_rect);
4947 /* Draw a hollow box cursor on window W in glyph row ROW. */
4949 static void
4950 x_draw_hollow_cursor (w, row)
4951 struct window *w;
4952 struct glyph_row *row;
4954 struct frame *f = XFRAME (WINDOW_FRAME (w));
4955 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
4956 Display *dpy = FRAME_MAC_DISPLAY (f);
4957 int x, y, wd, h;
4958 XGCValues xgcv;
4959 struct glyph *cursor_glyph;
4960 GC gc;
4962 /* Get the glyph the cursor is on. If we can't tell because
4963 the current matrix is invalid or such, give up. */
4964 cursor_glyph = get_phys_cursor_glyph (w);
4965 if (cursor_glyph == NULL)
4966 return;
4968 /* Compute frame-relative coordinates for phys cursor. */
4969 x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
4970 y = get_phys_cursor_geometry (w, row, cursor_glyph, &h);
4971 wd = w->phys_cursor_width;
4973 /* The foreground of cursor_gc is typically the same as the normal
4974 background color, which can cause the cursor box to be invisible. */
4975 xgcv.foreground = f->output_data.mac->cursor_pixel;
4976 if (dpyinfo->scratch_cursor_gc)
4977 XChangeGC (dpy, dpyinfo->scratch_cursor_gc, GCForeground, &xgcv);
4978 else
4979 dpyinfo->scratch_cursor_gc = XCreateGC (dpy, FRAME_MAC_WINDOW (f),
4980 GCForeground, &xgcv);
4981 gc = dpyinfo->scratch_cursor_gc;
4983 /* Set clipping, draw the rectangle, and reset clipping again. */
4984 x_clip_to_row (w, row, TEXT_AREA, gc);
4985 mac_draw_rectangle (dpy, FRAME_MAC_WINDOW (f), gc, x, y, wd, h);
4986 mac_reset_clipping (dpy, FRAME_MAC_WINDOW (f));
4990 /* Draw a bar cursor on window W in glyph row ROW.
4992 Implementation note: One would like to draw a bar cursor with an
4993 angle equal to the one given by the font property XA_ITALIC_ANGLE.
4994 Unfortunately, I didn't find a font yet that has this property set.
4995 --gerd. */
4997 static void
4998 x_draw_bar_cursor (w, row, width, kind)
4999 struct window *w;
5000 struct glyph_row *row;
5001 int width;
5002 enum text_cursor_kinds kind;
5004 struct frame *f = XFRAME (w->frame);
5005 struct glyph *cursor_glyph;
5007 /* If cursor is out of bounds, don't draw garbage. This can happen
5008 in mini-buffer windows when switching between echo area glyphs
5009 and mini-buffer. */
5010 cursor_glyph = get_phys_cursor_glyph (w);
5011 if (cursor_glyph == NULL)
5012 return;
5014 /* If on an image, draw like a normal cursor. That's usually better
5015 visible than drawing a bar, esp. if the image is large so that
5016 the bar might not be in the window. */
5017 if (cursor_glyph->type == IMAGE_GLYPH)
5019 struct glyph_row *row;
5020 row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos);
5021 draw_phys_cursor_glyph (w, row, DRAW_CURSOR);
5023 else
5025 Display *dpy = FRAME_MAC_DISPLAY (f);
5026 Window window = FRAME_MAC_WINDOW (f);
5027 GC gc = FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc;
5028 unsigned long mask = GCForeground | GCBackground;
5029 struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
5030 XGCValues xgcv;
5032 /* If the glyph's background equals the color we normally draw
5033 the bar cursor in, the bar cursor in its normal color is
5034 invisible. Use the glyph's foreground color instead in this
5035 case, on the assumption that the glyph's colors are chosen so
5036 that the glyph is legible. */
5037 if (face->background == f->output_data.mac->cursor_pixel)
5038 xgcv.background = xgcv.foreground = face->foreground;
5039 else
5040 xgcv.background = xgcv.foreground = f->output_data.mac->cursor_pixel;
5042 if (gc)
5043 XChangeGC (dpy, gc, mask, &xgcv);
5044 else
5046 gc = XCreateGC (dpy, window, mask, &xgcv);
5047 FRAME_MAC_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
5050 if (width < 0)
5051 width = FRAME_CURSOR_WIDTH (f);
5052 width = min (cursor_glyph->pixel_width, width);
5054 w->phys_cursor_width = width;
5055 x_clip_to_row (w, row, TEXT_AREA, gc);
5057 if (kind == BAR_CURSOR)
5058 XFillRectangle (dpy, window, gc,
5059 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5060 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
5061 width, row->height);
5062 else
5063 XFillRectangle (dpy, window, gc,
5064 WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
5065 WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
5066 row->height - width),
5067 cursor_glyph->pixel_width,
5068 width);
5070 mac_reset_clipping (dpy, FRAME_MAC_WINDOW (f));
5075 /* RIF: Define cursor CURSOR on frame F. */
5077 static void
5078 mac_define_frame_cursor (f, cursor)
5079 struct frame *f;
5080 Cursor cursor;
5082 SetThemeCursor (cursor);
5086 /* RIF: Clear area on frame F. */
5088 static void
5089 mac_clear_frame_area (f, x, y, width, height)
5090 struct frame *f;
5091 int x, y, width, height;
5093 XClearArea (FRAME_MAC_DISPLAY (f), FRAME_MAC_WINDOW (f),
5094 x, y, width, height, 0);
5098 /* RIF: Draw cursor on window W. */
5100 static void
5101 mac_draw_window_cursor (w, glyph_row, x, y, cursor_type, cursor_width, on_p, active_p)
5102 struct window *w;
5103 struct glyph_row *glyph_row;
5104 int x, y;
5105 int cursor_type, cursor_width;
5106 int on_p, active_p;
5108 if (on_p)
5110 w->phys_cursor_type = cursor_type;
5111 w->phys_cursor_on_p = 1;
5113 if (glyph_row->exact_window_width_line_p
5114 && w->phys_cursor.hpos >= glyph_row->used[TEXT_AREA])
5116 glyph_row->cursor_in_fringe_p = 1;
5117 draw_fringe_bitmap (w, glyph_row, 0);
5119 else
5120 switch (cursor_type)
5122 case HOLLOW_BOX_CURSOR:
5123 x_draw_hollow_cursor (w, glyph_row);
5124 break;
5126 case FILLED_BOX_CURSOR:
5127 draw_phys_cursor_glyph (w, glyph_row, DRAW_CURSOR);
5128 break;
5130 case BAR_CURSOR:
5131 x_draw_bar_cursor (w, glyph_row, cursor_width, BAR_CURSOR);
5132 break;
5134 case HBAR_CURSOR:
5135 x_draw_bar_cursor (w, glyph_row, cursor_width, HBAR_CURSOR);
5136 break;
5138 case NO_CURSOR:
5139 w->phys_cursor_width = 0;
5140 break;
5142 default:
5143 abort ();
5149 /* Icons. */
5151 #if 0 /* MAC_TODO: no icon support yet. */
5153 x_bitmap_icon (f, icon)
5154 struct frame *f;
5155 Lisp_Object icon;
5157 HANDLE hicon;
5159 if (FRAME_W32_WINDOW (f) == 0)
5160 return 1;
5162 if (NILP (icon))
5163 hicon = LoadIcon (hinst, EMACS_CLASS);
5164 else if (STRINGP (icon))
5165 hicon = LoadImage (NULL, (LPCTSTR) SDATA (icon), IMAGE_ICON, 0, 0,
5166 LR_DEFAULTSIZE | LR_LOADFROMFILE);
5167 else if (SYMBOLP (icon))
5169 LPCTSTR name;
5171 if (EQ (icon, intern ("application")))
5172 name = (LPCTSTR) IDI_APPLICATION;
5173 else if (EQ (icon, intern ("hand")))
5174 name = (LPCTSTR) IDI_HAND;
5175 else if (EQ (icon, intern ("question")))
5176 name = (LPCTSTR) IDI_QUESTION;
5177 else if (EQ (icon, intern ("exclamation")))
5178 name = (LPCTSTR) IDI_EXCLAMATION;
5179 else if (EQ (icon, intern ("asterisk")))
5180 name = (LPCTSTR) IDI_ASTERISK;
5181 else if (EQ (icon, intern ("winlogo")))
5182 name = (LPCTSTR) IDI_WINLOGO;
5183 else
5184 return 1;
5186 hicon = LoadIcon (NULL, name);
5188 else
5189 return 1;
5191 if (hicon == NULL)
5192 return 1;
5194 PostMessage (FRAME_W32_WINDOW (f), WM_SETICON, (WPARAM) ICON_BIG,
5195 (LPARAM) hicon);
5197 return 0;
5199 #endif /* MAC_TODO */
5201 /************************************************************************
5202 Handling X errors
5203 ************************************************************************/
5205 /* Display Error Handling functions not used on W32. Listing them here
5206 helps diff stay in step when comparing w32term.c with xterm.c.
5208 x_error_catcher (display, error)
5209 x_catch_errors (dpy)
5210 x_catch_errors_unwind (old_val)
5211 x_check_errors (dpy, format)
5212 x_had_errors_p (dpy)
5213 x_clear_errors (dpy)
5214 x_uncatch_errors (dpy, count)
5215 x_trace_wire ()
5216 x_connection_signal (signalnum)
5217 x_connection_closed (dpy, error_message)
5218 x_error_quitter (display, error)
5219 x_error_handler (display, error)
5220 x_io_error_quitter (display)
5225 /* Changing the font of the frame. */
5227 /* Give frame F the font named FONTNAME as its default font, and
5228 return the full name of that font. FONTNAME may be a wildcard
5229 pattern; in that case, we choose some font that fits the pattern.
5230 The return value shows which font we chose. */
5232 Lisp_Object
5233 x_new_font (f, fontname)
5234 struct frame *f;
5235 register char *fontname;
5237 struct font_info *fontp
5238 = FS_LOAD_FONT (f, 0, fontname, -1);
5240 if (!fontp)
5241 return Qnil;
5243 FRAME_FONT (f) = (XFontStruct *) (fontp->font);
5244 FRAME_BASELINE_OFFSET (f) = fontp->baseline_offset;
5245 FRAME_FONTSET (f) = -1;
5247 FRAME_COLUMN_WIDTH (f) = fontp->average_width;
5248 FRAME_SPACE_WIDTH (f) = fontp->space_width;
5249 FRAME_LINE_HEIGHT (f) = FONT_HEIGHT (FRAME_FONT (f));
5251 compute_fringe_widths (f, 1);
5253 /* Compute the scroll bar width in character columns. */
5254 if (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) > 0)
5256 int wid = FRAME_COLUMN_WIDTH (f);
5257 FRAME_CONFIG_SCROLL_BAR_COLS (f)
5258 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + wid-1) / wid;
5260 else
5262 int wid = FRAME_COLUMN_WIDTH (f);
5263 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (14 + wid - 1) / wid;
5266 /* Now make the frame display the given font. */
5267 if (FRAME_MAC_WINDOW (f) != 0)
5269 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->normal_gc,
5270 FRAME_FONT (f));
5271 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->reverse_gc,
5272 FRAME_FONT (f));
5273 XSetFont (FRAME_MAC_DISPLAY (f), f->output_data.mac->cursor_gc,
5274 FRAME_FONT (f));
5276 /* Don't change the size of a tip frame; there's no point in
5277 doing it because it's done in Fx_show_tip, and it leads to
5278 problems because the tip frame has no widget. */
5279 if (NILP (tip_frame) || XFRAME (tip_frame) != f)
5280 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
5283 return build_string (fontp->full_name);
5286 /* Give frame F the fontset named FONTSETNAME as its default font, and
5287 return the full name of that fontset. FONTSETNAME may be a wildcard
5288 pattern; in that case, we choose some fontset that fits the pattern.
5289 The return value shows which fontset we chose. */
5291 Lisp_Object
5292 x_new_fontset (f, fontsetname)
5293 struct frame *f;
5294 char *fontsetname;
5296 int fontset = fs_query_fontset (build_string (fontsetname), 0);
5297 Lisp_Object result;
5299 if (fontset < 0)
5300 return Qnil;
5302 if (FRAME_FONTSET (f) == fontset)
5303 /* This fontset is already set in frame F. There's nothing more
5304 to do. */
5305 return fontset_name (fontset);
5307 result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
5309 if (!STRINGP (result))
5310 /* Can't load ASCII font. */
5311 return Qnil;
5313 /* Since x_new_font doesn't update any fontset information, do it now. */
5314 FRAME_FONTSET (f) = fontset;
5316 return build_string (fontsetname);
5320 /***********************************************************************
5321 TODO: W32 Input Methods
5322 ***********************************************************************/
5323 /* Listing missing functions from xterm.c helps diff stay in step.
5325 xim_destroy_callback (xim, client_data, call_data)
5326 xim_open_dpy (dpyinfo, resource_name)
5327 struct xim_inst_t
5328 xim_instantiate_callback (display, client_data, call_data)
5329 xim_initialize (dpyinfo, resource_name)
5330 xim_close_dpy (dpyinfo)
5335 void
5336 mac_get_window_bounds (f, inner, outer)
5337 struct frame *f;
5338 Rect *inner, *outer;
5340 #if TARGET_API_MAC_CARBON
5341 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowContentRgn, inner);
5342 GetWindowBounds (FRAME_MAC_WINDOW (f), kWindowStructureRgn, outer);
5343 #else /* not TARGET_API_MAC_CARBON */
5344 RgnHandle region = NewRgn ();
5346 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowContentRgn, region);
5347 *inner = (*region)->rgnBBox;
5348 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowStructureRgn, region);
5349 *outer = (*region)->rgnBBox;
5350 DisposeRgn (region);
5351 #endif /* not TARGET_API_MAC_CARBON */
5356 /* Calculate the absolute position in frame F
5357 from its current recorded position values and gravity. */
5359 void
5360 x_calc_absolute_position (f)
5361 struct frame *f;
5363 int width_diff = 0, height_diff = 0;
5364 int flags = f->size_hint_flags;
5365 Rect inner, outer;
5367 /* We have nothing to do if the current position
5368 is already for the top-left corner. */
5369 if (! ((flags & XNegative) || (flags & YNegative)))
5370 return;
5372 /* Find the offsets of the outside upper-left corner of
5373 the inner window, with respect to the outer window. */
5374 mac_get_window_bounds (f, &inner, &outer);
5376 width_diff = (outer.right - outer.left) - (inner.right - inner.left);
5377 height_diff = (outer.bottom - outer.top) - (inner.bottom - inner.top);
5379 /* Treat negative positions as relative to the leftmost bottommost
5380 position that fits on the screen. */
5381 if (flags & XNegative)
5382 f->left_pos = (FRAME_MAC_DISPLAY_INFO (f)->width
5383 - width_diff
5384 - FRAME_PIXEL_WIDTH (f)
5385 + f->left_pos);
5387 if (flags & YNegative)
5388 f->top_pos = (FRAME_MAC_DISPLAY_INFO (f)->height
5389 - height_diff
5390 - FRAME_PIXEL_HEIGHT (f)
5391 + f->top_pos);
5393 /* The left_pos and top_pos
5394 are now relative to the top and left screen edges,
5395 so the flags should correspond. */
5396 f->size_hint_flags &= ~ (XNegative | YNegative);
5399 /* CHANGE_GRAVITY is 1 when calling from Fset_frame_position,
5400 to really change the position, and 0 when calling from
5401 x_make_frame_visible (in that case, XOFF and YOFF are the current
5402 position values). It is -1 when calling from x_set_frame_parameters,
5403 which means, do adjust for borders but don't change the gravity. */
5405 void
5406 x_set_offset (f, xoff, yoff, change_gravity)
5407 struct frame *f;
5408 register int xoff, yoff;
5409 int change_gravity;
5411 if (change_gravity > 0)
5413 f->top_pos = yoff;
5414 f->left_pos = xoff;
5415 f->size_hint_flags &= ~ (XNegative | YNegative);
5416 if (xoff < 0)
5417 f->size_hint_flags |= XNegative;
5418 if (yoff < 0)
5419 f->size_hint_flags |= YNegative;
5420 f->win_gravity = NorthWestGravity;
5422 x_calc_absolute_position (f);
5424 BLOCK_INPUT;
5425 x_wm_set_size_hint (f, (long) 0, 0);
5427 #if TARGET_API_MAC_CARBON
5428 MoveWindowStructure (FRAME_MAC_WINDOW (f), f->left_pos, f->top_pos);
5429 /* If the title bar is completely outside the screen, adjust the
5430 position. */
5431 ConstrainWindowToScreen (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn,
5432 kWindowConstrainMoveRegardlessOfFit
5433 | kWindowConstrainAllowPartial, NULL, NULL);
5434 x_real_positions (f, &f->left_pos, &f->top_pos);
5435 #else
5437 Rect inner, outer, screen_rect, dummy;
5438 RgnHandle region = NewRgn ();
5440 mac_get_window_bounds (f, &inner, &outer);
5441 f->x_pixels_diff = inner.left - outer.left;
5442 f->y_pixels_diff = inner.top - outer.top;
5443 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5444 f->top_pos + f->y_pixels_diff, false);
5446 /* If the title bar is completely outside the screen, adjust the
5447 position. The variable `outer' holds the title bar rectangle.
5448 The variable `inner' holds slightly smaller one than `outer',
5449 so that the calculation of overlapping may not become too
5450 strict. */
5451 GetWindowRegion (FRAME_MAC_WINDOW (f), kWindowTitleBarRgn, region);
5452 outer = (*region)->rgnBBox;
5453 DisposeRgn (region);
5454 inner = outer;
5455 InsetRect (&inner, 8, 8);
5456 screen_rect = qd.screenBits.bounds;
5457 screen_rect.top += GetMBarHeight ();
5459 if (!SectRect (&inner, &screen_rect, &dummy))
5461 if (inner.right <= screen_rect.left)
5462 f->left_pos = screen_rect.left;
5463 else if (inner.left >= screen_rect.right)
5464 f->left_pos = screen_rect.right - (outer.right - outer.left);
5466 if (inner.bottom <= screen_rect.top)
5467 f->top_pos = screen_rect.top;
5468 else if (inner.top >= screen_rect.bottom)
5469 f->top_pos = screen_rect.bottom - (outer.bottom - outer.top);
5471 MoveWindow (FRAME_MAC_WINDOW (f), f->left_pos + f->x_pixels_diff,
5472 f->top_pos + f->y_pixels_diff, false);
5475 #endif
5477 UNBLOCK_INPUT;
5480 /* Call this to change the size of frame F's x-window.
5481 If CHANGE_GRAVITY is 1, we change to top-left-corner window gravity
5482 for this size change and subsequent size changes.
5483 Otherwise we leave the window gravity unchanged. */
5485 void
5486 x_set_window_size (f, change_gravity, cols, rows)
5487 struct frame *f;
5488 int change_gravity;
5489 int cols, rows;
5491 int pixelwidth, pixelheight;
5493 BLOCK_INPUT;
5495 check_frame_size (f, &rows, &cols);
5496 f->scroll_bar_actual_width
5497 = FRAME_SCROLL_BAR_COLS (f) * FRAME_COLUMN_WIDTH (f);
5499 compute_fringe_widths (f, 0);
5501 pixelwidth = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, cols);
5502 pixelheight = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
5504 f->win_gravity = NorthWestGravity;
5505 x_wm_set_size_hint (f, (long) 0, 0);
5507 SizeWindow (FRAME_MAC_WINDOW (f), pixelwidth, pixelheight, 0);
5508 #if TARGET_API_MAC_CARBON
5509 if (f->output_data.mac->hourglass_control)
5510 MoveControl (f->output_data.mac->hourglass_control,
5511 pixelwidth - HOURGLASS_WIDTH, 0);
5512 #endif
5514 /* Now, strictly speaking, we can't be sure that this is accurate,
5515 but the window manager will get around to dealing with the size
5516 change request eventually, and we'll hear how it went when the
5517 ConfigureNotify event gets here.
5519 We could just not bother storing any of this information here,
5520 and let the ConfigureNotify event set everything up, but that
5521 might be kind of confusing to the Lisp code, since size changes
5522 wouldn't be reported in the frame parameters until some random
5523 point in the future when the ConfigureNotify event arrives.
5525 We pass 1 for DELAY since we can't run Lisp code inside of
5526 a BLOCK_INPUT. */
5527 change_frame_size (f, rows, cols, 0, 1, 0);
5528 FRAME_PIXEL_WIDTH (f) = pixelwidth;
5529 FRAME_PIXEL_HEIGHT (f) = pixelheight;
5531 /* We've set {FRAME,PIXEL}_{WIDTH,HEIGHT} to the values we hope to
5532 receive in the ConfigureNotify event; if we get what we asked
5533 for, then the event won't cause the screen to become garbaged, so
5534 we have to make sure to do it here. */
5535 SET_FRAME_GARBAGED (f);
5537 XFlush (FRAME_X_DISPLAY (f));
5539 /* If cursor was outside the new size, mark it as off. */
5540 mark_window_cursors_off (XWINDOW (f->root_window));
5542 /* Clear out any recollection of where the mouse highlighting was,
5543 since it might be in a place that's outside the new frame size.
5544 Actually checking whether it is outside is a pain in the neck,
5545 so don't try--just let the highlighting be done afresh with new size. */
5546 cancel_mouse_face (f);
5548 UNBLOCK_INPUT;
5551 /* Mouse warping. */
5553 void x_set_mouse_pixel_position (struct frame *f, int pix_x, int pix_y);
5555 void
5556 x_set_mouse_position (f, x, y)
5557 struct frame *f;
5558 int x, y;
5560 int pix_x, pix_y;
5562 pix_x = FRAME_COL_TO_PIXEL_X (f, x) + FRAME_COLUMN_WIDTH (f) / 2;
5563 pix_y = FRAME_LINE_TO_PIXEL_Y (f, y) + FRAME_LINE_HEIGHT (f) / 2;
5565 if (pix_x < 0) pix_x = 0;
5566 if (pix_x > FRAME_PIXEL_WIDTH (f)) pix_x = FRAME_PIXEL_WIDTH (f);
5568 if (pix_y < 0) pix_y = 0;
5569 if (pix_y > FRAME_PIXEL_HEIGHT (f)) pix_y = FRAME_PIXEL_HEIGHT (f);
5571 x_set_mouse_pixel_position (f, pix_x, pix_y);
5574 void
5575 x_set_mouse_pixel_position (f, pix_x, pix_y)
5576 struct frame *f;
5577 int pix_x, pix_y;
5579 #if 0 /* MAC_TODO: CursorDeviceMoveTo is non-Carbon */
5580 BLOCK_INPUT;
5582 XWarpPointer (FRAME_X_DISPLAY (f), None, FRAME_X_WINDOW (f),
5583 0, 0, 0, 0, pix_x, pix_y);
5584 UNBLOCK_INPUT;
5585 #endif
5588 /* focus shifting, raising and lowering. */
5590 void
5591 x_focus_on_frame (f)
5592 struct frame *f;
5594 #if 0 /* This proves to be unpleasant. */
5595 x_raise_frame (f);
5596 #endif
5597 #if 0
5598 /* I don't think that the ICCCM allows programs to do things like this
5599 without the interaction of the window manager. Whatever you end up
5600 doing with this code, do it to x_unfocus_frame too. */
5601 XSetInputFocus (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
5602 RevertToPointerRoot, CurrentTime);
5603 #endif /* ! 0 */
5606 void
5607 x_unfocus_frame (f)
5608 struct frame *f;
5612 /* Raise frame F. */
5614 void
5615 x_raise_frame (f)
5616 struct frame *f;
5618 if (f->async_visible)
5620 BLOCK_INPUT;
5621 SelectWindow (FRAME_MAC_WINDOW (f));
5622 UNBLOCK_INPUT;
5626 /* Lower frame F. */
5628 void
5629 x_lower_frame (f)
5630 struct frame *f;
5632 if (f->async_visible)
5634 BLOCK_INPUT;
5635 SendBehind (FRAME_MAC_WINDOW (f), nil);
5636 UNBLOCK_INPUT;
5640 static void
5641 XTframe_raise_lower (f, raise_flag)
5642 FRAME_PTR f;
5643 int raise_flag;
5645 if (raise_flag)
5646 x_raise_frame (f);
5647 else
5648 x_lower_frame (f);
5651 /* Change of visibility. */
5653 static void
5654 mac_handle_visibility_change (f)
5655 struct frame *f;
5657 WindowPtr wp = FRAME_MAC_WINDOW (f);
5658 int visible = 0, iconified = 0;
5659 struct input_event buf;
5661 if (IsWindowVisible (wp))
5662 if (IsWindowCollapsed (wp))
5663 iconified = 1;
5664 else
5665 visible = 1;
5667 if (!f->async_visible && visible)
5669 if (f->iconified)
5671 /* wait_reading_process_output will notice this and update
5672 the frame's display structures. If we were made
5673 invisible, we should not set garbaged, because that stops
5674 redrawing on Update events. */
5675 SET_FRAME_GARBAGED (f);
5677 EVENT_INIT (buf);
5678 buf.kind = DEICONIFY_EVENT;
5679 XSETFRAME (buf.frame_or_window, f);
5680 kbd_buffer_store_event (&buf);
5682 else if (! NILP (Vframe_list) && ! NILP (XCDR (Vframe_list)))
5683 /* Force a redisplay sooner or later to update the
5684 frame titles in case this is the second frame. */
5685 record_asynch_buffer_change ();
5687 else if (f->async_visible && !visible)
5688 if (iconified)
5690 EVENT_INIT (buf);
5691 buf.kind = ICONIFY_EVENT;
5692 XSETFRAME (buf.frame_or_window, f);
5693 kbd_buffer_store_event (&buf);
5696 f->async_visible = visible;
5697 f->async_iconified = iconified;
5700 /* This tries to wait until the frame is really visible.
5701 However, if the window manager asks the user where to position
5702 the frame, this will return before the user finishes doing that.
5703 The frame will not actually be visible at that time,
5704 but it will become visible later when the window manager
5705 finishes with it. */
5707 void
5708 x_make_frame_visible (f)
5709 struct frame *f;
5711 Lisp_Object type;
5712 int original_top, original_left;
5714 BLOCK_INPUT;
5716 if (! FRAME_VISIBLE_P (f))
5718 /* We test FRAME_GARBAGED_P here to make sure we don't
5719 call x_set_offset a second time
5720 if we get to x_make_frame_visible a second time
5721 before the window gets really visible. */
5722 if (! FRAME_ICONIFIED_P (f)
5723 && ! f->output_data.mac->asked_for_visible)
5724 #if TARGET_API_MAC_CARBON
5725 if (!(FRAME_SIZE_HINTS (f)->flags & (USPosition | PPosition)))
5727 struct frame *sf = SELECTED_FRAME ();
5728 if (!FRAME_MAC_P (sf))
5729 RepositionWindow (FRAME_MAC_WINDOW (f), NULL,
5730 kWindowCenterOnMainScreen);
5731 else
5732 RepositionWindow (FRAME_MAC_WINDOW (f),
5733 FRAME_MAC_WINDOW (sf),
5734 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
5735 kWindowCascadeStartAtParentWindowScreen
5736 #else
5737 kWindowCascadeOnParentWindowScreen
5738 #endif
5740 x_real_positions (f, &f->left_pos, &f->top_pos);
5742 else
5743 #endif
5744 x_set_offset (f, f->left_pos, f->top_pos, 0);
5746 f->output_data.mac->asked_for_visible = 1;
5748 SelectWindow (FRAME_MAC_WINDOW (f));
5749 CollapseWindow (FRAME_MAC_WINDOW (f), false);
5750 ShowWindow (FRAME_MAC_WINDOW (f));
5753 XFlush (FRAME_MAC_DISPLAY (f));
5755 /* Synchronize to ensure Emacs knows the frame is visible
5756 before we do anything else. We do this loop with input not blocked
5757 so that incoming events are handled. */
5759 Lisp_Object frame;
5760 int count;
5762 /* This must come after we set COUNT. */
5763 UNBLOCK_INPUT;
5765 XSETFRAME (frame, f);
5767 /* Wait until the frame is visible. Process X events until a
5768 MapNotify event has been seen, or until we think we won't get a
5769 MapNotify at all.. */
5770 for (count = input_signal_count + 10;
5771 input_signal_count < count && !FRAME_VISIBLE_P (f);)
5773 /* Force processing of queued events. */
5774 x_sync (f);
5776 /* Machines that do polling rather than SIGIO have been
5777 observed to go into a busy-wait here. So we'll fake an
5778 alarm signal to let the handler know that there's something
5779 to be read. We used to raise a real alarm, but it seems
5780 that the handler isn't always enabled here. This is
5781 probably a bug. */
5782 if (input_polling_used ())
5784 /* It could be confusing if a real alarm arrives while
5785 processing the fake one. Turn it off and let the
5786 handler reset it. */
5787 extern void poll_for_input_1 P_ ((void));
5788 int old_poll_suppress_count = poll_suppress_count;
5789 poll_suppress_count = 1;
5790 poll_for_input_1 ();
5791 poll_suppress_count = old_poll_suppress_count;
5794 /* See if a MapNotify event has been processed. */
5795 FRAME_SAMPLE_VISIBILITY (f);
5800 /* Change from mapped state to withdrawn state. */
5802 /* Make the frame visible (mapped and not iconified). */
5804 void
5805 x_make_frame_invisible (f)
5806 struct frame *f;
5808 /* A deactivate event does not occur when the last visible frame is
5809 made invisible. So if we clear the highlight here, it will not
5810 be rehighlighted when it is made visible. */
5811 #if 0
5812 /* Don't keep the highlight on an invisible frame. */
5813 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
5814 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
5815 #endif
5817 BLOCK_INPUT;
5819 /* Before unmapping the window, update the WM_SIZE_HINTS property to claim
5820 that the current position of the window is user-specified, rather than
5821 program-specified, so that when the window is mapped again, it will be
5822 placed at the same location, without forcing the user to position it
5823 by hand again (they have already done that once for this window.) */
5824 x_wm_set_size_hint (f, (long) 0, 1);
5826 HideWindow (FRAME_MAC_WINDOW (f));
5828 UNBLOCK_INPUT;
5830 #if !USE_CARBON_EVENTS
5831 mac_handle_visibility_change (f);
5832 #endif
5835 /* Change window state from mapped to iconified. */
5837 void
5838 x_iconify_frame (f)
5839 struct frame *f;
5841 OSErr err;
5843 /* A deactivate event does not occur when the last visible frame is
5844 iconified. So if we clear the highlight here, it will not be
5845 rehighlighted when it is deiconified. */
5846 #if 0
5847 /* Don't keep the highlight on an invisible frame. */
5848 if (FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame == f)
5849 FRAME_MAC_DISPLAY_INFO (f)->x_highlight_frame = 0;
5850 #endif
5852 if (f->async_iconified)
5853 return;
5855 BLOCK_INPUT;
5857 FRAME_SAMPLE_VISIBILITY (f);
5859 if (! FRAME_VISIBLE_P (f))
5860 ShowWindow (FRAME_MAC_WINDOW (f));
5862 err = CollapseWindow (FRAME_MAC_WINDOW (f), true);
5864 UNBLOCK_INPUT;
5866 if (err != noErr)
5867 error ("Can't notify window manager of iconification");
5869 #if !USE_CARBON_EVENTS
5870 mac_handle_visibility_change (f);
5871 #endif
5875 /* Free X resources of frame F. */
5877 void
5878 x_free_frame_resources (f)
5879 struct frame *f;
5881 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5882 WindowPtr wp = FRAME_MAC_WINDOW (f);
5884 BLOCK_INPUT;
5886 if (wp != tip_window)
5887 remove_window_handler (wp);
5889 DisposeWindow (wp);
5890 if (wp == tip_window)
5891 /* Neither WaitNextEvent nor ReceiveNextEvent receives `window
5892 closed' event. So we reset tip_window here. */
5893 tip_window = NULL;
5895 free_frame_menubar (f);
5897 if (FRAME_FACE_CACHE (f))
5898 free_frame_faces (f);
5900 x_free_gcs (f);
5902 if (FRAME_SIZE_HINTS (f))
5903 xfree (FRAME_SIZE_HINTS (f));
5905 xfree (f->output_data.mac);
5906 f->output_data.mac = NULL;
5908 if (f == dpyinfo->x_focus_frame)
5909 dpyinfo->x_focus_frame = 0;
5910 if (f == dpyinfo->x_focus_event_frame)
5911 dpyinfo->x_focus_event_frame = 0;
5912 if (f == dpyinfo->x_highlight_frame)
5913 dpyinfo->x_highlight_frame = 0;
5915 if (f == dpyinfo->mouse_face_mouse_frame)
5917 dpyinfo->mouse_face_beg_row
5918 = dpyinfo->mouse_face_beg_col = -1;
5919 dpyinfo->mouse_face_end_row
5920 = dpyinfo->mouse_face_end_col = -1;
5921 dpyinfo->mouse_face_window = Qnil;
5922 dpyinfo->mouse_face_deferred_gc = 0;
5923 dpyinfo->mouse_face_mouse_frame = 0;
5926 UNBLOCK_INPUT;
5930 /* Destroy the X window of frame F. */
5932 void
5933 x_destroy_window (f)
5934 struct frame *f;
5936 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
5938 x_free_frame_resources (f);
5940 dpyinfo->reference_count--;
5944 /* Setting window manager hints. */
5946 /* Set the normal size hints for the window manager, for frame F.
5947 FLAGS is the flags word to use--or 0 meaning preserve the flags
5948 that the window now has.
5949 If USER_POSITION is nonzero, we set the USPosition
5950 flag (this is useful when FLAGS is 0). */
5951 void
5952 x_wm_set_size_hint (f, flags, user_position)
5953 struct frame *f;
5954 long flags;
5955 int user_position;
5957 int base_width, base_height, width_inc, height_inc;
5958 int min_rows = 0, min_cols = 0;
5959 XSizeHints *size_hints;
5961 base_width = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, 0);
5962 base_height = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, 0);
5963 width_inc = FRAME_COLUMN_WIDTH (f);
5964 height_inc = FRAME_LINE_HEIGHT (f);
5966 check_frame_size (f, &min_rows, &min_cols);
5968 size_hints = FRAME_SIZE_HINTS (f);
5969 if (size_hints == NULL)
5971 size_hints = FRAME_SIZE_HINTS (f) = xmalloc (sizeof (XSizeHints));
5972 bzero (size_hints, sizeof (XSizeHints));
5975 size_hints->flags |= PResizeInc | PMinSize | PBaseSize ;
5976 size_hints->width_inc = width_inc;
5977 size_hints->height_inc = height_inc;
5978 size_hints->min_width = base_width + min_cols * width_inc;
5979 size_hints->min_height = base_height + min_rows * height_inc;
5980 size_hints->base_width = base_width;
5981 size_hints->base_height = base_height;
5983 if (flags)
5984 size_hints->flags = flags;
5985 else if (user_position)
5987 size_hints->flags &= ~ PPosition;
5988 size_hints->flags |= USPosition;
5992 #if 0 /* MAC_TODO: hide application instead of iconify? */
5993 /* Used for IconicState or NormalState */
5995 void
5996 x_wm_set_window_state (f, state)
5997 struct frame *f;
5998 int state;
6000 #ifdef USE_X_TOOLKIT
6001 Arg al[1];
6003 XtSetArg (al[0], XtNinitialState, state);
6004 XtSetValues (f->output_data.x->widget, al, 1);
6005 #else /* not USE_X_TOOLKIT */
6006 Window window = FRAME_X_WINDOW (f);
6008 f->output_data.x->wm_hints.flags |= StateHint;
6009 f->output_data.x->wm_hints.initial_state = state;
6011 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6012 #endif /* not USE_X_TOOLKIT */
6015 void
6016 x_wm_set_icon_pixmap (f, pixmap_id)
6017 struct frame *f;
6018 int pixmap_id;
6020 Pixmap icon_pixmap;
6022 #ifndef USE_X_TOOLKIT
6023 Window window = FRAME_X_WINDOW (f);
6024 #endif
6026 if (pixmap_id > 0)
6028 icon_pixmap = x_bitmap_pixmap (f, pixmap_id);
6029 f->output_data.x->wm_hints.icon_pixmap = icon_pixmap;
6031 else
6033 /* It seems there is no way to turn off use of an icon pixmap.
6034 The following line does it, only if no icon has yet been created,
6035 for some window managers. But with mwm it crashes.
6036 Some people say it should clear the IconPixmapHint bit in this case,
6037 but that doesn't work, and the X consortium said it isn't the
6038 right thing at all. Since there is no way to win,
6039 best to explicitly give up. */
6040 #if 0
6041 f->output_data.x->wm_hints.icon_pixmap = None;
6042 #else
6043 return;
6044 #endif
6047 #ifdef USE_X_TOOLKIT /* same as in x_wm_set_window_state. */
6050 Arg al[1];
6051 XtSetArg (al[0], XtNiconPixmap, icon_pixmap);
6052 XtSetValues (f->output_data.x->widget, al, 1);
6055 #else /* not USE_X_TOOLKIT */
6057 f->output_data.x->wm_hints.flags |= IconPixmapHint;
6058 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6060 #endif /* not USE_X_TOOLKIT */
6063 #endif /* MAC_TODO */
6065 void
6066 x_wm_set_icon_position (f, icon_x, icon_y)
6067 struct frame *f;
6068 int icon_x, icon_y;
6070 #if 0 /* MAC_TODO: no icons on Mac */
6071 #ifdef USE_X_TOOLKIT
6072 Window window = XtWindow (f->output_data.x->widget);
6073 #else
6074 Window window = FRAME_X_WINDOW (f);
6075 #endif
6077 f->output_data.x->wm_hints.flags |= IconPositionHint;
6078 f->output_data.x->wm_hints.icon_x = icon_x;
6079 f->output_data.x->wm_hints.icon_y = icon_y;
6081 XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
6082 #endif /* MAC_TODO */
6086 /***********************************************************************
6087 XLFD Pattern Match
6088 ***********************************************************************/
6090 /* An XLFD pattern is divided into blocks delimited by '*'. This
6091 structure holds information for each block. */
6092 struct xlfdpat_block
6094 /* Length of the pattern string in this block. Non-zero except for
6095 the first and the last blocks. */
6096 int len;
6098 /* Pattern string except the last character in this block. The last
6099 character is replaced with NUL in order to use it as a
6100 sentinel. */
6101 unsigned char *pattern;
6103 /* Last character of the pattern string. Must not be '?'. */
6104 unsigned char last_char;
6106 /* One of the tables for the Boyer-Moore string search. It
6107 specifies the number of positions to proceed for each character
6108 with which the match fails. */
6109 int skip[256];
6111 /* The skip value for the last character in the above `skip' is
6112 assigned to `infinity' in order to simplify a loop condition.
6113 The original value is saved here. */
6114 int last_char_skip;
6117 struct xlfdpat
6119 /* Normalized pattern string. "Normalized" means that capital
6120 letters are lowered, blocks are not empty except the first and
6121 the last ones, and trailing '?'s in a block that is not the last
6122 one are moved to the next one. The last character in each block
6123 is replaced with NUL. */
6124 unsigned char *buf;
6126 /* Number of characters except '*'s and trailing '?'s in the
6127 normalized pattern string. */
6128 int nchars;
6130 /* Number of trailing '?'s in the normalized pattern string. */
6131 int trailing_anychars;
6133 /* Number of blocks and information for each block. The latter is
6134 NULL if the pattern is exact (no '*' or '?' in it). */
6135 int nblocks;
6136 struct xlfdpat_block *blocks;
6139 static void
6140 xlfdpat_destroy (pat)
6141 struct xlfdpat *pat;
6143 if (pat)
6145 if (pat->buf)
6147 if (pat->blocks)
6148 xfree (pat->blocks);
6149 xfree (pat->buf);
6151 xfree (pat);
6155 static struct xlfdpat *
6156 xlfdpat_create (pattern)
6157 char *pattern;
6159 struct xlfdpat *pat;
6160 int nblocks, i, skip;
6161 unsigned char last_char, *p, *q, *anychar_head;
6162 struct xlfdpat_block *blk;
6164 pat = xmalloc (sizeof (struct xlfdpat));
6165 if (pat == NULL)
6166 goto error;
6168 pat->buf = xmalloc (strlen (pattern) + 1);
6169 if (pat->buf == NULL)
6170 goto error;
6172 /* Normalize the pattern string and store it to `pat->buf'. */
6173 nblocks = 0;
6174 anychar_head = NULL;
6175 q = pat->buf;
6176 last_char = '\0';
6177 for (p = pattern; *p; p++)
6179 unsigned char c = *p;
6181 if (c == '*')
6182 if (last_char == '*')
6183 /* ...a** -> ...a* */
6184 continue;
6185 else
6187 if (last_char == '?')
6188 if (anychar_head > pat->buf && *(anychar_head - 1) == '*')
6189 /* ...*??* -> ...*?? */
6190 continue;
6191 else
6192 /* ...a??* -> ...a*?? */
6194 *anychar_head++ = '*';
6195 c = '?';
6197 nblocks++;
6199 else if (c == '?')
6201 if (last_char != '?')
6202 anychar_head = q;
6204 else
6205 /* On Mac OS X 10.3, tolower also converts non-ASCII
6206 characters for some locales. */
6207 if (isascii (c))
6208 c = tolower (c);
6210 *q++ = last_char = c;
6212 *q = '\0';
6213 nblocks++;
6214 pat->nblocks = nblocks;
6215 if (last_char != '?')
6216 pat->trailing_anychars = 0;
6217 else
6219 pat->trailing_anychars = q - anychar_head;
6220 q = anychar_head;
6222 pat->nchars = q - pat->buf - (nblocks - 1);
6224 if (anychar_head == NULL && nblocks == 1)
6226 /* The pattern is exact. */
6227 pat->blocks = NULL;
6228 return pat;
6231 pat->blocks = xmalloc (sizeof (struct xlfdpat_block) * nblocks);
6232 if (pat->blocks == NULL)
6233 goto error;
6235 /* Divide the normalized pattern into blocks. */
6236 p = pat->buf;
6237 for (blk = pat->blocks; blk < pat->blocks + nblocks - 1; blk++)
6239 blk->pattern = p;
6240 while (*p != '*')
6241 p++;
6242 blk->len = p - blk->pattern;
6243 p++;
6245 blk->pattern = p;
6246 blk->len = q - blk->pattern;
6248 /* Setup a table for the Boyer-Moore string search. */
6249 for (blk = pat->blocks; blk < pat->blocks + nblocks; blk++)
6250 if (blk->len != 0)
6252 blk->last_char = blk->pattern[blk->len - 1];
6253 blk->pattern[blk->len - 1] = '\0';
6255 for (skip = 1; skip < blk->len; skip++)
6256 if (blk->pattern[blk->len - skip - 1] == '?')
6257 break;
6259 for (i = 0; i < 256; i++)
6260 blk->skip[i] = skip;
6262 p = blk->pattern + (blk->len - skip);
6263 while (--skip > 0)
6264 blk->skip[*p++] = skip;
6266 blk->last_char_skip = blk->skip[blk->last_char];
6269 return pat;
6271 error:
6272 xlfdpat_destroy (pat);
6273 return NULL;
6276 static INLINE int
6277 xlfdpat_exact_p (pat)
6278 struct xlfdpat *pat;
6280 return (pat)->blocks == NULL;
6283 /* Return the first string in STRING + 0, ..., STRING + START_MAX such
6284 that the pattern in *BLK matches with its prefix. Return NULL
6285 there is no such strings. STRING must be lowered in advance. */
6287 static char *
6288 xlfdpat_block_match_1 (blk, string, start_max)
6289 struct xlfdpat_block *blk;
6290 unsigned char *string;
6291 int start_max;
6293 int start, infinity;
6294 unsigned char *p, *s;
6296 xassert (blk->len > 0);
6297 xassert (start_max + blk->len <= strlen (string));
6298 xassert (blk->pattern[blk->len - 1] != '?');
6300 /* See the comments in the function `boyer_moore' (search.c) for the
6301 use of `infinity'. */
6302 infinity = start_max + blk->len + 1;
6303 blk->skip[blk->last_char] = infinity;
6305 start = 0;
6308 /* Check the last character of the pattern. */
6309 s = string + blk->len - 1;
6312 start += blk->skip[*(s + start)];
6314 while (start <= start_max);
6316 if (start < infinity)
6317 /* Couldn't find the last character. */
6318 return NULL;
6320 /* No less than `infinity' means we could find the last
6321 character at `s[start - infinity]'. */
6322 start -= infinity;
6324 /* Check the remaining characters. We prefer making no-'?'
6325 cases faster because the use of '?' is really rare. */
6326 p = blk->pattern;
6327 s = string + start;
6330 while (*p++ == *s++)
6333 while (*(p - 1) == '?');
6335 if (*(p - 1) == '\0')
6336 /* Matched. */
6337 return string + start;
6339 /* Didn't match. */
6340 start += blk->last_char_skip;
6342 while (start <= start_max);
6344 return NULL;
6347 #define xlfdpat_block_match(b, s, m) \
6348 ((b)->len == 1 ? memchr ((s), (b)->last_char, (m) + 1) \
6349 : xlfdpat_block_match_1 (b, s, m))
6351 /* Check if XLFD pattern PAT, which is generated by `xfldpat_create',
6352 matches with STRING. STRING must be lowered in advance. */
6354 static int
6355 xlfdpat_match (pat, string)
6356 struct xlfdpat *pat;
6357 unsigned char *string;
6359 int str_len, nblocks, i, start_max;
6360 struct xlfdpat_block *blk;
6361 unsigned char *s;
6363 xassert (pat->nblocks > 0);
6365 if (xlfdpat_exact_p (pat))
6366 return strcmp (pat->buf, string) == 0;
6368 /* The number of the characters in the string must not be smaller
6369 than that in the pattern. */
6370 str_len = strlen (string);
6371 if (str_len < pat->nchars + pat->trailing_anychars)
6372 return 0;
6374 /* Chop off the trailing '?'s. */
6375 str_len -= pat->trailing_anychars;
6377 /* The last block. When it is non-empty, it must match at the end
6378 of the string. */
6379 nblocks = pat->nblocks;
6380 blk = pat->blocks + (nblocks - 1);
6381 if (nblocks == 1)
6382 /* The last block is also the first one. */
6383 return (str_len == blk->len
6384 && (blk->len == 0 || xlfdpat_block_match (blk, string, 0)));
6385 else if (blk->len != 0)
6386 if (!xlfdpat_block_match (blk, string + (str_len - blk->len), 0))
6387 return 0;
6389 /* The first block. When it is non-empty, it must match at the
6390 beginning of the string. */
6391 blk = pat->blocks;
6392 if (blk->len != 0)
6394 s = xlfdpat_block_match (blk, string, 0);
6395 if (s == NULL)
6396 return 0;
6397 string = s + blk->len;
6400 /* The rest of the blocks. */
6401 start_max = str_len - pat->nchars;
6402 for (i = 1, blk++; i < nblocks - 1; i++, blk++)
6404 s = xlfdpat_block_match (blk, string, start_max);
6405 if (s == NULL)
6406 return 0;
6407 start_max -= s - string;
6408 string = s + blk->len;
6411 return 1;
6415 /***********************************************************************
6416 Fonts
6417 ***********************************************************************/
6419 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6421 struct font_info *
6422 x_get_font_info (f, font_idx)
6423 FRAME_PTR f;
6424 int font_idx;
6426 return (FRAME_MAC_FONT_TABLE (f) + font_idx);
6429 /* the global font name table */
6430 static char **font_name_table = NULL;
6431 static int font_name_table_size = 0;
6432 static int font_name_count = 0;
6434 /* Alist linking character set strings to Mac text encoding and Emacs
6435 coding system. */
6436 static Lisp_Object Vmac_charset_info_alist;
6438 static Lisp_Object
6439 create_text_encoding_info_alist ()
6441 Lisp_Object result = Qnil, rest;
6443 for (rest = Vmac_charset_info_alist; CONSP (rest); rest = XCDR (rest))
6445 Lisp_Object charset_info = XCAR (rest);
6446 Lisp_Object charset, coding_system, text_encoding;
6447 Lisp_Object existing_info;
6449 if (!(CONSP (charset_info)
6450 && STRINGP (charset = XCAR (charset_info))
6451 && CONSP (XCDR (charset_info))
6452 && INTEGERP (text_encoding = XCAR (XCDR (charset_info)))
6453 && CONSP (XCDR (XCDR (charset_info)))
6454 && SYMBOLP (coding_system = XCAR (XCDR (XCDR (charset_info))))))
6455 continue;
6457 existing_info = assq_no_quit (text_encoding, result);
6458 if (NILP (existing_info))
6459 result = Fcons (list3 (text_encoding, coding_system, charset),
6460 result);
6461 else
6462 if (NILP (Fmember (charset, XCDR (XCDR (existing_info)))))
6463 XSETCDR (XCDR (existing_info),
6464 Fcons (charset, XCDR (XCDR (existing_info))));
6467 return result;
6471 static void
6472 decode_mac_font_name (name, size, coding_system)
6473 char *name;
6474 int size;
6475 Lisp_Object coding_system;
6477 struct coding_system coding;
6478 char *buf, *p;
6480 for (p = name; *p; p++)
6481 if (!isascii (*p) || iscntrl (*p))
6482 break;
6484 if (*p == '\0'
6485 || NILP (coding_system) || NILP (Fcoding_system_p (coding_system)))
6486 return;
6488 setup_coding_system (coding_system, &coding);
6489 coding.src_multibyte = 0;
6490 coding.dst_multibyte = 1;
6491 coding.mode |= CODING_MODE_LAST_BLOCK;
6492 coding.composing = COMPOSITION_DISABLED;
6493 buf = (char *) alloca (size);
6495 decode_coding (&coding, name, buf, strlen (name), size - 1);
6496 bcopy (buf, name, coding.produced);
6497 name[coding.produced] = '\0';
6501 static char *
6502 mac_to_x_fontname (name, size, style, charset)
6503 char *name;
6504 int size;
6505 Style style;
6506 char *charset;
6508 Str31 foundry, cs;
6509 Str255 family;
6510 char xf[256], *result;
6511 unsigned char *p;
6513 if (sscanf (name, "%31[^-]-%255[^-]-%31s", foundry, family, cs) == 3)
6514 charset = cs;
6515 else
6517 strcpy(foundry, "Apple");
6518 strcpy(family, name);
6521 sprintf (xf, "%s-%c-normal--%d-%d-%d-%d-m-%d-%s",
6522 style & bold ? "bold" : "medium", style & italic ? 'i' : 'r',
6523 size, size * 10, size ? 75 : 0, size ? 75 : 0, size * 10, charset);
6525 result = xmalloc (strlen (foundry) + strlen (family) + strlen (xf) + 3 + 1);
6526 sprintf (result, "-%s-%s-%s", foundry, family, xf);
6527 for (p = result; *p; p++)
6528 /* On Mac OS X 10.3, tolower also converts non-ASCII characters
6529 for some locales. */
6530 if (isascii (*p))
6531 *p = tolower (*p);
6532 return result;
6536 /* Convert an X font spec to the corresponding mac font name, which
6537 can then be passed to GetFNum after conversion to a Pascal string.
6538 For ordinary Mac fonts, this should just be their names, like
6539 "monaco", "Taipei", etc. Fonts converted from the GNU intlfonts
6540 collection contain their charset designation in their names, like
6541 "ETL-Fixed-iso8859-1", "ETL-Fixed-koi8-r", etc. Both types of font
6542 names are handled accordingly. */
6543 static void
6544 x_font_name_to_mac_font_name (xf, mf, mf_decoded, style, cs)
6545 char *xf, *mf, *mf_decoded;
6546 Style *style;
6547 char *cs;
6549 Str31 foundry;
6550 Str255 family;
6551 char weight[20], slant[2], *p;
6552 Lisp_Object charset_info, coding_system = Qnil;
6553 struct coding_system coding;
6555 strcpy (mf, "");
6557 if (sscanf (xf, "-%31[^-]-%255[^-]-%19[^-]-%1[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%31s",
6558 foundry, family, weight, slant, cs) != 5 &&
6559 sscanf (xf, "-%31[^-]-%255[^-]-%19[^-]-%1[^-]-%*[^-]--%*[^-]-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]-%31s",
6560 foundry, family, weight, slant, cs) != 5)
6561 return;
6563 *style = normal;
6564 if (strcmp (weight, "bold") == 0)
6565 *style |= bold;
6566 if (*slant == 'i')
6567 *style |= italic;
6569 charset_info = Fassoc (build_string (cs), Vmac_charset_info_alist);
6570 if (!NILP (charset_info))
6572 strcpy (mf_decoded, family);
6573 coding_system = Fcar (Fcdr (Fcdr (charset_info)));
6575 else
6576 sprintf (mf_decoded, "%s-%s-%s", foundry, family, cs);
6578 for (p = mf_decoded; *p; p++)
6579 if (!isascii (*p) || iscntrl (*p))
6580 break;
6582 if (*p == '\0'
6583 || NILP (coding_system) || NILP (Fcoding_system_p (coding_system)))
6584 strcpy (mf, mf_decoded);
6585 else
6587 setup_coding_system (coding_system, &coding);
6588 coding.src_multibyte = 1;
6589 coding.dst_multibyte = 0;
6590 coding.mode |= CODING_MODE_LAST_BLOCK;
6591 encode_coding (&coding, mf_decoded, mf,
6592 strlen (mf_decoded), sizeof (Str255) - 1);
6593 mf[coding.produced] = '\0';
6598 static void
6599 add_font_name_table_entry (char *font_name)
6601 if (font_name_table_size == 0)
6603 font_name_table_size = 256;
6604 font_name_table = (char **)
6605 xmalloc (font_name_table_size * sizeof (char *));
6607 else if (font_name_count + 1 >= font_name_table_size)
6609 font_name_table_size *= 2;
6610 font_name_table = (char **)
6611 xrealloc (font_name_table,
6612 font_name_table_size * sizeof (char *));
6615 font_name_table[font_name_count++] = font_name;
6618 /* Sets up the table font_name_table to contain the list of all fonts
6619 in the system the first time the table is used so that the Resource
6620 Manager need not be accessed every time this information is
6621 needed. */
6623 static void
6624 init_font_name_table ()
6626 #if TARGET_API_MAC_CARBON
6627 FMFontFamilyIterator ffi;
6628 FMFontFamilyInstanceIterator ffii;
6629 FMFontFamily ff;
6630 Lisp_Object text_encoding_info_alist;
6631 struct gcpro gcpro1;
6633 /* Create a dummy instance iterator here to avoid creating and
6634 destroying it in the loop. */
6635 if (FMCreateFontFamilyInstanceIterator (0, &ffii) != noErr)
6636 return;
6637 /* Create an iterator to enumerate the font families. */
6638 if (FMCreateFontFamilyIterator (NULL, NULL, kFMDefaultOptions, &ffi)
6639 != noErr)
6641 FMDisposeFontFamilyInstanceIterator (&ffii);
6642 return;
6645 text_encoding_info_alist = create_text_encoding_info_alist ();
6647 GCPRO1 (text_encoding_info_alist);
6649 while (FMGetNextFontFamily (&ffi, &ff) == noErr)
6651 Str255 name;
6652 FMFont font;
6653 FMFontStyle style;
6654 FMFontSize size;
6655 TextEncoding encoding;
6656 TextEncodingBase sc;
6657 Lisp_Object text_encoding_info;
6659 if (FMGetFontFamilyName (ff, name) != noErr)
6660 break;
6661 p2cstr (name);
6662 if (*name == '.')
6663 continue;
6665 if (FMGetFontFamilyTextEncoding (ff, &encoding) != noErr)
6666 break;
6667 sc = GetTextEncodingBase (encoding);
6668 text_encoding_info = assq_no_quit (make_number (sc),
6669 text_encoding_info_alist);
6670 if (!NILP (text_encoding_info))
6671 decode_mac_font_name (name, sizeof (name),
6672 XCAR (XCDR (text_encoding_info)));
6673 else
6674 text_encoding_info = assq_no_quit (make_number (kTextEncodingMacRoman),
6675 text_encoding_info_alist);
6677 /* Point the instance iterator at the current font family. */
6678 if (FMResetFontFamilyInstanceIterator (ff, &ffii) != noErr)
6679 break;
6681 while (FMGetNextFontFamilyInstance (&ffii, &font, &style, &size)
6682 == noErr)
6684 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
6686 for (; !NILP (rest); rest = XCDR (rest))
6688 char *cs = SDATA (XCAR (rest));
6690 if (size == 0)
6692 add_font_name_table_entry (mac_to_x_fontname (name, size,
6693 style, cs));
6694 add_font_name_table_entry (mac_to_x_fontname (name, size,
6695 italic, cs));
6696 add_font_name_table_entry (mac_to_x_fontname (name, size,
6697 bold, cs));
6698 add_font_name_table_entry (mac_to_x_fontname (name, size,
6699 italic | bold,
6700 cs));
6702 else
6704 add_font_name_table_entry (mac_to_x_fontname (name, size,
6705 style, cs));
6711 UNGCPRO;
6713 /* Dispose of the iterators. */
6714 FMDisposeFontFamilyIterator (&ffi);
6715 FMDisposeFontFamilyInstanceIterator (&ffii);
6716 #else /* !TARGET_API_MAC_CARBON */
6717 GrafPtr port;
6718 SInt16 fontnum, old_fontnum;
6719 int num_mac_fonts = CountResources('FOND');
6720 int i, j;
6721 Handle font_handle, font_handle_2;
6722 short id, scriptcode;
6723 ResType type;
6724 Str255 name;
6725 struct FontAssoc *fat;
6726 struct AsscEntry *assc_entry;
6727 Lisp_Object text_encoding_info_alist, text_encoding_info;
6728 struct gcpro gcpro1;
6730 GetPort (&port); /* save the current font number used */
6731 old_fontnum = port->txFont;
6733 text_encoding_info_alist = create_text_encoding_info_alist ();
6735 GCPRO1 (text_encoding_info_alist);
6737 for (i = 1; i <= num_mac_fonts; i++) /* get all available fonts */
6739 font_handle = GetIndResource ('FOND', i);
6740 if (!font_handle)
6741 continue;
6743 GetResInfo (font_handle, &id, &type, name);
6744 GetFNum (name, &fontnum);
6745 p2cstr (name);
6746 if (fontnum == 0)
6747 continue;
6749 TextFont (fontnum);
6750 scriptcode = FontToScript (fontnum);
6751 text_encoding_info = assq_no_quit (make_number (scriptcode),
6752 text_encoding_info_alist);
6753 if (!NILP (text_encoding_info))
6754 decode_mac_font_name (name, sizeof (name),
6755 XCAR (XCDR (text_encoding_info)));
6756 else
6757 text_encoding_info = assq_no_quit (make_number (smRoman),
6758 text_encoding_info_alist);
6761 HLock (font_handle);
6763 if (GetResourceSizeOnDisk (font_handle)
6764 >= sizeof (struct FamRec))
6766 fat = (struct FontAssoc *) (*font_handle
6767 + sizeof (struct FamRec));
6768 assc_entry
6769 = (struct AsscEntry *) (*font_handle
6770 + sizeof (struct FamRec)
6771 + sizeof (struct FontAssoc));
6773 for (j = 0; j <= fat->numAssoc; j++, assc_entry++)
6775 Lisp_Object rest = XCDR (XCDR (text_encoding_info));
6777 for (; !NILP (rest); rest = XCDR (rest))
6779 char *cs = SDATA (XCAR (rest));
6781 add_font_name_table_entry (mac_to_x_fontname (name,
6782 assc_entry->fontSize,
6783 assc_entry->fontStyle,
6784 cs));
6789 HUnlock (font_handle);
6790 font_handle_2 = GetNextFOND (font_handle);
6791 ReleaseResource (font_handle);
6792 font_handle = font_handle_2;
6794 while (ResError () == noErr && font_handle);
6797 UNGCPRO;
6799 TextFont (old_fontnum);
6800 #endif /* !TARGET_API_MAC_CARBON */
6804 void
6805 mac_clear_font_name_table ()
6807 int i;
6809 for (i = 0; i < font_name_count; i++)
6810 xfree (font_name_table[i]);
6811 xfree (font_name_table);
6812 font_name_table = NULL;
6813 font_name_table_size = font_name_count = 0;
6817 enum xlfd_scalable_field_index
6819 XLFD_SCL_PIXEL_SIZE,
6820 XLFD_SCL_POINT_SIZE,
6821 XLFD_SCL_AVGWIDTH,
6822 XLFD_SCL_LAST
6825 static int xlfd_scalable_fields[] =
6827 6, /* PIXEL_SIZE */
6828 7, /* POINT_SIZE */
6829 11, /* AVGWIDTH */
6833 static Lisp_Object
6834 mac_do_list_fonts (pattern, maxnames)
6835 char *pattern;
6836 int maxnames;
6838 int i, n_fonts = 0;
6839 Lisp_Object font_list = Qnil;
6840 struct xlfdpat *pat;
6841 char *scaled, *ptr;
6842 int scl_val[XLFD_SCL_LAST], *field, *val;
6843 int exact;
6845 if (font_name_table == NULL) /* Initialize when first used. */
6846 init_font_name_table ();
6848 for (i = 0; i < XLFD_SCL_LAST; i++)
6849 scl_val[i] = -1;
6851 /* If the pattern contains 14 dashes and one of PIXEL_SIZE,
6852 POINT_SIZE, and AVGWIDTH fields is explicitly specified, scalable
6853 fonts are scaled according to the specified size. */
6854 ptr = pattern;
6855 i = 0;
6856 field = xlfd_scalable_fields;
6857 val = scl_val;
6858 if (*ptr == '-')
6861 ptr++;
6862 if (i == *field)
6864 if ('0' <= *ptr && *ptr <= '9')
6866 *val = *ptr++ - '0';
6867 while ('0' <= *ptr && *ptr <= '9' && *val < 10000)
6868 *val = *val * 10 + *ptr++ - '0';
6869 if (*ptr != '-')
6870 *val = -1;
6872 field++;
6873 val++;
6875 ptr = strchr (ptr, '-');
6876 i++;
6878 while (ptr && i < 14);
6880 if (i == 14 && ptr == NULL)
6882 if (scl_val[XLFD_SCL_PIXEL_SIZE] < 0)
6883 scl_val[XLFD_SCL_PIXEL_SIZE] =
6884 (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE] / 10
6885 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH] / 10
6886 : -1));
6887 if (scl_val[XLFD_SCL_POINT_SIZE] < 0)
6888 scl_val[XLFD_SCL_POINT_SIZE] =
6889 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
6890 : (scl_val[XLFD_SCL_AVGWIDTH] > 0 ? scl_val[XLFD_SCL_AVGWIDTH]
6891 : -1));
6892 if (scl_val[XLFD_SCL_AVGWIDTH] < 0)
6893 scl_val[XLFD_SCL_AVGWIDTH] =
6894 (scl_val[XLFD_SCL_PIXEL_SIZE] > 0 ? scl_val[XLFD_SCL_PIXEL_SIZE] * 10
6895 : (scl_val[XLFD_SCL_POINT_SIZE] > 0 ? scl_val[XLFD_SCL_POINT_SIZE]
6896 : -1));
6898 else
6899 scl_val[XLFD_SCL_PIXEL_SIZE] = -1;
6901 pat = xlfdpat_create (pattern);
6902 if (pat == NULL)
6903 return Qnil;
6905 exact = xlfdpat_exact_p (pat);
6907 for (i = 0; i < font_name_count; i++)
6909 if (xlfdpat_match (pat, font_name_table[i]))
6911 font_list = Fcons (build_string (font_name_table[i]), font_list);
6912 if (exact || maxnames > 0 && ++n_fonts >= maxnames)
6913 break;
6915 else if (scl_val[XLFD_SCL_PIXEL_SIZE] > 0
6916 && (ptr = strstr (font_name_table[i], "-0-0-0-0-m-0-")))
6918 int former_len = ptr - font_name_table[i];
6920 scaled = xmalloc (strlen (font_name_table[i]) + 20 + 1);
6921 if (scaled == NULL)
6922 continue;
6923 memcpy (scaled, font_name_table[i], former_len);
6924 sprintf (scaled + former_len,
6925 "-%d-%d-75-75-m-%d-%s",
6926 scl_val[XLFD_SCL_PIXEL_SIZE],
6927 scl_val[XLFD_SCL_POINT_SIZE],
6928 scl_val[XLFD_SCL_AVGWIDTH],
6929 ptr + sizeof ("-0-0-0-0-m-0-") - 1);
6931 if (xlfdpat_match (pat, scaled))
6933 font_list = Fcons (build_string (scaled), font_list);
6934 xfree (scaled);
6935 if (exact || maxnames > 0 && ++n_fonts >= maxnames)
6936 break;
6938 else
6939 xfree (scaled);
6943 xlfdpat_destroy (pat);
6945 return font_list;
6948 /* Return a list of names of available fonts matching PATTERN on frame F.
6950 Frame F null means we have not yet created any frame on Mac, and
6951 consult the first display in x_display_list. MAXNAMES sets a limit
6952 on how many fonts to match. */
6954 Lisp_Object
6955 x_list_fonts (f, pattern, size, maxnames)
6956 struct frame *f;
6957 Lisp_Object pattern;
6958 int size, maxnames;
6960 Lisp_Object list = Qnil, patterns, tem, key;
6961 struct mac_display_info *dpyinfo
6962 = f ? FRAME_MAC_DISPLAY_INFO (f) : x_display_list;
6964 xassert (size <= 0);
6966 patterns = Fassoc (pattern, Valternate_fontname_alist);
6967 if (NILP (patterns))
6968 patterns = Fcons (pattern, Qnil);
6970 for (; CONSP (patterns); patterns = XCDR (patterns))
6972 pattern = XCAR (patterns);
6974 if (!STRINGP (pattern))
6975 continue;
6977 tem = XCAR (XCDR (dpyinfo->name_list_element));
6978 key = Fcons (pattern, make_number (maxnames));
6980 list = Fassoc (key, tem);
6981 if (!NILP (list))
6983 list = Fcdr_safe (list);
6984 /* We have a cashed list. Don't have to get the list again. */
6985 goto label_cached;
6988 BLOCK_INPUT;
6989 list = mac_do_list_fonts (SDATA (pattern), maxnames);
6990 UNBLOCK_INPUT;
6992 /* MAC_TODO: add code for matching outline fonts here */
6994 /* Now store the result in the cache. */
6995 XSETCAR (XCDR (dpyinfo->name_list_element),
6996 Fcons (Fcons (key, list),
6997 XCAR (XCDR (dpyinfo->name_list_element))));
6999 label_cached:
7000 if (NILP (list)) continue; /* Try the remaining alternatives. */
7003 return list;
7007 #if GLYPH_DEBUG
7009 /* Check that FONT is valid on frame F. It is if it can be found in F's
7010 font table. */
7012 static void
7013 x_check_font (f, font)
7014 struct frame *f;
7015 XFontStruct *font;
7017 int i;
7018 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
7020 xassert (font != NULL);
7022 for (i = 0; i < dpyinfo->n_fonts; i++)
7023 if (dpyinfo->font_table[i].name
7024 && font == dpyinfo->font_table[i].font)
7025 break;
7027 xassert (i < dpyinfo->n_fonts);
7030 #endif /* GLYPH_DEBUG != 0 */
7032 /* Set *W to the minimum width, *H to the minimum font height of FONT.
7033 Note: There are (broken) X fonts out there with invalid XFontStruct
7034 min_bounds contents. For example, handa@etl.go.jp reports that
7035 "-adobe-courier-medium-r-normal--*-180-*-*-m-*-iso8859-1" fonts
7036 have font->min_bounds.width == 0. */
7038 static INLINE void
7039 x_font_min_bounds (font, w, h)
7040 MacFontStruct *font;
7041 int *w, *h;
7043 *h = FONT_HEIGHT (font);
7044 *w = font->min_bounds.width;
7048 /* Compute the smallest character width and smallest font height over
7049 all fonts available on frame F. Set the members smallest_char_width
7050 and smallest_font_height in F's x_display_info structure to
7051 the values computed. Value is non-zero if smallest_font_height or
7052 smallest_char_width become smaller than they were before. */
7054 static int
7055 x_compute_min_glyph_bounds (f)
7056 struct frame *f;
7058 int i;
7059 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7060 MacFontStruct *font;
7061 int old_width = dpyinfo->smallest_char_width;
7062 int old_height = dpyinfo->smallest_font_height;
7064 dpyinfo->smallest_font_height = 100000;
7065 dpyinfo->smallest_char_width = 100000;
7067 for (i = 0; i < dpyinfo->n_fonts; ++i)
7068 if (dpyinfo->font_table[i].name)
7070 struct font_info *fontp = dpyinfo->font_table + i;
7071 int w, h;
7073 font = (MacFontStruct *) fontp->font;
7074 xassert (font != (MacFontStruct *) ~0);
7075 x_font_min_bounds (font, &w, &h);
7077 dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
7078 dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
7081 xassert (dpyinfo->smallest_char_width > 0
7082 && dpyinfo->smallest_font_height > 0);
7084 return (dpyinfo->n_fonts == 1
7085 || dpyinfo->smallest_char_width < old_width
7086 || dpyinfo->smallest_font_height < old_height);
7090 /* Determine whether given string is a fully-specified XLFD: all 14
7091 fields are present, none is '*'. */
7093 static int
7094 is_fully_specified_xlfd (char *p)
7096 int i;
7097 char *q;
7099 if (*p != '-')
7100 return 0;
7102 for (i = 0; i < 13; i++)
7104 q = strchr (p + 1, '-');
7105 if (q == NULL)
7106 return 0;
7107 if (q - p == 2 && *(p + 1) == '*')
7108 return 0;
7109 p = q;
7112 if (strchr (p + 1, '-') != NULL)
7113 return 0;
7115 if (*(p + 1) == '*' && *(p + 2) == '\0')
7116 return 0;
7118 return 1;
7122 const int kDefaultFontSize = 12;
7125 /* XLoadQueryFont creates and returns an internal representation for a
7126 font in a MacFontStruct struct. There is really no concept
7127 corresponding to "loading" a font on the Mac. But we check its
7128 existence and find the font number and all other information for it
7129 and store them in the returned MacFontStruct. */
7131 static MacFontStruct *
7132 XLoadQueryFont (Display *dpy, char *fontname)
7134 int i, size, point_size, avgwidth, is_two_byte_font, char_width;
7135 char *name;
7136 GrafPtr port;
7137 SInt16 old_fontnum, old_fontsize;
7138 Style old_fontface;
7139 Str255 mfontname, mfontname_decoded;
7140 Str31 charset;
7141 SInt16 fontnum;
7142 Style fontface;
7143 #if TARGET_API_MAC_CARBON
7144 TextEncoding encoding;
7145 int scriptcode;
7146 #else
7147 short scriptcode;
7148 #endif
7149 MacFontStruct *font;
7150 FontInfo the_fontinfo;
7151 #ifdef MAC_OSX
7152 UInt32 old_flags, new_flags;
7153 #endif
7155 if (is_fully_specified_xlfd (fontname))
7156 name = fontname;
7157 else
7159 Lisp_Object matched_fonts;
7161 matched_fonts = mac_do_list_fonts (fontname, 1);
7162 if (NILP (matched_fonts))
7163 return NULL;
7164 name = SDATA (XCAR (matched_fonts));
7167 GetPort (&port); /* save the current font number used */
7168 #if TARGET_API_MAC_CARBON
7169 old_fontnum = GetPortTextFont (port);
7170 old_fontsize = GetPortTextSize (port);
7171 old_fontface = GetPortTextFace (port);
7172 #else
7173 old_fontnum = port->txFont;
7174 old_fontsize = port->txSize;
7175 old_fontface = port->txFace;
7176 #endif
7178 if (sscanf (name, "-%*[^-]-%*[^-]-%*[^-]-%*c-%*[^-]--%d-%d-%*[^-]-%*[^-]-%*c-%d-%*s", &size, &point_size, &avgwidth) != 3)
7179 size = 0;
7180 else
7182 if (size == 0)
7183 if (point_size > 0)
7184 size = point_size / 10;
7185 else if (avgwidth > 0)
7186 size = avgwidth / 10;
7188 if (size == 0)
7189 size = kDefaultFontSize;
7191 x_font_name_to_mac_font_name (name, mfontname, mfontname_decoded,
7192 &fontface, charset);
7193 c2pstr (mfontname);
7194 #if TARGET_API_MAC_CARBON
7195 fontnum = FMGetFontFamilyFromName (mfontname);
7196 if (fontnum == kInvalidFontFamily
7197 || FMGetFontFamilyTextEncoding (fontnum, &encoding) != noErr)
7198 return NULL;
7199 scriptcode = GetTextEncodingBase (encoding);
7200 #else
7201 GetFNum (mfontname, &fontnum);
7202 if (fontnum == 0)
7203 return NULL;
7204 scriptcode = FontToScript (fontnum);
7205 #endif
7207 font = (MacFontStruct *) xmalloc (sizeof (struct MacFontStruct));
7209 font->mac_fontnum = fontnum;
7210 font->mac_fontsize = size;
7211 font->mac_fontface = fontface;
7212 font->mac_scriptcode = scriptcode;
7214 /* Apple Japanese (SJIS) font is listed as both
7215 "*-jisx0208.1983-sjis" (Japanese script) and "*-jisx0201.1976-0"
7216 (Roman script) in init_font_name_table (). The latter should be
7217 treated as a one-byte font. */
7218 if (scriptcode == smJapanese && strcmp (charset, "jisx0201.1976-0") == 0)
7219 font->mac_scriptcode = smRoman;
7221 font->full_name = mac_to_x_fontname (mfontname_decoded, size, fontface, charset);
7223 is_two_byte_font = font->mac_scriptcode == smJapanese ||
7224 font->mac_scriptcode == smTradChinese ||
7225 font->mac_scriptcode == smSimpChinese ||
7226 font->mac_scriptcode == smKorean;
7228 TextFont (fontnum);
7229 TextSize (size);
7230 TextFace (fontface);
7232 GetFontInfo (&the_fontinfo);
7234 font->ascent = the_fontinfo.ascent;
7235 font->descent = the_fontinfo.descent;
7237 font->min_byte1 = 0;
7238 if (is_two_byte_font)
7239 font->max_byte1 = 1;
7240 else
7241 font->max_byte1 = 0;
7242 font->min_char_or_byte2 = 0x20;
7243 font->max_char_or_byte2 = 0xff;
7245 if (is_two_byte_font)
7247 /* Use the width of an "ideographic space" of that font because
7248 the_fontinfo.widMax returns the wrong width for some fonts. */
7249 switch (font->mac_scriptcode)
7251 case smJapanese:
7252 char_width = StringWidth("\p\x81\x40");
7253 break;
7254 case smTradChinese:
7255 char_width = StringWidth("\p\xa1\x40");
7256 break;
7257 case smSimpChinese:
7258 char_width = StringWidth("\p\xa1\xa1");
7259 break;
7260 case smKorean:
7261 char_width = StringWidth("\p\xa1\xa1");
7262 break;
7265 else
7266 /* Do this instead of use the_fontinfo.widMax, which incorrectly
7267 returns 15 for 12-point Monaco! */
7268 char_width = CharWidth ('m');
7270 if (is_two_byte_font)
7272 font->per_char = NULL;
7274 if (fontface & italic)
7275 font->max_bounds.rbearing = char_width + 1;
7276 else
7277 font->max_bounds.rbearing = char_width;
7278 font->max_bounds.lbearing = 0;
7279 font->max_bounds.width = char_width;
7280 font->max_bounds.ascent = the_fontinfo.ascent;
7281 font->max_bounds.descent = the_fontinfo.descent;
7283 font->min_bounds = font->max_bounds;
7285 else
7287 font->per_char = (XCharStruct *)
7288 xmalloc (sizeof (XCharStruct) * (0xff - 0x20 + 1));
7290 int c, min_width, max_width;
7291 Rect char_bounds, min_bounds, max_bounds;
7292 char ch;
7294 min_width = max_width = char_width;
7295 SetRect (&min_bounds, -32767, -32767, 32767, 32767);
7296 SetRect (&max_bounds, 0, 0, 0, 0);
7297 for (c = 0x20; c <= 0xff; c++)
7299 ch = c;
7300 char_width = CharWidth (ch);
7301 QDTextBounds (1, &ch, &char_bounds);
7302 STORE_XCHARSTRUCT (font->per_char[c - 0x20],
7303 char_width, char_bounds);
7304 /* Some Japanese fonts (in SJIS encoding) return 0 as the
7305 character width of 0x7f. */
7306 if (char_width > 0)
7308 min_width = min (min_width, char_width);
7309 max_width = max (max_width, char_width);
7311 if (!EmptyRect (&char_bounds))
7313 SetRect (&min_bounds,
7314 max (min_bounds.left, char_bounds.left),
7315 max (min_bounds.top, char_bounds.top),
7316 min (min_bounds.right, char_bounds.right),
7317 min (min_bounds.bottom, char_bounds.bottom));
7318 UnionRect (&max_bounds, &char_bounds, &max_bounds);
7321 STORE_XCHARSTRUCT (font->min_bounds, min_width, min_bounds);
7322 STORE_XCHARSTRUCT (font->max_bounds, max_width, max_bounds);
7323 if (min_width == max_width
7324 && max_bounds.left >= 0 && max_bounds.right <= max_width)
7326 /* Fixed width and no overhangs. */
7327 xfree (font->per_char);
7328 font->per_char = NULL;
7333 TextFont (old_fontnum); /* restore previous font number, size and face */
7334 TextSize (old_fontsize);
7335 TextFace (old_fontface);
7337 return font;
7341 void
7342 mac_unload_font (dpyinfo, font)
7343 struct mac_display_info *dpyinfo;
7344 XFontStruct *font;
7346 xfree (font->full_name);
7347 if (font->per_char)
7348 xfree (font->per_char);
7349 xfree (font);
7353 /* Load font named FONTNAME of the size SIZE for frame F, and return a
7354 pointer to the structure font_info while allocating it dynamically.
7355 If SIZE is 0, load any size of font.
7356 If loading is failed, return NULL. */
7358 struct font_info *
7359 x_load_font (f, fontname, size)
7360 struct frame *f;
7361 register char *fontname;
7362 int size;
7364 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7365 Lisp_Object font_names;
7367 /* Get a list of all the fonts that match this name. Once we
7368 have a list of matching fonts, we compare them against the fonts
7369 we already have by comparing names. */
7370 font_names = x_list_fonts (f, build_string (fontname), size, 1);
7372 if (!NILP (font_names))
7374 Lisp_Object tail;
7375 int i;
7377 for (i = 0; i < dpyinfo->n_fonts; i++)
7378 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
7379 if (dpyinfo->font_table[i].name
7380 && (!strcmp (dpyinfo->font_table[i].name,
7381 SDATA (XCAR (tail)))
7382 || !strcmp (dpyinfo->font_table[i].full_name,
7383 SDATA (XCAR (tail)))))
7384 return (dpyinfo->font_table + i);
7386 else
7387 return NULL;
7389 /* Load the font and add it to the table. */
7391 char *full_name;
7392 struct MacFontStruct *font;
7393 struct font_info *fontp;
7394 unsigned long value;
7395 int i;
7397 fontname = (char *) SDATA (XCAR (font_names));
7399 BLOCK_INPUT;
7400 font = (MacFontStruct *) XLoadQueryFont (FRAME_MAC_DISPLAY (f), fontname);
7401 UNBLOCK_INPUT;
7402 if (!font)
7403 return NULL;
7405 /* Find a free slot in the font table. */
7406 for (i = 0; i < dpyinfo->n_fonts; ++i)
7407 if (dpyinfo->font_table[i].name == NULL)
7408 break;
7410 /* If no free slot found, maybe enlarge the font table. */
7411 if (i == dpyinfo->n_fonts
7412 && dpyinfo->n_fonts == dpyinfo->font_table_size)
7414 int sz;
7415 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
7416 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
7417 dpyinfo->font_table
7418 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
7421 fontp = dpyinfo->font_table + i;
7422 if (i == dpyinfo->n_fonts)
7423 ++dpyinfo->n_fonts;
7425 /* Now fill in the slots of *FONTP. */
7426 BLOCK_INPUT;
7427 bzero (fontp, sizeof (*fontp));
7428 fontp->font = font;
7429 fontp->font_idx = i;
7430 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
7431 bcopy (fontname, fontp->name, strlen (fontname) + 1);
7433 if (font->min_bounds.width == font->max_bounds.width)
7435 /* Fixed width font. */
7436 fontp->average_width = fontp->space_width = font->min_bounds.width;
7438 else
7440 XChar2b char2b;
7441 XCharStruct *pcm;
7443 char2b.byte1 = 0x00, char2b.byte2 = 0x20;
7444 pcm = mac_per_char_metric (font, &char2b, 0);
7445 if (pcm)
7446 fontp->space_width = pcm->width;
7447 else
7448 fontp->space_width = FONT_WIDTH (font);
7450 if (pcm)
7452 int width = pcm->width;
7453 for (char2b.byte2 = 33; char2b.byte2 <= 126; char2b.byte2++)
7454 if ((pcm = mac_per_char_metric (font, &char2b, 0)) != NULL)
7455 width += pcm->width;
7456 fontp->average_width = width / 95;
7458 else
7459 fontp->average_width = FONT_WIDTH (font);
7462 fontp->full_name = (char *) xmalloc (strlen (font->full_name) + 1);
7463 bcopy (font->full_name, fontp->full_name, strlen (font->full_name) + 1);
7465 fontp->size = font->max_bounds.width;
7466 fontp->height = FONT_HEIGHT (font);
7468 /* For some font, ascent and descent in max_bounds field is
7469 larger than the above value. */
7470 int max_height = font->max_bounds.ascent + font->max_bounds.descent;
7471 if (max_height > fontp->height)
7472 fontp->height = max_height;
7475 /* The slot `encoding' specifies how to map a character
7476 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
7477 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
7478 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
7479 2:0xA020..0xFF7F). For the moment, we don't know which charset
7480 uses this font. So, we set information in fontp->encoding[1]
7481 which is never used by any charset. If mapping can't be
7482 decided, set FONT_ENCODING_NOT_DECIDED. */
7483 if (font->mac_scriptcode == smJapanese)
7484 fontp->encoding[1] = 4;
7485 else
7487 fontp->encoding[1]
7488 = (font->max_byte1 == 0
7489 /* 1-byte font */
7490 ? (font->min_char_or_byte2 < 0x80
7491 ? (font->max_char_or_byte2 < 0x80
7492 ? 0 /* 0x20..0x7F */
7493 : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
7494 : 1) /* 0xA0..0xFF */
7495 /* 2-byte font */
7496 : (font->min_byte1 < 0x80
7497 ? (font->max_byte1 < 0x80
7498 ? (font->min_char_or_byte2 < 0x80
7499 ? (font->max_char_or_byte2 < 0x80
7500 ? 0 /* 0x2020..0x7F7F */
7501 : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
7502 : 3) /* 0x20A0..0x7FFF */
7503 : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
7504 : (font->min_char_or_byte2 < 0x80
7505 ? (font->max_char_or_byte2 < 0x80
7506 ? 2 /* 0xA020..0xFF7F */
7507 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
7508 : 1))); /* 0xA0A0..0xFFFF */
7511 #if 0 /* MAC_TODO: fill these out with more reasonably values */
7512 fontp->baseline_offset
7513 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
7514 ? (long) value : 0);
7515 fontp->relative_compose
7516 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
7517 ? (long) value : 0);
7518 fontp->default_ascent
7519 = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
7520 ? (long) value : 0);
7521 #else
7522 fontp->baseline_offset = 0;
7523 fontp->relative_compose = 0;
7524 fontp->default_ascent = 0;
7525 #endif
7527 /* Set global flag fonts_changed_p to non-zero if the font loaded
7528 has a character with a smaller width than any other character
7529 before, or if the font loaded has a smaller height than any
7530 other font loaded before. If this happens, it will make a
7531 glyph matrix reallocation necessary. */
7532 fonts_changed_p |= x_compute_min_glyph_bounds (f);
7533 UNBLOCK_INPUT;
7534 return fontp;
7539 /* Return a pointer to struct font_info of a font named FONTNAME for
7540 frame F. If no such font is loaded, return NULL. */
7542 struct font_info *
7543 x_query_font (f, fontname)
7544 struct frame *f;
7545 register char *fontname;
7547 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
7548 int i;
7550 for (i = 0; i < dpyinfo->n_fonts; i++)
7551 if (dpyinfo->font_table[i].name
7552 && (!strcmp (dpyinfo->font_table[i].name, fontname)
7553 || !strcmp (dpyinfo->font_table[i].full_name, fontname)))
7554 return (dpyinfo->font_table + i);
7555 return NULL;
7559 /* Find a CCL program for a font specified by FONTP, and set the member
7560 `encoder' of the structure. */
7562 void
7563 x_find_ccl_program (fontp)
7564 struct font_info *fontp;
7566 Lisp_Object list, elt;
7568 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
7570 elt = XCAR (list);
7571 if (CONSP (elt)
7572 && STRINGP (XCAR (elt))
7573 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
7574 >= 0))
7575 break;
7577 if (! NILP (list))
7579 struct ccl_program *ccl
7580 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
7582 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
7583 xfree (ccl);
7584 else
7585 fontp->font_encoder = ccl;
7591 /* The Mac Event loop code */
7593 #if !TARGET_API_MAC_CARBON
7594 #include <Events.h>
7595 #include <Quickdraw.h>
7596 #include <Balloons.h>
7597 #include <Devices.h>
7598 #include <Fonts.h>
7599 #include <Gestalt.h>
7600 #include <Menus.h>
7601 #include <Processes.h>
7602 #include <Sound.h>
7603 #include <ToolUtils.h>
7604 #include <TextUtils.h>
7605 #include <Dialogs.h>
7606 #include <Script.h>
7607 #include <Types.h>
7608 #include <Resources.h>
7610 #if __MWERKS__
7611 #include <unix.h>
7612 #endif
7613 #endif /* ! TARGET_API_MAC_CARBON */
7615 #define M_APPLE 128
7616 #define I_ABOUT 1
7618 #define WINDOW_RESOURCE 128
7619 #define TERM_WINDOW_RESOURCE 129
7621 #define DEFAULT_NUM_COLS 80
7623 #define MIN_DOC_SIZE 64
7624 #define MAX_DOC_SIZE 32767
7626 #define EXTRA_STACK_ALLOC (256 * 1024)
7628 #define ARGV_STRING_LIST_ID 129
7629 #define ABOUT_ALERT_ID 128
7630 #define RAM_TOO_LARGE_ALERT_ID 129
7632 /* Contains the string "reverse", which is a constant for mouse button emu.*/
7633 Lisp_Object Qreverse;
7635 /* True if using command key as meta key. */
7636 Lisp_Object Vmac_command_key_is_meta;
7638 /* Modifier associated with the option key, or nil for normal behavior. */
7639 Lisp_Object Vmac_option_modifier;
7641 /* True if the ctrl and meta keys should be reversed. */
7642 Lisp_Object Vmac_reverse_ctrl_meta;
7644 /* True if the option and command modifiers should be used to emulate
7645 a three button mouse */
7646 Lisp_Object Vmac_emulate_three_button_mouse;
7648 #if USE_CARBON_EVENTS
7649 /* True if the mouse wheel button (i.e. button 4) should map to
7650 mouse-2, instead of mouse-3. */
7651 Lisp_Object Vmac_wheel_button_is_mouse_2;
7653 /* If Non-nil, the Mac "Command" key is passed on to the Mac Toolbox
7654 for processing before Emacs sees it. */
7655 Lisp_Object Vmac_pass_command_to_system;
7657 /* If Non-nil, the Mac "Control" key is passed on to the Mac Toolbox
7658 for processing before Emacs sees it. */
7659 Lisp_Object Vmac_pass_control_to_system;
7660 #endif
7662 /* Points to the variable `inev' in the function XTread_socket. It is
7663 used for passing an input event to the function back from
7664 Carbon/Apple event handlers. */
7665 static struct input_event *read_socket_inev = NULL;
7667 /* Set in term/mac-win.el to indicate that event loop can now generate
7668 drag and drop events. */
7669 Lisp_Object Qmac_ready_for_drag_n_drop;
7671 Point saved_menu_event_location;
7673 /* Apple Events */
7674 static void init_required_apple_events (void);
7675 static pascal OSErr
7676 do_ae_open_application (const AppleEvent *, AppleEvent *, long);
7677 static pascal OSErr
7678 do_ae_print_documents (const AppleEvent *, AppleEvent *, long);
7679 static pascal OSErr do_ae_open_documents (AppleEvent *, AppleEvent *, long);
7680 static pascal OSErr do_ae_quit_application (AppleEvent *, AppleEvent *, long);
7682 #if TARGET_API_MAC_CARBON
7683 /* Drag and Drop */
7684 static pascal OSErr mac_do_track_drag (DragTrackingMessage, WindowPtr, void*, DragReference);
7685 static pascal OSErr mac_do_receive_drag (WindowPtr, void*, DragReference);
7686 static DragTrackingHandlerUPP mac_do_track_dragUPP = NULL;
7687 static DragReceiveHandlerUPP mac_do_receive_dragUPP = NULL;
7688 #endif
7690 static Lisp_Object Qapplication, Qabout;
7691 #if USE_CARBON_EVENTS
7692 #ifdef MAC_OSX
7693 extern void init_service_handler ();
7694 static Lisp_Object Qpreferences, Qservices, Qpaste, Qperform;
7695 #endif
7696 /* Window Event Handler */
7697 static pascal OSStatus mac_handle_window_event (EventHandlerCallRef,
7698 EventRef, void *);
7699 #endif
7700 OSErr install_window_handler (WindowPtr);
7702 extern void init_emacs_passwd_dir ();
7703 extern int emacs_main (int, char **, char **);
7705 extern void initialize_applescript();
7706 extern void terminate_applescript();
7708 static unsigned int
7709 #if USE_CARBON_EVENTS
7710 mac_to_emacs_modifiers (UInt32 mods)
7711 #else
7712 mac_to_emacs_modifiers (EventModifiers mods)
7713 #endif
7715 unsigned int result = 0;
7716 if (mods & macShiftKey)
7717 result |= shift_modifier;
7718 if (mods & macCtrlKey)
7719 result |= ctrl_modifier;
7720 if (mods & macMetaKey)
7721 result |= meta_modifier;
7722 if (NILP (Vmac_command_key_is_meta) && (mods & macAltKey))
7723 result |= alt_modifier;
7724 if (!NILP (Vmac_option_modifier) && (mods & optionKey)) {
7725 Lisp_Object val = Fget(Vmac_option_modifier, Qmodifier_value);
7726 if (!NILP(val))
7727 result |= XUINT(val);
7730 return result;
7733 static int
7734 mac_get_emulated_btn ( UInt32 modifiers )
7736 int result = 0;
7737 if (!NILP (Vmac_emulate_three_button_mouse)) {
7738 int cmdIs3 = !EQ (Vmac_emulate_three_button_mouse, Qreverse);
7739 if (modifiers & cmdKey)
7740 result = cmdIs3 ? 2 : 1;
7741 else if (modifiers & optionKey)
7742 result = cmdIs3 ? 1 : 2;
7744 return result;
7747 #if USE_CARBON_EVENTS
7748 /* Obtains the event modifiers from the event ref and then calls
7749 mac_to_emacs_modifiers. */
7750 static int
7751 mac_event_to_emacs_modifiers (EventRef eventRef)
7753 UInt32 mods = 0;
7754 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32, NULL,
7755 sizeof (UInt32), NULL, &mods);
7756 if (!NILP (Vmac_emulate_three_button_mouse) &&
7757 GetEventClass(eventRef) == kEventClassMouse)
7759 mods &= ~(optionKey | cmdKey);
7761 return mac_to_emacs_modifiers (mods);
7764 /* Given an event ref, return the code to use for the mouse button
7765 code in the emacs input_event. */
7766 static int
7767 mac_get_mouse_btn (EventRef ref)
7769 EventMouseButton result = kEventMouseButtonPrimary;
7770 GetEventParameter (ref, kEventParamMouseButton, typeMouseButton, NULL,
7771 sizeof (EventMouseButton), NULL, &result);
7772 switch (result)
7774 case kEventMouseButtonPrimary:
7775 if (NILP (Vmac_emulate_three_button_mouse))
7776 return 0;
7777 else {
7778 UInt32 mods = 0;
7779 GetEventParameter (ref, kEventParamKeyModifiers, typeUInt32, NULL,
7780 sizeof (UInt32), NULL, &mods);
7781 return mac_get_emulated_btn(mods);
7783 case kEventMouseButtonSecondary:
7784 return NILP (Vmac_wheel_button_is_mouse_2) ? 1 : 2;
7785 case kEventMouseButtonTertiary:
7786 case 4: /* 4 is the number for the mouse wheel button */
7787 return NILP (Vmac_wheel_button_is_mouse_2) ? 2 : 1;
7788 default:
7789 return 0;
7793 /* Normally, ConvertEventRefToEventRecord will correctly handle all
7794 events. However the click of the mouse wheel is not converted to a
7795 mouseDown or mouseUp event. Likewise for dead key down events.
7796 This calls ConvertEventRef, but then checks to see if it is a mouse
7797 up/down, or a dead key down carbon event that has not been
7798 converted, and if so, converts it by hand (to be picked up in the
7799 XTread_socket loop). */
7800 static Boolean mac_convert_event_ref (EventRef eventRef, EventRecord *eventRec)
7802 Boolean result = ConvertEventRefToEventRecord (eventRef, eventRec);
7804 if (result)
7805 return result;
7807 switch (GetEventClass (eventRef))
7809 case kEventClassMouse:
7810 switch (GetEventKind (eventRef))
7812 case kEventMouseDown:
7813 eventRec->what = mouseDown;
7814 result = 1;
7815 break;
7817 case kEventMouseUp:
7818 eventRec->what = mouseUp;
7819 result = 1;
7820 break;
7822 default:
7823 break;
7825 break;
7827 case kEventClassKeyboard:
7828 switch (GetEventKind (eventRef))
7830 case kEventRawKeyDown:
7832 unsigned char char_codes;
7833 UInt32 key_code;
7835 eventRec->what = keyDown;
7836 GetEventParameter (eventRef, kEventParamKeyMacCharCodes, typeChar,
7837 NULL, sizeof (char), NULL, &char_codes);
7838 GetEventParameter (eventRef, kEventParamKeyCode, typeUInt32,
7839 NULL, sizeof (UInt32), NULL, &key_code);
7840 eventRec->message = char_codes | ((key_code & 0xff) << 8);
7841 result = 1;
7843 break;
7845 default:
7846 break;
7848 break;
7850 default:
7851 break;
7854 if (result)
7856 /* Need where and when. */
7857 UInt32 mods;
7859 GetEventParameter (eventRef, kEventParamMouseLocation, typeQDPoint,
7860 NULL, sizeof (Point), NULL, &eventRec->where);
7861 /* Use two step process because new event modifiers are 32-bit
7862 and old are 16-bit. Currently, only loss is NumLock & Fn. */
7863 GetEventParameter (eventRef, kEventParamKeyModifiers, typeUInt32,
7864 NULL, sizeof (UInt32), NULL, &mods);
7865 eventRec->modifiers = mods;
7867 eventRec->when = EventTimeToTicks (GetEventTime (eventRef));
7870 return result;
7873 #endif
7875 static void
7876 do_get_menus (void)
7878 Handle menubar_handle;
7879 MenuHandle menu_handle;
7881 menubar_handle = GetNewMBar (128);
7882 if(menubar_handle == NULL)
7883 abort ();
7884 SetMenuBar (menubar_handle);
7885 DrawMenuBar ();
7887 #if !TARGET_API_MAC_CARBON
7888 menu_handle = GetMenuHandle (M_APPLE);
7889 if(menu_handle != NULL)
7890 AppendResMenu (menu_handle,'DRVR');
7891 else
7892 abort ();
7893 #endif
7897 static void
7898 do_init_managers (void)
7900 #if !TARGET_API_MAC_CARBON
7901 InitGraf (&qd.thePort);
7902 InitFonts ();
7903 FlushEvents (everyEvent, 0);
7904 InitWindows ();
7905 InitMenus ();
7906 TEInit ();
7907 InitDialogs (NULL);
7908 #endif /* !TARGET_API_MAC_CARBON */
7909 InitCursor ();
7911 #if !TARGET_API_MAC_CARBON
7912 /* set up some extra stack space for use by emacs */
7913 SetApplLimit ((Ptr) ((long) GetApplLimit () - EXTRA_STACK_ALLOC));
7915 /* MaxApplZone must be called for AppleScript to execute more
7916 complicated scripts */
7917 MaxApplZone ();
7918 MoreMasters ();
7919 #endif /* !TARGET_API_MAC_CARBON */
7922 static void
7923 do_check_ram_size (void)
7925 SInt32 physical_ram_size, logical_ram_size;
7927 if (Gestalt (gestaltPhysicalRAMSize, &physical_ram_size) != noErr
7928 || Gestalt (gestaltLogicalRAMSize, &logical_ram_size) != noErr
7929 || physical_ram_size > (1 << VALBITS)
7930 || logical_ram_size > (1 << VALBITS))
7932 StopAlert (RAM_TOO_LARGE_ALERT_ID, NULL);
7933 exit (1);
7937 static void
7938 do_window_update (WindowPtr win)
7940 struct frame *f = mac_window_to_frame (win);
7942 BeginUpdate (win);
7944 /* The tooltip has been drawn already. Avoid the SET_FRAME_GARBAGED
7945 below. */
7946 if (win != tip_window)
7948 if (f->async_visible == 0)
7950 /* Update events may occur when a frame gets iconified. */
7951 #if 0
7952 f->async_visible = 1;
7953 f->async_iconified = 0;
7954 SET_FRAME_GARBAGED (f);
7955 #endif
7957 else
7959 Rect r;
7960 #if TARGET_API_MAC_CARBON
7961 RgnHandle region = NewRgn ();
7963 GetPortVisibleRegion (GetWindowPort (win), region);
7964 GetRegionBounds (region, &r);
7965 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
7966 UpdateControls (win, region);
7967 DisposeRgn (region);
7968 #else
7969 r = (*win->visRgn)->rgnBBox;
7970 expose_frame (f, r.left, r.top, r.right - r.left, r.bottom - r.top);
7971 UpdateControls (win, win->visRgn);
7972 #endif
7976 EndUpdate (win);
7979 static int
7980 is_emacs_window (WindowPtr win)
7982 Lisp_Object tail, frame;
7984 if (!win)
7985 return 0;
7987 FOR_EACH_FRAME (tail, frame)
7988 if (FRAME_MAC_P (XFRAME (frame)))
7989 if (FRAME_MAC_WINDOW (XFRAME (frame)) == win)
7990 return 1;
7992 return 0;
7995 static void
7996 do_app_resume ()
7998 /* Window-activate events will do the job. */
8001 static void
8002 do_app_suspend ()
8004 /* Window-deactivate events will do the job. */
8008 static void
8009 do_apple_menu (SInt16 menu_item)
8011 #if !TARGET_API_MAC_CARBON
8012 Str255 item_name;
8013 SInt16 da_driver_refnum;
8015 if (menu_item == I_ABOUT)
8016 NoteAlert (ABOUT_ALERT_ID, NULL);
8017 else
8019 GetMenuItemText (GetMenuHandle (M_APPLE), menu_item, item_name);
8020 da_driver_refnum = OpenDeskAcc (item_name);
8022 #endif /* !TARGET_API_MAC_CARBON */
8025 void
8026 do_menu_choice (SInt32 menu_choice)
8028 SInt16 menu_id, menu_item;
8030 menu_id = HiWord (menu_choice);
8031 menu_item = LoWord (menu_choice);
8033 switch (menu_id)
8035 case 0:
8036 break;
8038 case M_APPLE:
8039 do_apple_menu (menu_item);
8040 break;
8042 default:
8044 struct frame *f = mac_focus_frame (&one_mac_display_info);
8045 MenuHandle menu = GetMenuHandle (menu_id);
8046 if (menu)
8048 UInt32 refcon;
8050 GetMenuItemRefCon (menu, menu_item, &refcon);
8051 menubar_selection_callback (f, refcon);
8056 HiliteMenu (0);
8060 /* Handle drags in size box. Based on code contributed by Ben
8061 Mesander and IM - Window Manager A. */
8063 static void
8064 do_grow_window (WindowPtr w, EventRecord *e)
8066 Rect limit_rect;
8067 int rows, columns, width, height;
8068 struct frame *f = mac_window_to_frame (w);
8069 XSizeHints *size_hints = FRAME_SIZE_HINTS (f);
8070 int min_width = MIN_DOC_SIZE, min_height = MIN_DOC_SIZE;
8071 #if TARGET_API_MAC_CARBON
8072 Rect new_rect;
8073 #else
8074 long grow_size;
8075 #endif
8077 if (size_hints->flags & PMinSize)
8079 min_width = size_hints->min_width;
8080 min_height = size_hints->min_height;
8082 SetRect (&limit_rect, min_width, min_height, MAX_DOC_SIZE, MAX_DOC_SIZE);
8084 #if TARGET_API_MAC_CARBON
8085 if (!ResizeWindow (w, e->where, &limit_rect, &new_rect))
8086 return;
8087 height = new_rect.bottom - new_rect.top;
8088 width = new_rect.right - new_rect.left;
8089 #else
8090 grow_size = GrowWindow (w, e->where, &limit_rect);
8091 /* see if it really changed size */
8092 if (grow_size == 0)
8093 return;
8094 height = HiWord (grow_size);
8095 width = LoWord (grow_size);
8096 #endif
8098 if (width != FRAME_PIXEL_WIDTH (f)
8099 || height != FRAME_PIXEL_HEIGHT (f))
8101 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8102 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8104 x_set_window_size (f, 0, columns, rows);
8109 /* Handle clicks in zoom box. Calculation of "standard state" based
8110 on code in IM - Window Manager A and code contributed by Ben
8111 Mesander. The standard state of an Emacs window is 80-characters
8112 wide (DEFAULT_NUM_COLS) and as tall as will fit on the screen. */
8114 static void
8115 do_zoom_window (WindowPtr w, int zoom_in_or_out)
8117 GrafPtr save_port;
8118 Rect zoom_rect, port_rect;
8119 Point top_left;
8120 int w_title_height, columns, rows, width, height;
8121 struct frame *f = mac_window_to_frame (w);
8122 struct mac_display_info *dpyinfo = FRAME_MAC_DISPLAY_INFO (f);
8124 #if TARGET_API_MAC_CARBON
8126 Point standard_size;
8128 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8129 standard_size.v = dpyinfo->height;
8131 if (IsWindowInStandardState (w, &standard_size, &zoom_rect))
8132 zoom_in_or_out = inZoomIn;
8133 else
8135 /* Adjust the standard size according to character boundaries. */
8137 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, zoom_rect.right - zoom_rect.left);
8138 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8139 standard_size.h = FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, columns);
8140 standard_size.v = FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8141 GetWindowBounds (w, kWindowContentRgn, &port_rect);
8142 if (IsWindowInStandardState (w, &standard_size, &zoom_rect)
8143 && port_rect.left == zoom_rect.left
8144 && port_rect.top == zoom_rect.top)
8145 zoom_in_or_out = inZoomIn;
8146 else
8147 zoom_in_or_out = inZoomOut;
8150 ZoomWindowIdeal (w, zoom_in_or_out, &standard_size);
8152 #else /* not TARGET_API_MAC_CARBON */
8153 GetPort (&save_port);
8155 SetPortWindowPort (w);
8157 /* Clear window to avoid flicker. */
8158 EraseRect (&(w->portRect));
8159 if (zoom_in_or_out == inZoomOut)
8161 SetPt (&top_left, w->portRect.left, w->portRect.top);
8162 LocalToGlobal (&top_left);
8164 /* calculate height of window's title bar */
8165 w_title_height = top_left.v - 1
8166 - (**((WindowPeek) w)->strucRgn).rgnBBox.top + GetMBarHeight ();
8168 /* get maximum height of window into zoom_rect.bottom - zoom_rect.top */
8169 zoom_rect = qd.screenBits.bounds;
8170 zoom_rect.top += w_title_height;
8171 InsetRect (&zoom_rect, 8, 4); /* not too tight */
8173 zoom_rect.right = zoom_rect.left
8174 + FRAME_TEXT_COLS_TO_PIXEL_WIDTH (f, DEFAULT_NUM_COLS);
8176 /* Adjust the standard size according to character boundaries. */
8177 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, zoom_rect.bottom - zoom_rect.top);
8178 zoom_rect.bottom =
8179 zoom_rect.top + FRAME_TEXT_LINES_TO_PIXEL_HEIGHT (f, rows);
8181 (**((WStateDataHandle) ((WindowPeek) w)->dataHandle)).stdState
8182 = zoom_rect;
8185 ZoomWindow (w, zoom_in_or_out, f == mac_focus_frame (dpyinfo));
8187 SetPort (save_port);
8188 #endif /* not TARGET_API_MAC_CARBON */
8190 /* retrieve window size and update application values */
8191 #if TARGET_API_MAC_CARBON
8192 GetWindowPortBounds (w, &port_rect);
8193 #else
8194 port_rect = w->portRect;
8195 #endif
8196 height = port_rect.bottom - port_rect.top;
8197 width = port_rect.right - port_rect.left;
8199 if (width != FRAME_PIXEL_WIDTH (f)
8200 || height != FRAME_PIXEL_HEIGHT (f))
8202 rows = FRAME_PIXEL_HEIGHT_TO_TEXT_LINES (f, height);
8203 columns = FRAME_PIXEL_WIDTH_TO_TEXT_COLS (f, width);
8205 change_frame_size (f, rows, columns, 0, 1, 0);
8206 SET_FRAME_GARBAGED (f);
8207 cancel_mouse_face (f);
8209 FRAME_PIXEL_WIDTH (f) = width;
8210 FRAME_PIXEL_HEIGHT (f) = height;
8212 x_real_positions (f, &f->left_pos, &f->top_pos);
8215 /* Intialize AppleEvent dispatcher table for the required events. */
8216 void
8217 init_required_apple_events ()
8219 OSErr err;
8220 long result;
8222 /* Make sure we have apple events before starting. */
8223 err = Gestalt (gestaltAppleEventsAttr, &result);
8224 if (err != noErr)
8225 abort ();
8227 if (!(result & (1 << gestaltAppleEventsPresent)))
8228 abort ();
8230 #if TARGET_API_MAC_CARBON
8231 err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
8232 NewAEEventHandlerUPP
8233 ((AEEventHandlerProcPtr) do_ae_open_application),
8234 0L, false);
8235 #else
8236 err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
8237 NewAEEventHandlerProc
8238 ((AEEventHandlerProcPtr) do_ae_open_application),
8239 0L, false);
8240 #endif
8241 if (err != noErr)
8242 abort ();
8244 #if TARGET_API_MAC_CARBON
8245 err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
8246 NewAEEventHandlerUPP
8247 ((AEEventHandlerProcPtr) do_ae_open_documents),
8248 0L, false);
8249 #else
8250 err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
8251 NewAEEventHandlerProc
8252 ((AEEventHandlerProcPtr) do_ae_open_documents),
8253 0L, false);
8254 #endif
8255 if (err != noErr)
8256 abort ();
8258 #if TARGET_API_MAC_CARBON
8259 err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
8260 NewAEEventHandlerUPP
8261 ((AEEventHandlerProcPtr) do_ae_print_documents),
8262 0L, false);
8263 #else
8264 err = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
8265 NewAEEventHandlerProc
8266 ((AEEventHandlerProcPtr) do_ae_print_documents),
8267 0L, false);
8268 #endif
8269 if (err != noErr)
8270 abort ();
8272 #if TARGET_API_MAC_CARBON
8273 err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
8274 NewAEEventHandlerUPP
8275 ((AEEventHandlerProcPtr) do_ae_quit_application),
8276 0L, false);
8277 #else
8278 err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
8279 NewAEEventHandlerProc
8280 ((AEEventHandlerProcPtr) do_ae_quit_application),
8281 0L, false);
8282 #endif
8283 if (err != noErr)
8284 abort ();
8287 void
8288 mac_store_application_menu_event (event)
8289 #if USE_CARBON_EVENTS
8290 EventRef event;
8291 #else
8292 UInt32 event;
8293 #endif
8295 struct input_event buf;
8296 Lisp_Object frame, entry;
8298 EVENT_INIT (buf);
8300 XSETFRAME (frame, mac_focus_frame (&one_mac_display_info));
8301 buf.kind = MENU_BAR_EVENT;
8302 buf.frame_or_window = frame;
8303 buf.arg = frame;
8304 kbd_buffer_store_event (&buf);
8306 buf.arg = Qapplication;
8307 kbd_buffer_store_event (&buf);
8309 #if USE_CARBON_EVENTS
8310 switch (GetEventClass (event))
8312 #ifdef MAC_OSX
8313 case kEventClassService:
8314 buf.arg = Qservices;
8315 kbd_buffer_store_event (&buf);
8316 switch (GetEventKind (event))
8318 case kEventServicePaste:
8319 entry = Qpaste;
8320 break;
8322 case kEventServicePerform:
8324 OSErr err;
8325 CFStringRef message;
8327 err = GetEventParameter (event, kEventParamServiceMessageName,
8328 typeCFStringRef, NULL,
8329 sizeof (CFStringRef), NULL, &message);
8330 buf.arg = Qperform;
8331 kbd_buffer_store_event (&buf);
8332 if (err == noErr && message)
8333 entry = intern (SDATA (cfstring_to_lisp (message)));
8334 else
8335 entry = Qnil;
8337 break;
8339 default:
8340 abort ();
8342 break;
8343 #endif /* MAC_OSX */
8344 case kEventClassCommand:
8346 HICommand command;
8348 GetEventParameter(event, kEventParamDirectObject, typeHICommand,
8349 NULL, sizeof (HICommand), NULL, &command);
8350 switch (command.commandID)
8352 case kHICommandAbout:
8353 entry = Qabout;
8354 break;
8355 #ifdef MAC_OSX
8356 case kHICommandPreferences:
8357 entry = Qpreferences;
8358 break;
8359 #endif /* MAC_OSX */
8360 case kHICommandQuit:
8361 entry = Qquit;
8362 break;
8363 default:
8364 abort ();
8367 break;
8369 default:
8370 abort ();
8372 #else /* USE_CARBON_EVENTS */
8373 switch (event)
8375 case kHICommandAbout:
8376 entry = Qabout;
8377 break;
8378 case kHICommandQuit:
8379 entry = Qquit;
8380 break;
8381 default:
8382 abort ();
8384 #endif
8386 buf.arg = entry;
8387 kbd_buffer_store_event (&buf);
8390 #if USE_CARBON_EVENTS
8391 static pascal OSStatus
8392 mac_handle_command_event (next_handler, event, data)
8393 EventHandlerCallRef next_handler;
8394 EventRef event;
8395 void *data;
8397 HICommand command;
8398 OSErr result;
8400 GetEventParameter(event, kEventParamDirectObject, typeHICommand, NULL,
8401 sizeof (HICommand), NULL, &command);
8403 switch (command.commandID)
8405 case kHICommandAbout:
8406 #ifdef MAC_OSX
8407 case kHICommandPreferences:
8408 #endif /* MAC_OSX */
8409 result = CallNextEventHandler (next_handler, event);
8410 if (result != eventNotHandledErr)
8411 return result;
8413 mac_store_application_menu_event (event);
8414 return noErr;
8416 default:
8417 break;
8420 return eventNotHandledErr;
8423 static OSErr
8424 init_command_handler ()
8426 OSErr err = noErr;
8427 EventTypeSpec specs[] = {{kEventClassCommand, kEventCommandProcess}};
8428 static EventHandlerUPP handle_command_eventUPP = NULL;
8430 if (handle_command_eventUPP == NULL)
8431 handle_command_eventUPP = NewEventHandlerUPP (mac_handle_command_event);
8432 return InstallApplicationEventHandler (handle_command_eventUPP,
8433 GetEventTypeCount (specs), specs,
8434 NULL, NULL);
8437 static pascal OSStatus
8438 mac_handle_window_event (next_handler, event, data)
8439 EventHandlerCallRef next_handler;
8440 EventRef event;
8441 void *data;
8443 WindowPtr wp;
8444 OSStatus result;
8445 UInt32 attributes;
8446 XSizeHints *size_hints;
8448 GetEventParameter (event, kEventParamDirectObject, typeWindowRef,
8449 NULL, sizeof (WindowPtr), NULL, &wp);
8451 switch (GetEventKind (event))
8453 case kEventWindowUpdate:
8454 result = CallNextEventHandler (next_handler, event);
8455 if (result != eventNotHandledErr)
8456 return result;
8458 do_window_update (wp);
8459 return noErr;
8461 case kEventWindowBoundsChanging:
8462 result = CallNextEventHandler (next_handler, event);
8463 if (result != eventNotHandledErr)
8464 return result;
8466 GetEventParameter (event, kEventParamAttributes, typeUInt32,
8467 NULL, sizeof (UInt32), NULL, &attributes);
8468 size_hints = FRAME_SIZE_HINTS (mac_window_to_frame (wp));
8469 if ((attributes & kWindowBoundsChangeUserResize)
8470 && ((size_hints->flags & (PResizeInc | PBaseSize | PMinSize))
8471 == (PResizeInc | PBaseSize | PMinSize)))
8473 Rect bounds;
8474 int width, height;
8476 GetEventParameter (event, kEventParamCurrentBounds,
8477 typeQDRectangle,
8478 NULL, sizeof (Rect), NULL, &bounds);
8479 width = bounds.right - bounds.left;
8480 height = bounds.bottom - bounds.top;
8482 if (width < size_hints->min_width)
8483 width = size_hints->min_width;
8484 else
8485 width = size_hints->base_width
8486 + (int) ((width - size_hints->base_width)
8487 / (float) size_hints->width_inc + .5)
8488 * size_hints->width_inc;
8490 if (height < size_hints->min_height)
8491 height = size_hints->min_height;
8492 else
8493 height = size_hints->base_height
8494 + (int) ((height - size_hints->base_height)
8495 / (float) size_hints->height_inc + .5)
8496 * size_hints->height_inc;
8498 bounds.right = bounds.left + width;
8499 bounds.bottom = bounds.top + height;
8500 SetEventParameter (event, kEventParamCurrentBounds,
8501 typeQDRectangle, sizeof (Rect), &bounds);
8502 return noErr;
8504 break;
8506 case kEventWindowShown:
8507 case kEventWindowHidden:
8508 case kEventWindowExpanded:
8509 case kEventWindowCollapsed:
8510 result = CallNextEventHandler (next_handler, event);
8512 mac_handle_visibility_change (mac_window_to_frame (wp));
8513 return noErr;
8515 break;
8518 return eventNotHandledErr;
8521 static pascal OSStatus
8522 mac_handle_mouse_event (next_handler, event, data)
8523 EventHandlerCallRef next_handler;
8524 EventRef event;
8525 void *data;
8527 OSStatus result;
8529 switch (GetEventKind (event))
8531 case kEventMouseWheelMoved:
8533 WindowPtr wp;
8534 struct frame *f;
8535 EventMouseWheelAxis axis;
8536 SInt32 delta;
8537 Point point;
8539 result = CallNextEventHandler (next_handler, event);
8540 if (result != eventNotHandledErr || read_socket_inev == NULL)
8541 return result;
8543 GetEventParameter (event, kEventParamWindowRef, typeWindowRef,
8544 NULL, sizeof (WindowRef), NULL, &wp);
8545 f = mac_window_to_frame (wp);
8546 if (f != mac_focus_frame (&one_mac_display_info))
8547 break;
8549 GetEventParameter (event, kEventParamMouseWheelAxis,
8550 typeMouseWheelAxis, NULL,
8551 sizeof (EventMouseWheelAxis), NULL, &axis);
8552 if (axis != kEventMouseWheelAxisY)
8553 break;
8555 GetEventParameter (event, kEventParamMouseWheelDelta, typeSInt32,
8556 NULL, sizeof (SInt32), NULL, &delta);
8557 GetEventParameter (event, kEventParamMouseLocation, typeQDPoint,
8558 NULL, sizeof (Point), NULL, &point);
8559 read_socket_inev->kind = WHEEL_EVENT;
8560 read_socket_inev->code = 0;
8561 read_socket_inev->modifiers =
8562 (mac_event_to_emacs_modifiers (event)
8563 | ((delta < 0) ? down_modifier : up_modifier));
8564 SetPortWindowPort (wp);
8565 GlobalToLocal (&point);
8566 XSETINT (read_socket_inev->x, point.h);
8567 XSETINT (read_socket_inev->y, point.v);
8568 XSETFRAME (read_socket_inev->frame_or_window, f);
8570 return noErr;
8572 break;
8574 default:
8575 break;
8578 return eventNotHandledErr;
8580 #endif /* USE_CARBON_EVENTS */
8583 OSErr
8584 install_window_handler (window)
8585 WindowPtr window;
8587 OSErr err = noErr;
8588 #if USE_CARBON_EVENTS
8589 EventTypeSpec specs_window[] =
8590 {{kEventClassWindow, kEventWindowUpdate},
8591 {kEventClassWindow, kEventWindowBoundsChanging},
8592 {kEventClassWindow, kEventWindowShown},
8593 {kEventClassWindow, kEventWindowHidden},
8594 {kEventClassWindow, kEventWindowExpanded},
8595 {kEventClassWindow, kEventWindowCollapsed}};
8596 EventTypeSpec specs_mouse[] = {{kEventClassMouse, kEventMouseWheelMoved}};
8597 static EventHandlerUPP handle_window_eventUPP = NULL;
8598 static EventHandlerUPP handle_mouse_eventUPP = NULL;
8600 if (handle_window_eventUPP == NULL)
8601 handle_window_eventUPP = NewEventHandlerUPP (mac_handle_window_event);
8602 if (handle_mouse_eventUPP == NULL)
8603 handle_mouse_eventUPP = NewEventHandlerUPP (mac_handle_mouse_event);
8604 err = InstallWindowEventHandler (window, handle_window_eventUPP,
8605 GetEventTypeCount (specs_window),
8606 specs_window, NULL, NULL);
8607 if (err == noErr)
8608 err = InstallWindowEventHandler (window, handle_mouse_eventUPP,
8609 GetEventTypeCount (specs_mouse),
8610 specs_mouse, NULL, NULL);
8611 #endif
8612 #if TARGET_API_MAC_CARBON
8613 if (mac_do_track_dragUPP == NULL)
8614 mac_do_track_dragUPP = NewDragTrackingHandlerUPP (mac_do_track_drag);
8615 if (mac_do_receive_dragUPP == NULL)
8616 mac_do_receive_dragUPP = NewDragReceiveHandlerUPP (mac_do_receive_drag);
8618 if (err == noErr)
8619 err = InstallTrackingHandler (mac_do_track_dragUPP, window, NULL);
8620 if (err == noErr)
8621 err = InstallReceiveHandler (mac_do_receive_dragUPP, window, NULL);
8622 #endif
8623 return err;
8626 void
8627 remove_window_handler (window)
8628 WindowPtr window;
8630 #if TARGET_API_MAC_CARBON
8631 if (mac_do_track_dragUPP)
8632 RemoveTrackingHandler (mac_do_track_dragUPP, window);
8633 if (mac_do_receive_dragUPP)
8634 RemoveReceiveHandler (mac_do_receive_dragUPP, window);
8635 #endif
8638 /* Open Application Apple Event */
8639 static pascal OSErr
8640 do_ae_open_application(const AppleEvent *pae, AppleEvent *preply, long prefcon)
8642 return noErr;
8646 /* Called when we receive an AppleEvent with an ID of
8647 "kAEOpenDocuments". This routine gets the direct parameter,
8648 extracts the FSSpecs in it, and puts their names on a list. */
8649 #pragma options align=mac68k
8650 typedef struct SelectionRange {
8651 short unused1; // 0 (not used)
8652 short lineNum; // line to select (<0 to specify range)
8653 long startRange; // start of selection range (if line < 0)
8654 long endRange; // end of selection range (if line < 0)
8655 long unused2; // 0 (not used)
8656 long theDate; // modification date/time
8657 } SelectionRange;
8658 #pragma options align=reset
8660 static pascal OSErr
8661 do_ae_open_documents(AppleEvent *message, AppleEvent *reply, long refcon)
8663 OSErr err, err2;
8664 AEDesc the_desc;
8665 AEKeyword keyword;
8666 DescType actual_type;
8667 Size actual_size;
8668 SelectionRange position;
8669 Lisp_Object file_list = Qnil;
8671 xassert (read_socket_inev);
8673 err = AEGetParamDesc (message, keyDirectObject, typeAEList, &the_desc);
8674 if (err != noErr)
8675 goto descriptor_error_exit;
8677 err = AEGetParamPtr (message, keyAEPosition, typeChar, &actual_type, &position, sizeof(SelectionRange), &actual_size);
8678 if (err == noErr)
8679 file_list = Fcons (list3 (make_number (position.lineNum + 1),
8680 make_number (position.startRange + 1),
8681 make_number (position.endRange + 1)),
8682 file_list);
8684 /* Check to see that we got all of the required parameters from the
8685 event descriptor. For an 'odoc' event this should just be the
8686 file list. */
8687 err = AEGetAttributePtr(message, keyMissedKeywordAttr, typeWildCard,
8688 &actual_type, (Ptr) &keyword,
8689 sizeof (keyword), &actual_size);
8690 /* No error means that we found some unused parameters.
8691 errAEDescNotFound means that there are no more parameters. If we
8692 get an error code other than that, flag it. */
8693 if ((err == noErr) || (err != errAEDescNotFound))
8695 err = errAEEventNotHandled;
8696 goto error_exit;
8698 err = noErr;
8700 /* Got all the parameters we need. Now, go through the direct
8701 object list and parse it up. */
8703 long num_files_to_open;
8705 err = AECountItems (&the_desc, &num_files_to_open);
8706 if (err == noErr)
8708 int i;
8710 /* AE file list is one based so just use that for indexing here. */
8711 for (i = 1; i <= num_files_to_open; i++)
8713 char unix_path_name[MAXPATHLEN];
8714 #ifdef MAC_OSX
8715 FSRef fref;
8717 err = AEGetNthPtr (&the_desc, i, typeFSRef, &keyword,
8718 &actual_type, &fref, sizeof (FSRef),
8719 &actual_size);
8720 if (err != noErr || actual_type != typeFSRef)
8721 continue;
8723 if (FSRefMakePath (&fref, unix_path_name, sizeof (unix_path_name))
8724 == noErr)
8725 #else
8726 FSSpec fs;
8728 err = AEGetNthPtr(&the_desc, i, typeFSS, &keyword, &actual_type,
8729 (Ptr) &fs, sizeof (fs), &actual_size);
8730 if (err != noErr) continue;
8732 if (fsspec_to_posix_pathname (&fs, unix_path_name,
8733 sizeof (unix_path_name) - 1) == noErr)
8734 #endif
8735 /* x-dnd functions expect undecoded filenames. */
8736 file_list = Fcons (make_unibyte_string (unix_path_name,
8737 strlen (unix_path_name)),
8738 file_list);
8742 /* Build a DRAG_N_DROP_EVENT type event as is done in
8743 constuct_drag_n_drop in w32term.c. */
8744 if (!NILP (file_list))
8746 struct frame *f = mac_focus_frame (&one_mac_display_info);
8747 WindowPtr wp;
8748 Lisp_Object frame;
8750 read_socket_inev->kind = DRAG_N_DROP_EVENT;
8751 read_socket_inev->code = 0;
8752 read_socket_inev->modifiers = 0;
8754 XSETINT (read_socket_inev->x, 0);
8755 XSETINT (read_socket_inev->y, 0);
8757 XSETFRAME (frame, f);
8758 read_socket_inev->frame_or_window = Fcons (frame, file_list);
8760 #if 0
8761 /* Regardless of whether Emacs was suspended or in the
8762 foreground, ask it to redraw its entire screen. Otherwise
8763 parts of the screen can be left in an inconsistent
8764 state. */
8765 wp = FRAME_MAC_WINDOW (f);
8766 if (wp)
8767 #if TARGET_API_MAC_CARBON
8769 Rect r;
8771 GetWindowPortBounds (wp, &r);
8772 InvalWindowRect (wp, &r);
8774 #else /* not TARGET_API_MAC_CARBON */
8775 InvalRect (&(wp->portRect));
8776 #endif /* not TARGET_API_MAC_CARBON */
8777 #endif
8781 error_exit:
8782 /* Nuke the coerced file list in any case */
8783 err2 = AEDisposeDesc(&the_desc);
8785 descriptor_error_exit:
8786 /* InvalRect(&(gFrontMacWindowP->mWP->portRect)); */
8787 return err;
8791 #if TARGET_API_MAC_CARBON
8792 static pascal OSErr
8793 mac_do_track_drag (DragTrackingMessage message, WindowPtr window,
8794 void *handlerRefCon, DragReference theDrag)
8796 static int can_accept;
8797 short items;
8798 short index;
8799 ItemReference theItem;
8800 FlavorFlags theFlags;
8801 OSErr result;
8803 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
8804 return dragNotAcceptedErr;
8806 switch (message)
8808 case kDragTrackingEnterHandler:
8809 CountDragItems (theDrag, &items);
8810 can_accept = 0;
8811 for (index = 1; index <= items; index++)
8813 GetDragItemReferenceNumber (theDrag, index, &theItem);
8814 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
8815 if (result == noErr)
8817 can_accept = 1;
8818 break;
8821 break;
8823 case kDragTrackingEnterWindow:
8824 if (can_accept)
8826 RgnHandle hilite_rgn = NewRgn ();
8827 Rect r;
8828 struct frame *f = mac_window_to_frame (window);
8830 GetWindowPortBounds (window, &r);
8831 OffsetRect (&r, -r.left, -r.top);
8832 RectRgn (hilite_rgn, &r);
8833 ShowDragHilite (theDrag, hilite_rgn, true);
8834 DisposeRgn (hilite_rgn);
8835 SetThemeCursor (kThemeCopyArrowCursor);
8837 break;
8839 case kDragTrackingInWindow:
8840 break;
8842 case kDragTrackingLeaveWindow:
8843 if (can_accept)
8845 struct frame *f = mac_window_to_frame (window);
8847 HideDragHilite (theDrag);
8848 SetThemeCursor (kThemeArrowCursor);
8850 break;
8852 case kDragTrackingLeaveHandler:
8853 break;
8856 return noErr;
8859 static pascal OSErr
8860 mac_do_receive_drag (WindowPtr window, void *handlerRefCon,
8861 DragReference theDrag)
8863 short items;
8864 short index;
8865 FlavorFlags theFlags;
8866 Point mouse;
8867 OSErr result;
8868 ItemReference theItem;
8869 HFSFlavor data;
8870 Size size = sizeof (HFSFlavor);
8871 Lisp_Object file_list;
8873 if (GetFrontWindowOfClass (kMovableModalWindowClass, false))
8874 return dragNotAcceptedErr;
8876 file_list = Qnil;
8877 GetDragMouse (theDrag, &mouse, 0L);
8878 CountDragItems (theDrag, &items);
8879 for (index = 1; index <= items; index++)
8881 /* Only handle file references. */
8882 GetDragItemReferenceNumber (theDrag, index, &theItem);
8883 result = GetFlavorFlags (theDrag, theItem, flavorTypeHFS, &theFlags);
8884 if (result == noErr)
8886 #ifdef MAC_OSX
8887 FSRef fref;
8888 #endif
8889 char unix_path_name[MAXPATHLEN];
8891 GetFlavorData (theDrag, theItem, flavorTypeHFS, &data, &size, 0L);
8892 #ifdef MAC_OSX
8893 /* Use Carbon routines, otherwise it converts the file name
8894 to /Macintosh HD/..., which is not correct. */
8895 FSpMakeFSRef (&data.fileSpec, &fref);
8896 if (! FSRefMakePath (&fref, unix_path_name, sizeof (unix_path_name)));
8897 #else
8898 if (fsspec_to_posix_pathname (&data.fileSpec, unix_path_name,
8899 sizeof (unix_path_name) - 1) == noErr)
8900 #endif
8901 /* x-dnd functions expect undecoded filenames. */
8902 file_list = Fcons (make_unibyte_string (unix_path_name,
8903 strlen (unix_path_name)),
8904 file_list);
8907 /* If there are items in the list, construct an event and post it to
8908 the queue like an interrupt using kbd_buffer_store_event. */
8909 if (!NILP (file_list))
8911 struct input_event event;
8912 Lisp_Object frame;
8913 struct frame *f = mac_window_to_frame (window);
8914 SInt16 modifiers;
8916 GlobalToLocal (&mouse);
8917 GetDragModifiers (theDrag, NULL, NULL, &modifiers);
8919 event.kind = DRAG_N_DROP_EVENT;
8920 event.code = 0;
8921 event.modifiers = mac_to_emacs_modifiers (modifiers);
8922 event.timestamp = TickCount () * (1000 / 60);
8923 XSETINT (event.x, mouse.h);
8924 XSETINT (event.y, mouse.v);
8925 XSETFRAME (frame, f);
8926 event.frame_or_window = Fcons (frame, file_list);
8927 event.arg = Qnil;
8928 /* Post to the interrupt queue */
8929 kbd_buffer_store_event (&event);
8930 /* MAC_TODO: Mimic behavior of windows by switching contexts to Emacs */
8932 ProcessSerialNumber psn;
8933 GetCurrentProcess (&psn);
8934 SetFrontProcess (&psn);
8937 return noErr;
8939 else
8940 return dragNotAcceptedErr;
8942 #endif
8945 /* Print Document Apple Event */
8946 static pascal OSErr
8947 do_ae_print_documents (const AppleEvent *pAE, AppleEvent *reply, long refcon)
8949 return errAEEventNotHandled;
8953 static pascal OSErr
8954 do_ae_quit_application (AppleEvent* message, AppleEvent *reply, long refcon)
8956 #if USE_CARBON_EVENTS
8957 OSErr err;
8958 EventRef event = NULL;
8959 static const HICommand quit_command = {kEventAttributeNone, kHICommandQuit};
8961 err = CreateEvent (NULL, kEventClassCommand, kEventCommandProcess, 0,
8962 kEventAttributeUserEvent, &event);
8963 if (err == noErr)
8964 err = SetEventParameter (event, kEventParamDirectObject, typeHICommand,
8965 sizeof (HICommand), &quit_command);
8966 if (err == noErr)
8967 mac_store_application_menu_event (event);
8968 if (event)
8969 ReleaseEvent (event);
8971 if (err == noErr)
8972 return noErr;
8973 else
8974 return errAEEventNotHandled;
8975 #else
8976 mac_store_application_menu_event (kHICommandQuit);
8978 return noErr;
8979 #endif
8983 #if __profile__
8984 void
8985 profiler_exit_proc ()
8987 ProfilerDump ("\pEmacs.prof");
8988 ProfilerTerm ();
8990 #endif
8992 /* These few functions implement Emacs as a normal Mac application
8993 (almost): set up the heap and the Toolbox, handle necessary system
8994 events plus a few simple menu events. They also set up Emacs's
8995 access to functions defined in the rest of this file. Emacs uses
8996 function hooks to perform all its terminal I/O. A complete list of
8997 these functions appear in termhooks.h. For what they do, read the
8998 comments there and see also w32term.c and xterm.c. What's
8999 noticeably missing here is the event loop, which is normally
9000 present in most Mac application. After performing the necessary
9001 Mac initializations, main passes off control to emacs_main
9002 (corresponding to main in emacs.c). Emacs_main calls XTread_socket
9003 (defined further below) to read input. This is where
9004 WaitNextEvent/ReceiveNextEvent is called to process Mac events. */
9006 #ifdef MAC_OS8
9007 #undef main
9009 main (void)
9011 #if __profile__ /* is the profiler on? */
9012 if (ProfilerInit(collectDetailed, bestTimeBase, 5000, 200))
9013 exit(1);
9014 #endif
9016 #if __MWERKS__
9017 /* set creator and type for files created by MSL */
9018 _fcreator = 'EMAx';
9019 _ftype = 'TEXT';
9020 #endif
9022 do_init_managers ();
9024 do_get_menus ();
9026 #ifndef USE_LSB_TAG
9027 do_check_ram_size ();
9028 #endif
9030 init_emacs_passwd_dir ();
9032 init_environ ();
9034 initialize_applescript ();
9036 init_required_apple_events ();
9039 char **argv;
9040 int argc = 0;
9042 /* set up argv array from STR# resource */
9043 get_string_list (&argv, ARGV_STRING_LIST_ID);
9044 while (argv[argc])
9045 argc++;
9047 /* free up AppleScript resources on exit */
9048 atexit (terminate_applescript);
9050 #if __profile__ /* is the profiler on? */
9051 atexit (profiler_exit_proc);
9052 #endif
9054 /* 3rd param "envp" never used in emacs_main */
9055 (void) emacs_main (argc, argv, 0);
9058 /* Never reached - real exit in Fkill_emacs */
9059 return 0;
9061 #endif
9063 /* Table for translating Mac keycode to X keysym values. Contributed
9064 by Sudhir Shenoy.
9065 Mapping for special keys is now identical to that in Apple X11
9066 except `clear' (-> <clear>) on the KeyPad, `enter' (-> <kp-enter>)
9067 on the right of the Cmd key on laptops, and fn + `enter' (->
9068 <linefeed>). */
9069 static unsigned char keycode_to_xkeysym_table[] = {
9070 /*0x00*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9071 /*0x10*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9072 /*0x20*/ 0, 0, 0, 0, 0x0d /*return*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9074 /*0x30*/ 0x09 /*tab*/, 0 /*0x0020 space*/, 0, 0x08 /*backspace*/,
9075 /*0x34*/ 0x8d /*enter on laptops*/, 0x1b /*escape*/, 0, 0,
9076 /*0x38*/ 0, 0, 0, 0,
9077 /*0x3C*/ 0, 0, 0, 0,
9079 /*0x40*/ 0, 0xae /*kp-.*/, 0, 0xaa /*kp-**/,
9080 /*0x44*/ 0, 0xab /*kp-+*/, 0, 0x0b /*clear*/,
9081 /*0x48*/ 0, 0, 0, 0xaf /*kp-/*/,
9082 /*0x4C*/ 0x8d /*kp-enter*/, 0, 0xad /*kp--*/, 0,
9084 /*0x50*/ 0, 0xbd /*kp-=*/, 0xb0 /*kp-0*/, 0xb1 /*kp-1*/,
9085 /*0x54*/ 0xb2 /*kp-2*/, 0xb3 /*kp-3*/, 0xb4 /*kp-4*/, 0xb5 /*kp-5*/,
9086 /*0x58*/ 0xb6 /*kp-6*/, 0xb7 /*kp-7*/, 0, 0xb8 /*kp-8*/,
9087 /*0x5C*/ 0xb9 /*kp-9*/, 0, 0, 0,
9089 /*0x60*/ 0xc2 /*f5*/, 0xc3 /*f6*/, 0xc4 /*f7*/, 0xc0 /*f3*/,
9090 /*0x64*/ 0xc5 /*f8*/, 0xc6 /*f9*/, 0, 0xc8 /*f11*/,
9091 /*0x68*/ 0, 0xca /*f13*/, 0, 0xcb /*f14*/,
9092 /*0x6C*/ 0, 0xc7 /*f10*/, 0x0a /*fn+enter on laptops*/, 0xc9 /*f12*/,
9094 /*0x70*/ 0, 0xcc /*f15*/, 0x6a /*help*/, 0x50 /*home*/,
9095 /*0x74*/ 0x55 /*pgup*/, 0xff /*delete*/, 0xc1 /*f4*/, 0x57 /*end*/,
9096 /*0x78*/ 0xbf /*f2*/, 0x56 /*pgdown*/, 0xbe /*f1*/, 0x51 /*left*/,
9097 /*0x7C*/ 0x53 /*right*/, 0x54 /*down*/, 0x52 /*up*/, 0
9100 static int
9101 keycode_to_xkeysym (int keyCode, int *xKeySym)
9103 *xKeySym = keycode_to_xkeysym_table [keyCode & 0x7f];
9104 return *xKeySym != 0;
9107 #if !USE_CARBON_EVENTS
9108 static RgnHandle mouse_region = NULL;
9110 Boolean
9111 mac_wait_next_event (er, sleep_time, dequeue)
9112 EventRecord *er;
9113 UInt32 sleep_time;
9114 Boolean dequeue;
9116 static EventRecord er_buf = {nullEvent};
9117 UInt32 target_tick, current_tick;
9118 EventMask event_mask;
9120 if (mouse_region == NULL)
9121 mouse_region = NewRgn ();
9123 event_mask = everyEvent;
9124 if (NILP (Fboundp (Qmac_ready_for_drag_n_drop)))
9125 event_mask -= highLevelEventMask;
9127 current_tick = TickCount ();
9128 target_tick = current_tick + sleep_time;
9130 if (er_buf.what == nullEvent)
9131 while (!WaitNextEvent (event_mask, &er_buf,
9132 target_tick - current_tick, mouse_region))
9134 current_tick = TickCount ();
9135 if (target_tick <= current_tick)
9136 return false;
9139 *er = er_buf;
9140 if (dequeue)
9141 er_buf.what = nullEvent;
9142 return true;
9144 #endif /* not USE_CARBON_EVENTS */
9146 /* Emacs calls this whenever it wants to read an input event from the
9147 user. */
9149 XTread_socket (sd, expected, hold_quit)
9150 int sd, expected;
9151 struct input_event *hold_quit;
9153 struct input_event inev;
9154 int count = 0;
9155 #if USE_CARBON_EVENTS
9156 EventRef eventRef;
9157 EventTargetRef toolbox_dispatcher;
9158 #endif
9159 EventRecord er;
9160 struct mac_display_info *dpyinfo = &one_mac_display_info;
9162 if (interrupt_input_blocked)
9164 interrupt_input_pending = 1;
9165 return -1;
9168 interrupt_input_pending = 0;
9169 BLOCK_INPUT;
9171 /* So people can tell when we have read the available input. */
9172 input_signal_count++;
9174 #if USE_CARBON_EVENTS
9175 toolbox_dispatcher = GetEventDispatcherTarget ();
9177 while (!ReceiveNextEvent (0, NULL, kEventDurationNoWait,
9178 kEventRemoveFromQueue, &eventRef))
9179 #else /* !USE_CARBON_EVENTS */
9180 while (mac_wait_next_event (&er, 0, true))
9181 #endif /* !USE_CARBON_EVENTS */
9183 int do_help = 0;
9184 struct frame *f;
9185 unsigned long timestamp;
9187 /* It is necessary to set this (additional) argument slot of an
9188 event to nil because keyboard.c protects incompletely
9189 processed event from being garbage collected by placing them
9190 in the kbd_buffer_gcpro vector. */
9191 EVENT_INIT (inev);
9192 inev.kind = NO_EVENT;
9193 inev.arg = Qnil;
9195 #if USE_CARBON_EVENTS
9196 timestamp = GetEventTime (eventRef) / kEventDurationMillisecond;
9197 #else
9198 timestamp = er.when * (1000 / 60); /* ticks to milliseconds */
9199 #endif
9201 #if USE_CARBON_EVENTS
9202 /* Handle new events */
9203 if (!mac_convert_event_ref (eventRef, &er))
9205 /* There used to be a handler for the kEventMouseWheelMoved
9206 event here. But as of Mac OS X 10.4, this kind of event
9207 is not directly posted to the main event queue by
9208 two-finger scrolling on the trackpad. Instead, some
9209 private event is posted and it is converted to a wheel
9210 event by the default handler for the application target.
9211 The converted one can be received by a Carbon event
9212 handler installed on a window target. */
9213 read_socket_inev = &inev;
9214 SendEventToEventTarget (eventRef, toolbox_dispatcher);
9215 read_socket_inev = NULL;
9217 else
9218 #endif /* USE_CARBON_EVENTS */
9219 switch (er.what)
9221 case mouseDown:
9222 case mouseUp:
9224 WindowPtr window_ptr;
9225 ControlPartCode part_code;
9226 int tool_bar_p = 0;
9228 #if USE_CARBON_EVENTS
9229 /* This is needed to send mouse events like aqua window
9230 buttons to the correct handler. */
9231 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9232 != eventNotHandledErr)
9233 break;
9234 #endif
9236 if (dpyinfo->grabbed && last_mouse_frame
9237 && FRAME_LIVE_P (last_mouse_frame))
9239 window_ptr = FRAME_MAC_WINDOW (last_mouse_frame);
9240 part_code = inContent;
9242 else
9244 part_code = FindWindow (er.where, &window_ptr);
9245 if (tip_window && window_ptr == tip_window)
9247 HideWindow (tip_window);
9248 part_code = FindWindow (er.where, &window_ptr);
9252 if (er.what != mouseDown && part_code != inContent)
9253 break;
9255 switch (part_code)
9257 case inMenuBar:
9258 f = mac_focus_frame (dpyinfo);
9259 saved_menu_event_location = er.where;
9260 inev.kind = MENU_BAR_ACTIVATE_EVENT;
9261 XSETFRAME (inev.frame_or_window, f);
9262 break;
9264 case inContent:
9265 if (window_ptr != FRAME_MAC_WINDOW (mac_focus_frame (dpyinfo)))
9266 SelectWindow (window_ptr);
9267 else
9269 ControlPartCode control_part_code;
9270 ControlHandle ch;
9271 Point mouse_loc = er.where;
9272 #ifdef MAC_OSX
9273 ControlKind control_kind;
9274 #endif
9276 f = mac_window_to_frame (window_ptr);
9277 /* convert to local coordinates of new window */
9278 SetPortWindowPort (window_ptr);
9280 GlobalToLocal (&mouse_loc);
9281 #if TARGET_API_MAC_CARBON
9282 ch = FindControlUnderMouse (mouse_loc, window_ptr,
9283 &control_part_code);
9284 #ifdef MAC_OSX
9285 if (ch)
9286 GetControlKind (ch, &control_kind);
9287 #endif
9288 #else
9289 control_part_code = FindControl (mouse_loc, window_ptr,
9290 &ch);
9291 #endif
9293 #if USE_CARBON_EVENTS
9294 inev.code = mac_get_mouse_btn (eventRef);
9295 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
9296 #else
9297 inev.code = mac_get_emulated_btn (er.modifiers);
9298 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
9299 #endif
9300 XSETINT (inev.x, mouse_loc.h);
9301 XSETINT (inev.y, mouse_loc.v);
9303 if (dpyinfo->grabbed && tracked_scroll_bar
9304 || ch != 0
9305 #ifndef USE_TOOLKIT_SCROLL_BARS
9306 /* control_part_code becomes kControlNoPart if
9307 a progress indicator is clicked. */
9308 && control_part_code != kControlNoPart
9309 #else /* USE_TOOLKIT_SCROLL_BARS */
9310 #ifdef MAC_OSX
9311 && control_kind.kind == kControlKindScrollBar
9312 #endif /* MAC_OSX */
9313 #endif /* USE_TOOLKIT_SCROLL_BARS */
9316 struct scroll_bar *bar;
9318 if (dpyinfo->grabbed && tracked_scroll_bar)
9320 bar = tracked_scroll_bar;
9321 #ifndef USE_TOOLKIT_SCROLL_BARS
9322 control_part_code = kControlIndicatorPart;
9323 #endif
9325 else
9326 bar = (struct scroll_bar *) GetControlReference (ch);
9327 #ifdef USE_TOOLKIT_SCROLL_BARS
9328 /* Make the "Ctrl-Mouse-2 splits window" work
9329 for toolkit scroll bars. */
9330 if (er.modifiers & controlKey)
9331 x_scroll_bar_handle_click (bar, control_part_code,
9332 &er, &inev);
9333 else if (er.what == mouseDown)
9334 x_scroll_bar_handle_press (bar, control_part_code,
9335 &inev);
9336 else
9337 x_scroll_bar_handle_release (bar, &inev);
9338 #else /* not USE_TOOLKIT_SCROLL_BARS */
9339 x_scroll_bar_handle_click (bar, control_part_code,
9340 &er, &inev);
9341 if (er.what == mouseDown
9342 && control_part_code == kControlIndicatorPart)
9343 tracked_scroll_bar = bar;
9344 else
9345 tracked_scroll_bar = NULL;
9346 #endif /* not USE_TOOLKIT_SCROLL_BARS */
9348 else
9350 Lisp_Object window;
9351 int x = mouse_loc.h;
9352 int y = mouse_loc.v;
9354 window = window_from_coordinates (f, x, y, 0, 0, 0, 1);
9355 if (EQ (window, f->tool_bar_window))
9357 if (er.what == mouseDown)
9358 handle_tool_bar_click (f, x, y, 1, 0);
9359 else
9360 handle_tool_bar_click (f, x, y, 0,
9361 inev.modifiers);
9362 tool_bar_p = 1;
9364 else
9366 XSETFRAME (inev.frame_or_window, f);
9367 inev.kind = MOUSE_CLICK_EVENT;
9371 if (er.what == mouseDown)
9373 dpyinfo->grabbed |= (1 << inev.code);
9374 last_mouse_frame = f;
9375 /* Ignore any mouse motion that happened
9376 before this event; any subsequent
9377 mouse-movement Emacs events should reflect
9378 only motion after the ButtonPress. */
9379 if (f != 0)
9380 f->mouse_moved = 0;
9382 if (!tool_bar_p)
9383 last_tool_bar_item = -1;
9385 else
9387 if ((dpyinfo->grabbed & (1 << inev.code)) == 0)
9388 /* If a button is released though it was not
9389 previously pressed, that would be because
9390 of multi-button emulation. */
9391 dpyinfo->grabbed = 0;
9392 else
9393 dpyinfo->grabbed &= ~(1 << inev.code);
9396 #ifdef USE_TOOLKIT_SCROLL_BARS
9397 if (inev.kind == MOUSE_CLICK_EVENT)
9398 #endif
9399 switch (er.what)
9401 case mouseDown:
9402 inev.modifiers |= down_modifier;
9403 break;
9404 case mouseUp:
9405 inev.modifiers |= up_modifier;
9406 break;
9409 break;
9411 case inDrag:
9412 #if TARGET_API_MAC_CARBON
9413 DragWindow (window_ptr, er.where, NULL);
9414 #else /* not TARGET_API_MAC_CARBON */
9415 DragWindow (window_ptr, er.where, &qd.screenBits.bounds);
9416 #endif /* not TARGET_API_MAC_CARBON */
9417 /* Update the frame parameters. */
9419 struct frame *f = mac_window_to_frame (window_ptr);
9421 if (f && !f->async_iconified)
9422 x_real_positions (f, &f->left_pos, &f->top_pos);
9424 break;
9426 case inGoAway:
9427 if (TrackGoAway (window_ptr, er.where))
9429 inev.kind = DELETE_WINDOW_EVENT;
9430 XSETFRAME (inev.frame_or_window,
9431 mac_window_to_frame (window_ptr));
9433 break;
9435 /* window resize handling added --ben */
9436 case inGrow:
9437 do_grow_window (window_ptr, &er);
9438 break;
9440 /* window zoom handling added --ben */
9441 case inZoomIn:
9442 case inZoomOut:
9443 if (TrackBox (window_ptr, er.where, part_code))
9444 do_zoom_window (window_ptr, part_code);
9445 break;
9447 default:
9448 break;
9451 break;
9453 case updateEvt:
9454 #if USE_CARBON_EVENTS
9455 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9456 != eventNotHandledErr)
9457 break;
9458 #else
9459 do_window_update ((WindowPtr) er.message);
9460 #endif
9461 break;
9463 case osEvt:
9464 #if USE_CARBON_EVENTS
9465 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9466 != eventNotHandledErr)
9467 break;
9468 #endif
9469 switch ((er.message >> 24) & 0x000000FF)
9471 case suspendResumeMessage:
9472 if ((er.message & resumeFlag) == 1)
9473 do_app_resume ();
9474 else
9475 do_app_suspend ();
9476 break;
9478 case mouseMovedMessage:
9479 #if !USE_CARBON_EVENTS
9480 SetRectRgn (mouse_region, er.where.h, er.where.v,
9481 er.where.h + 1, er.where.v + 1);
9482 #endif
9483 previous_help_echo_string = help_echo_string;
9484 help_echo_string = help_echo_object = help_echo_window = Qnil;
9485 help_echo_pos = -1;
9487 if (dpyinfo->grabbed && last_mouse_frame
9488 && FRAME_LIVE_P (last_mouse_frame))
9489 f = last_mouse_frame;
9490 else
9491 f = dpyinfo->x_focus_frame;
9493 if (dpyinfo->mouse_face_hidden)
9495 dpyinfo->mouse_face_hidden = 0;
9496 clear_mouse_face (dpyinfo);
9499 if (f)
9501 WindowPtr wp = FRAME_MAC_WINDOW (f);
9502 Point mouse_pos = er.where;
9504 SetPortWindowPort (wp);
9506 GlobalToLocal (&mouse_pos);
9508 if (dpyinfo->grabbed && tracked_scroll_bar)
9509 #ifdef USE_TOOLKIT_SCROLL_BARS
9510 x_scroll_bar_handle_drag (wp, tracked_scroll_bar,
9511 mouse_pos, &inev);
9512 #else /* not USE_TOOLKIT_SCROLL_BARS */
9513 x_scroll_bar_note_movement (tracked_scroll_bar,
9514 mouse_pos.v
9515 - XINT (tracked_scroll_bar->top),
9516 er.when * (1000 / 60));
9517 #endif /* not USE_TOOLKIT_SCROLL_BARS */
9518 else
9520 /* Generate SELECT_WINDOW_EVENTs when needed. */
9521 if (mouse_autoselect_window)
9523 Lisp_Object window;
9525 window = window_from_coordinates (f,
9526 mouse_pos.h,
9527 mouse_pos.v,
9528 0, 0, 0, 0);
9530 /* Window will be selected only when it is
9531 not selected now and last mouse movement
9532 event was not in it. Minibuffer window
9533 will be selected iff it is active. */
9534 if (WINDOWP (window)
9535 && !EQ (window, last_window)
9536 && !EQ (window, selected_window))
9538 inev.kind = SELECT_WINDOW_EVENT;
9539 inev.frame_or_window = window;
9542 last_window=window;
9544 note_mouse_movement (f, &mouse_pos);
9548 /* If the contents of the global variable
9549 help_echo_string has changed, generate a
9550 HELP_EVENT. */
9551 if (!NILP (help_echo_string) || !NILP (previous_help_echo_string))
9552 do_help = 1;
9553 break;
9555 break;
9557 case activateEvt:
9559 WindowPtr window_ptr = (WindowPtr) er.message;
9561 #if USE_CARBON_EVENTS
9562 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9563 != eventNotHandledErr)
9564 break;
9565 #endif
9566 if (window_ptr == tip_window)
9568 HideWindow (tip_window);
9569 break;
9572 if (!is_emacs_window (window_ptr))
9573 break;
9575 if ((er.modifiers & activeFlag) != 0)
9577 /* A window has been activated */
9578 Point mouse_loc = er.where;
9580 x_detect_focus_change (dpyinfo, &er, &inev);
9582 SetPortWindowPort (window_ptr);
9583 GlobalToLocal (&mouse_loc);
9584 /* Window-activated event counts as mouse movement,
9585 so update things that depend on mouse position. */
9586 note_mouse_movement (mac_window_to_frame (window_ptr),
9587 &mouse_loc);
9589 else
9591 /* A window has been deactivated */
9592 #if USE_TOOLKIT_SCROLL_BARS
9593 if (dpyinfo->grabbed && tracked_scroll_bar)
9595 struct input_event event;
9597 EVENT_INIT (event);
9598 event.kind = NO_EVENT;
9599 x_scroll_bar_handle_release (tracked_scroll_bar, &event);
9600 if (event.kind != NO_EVENT)
9602 event.timestamp = timestamp;
9603 kbd_buffer_store_event_hold (&event, hold_quit);
9604 count++;
9607 #endif
9608 dpyinfo->grabbed = 0;
9610 x_detect_focus_change (dpyinfo, &er, &inev);
9612 f = mac_window_to_frame (window_ptr);
9613 if (f == dpyinfo->mouse_face_mouse_frame)
9615 /* If we move outside the frame, then we're
9616 certainly no longer on any text in the
9617 frame. */
9618 clear_mouse_face (dpyinfo);
9619 dpyinfo->mouse_face_mouse_frame = 0;
9622 /* Generate a nil HELP_EVENT to cancel a help-echo.
9623 Do it only if there's something to cancel.
9624 Otherwise, the startup message is cleared when the
9625 mouse leaves the frame. */
9626 if (any_help_event_p)
9627 do_help = -1;
9630 break;
9632 case keyDown:
9633 case autoKey:
9635 int keycode = (er.message & keyCodeMask) >> 8;
9636 int xkeysym;
9638 #if USE_CARBON_EVENTS && defined (MAC_OSX)
9639 /* When using Carbon Events, we need to pass raw keyboard
9640 events to the TSM ourselves. If TSM handles it, it
9641 will pass back noErr, otherwise it will pass back
9642 "eventNotHandledErr" and we can process it
9643 normally. */
9644 if ((!NILP (Vmac_pass_command_to_system)
9645 || !(er.modifiers & cmdKey))
9646 && (!NILP (Vmac_pass_control_to_system)
9647 || !(er.modifiers & controlKey))
9648 && (!NILP (Vmac_command_key_is_meta)
9649 && NILP (Vmac_option_modifier)
9650 || !(er.modifiers & optionKey)))
9651 if (SendEventToEventTarget (eventRef, toolbox_dispatcher)
9652 != eventNotHandledErr)
9653 break;
9654 #endif
9656 #if 0
9657 if (dpyinfo->x_focus_frame == NULL)
9659 /* Beep if keyboard input occurs when all the frames
9660 are invisible. */
9661 SysBeep (1);
9662 break;
9664 #endif
9667 static SInt16 last_key_script = -1;
9668 SInt16 current_key_script = GetScriptManagerVariable (smKeyScript);
9670 if (last_key_script != current_key_script)
9672 struct input_event event;
9674 EVENT_INIT (event);
9675 event.kind = LANGUAGE_CHANGE_EVENT;
9676 event.arg = Qnil;
9677 event.code = current_key_script;
9678 event.timestamp = timestamp;
9679 kbd_buffer_store_event (&event);
9680 count++;
9682 last_key_script = current_key_script;
9685 ObscureCursor ();
9687 if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
9689 clear_mouse_face (dpyinfo);
9690 dpyinfo->mouse_face_hidden = 1;
9693 if (keycode_to_xkeysym (keycode, &xkeysym))
9695 inev.code = 0xff00 | xkeysym;
9696 inev.kind = NON_ASCII_KEYSTROKE_EVENT;
9698 else
9700 if (er.modifiers & (controlKey |
9701 (NILP (Vmac_command_key_is_meta) ? optionKey
9702 : cmdKey)))
9704 /* This code comes from Keyboard Resource,
9705 Appendix C of IM - Text. This is necessary
9706 since shift is ignored in KCHR table
9707 translation when option or command is pressed.
9708 It also does not translate correctly
9709 control-shift chars like C-% so mask off shift
9710 here also */
9711 int new_modifiers = er.modifiers & 0xe600;
9712 /* mask off option and command */
9713 int new_keycode = keycode | new_modifiers;
9714 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
9715 unsigned long some_state = 0;
9716 inev.code = KeyTranslate (kchr_ptr, new_keycode,
9717 &some_state) & 0xff;
9719 else if (!NILP (Vmac_option_modifier)
9720 && (er.modifiers & optionKey))
9722 /* When using the option key as an emacs modifier,
9723 convert the pressed key code back to one
9724 without the Mac option modifier applied. */
9725 int new_modifiers = er.modifiers & ~optionKey;
9726 int new_keycode = keycode | new_modifiers;
9727 Ptr kchr_ptr = (Ptr) GetScriptManagerVariable (smKCHRCache);
9728 unsigned long some_state = 0;
9729 inev.code = KeyTranslate (kchr_ptr, new_keycode,
9730 &some_state) & 0xff;
9732 else
9733 inev.code = er.message & charCodeMask;
9734 inev.kind = ASCII_KEYSTROKE_EVENT;
9738 #if USE_CARBON_EVENTS
9739 inev.modifiers = mac_event_to_emacs_modifiers (eventRef);
9740 #else
9741 inev.modifiers = mac_to_emacs_modifiers (er.modifiers);
9742 #endif
9743 inev.modifiers |= (extra_keyboard_modifiers
9744 & (meta_modifier | alt_modifier
9745 | hyper_modifier | super_modifier));
9746 XSETFRAME (inev.frame_or_window, mac_focus_frame (dpyinfo));
9747 break;
9749 case kHighLevelEvent:
9750 read_socket_inev = &inev;
9751 AEProcessAppleEvent (&er);
9752 read_socket_inev = NULL;
9753 break;
9755 default:
9756 break;
9758 #if USE_CARBON_EVENTS
9759 ReleaseEvent (eventRef);
9760 #endif
9762 if (inev.kind != NO_EVENT)
9764 inev.timestamp = timestamp;
9765 kbd_buffer_store_event_hold (&inev, hold_quit);
9766 count++;
9769 if (do_help
9770 && !(hold_quit && hold_quit->kind != NO_EVENT))
9772 Lisp_Object frame;
9774 if (f)
9775 XSETFRAME (frame, f);
9776 else
9777 frame = Qnil;
9779 if (do_help > 0)
9781 any_help_event_p = 1;
9782 gen_help_event (help_echo_string, frame, help_echo_window,
9783 help_echo_object, help_echo_pos);
9785 else
9787 help_echo_string = Qnil;
9788 gen_help_event (Qnil, frame, Qnil, Qnil, 0);
9790 count++;
9795 /* If the focus was just given to an autoraising frame,
9796 raise it now. */
9797 /* ??? This ought to be able to handle more than one such frame. */
9798 if (pending_autoraise_frame)
9800 x_raise_frame (pending_autoraise_frame);
9801 pending_autoraise_frame = 0;
9804 #if !USE_CARBON_EVENTS
9805 /* Check which frames are still visible. We do this here because
9806 there doesn't seem to be any direct notification from the Window
9807 Manager that the visibility of a window has changed (at least,
9808 not in all cases). */
9810 Lisp_Object tail, frame;
9812 FOR_EACH_FRAME (tail, frame)
9814 struct frame *f = XFRAME (frame);
9816 /* The tooltip has been drawn already. Avoid the
9817 SET_FRAME_GARBAGED in mac_handle_visibility_change. */
9818 if (EQ (frame, tip_frame))
9819 continue;
9821 if (FRAME_MAC_P (f))
9822 mac_handle_visibility_change (f);
9825 #endif
9827 UNBLOCK_INPUT;
9828 return count;
9832 /* Need to override CodeWarrior's input function so no conversion is
9833 done on newlines Otherwise compiled functions in .elc files will be
9834 read incorrectly. Defined in ...:MSL C:MSL
9835 Common:Source:buffer_io.c. */
9836 #ifdef __MWERKS__
9837 void
9838 __convert_to_newlines (unsigned char * p, size_t * n)
9840 #pragma unused(p,n)
9843 void
9844 __convert_from_newlines (unsigned char * p, size_t * n)
9846 #pragma unused(p,n)
9848 #endif
9850 #ifdef MAC_OS8
9851 void
9852 make_mac_terminal_frame (struct frame *f)
9854 Lisp_Object frame;
9855 Rect r;
9857 XSETFRAME (frame, f);
9859 f->output_method = output_mac;
9860 f->output_data.mac = (struct mac_output *)
9861 xmalloc (sizeof (struct mac_output));
9862 bzero (f->output_data.mac, sizeof (struct mac_output));
9864 XSETFRAME (FRAME_KBOARD (f)->Vdefault_minibuffer_frame, f);
9866 FRAME_COLS (f) = 96;
9867 FRAME_LINES (f) = 4;
9869 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
9870 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_right;
9872 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
9874 f->output_data.mac->cursor_pixel = 0;
9875 f->output_data.mac->border_pixel = 0x00ff00;
9876 f->output_data.mac->mouse_pixel = 0xff00ff;
9877 f->output_data.mac->cursor_foreground_pixel = 0x0000ff;
9879 f->output_data.mac->text_cursor = kThemeIBeamCursor;
9880 f->output_data.mac->nontext_cursor = kThemeArrowCursor;
9881 f->output_data.mac->modeline_cursor = kThemeArrowCursor;
9882 f->output_data.mac->hand_cursor = kThemePointingHandCursor;
9883 f->output_data.mac->hourglass_cursor = kThemeWatchCursor;
9884 f->output_data.mac->horizontal_drag_cursor = kThemeResizeLeftRightCursor;
9886 FRAME_FONTSET (f) = -1;
9887 f->output_data.mac->explicit_parent = 0;
9888 f->left_pos = 8;
9889 f->top_pos = 32;
9890 f->border_width = 0;
9892 f->internal_border_width = 0;
9894 f->auto_raise = 1;
9895 f->auto_lower = 1;
9897 f->new_text_cols = 0;
9898 f->new_text_lines = 0;
9900 SetRect (&r, f->left_pos, f->top_pos,
9901 f->left_pos + FRAME_PIXEL_WIDTH (f),
9902 f->top_pos + FRAME_PIXEL_HEIGHT (f));
9904 BLOCK_INPUT;
9906 if (!(FRAME_MAC_WINDOW (f) =
9907 NewCWindow (NULL, &r, "\p", true, dBoxProc,
9908 (WindowPtr) -1, 1, (long) f->output_data.mac)))
9909 abort ();
9910 /* so that update events can find this mac_output struct */
9911 f->output_data.mac->mFP = f; /* point back to emacs frame */
9913 UNBLOCK_INPUT;
9915 x_make_gc (f);
9917 /* Need to be initialized for unshow_buffer in window.c. */
9918 selected_window = f->selected_window;
9920 Fmodify_frame_parameters (frame,
9921 Fcons (Fcons (Qfont,
9922 build_string ("-*-monaco-medium-r-*--*-90-*-*-*-*-mac-roman")), Qnil));
9923 Fmodify_frame_parameters (frame,
9924 Fcons (Fcons (Qforeground_color,
9925 build_string ("black")), Qnil));
9926 Fmodify_frame_parameters (frame,
9927 Fcons (Fcons (Qbackground_color,
9928 build_string ("white")), Qnil));
9930 #endif
9933 /***********************************************************************
9934 Initialization
9935 ***********************************************************************/
9937 int mac_initialized = 0;
9939 void
9940 mac_initialize_display_info ()
9942 struct mac_display_info *dpyinfo = &one_mac_display_info;
9943 GDHandle main_device_handle;
9945 bzero (dpyinfo, sizeof (*dpyinfo));
9947 #ifdef MAC_OSX
9948 dpyinfo->mac_id_name
9949 = (char *) xmalloc (SCHARS (Vinvocation_name)
9950 + SCHARS (Vsystem_name)
9951 + 2);
9952 sprintf (dpyinfo->mac_id_name, "%s@%s",
9953 SDATA (Vinvocation_name), SDATA (Vsystem_name));
9954 #else
9955 dpyinfo->mac_id_name = (char *) xmalloc (strlen ("Mac Display") + 1);
9956 strcpy (dpyinfo->mac_id_name, "Mac Display");
9957 #endif
9959 main_device_handle = LMGetMainDevice();
9961 dpyinfo->reference_count = 0;
9962 dpyinfo->resx = 75.0;
9963 dpyinfo->resy = 75.0;
9964 dpyinfo->color_p = TestDeviceAttribute (main_device_handle, gdDevType);
9965 #ifdef MAC_OSX
9966 /* HasDepth returns true if it is possible to have a 32 bit display,
9967 but this may not be what is actually used. Mac OSX can do better.
9968 CGMainDisplayID is only available on OSX 10.2 and higher, but the
9969 header for CGGetActiveDisplayList says that the first display returned
9970 is the active one, so we use that. */
9972 CGDirectDisplayID disp_id[1];
9973 CGDisplayCount disp_count;
9974 CGDisplayErr error_code;
9976 error_code = CGGetActiveDisplayList (1, disp_id, &disp_count);
9977 if (error_code != 0)
9978 error ("No display found, CGGetActiveDisplayList error %d", error_code);
9980 dpyinfo->n_planes = CGDisplayBitsPerPixel (disp_id[0]);
9982 #else
9983 for (dpyinfo->n_planes = 32; dpyinfo->n_planes > 0; dpyinfo->n_planes >>= 1)
9984 if (HasDepth (main_device_handle, dpyinfo->n_planes,
9985 gdDevType, dpyinfo->color_p))
9986 break;
9987 #endif
9988 dpyinfo->height = (**main_device_handle).gdRect.bottom;
9989 dpyinfo->width = (**main_device_handle).gdRect.right;
9990 dpyinfo->grabbed = 0;
9991 dpyinfo->root_window = NULL;
9992 dpyinfo->image_cache = make_image_cache ();
9994 dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
9995 dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
9996 dpyinfo->mouse_face_face_id = DEFAULT_FACE_ID;
9997 dpyinfo->mouse_face_window = Qnil;
9998 dpyinfo->mouse_face_overlay = Qnil;
9999 dpyinfo->mouse_face_hidden = 0;
10003 static XrmDatabase
10004 mac_make_rdb (xrm_option)
10005 char *xrm_option;
10007 XrmDatabase database;
10009 database = xrm_get_preference_database (NULL);
10010 if (xrm_option)
10011 xrm_merge_string_database (database, xrm_option);
10013 return database;
10016 struct mac_display_info *
10017 mac_term_init (display_name, xrm_option, resource_name)
10018 Lisp_Object display_name;
10019 char *xrm_option;
10020 char *resource_name;
10022 struct mac_display_info *dpyinfo;
10024 BLOCK_INPUT;
10026 if (!mac_initialized)
10028 mac_initialize ();
10029 mac_initialized = 1;
10032 if (x_display_list)
10033 error ("Sorry, this version can only handle one display");
10035 mac_initialize_display_info ();
10037 dpyinfo = &one_mac_display_info;
10039 dpyinfo->xrdb = mac_make_rdb (xrm_option);
10041 /* Put this display on the chain. */
10042 dpyinfo->next = x_display_list;
10043 x_display_list = dpyinfo;
10045 /* Put it on x_display_name_list. */
10046 x_display_name_list = Fcons (Fcons (display_name,
10047 Fcons (Qnil, dpyinfo->xrdb)),
10048 x_display_name_list);
10049 dpyinfo->name_list_element = XCAR (x_display_name_list);
10051 UNBLOCK_INPUT;
10053 return dpyinfo;
10055 /* Get rid of display DPYINFO, assuming all frames are already gone. */
10057 void
10058 x_delete_display (dpyinfo)
10059 struct mac_display_info *dpyinfo;
10061 int i;
10063 /* Discard this display from x_display_name_list and x_display_list.
10064 We can't use Fdelq because that can quit. */
10065 if (! NILP (x_display_name_list)
10066 && EQ (XCAR (x_display_name_list), dpyinfo->name_list_element))
10067 x_display_name_list = XCDR (x_display_name_list);
10068 else
10070 Lisp_Object tail;
10072 tail = x_display_name_list;
10073 while (CONSP (tail) && CONSP (XCDR (tail)))
10075 if (EQ (XCAR (XCDR (tail)), dpyinfo->name_list_element))
10077 XSETCDR (tail, XCDR (XCDR (tail)));
10078 break;
10080 tail = XCDR (tail);
10084 if (x_display_list == dpyinfo)
10085 x_display_list = dpyinfo->next;
10086 else
10088 struct x_display_info *tail;
10090 for (tail = x_display_list; tail; tail = tail->next)
10091 if (tail->next == dpyinfo)
10092 tail->next = tail->next->next;
10095 /* Free the font names in the font table. */
10096 for (i = 0; i < dpyinfo->n_fonts; i++)
10097 if (dpyinfo->font_table[i].name)
10099 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
10100 xfree (dpyinfo->font_table[i].full_name);
10101 xfree (dpyinfo->font_table[i].name);
10104 if (dpyinfo->font_table->font_encoder)
10105 xfree (dpyinfo->font_table->font_encoder);
10107 xfree (dpyinfo->font_table);
10108 xfree (dpyinfo->mac_id_name);
10110 if (x_display_list == 0)
10112 mac_clear_font_name_table ();
10113 bzero (dpyinfo, sizeof (*dpyinfo));
10118 #ifdef MAC_OSX
10119 void
10120 mac_check_bundle()
10122 extern int inhibit_window_system;
10123 extern int noninteractive;
10124 CFBundleRef appsBundle;
10125 pid_t child;
10127 /* No need to test if already -nw*/
10128 if (inhibit_window_system || noninteractive)
10129 return;
10131 appsBundle = CFBundleGetMainBundle();
10132 if (appsBundle != NULL)
10134 CFStringRef cfBI = CFSTR("CFBundleIdentifier");
10135 CFTypeRef res = CFBundleGetValueForInfoDictionaryKey(appsBundle, cfBI);
10136 /* We found the bundle identifier, now we know we are valid. */
10137 if (res != NULL)
10139 CFRelease(res);
10140 return;
10143 /* MAC_TODO: Have this start the bundled executable */
10145 /* For now, prevent the fatal error by bringing it up in the terminal */
10146 inhibit_window_system = 1;
10149 void
10150 MakeMeTheFrontProcess ()
10152 ProcessSerialNumber psn;
10153 OSErr err;
10155 err = GetCurrentProcess (&psn);
10156 if (err == noErr)
10157 (void) SetFrontProcess (&psn);
10160 /***** Code to handle C-g testing *****/
10162 /* Contains the Mac modifier formed from quit_char */
10163 int mac_quit_char_modifiers = 0;
10164 int mac_quit_char_keycode;
10165 extern int quit_char;
10167 static void
10168 mac_determine_quit_char_modifiers()
10170 /* Todo: Determine modifiers from quit_char. */
10171 UInt32 qc_modifiers = ctrl_modifier;
10173 /* Map modifiers */
10174 mac_quit_char_modifiers = 0;
10175 if (qc_modifiers & ctrl_modifier) mac_quit_char_modifiers |= macCtrlKey;
10176 if (qc_modifiers & shift_modifier) mac_quit_char_modifiers |= macShiftKey;
10177 if (qc_modifiers & meta_modifier) mac_quit_char_modifiers |= macMetaKey;
10178 if (qc_modifiers & alt_modifier) mac_quit_char_modifiers |= macAltKey;
10181 static void
10182 init_quit_char_handler ()
10184 /* TODO: Let this support keys other the 'g' */
10185 mac_quit_char_keycode = 5;
10186 /* Look at <architecture/adb_kb_map.h> for details */
10187 /* http://gemma.apple.com/techpubs/mac/Toolbox/Toolbox-40.html#MARKER-9-184*/
10189 mac_determine_quit_char_modifiers();
10192 static Boolean
10193 quit_char_comp (EventRef inEvent, void *inCompData)
10195 if (GetEventClass(inEvent) != kEventClassKeyboard)
10196 return false;
10197 if (GetEventKind(inEvent) != kEventRawKeyDown)
10198 return false;
10200 UInt32 keyCode;
10201 UInt32 keyModifiers;
10202 GetEventParameter(inEvent, kEventParamKeyCode,
10203 typeUInt32, NULL, sizeof(UInt32), NULL, &keyCode);
10204 if (keyCode != mac_quit_char_keycode)
10205 return false;
10206 GetEventParameter(inEvent, kEventParamKeyModifiers,
10207 typeUInt32, NULL, sizeof(UInt32), NULL, &keyModifiers);
10208 if (keyModifiers != mac_quit_char_modifiers)
10209 return false;
10211 return true;
10214 void
10215 mac_check_for_quit_char ()
10217 EventRef event;
10218 static EMACS_TIME last_check_time = { 0, 0 };
10219 static EMACS_TIME one_second = { 1, 0 };
10220 EMACS_TIME now, t;
10222 /* If windows are not initialized, return immediately (keep it bouncin'). */
10223 if (!mac_quit_char_modifiers)
10224 return;
10226 /* Don't check if last check is less than a second ago. */
10227 EMACS_GET_TIME (now);
10228 EMACS_SUB_TIME (t, now, last_check_time);
10229 if (EMACS_TIME_LT (t, one_second))
10230 return;
10231 last_check_time = now;
10233 /* Redetermine modifiers because they are based on lisp variables */
10234 mac_determine_quit_char_modifiers ();
10236 /* Fill the queue with events */
10237 BLOCK_INPUT;
10238 ReceiveNextEvent (0, NULL, kEventDurationNoWait, false, &event);
10239 event = FindSpecificEventInQueue (GetMainEventQueue (), quit_char_comp,
10240 NULL);
10241 UNBLOCK_INPUT;
10242 if (event)
10244 struct input_event e;
10246 /* Use an input_event to emulate what the interrupt handler does. */
10247 EVENT_INIT (e);
10248 e.kind = ASCII_KEYSTROKE_EVENT;
10249 e.code = quit_char;
10250 e.arg = Qnil;
10251 e.modifiers = NULL;
10252 e.timestamp = EventTimeToTicks (GetEventTime (event)) * (1000/60);
10253 XSETFRAME (e.frame_or_window, mac_focus_frame (&one_mac_display_info));
10254 /* Remove event from queue to prevent looping. */
10255 RemoveEventFromQueue (GetMainEventQueue (), event);
10256 ReleaseEvent (event);
10257 kbd_buffer_store_event (&e);
10260 #endif /* MAC_OSX */
10262 static void
10263 init_menu_bar ()
10265 #ifdef MAC_OSX
10266 OSErr err;
10267 MenuRef menu;
10268 MenuItemIndex menu_index;
10270 err = GetIndMenuItemWithCommandID (NULL, kHICommandQuit, 1,
10271 &menu, &menu_index);
10272 if (err == noErr)
10273 SetMenuItemCommandKey (menu, menu_index, false, 0);
10274 #if USE_CARBON_EVENTS
10275 EnableMenuCommand (NULL, kHICommandPreferences);
10276 err = GetIndMenuItemWithCommandID (NULL, kHICommandPreferences, 1,
10277 &menu, &menu_index);
10278 if (err == noErr)
10280 SetMenuItemCommandKey (menu, menu_index, false, 0);
10281 InsertMenuItemTextWithCFString (menu, NULL,
10282 0, kMenuItemAttrSeparator, 0);
10283 InsertMenuItemTextWithCFString (menu, CFSTR ("About Emacs"),
10284 0, 0, kHICommandAbout);
10286 #endif /* USE_CARBON_EVENTS */
10287 #else /* !MAC_OSX */
10288 #if USE_CARBON_EVENTS
10289 SetMenuItemCommandID (GetMenuHandle (M_APPLE), I_ABOUT, kHICommandAbout);
10290 #endif
10291 #endif
10295 /* Set up use of X before we make the first connection. */
10297 extern frame_parm_handler mac_frame_parm_handlers[];
10299 static struct redisplay_interface x_redisplay_interface =
10301 mac_frame_parm_handlers,
10302 x_produce_glyphs,
10303 x_write_glyphs,
10304 x_insert_glyphs,
10305 x_clear_end_of_line,
10306 x_scroll_run,
10307 x_after_update_window_line,
10308 x_update_window_begin,
10309 x_update_window_end,
10310 x_cursor_to,
10311 x_flush,
10312 0, /* flush_display_optional */
10313 x_clear_window_mouse_face,
10314 x_get_glyph_overhangs,
10315 x_fix_overlapping_area,
10316 x_draw_fringe_bitmap,
10317 0, /* define_fringe_bitmap */
10318 0, /* destroy_fringe_bitmap */
10319 mac_per_char_metric,
10320 mac_encode_char,
10321 mac_compute_glyph_string_overhangs,
10322 x_draw_glyph_string,
10323 mac_define_frame_cursor,
10324 mac_clear_frame_area,
10325 mac_draw_window_cursor,
10326 mac_draw_vertical_window_border,
10327 mac_shift_glyphs_for_insert
10330 void
10331 mac_initialize ()
10333 rif = &x_redisplay_interface;
10335 clear_frame_hook = x_clear_frame;
10336 ins_del_lines_hook = x_ins_del_lines;
10337 delete_glyphs_hook = x_delete_glyphs;
10338 ring_bell_hook = XTring_bell;
10339 reset_terminal_modes_hook = XTreset_terminal_modes;
10340 set_terminal_modes_hook = XTset_terminal_modes;
10341 update_begin_hook = x_update_begin;
10342 update_end_hook = x_update_end;
10343 set_terminal_window_hook = XTset_terminal_window;
10344 read_socket_hook = XTread_socket;
10345 frame_up_to_date_hook = XTframe_up_to_date;
10346 mouse_position_hook = XTmouse_position;
10347 frame_rehighlight_hook = XTframe_rehighlight;
10348 frame_raise_lower_hook = XTframe_raise_lower;
10350 set_vertical_scroll_bar_hook = XTset_vertical_scroll_bar;
10351 condemn_scroll_bars_hook = XTcondemn_scroll_bars;
10352 redeem_scroll_bar_hook = XTredeem_scroll_bar;
10353 judge_scroll_bars_hook = XTjudge_scroll_bars;
10355 scroll_region_ok = 1; /* we'll scroll partial frames */
10356 char_ins_del_ok = 1;
10357 line_ins_del_ok = 1; /* we'll just blt 'em */
10358 fast_clear_end_of_line = 1; /* X does this well */
10359 memory_below_frame = 0; /* we don't remember what scrolls
10360 off the bottom */
10361 baud_rate = 19200;
10363 last_tool_bar_item = -1;
10364 any_help_event_p = 0;
10366 /* Try to use interrupt input; if we can't, then start polling. */
10367 Fset_input_mode (Qt, Qnil, Qt, Qnil);
10369 BLOCK_INPUT;
10371 #if TARGET_API_MAC_CARBON
10372 init_required_apple_events ();
10374 #if USE_CARBON_EVENTS
10375 #ifdef MAC_OSX
10376 init_service_handler ();
10378 init_quit_char_handler ();
10379 #endif /* MAC_OSX */
10381 init_command_handler ();
10383 init_menu_bar ();
10384 #endif /* USE_CARBON_EVENTS */
10386 #ifdef MAC_OSX
10387 if (!inhibit_window_system)
10388 MakeMeTheFrontProcess ();
10389 #endif
10390 #endif
10391 UNBLOCK_INPUT;
10395 void
10396 syms_of_macterm ()
10398 #if 0
10399 staticpro (&x_error_message_string);
10400 x_error_message_string = Qnil;
10401 #endif
10403 Qmodifier_value = intern ("modifier-value");
10404 Qalt = intern ("alt");
10405 Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
10406 Qhyper = intern ("hyper");
10407 Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
10408 Qsuper = intern ("super");
10409 Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
10411 Qapplication = intern ("application"); staticpro (&Qapplication);
10412 Qabout = intern ("about"); staticpro (&Qabout);
10414 #if USE_CARBON_EVENTS && defined (MAC_OSX)
10415 Qpreferences = intern ("preferences"); staticpro (&Qpreferences);
10416 Qservices = intern ("services"); staticpro (&Qservices);
10417 Qpaste = intern ("paste"); staticpro (&Qpaste);
10418 Qperform = intern ("perform"); staticpro (&Qperform);
10419 #endif
10421 #ifdef MAC_OSX
10422 Fprovide (intern ("mac-carbon"), Qnil);
10423 #endif
10425 staticpro (&Qreverse);
10426 Qreverse = intern ("reverse");
10428 staticpro (&x_display_name_list);
10429 x_display_name_list = Qnil;
10431 staticpro (&last_mouse_scroll_bar);
10432 last_mouse_scroll_bar = Qnil;
10434 Qmac_ready_for_drag_n_drop = intern ("mac-ready-for-drag-n-drop");
10435 staticpro (&Qmac_ready_for_drag_n_drop);
10437 DEFVAR_LISP ("x-toolkit-scroll-bars", &Vx_toolkit_scroll_bars,
10438 doc: /* If not nil, Emacs uses toolkit scroll bars. */);
10439 #ifdef USE_TOOLKIT_SCROLL_BARS
10440 Vx_toolkit_scroll_bars = Qt;
10441 #else
10442 Vx_toolkit_scroll_bars = Qnil;
10443 #endif
10445 staticpro (&last_mouse_motion_frame);
10446 last_mouse_motion_frame = Qnil;
10448 DEFVAR_LISP ("mac-command-key-is-meta", &Vmac_command_key_is_meta,
10449 doc: /* Non-nil means that the command key is used as the Emacs meta key.
10450 Otherwise the option key is used. */);
10451 Vmac_command_key_is_meta = Qt;
10453 DEFVAR_LISP ("mac-option-modifier", &Vmac_option_modifier,
10454 doc: /* Modifier to use for the Mac alt/option key. The value can
10455 be alt, hyper, or super for the respective modifier. If the value is
10456 nil then the key will act as the normal Mac option modifier. */);
10457 Vmac_option_modifier = Qnil;
10459 DEFVAR_LISP ("mac-reverse-ctrl-meta", &Vmac_reverse_ctrl_meta,
10460 doc: /* Non-nil means that the control and meta keys are reversed. This is
10461 useful for non-standard keyboard layouts. */);
10462 Vmac_reverse_ctrl_meta = Qnil;
10464 DEFVAR_LISP ("mac-emulate-three-button-mouse",
10465 &Vmac_emulate_three_button_mouse,
10466 doc: /* t means that when the option-key is held down while pressing the
10467 mouse button, the click will register as mouse-2 and while the
10468 command-key is held down, the click will register as mouse-3.
10469 'reverse means that the option-key will register for mouse-3
10470 and the command-key will register for mouse-2. nil means that
10471 no emulation should be done and the modifiers should be placed
10472 on the mouse-1 event. */);
10473 Vmac_emulate_three_button_mouse = Qnil;
10475 #if USE_CARBON_EVENTS
10476 DEFVAR_LISP ("mac-wheel-button-is-mouse-2", &Vmac_wheel_button_is_mouse_2,
10477 doc: /* Non-nil means that the wheel button will be treated as mouse-2 and
10478 the right click will be mouse-3.
10479 Otherwise, the right click will be mouse-2 and the wheel button mouse-3.*/);
10480 Vmac_wheel_button_is_mouse_2 = Qt;
10482 DEFVAR_LISP ("mac-pass-command-to-system", &Vmac_pass_command_to_system,
10483 doc: /* If non-nil, the Mac \"Command\" key is passed on to the Mac
10484 Toolbox for processing before Emacs sees it. */);
10485 Vmac_pass_command_to_system = Qt;
10487 DEFVAR_LISP ("mac-pass-control-to-system", &Vmac_pass_control_to_system,
10488 doc: /* If non-nil, the Mac \"Control\" key is passed on to the Mac
10489 Toolbox for processing before Emacs sees it. */);
10490 Vmac_pass_control_to_system = Qt;
10492 #endif
10494 DEFVAR_LISP ("mac-allow-anti-aliasing", &Vmac_use_core_graphics,
10495 doc: /* If non-nil, allow anti-aliasing.
10496 The text will be rendered using Core Graphics text rendering which
10497 may anti-alias the text. */);
10498 Vmac_use_core_graphics = Qnil;
10500 /* Register an entry for `mac-roman' so that it can be used when
10501 creating the terminal frame on Mac OS 9 before loading
10502 term/mac-win.elc. */
10503 DEFVAR_LISP ("mac-charset-info-alist", &Vmac_charset_info_alist,
10504 doc: /* Alist linking Emacs character sets to Mac text encoding and Emacs coding system.
10505 Each entry should be of the form:
10507 (CHARSET-NAME TEXT-ENCODING CODING-SYSTEM)
10509 where CHARSET-NAME is a string used in font names to identify the
10510 charset, TEXT-ENCODING is a TextEncodingBase value, and CODING_SYSTEM
10511 is a coding system corresponding to TEXT-ENCODING. */);
10512 Vmac_charset_info_alist =
10513 Fcons (list3 (build_string ("mac-roman"),
10514 make_number (smRoman), Qnil), Qnil);
10517 /* arch-tag: f2259165-4454-4c04-a029-a133c8af7b5b
10518 (do not change this comment) */